http://stackoverflow.com/q/50461126
has comment: http://stackoverflow.com/comment/87936867
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87936485
type: Question
tagged with: dask
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50462000
has comment: http://stackoverflow.com/comment/87936581
tagged with: python
has comment: http://stackoverflow.com/comment/87935511
has body: Can any one explain how to rectify this error Where do i get a detailed info of dask Can it replace pandas. How is it different from other dataframes, is it fast in processing Code: import dask.dataframe as dd df = dd.demo.make_timeseries('2000-01-01', '2000-12-31', freq='10s', partition_freq='1M',dtypes={'name': str, 'id': int, 'x': float, 'y': float}) print df o/p: Traceback (most recent call last): File "C:/Users/divya.nagandla/PycharmProjects/python/supressions1/dask.py", line 1, in import dask.dataframe as dd File "C:\Users\divya.nagandla\PycharmProjects\python\supressions1\dask.py", line 1, in import dask.dataframe as dd ImportError: No module named dataframe
has title: what is dask and how is it different from pandas
tagged with: pandas
has comment: http://stackoverflow.com/comment/87937384
score: 1
has comment: http://stackoverflow.com/comment/87936807
answer count: 1

http://stackoverflow.com/q/50517000
tagged with: pytest
answer count: 1
has title: Tavern(pytest), disable SSL Certificate Validation
favorite count: 0
type: Question
tagged with: testing
has answer: http://stackoverflow.com/a/50533613
accepted answer: http://stackoverflow.com/a/50533613
has body: I'm attempting to test Tavern in our test environment. Of course, there is an invalid SSL Certificate in the test environment and this is preventing Tavern from completing a test. The error message reads: SSLError: HTTPSConnectionPool(host='url-to-host' port=443): Max retires exceed with url: /folders/in/url (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:726)')) Is there a way to disable SSL Certificate Validation in Tavern so I can continue in our test environment?
tagged with: python
score: 4
upvote count: 4
tagged with: ssl-certificate
has comment: http://stackoverflow.com/comment/88048332
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/88893687
has text: Thanks @jpp. I found your answer to be most elegant and extensible. I made a modification to satisfy a requirement I forgot to mention, and one that truly preserves the old index. I'll put this in my original question.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50867758

http://stackoverflow.com/comment/87959442
comment on: http://stackoverflow.com/q/50472710
has text: @MarkSetchell and @ricco19 `std::istream::read` expects `char *` as first parameter, your suggestion is wrong and useless.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50420233
has title: `with open` multiple `findall` but open file once
score: 2
type: AnsweredQuestion
tagged with: findall
downvote count: 0
has body: I'm working in some python code to parse this .h file: #include &lt;limits.h&gt; // Offsets // UINT_MAX == 4294967295 (Note: do not remove the comments, they are used by parser.py) #define ID_OFFSET UINT_MAX - (1 &lt;&lt; 6) // ID_OFFSET == 4294967231 #define CALL_NR_OFFSET ID_OFFSET - (1 &lt;&lt; 20) // CALL_NR_OFFSET == 4293918655 // Range of lower 2^20 numbers is reserved for debug statements. #define DEBUG_OFFSET (2 &lt;&lt; 20) // DEBUG_OFFSET == 1048576 // IDs for jpeg library functions #define INIT_HEADER_VLD_ID ID_OFFSET + 1 #define HEADER_VLD_ID ID_OFFSET + 2 #define IQZZ_ID ID_OFFSET + 3 #define IDCT_ID ID_OFFSET + 4 #define CC_ID ID_OFFSET + 5 #define RASTER_ID ID_OFFSET + 6 // Core frequencies #define MB1_FREQ 2.5 // in Mhz #define MB2_FREQ 2.5 // in Mhz #define MB3_FREQ 3 // in Mhz #define MB4_FREQ 3 // in Mhz I have multiple regexes like this: uint_max_re = re.compile('UINT_MAX\s+=+\s+(\d+)\s+') # https://regexr.com/3pmk5 id_offset_re = re.compile('ID_OFFSET\s+=+\s+(\d+)') # https://regexr.com/3pmn8 call_nr_offset_re = re.compile('CALL_NR_OFFSET\s+=+\s+(\d+)') # https://regexr.com/3pmnh debug_offset_re = re.compile('DEBUG_OFFSET\s+=+\s+(\d+)') # https://regexr.com/3pmnk function_ids_re = re.compile('#define\s+(\w+)\s+ID_OFFSET\s+\+\s+(\d)') # https://regexr.com/3pmkt core_freqs_re = re.compile('#define MB(\d+)_FREQ\s+(\d[.\d]*)') # https://regexr.com/3pml6 def parse_wrapper_params(): "This parses the wrapper_params.h file and returns a dictionary with function_id as key and function_name as value" with open(wrapper_params_file, 'r') as f: uint_max = int(uint_max_re.findall(f.read())[0]) with open(wrapper_params_file, 'r') as f: id_offset = int(id_offset_re.findall(f.read())[0]) with open(wrapper_params_file, 'r') as f: call_nr_offset = int(call_nr_offset_re.findall(f.read())[0]) with open(wrapper_params_file, 'r') as f: debug_offset = int(debug_offset_re.findall(f.read())[0]) with open(wrapper_params_file, 'r') as f: function_ids = function_ids_re.find…
accepted answer: http://stackoverflow.com/a/50420314
favorite count: 0
has answer: http://stackoverflow.com/a/50420314
type: Question
upvote count: 2
tagged with: python
tagged with: regex
answer count: 1

http://stackoverflow.com/a/50435861
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50435737
score: 1
has body: Your function wants to have the header and the rows all together in one list. Concatenate your header list with the q list: return [("Name", "Age")] + q

http://stackoverflow.com/q/50509905
downvote count: 2
has answer: http://stackoverflow.com/a/50583602
tagged with: forms
has title: Python to input form data from CSV file to local HTML file
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88034320
has comment: http://stackoverflow.com/comment/88034346
type: Question
tagged with: mechanize
has comment: http://stackoverflow.com/comment/88034275
tagged with: http://stackoverflow.com/tag/html
tagged with: input
tagged with: python
type: UnansweredQuestion
score: -2
has body: I am currently attempting to write a python script to pull specific data from a locally saved csv file and then input that data to a website and click submit. I have successfully extracted the data but I have been unable to open the file using the mechanize module. I am open to using a different language if there is another way I just figured that python would have been the simplest way to get this task done. Any feedback would be greatly appreciated. ` import datetime import webbrowser import csv import mechanize now = datetime.datetime.now() mont = now.month mon = mont + 2 with open(r'\\MyDataNEE\user$\bat0km4\Desktop\automation.csv') as f: mycsv = csv.reader(f) mycsv = list(mycsv) osha = mycsv[mon][2] occasional = mycsv[mon][3] fleet = mycsv[mon][4] print(osha) print(occasional) print(fleet) url = r"\\mydatanee\user$\bat0km4\Documents\test.html" br = mechanize.Browser() br.set_handle_robots( False ) br.open(url) br.form['osh'] = osha br.form['occasion'] = occasional br.form['flee'] = fleet br.submit() ` UPDATE : here is my html code in case that could be an issue Safety Indicator OSHA Injuries Occasional Use Incidents Fleet Incidents UPDATE : I used the file type that was suggested by placing file:// at the front and now I'm getting this error. Is there something that I should be placing in my html file to allow mechanize to do this? Can anyone confirm that mechanize does in fact have the ability to interact with local html files? I am having a hard time finding anyone who is using mechanize in this way C:\Python27>python pyth.py 0 1 2 Traceback (most recent call last): File "pyth.py", line 24, in <module> br.open(url) File "C:\Python27\lib\site-packages\mechanize\_mechanize.py", line 254, in open return self._mech_open(url_or_request, data, timeout=timeout) File "C:\Python27\lib\site-packages\mechanize\_mechanize.py", line 284, in _mech_open response = UserAgentBase.open(self, request, data) File "C:\Python27\lib\site-packages\mechanize\_opener.py", line 195, in…
upvote count: 0

http://stackoverflow.com/comment/88033787
comment on: http://stackoverflow.com/q/50507404
has text: I can't reproduce your font problem, but I don't use Jupyter. It might be a good idea to include version numbers for Python, matplotlib and Jupyter. And a picture that shows, what kind of font the system chooses instead of Arial.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50427421
accepted answer of: http://stackoverflow.com/q/50426891
answers question: http://stackoverflow.com/q/50426891
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has body: Your code has several errors and bad programming practices: if you declare variables that are inside a class and outside any method of the class will be class variables and not attributes of the class, so it is not a good practice to do so if you want to use later self, all that code must be within a method of a class. on_someproperty wait as parameter a function that receives parameters, in your case sas() does not receive them so the solution is to use a lambda method. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.scrollview import ScrollView from kivy.effects.scroll import ScrollEffect from kivy.uix.button import Button class BSGameMain: def __init__(self): self.blmain = BoxLayout(orientation = 'vertical') # MainBoxLayout init self.scrlFBtns = ScrollView(effect_cls = 'ScrollEffect') self.blbtns = BoxLayout( orientation = 'vertical', size_hint_y = None ) self.blbtns.bind(minimum_height = self.blbtns.setter('height')) self.scrlFBtns.add_widget(self.blbtns) for i in range(2): self.blbtns.add_widget(Button( text='asd', size_hint_y = None, height = 40, on_press = lambda *args: self.sas())) lblmain = Label(text = 'asd') self.blmain.add_widget(lblmain) self.blmain.add_widget(self.scrlFBtns) def sas(self): self.scrlFBtns.remove_widget(self.blbtns) class BSApp(App): def build(self): game = BSGameMain() return game.blmain if __name__ == "__main__": BSApp().run()

http://stackoverflow.com/comment/87873639
type: Comment
has text: @GoldenMatrices Make sure you use the right file name. Check the name of the `.exe` file in your `download` file. If you download from selenium website, the file name shall be `chromedriver.exe`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50420952

http://stackoverflow.com/q/50531087
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: Python SSL Error - cert issues vs. SSL disabled
has comment: http://stackoverflow.com/comment/88079496
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88075695
downvote count: 0
tagged with: ssl
has comment: http://stackoverflow.com/comment/88076264
tagged with: python
tagged with: handshake
has comment: http://stackoverflow.com/comment/88075227
has comment: http://stackoverflow.com/comment/88075032
has body: I'm using Python 3.5.2 to create a script to simply check if SSLv3 is enabled on a given host/port. Unfortunately, it seems ssl.SSLContext.wrap_socket() returns the same error (SSLV3_ALERT_HANDSHAKE_FAILURE) under the following two conditions: SSLv3 is disabled on the host or certificate hostname mismatch or other problems exist. Is there a way to differentiate these? I don't care about the SNI type problems in the current application. Are there other conditions that will return the same error as well?
answer count: 0

http://stackoverflow.com/comment/88037083
type: QuestionComment
comment on: http://stackoverflow.com/q/50508848
score: 0
has text: So you're using `all_dress` - which is the full unpaginated queryset - as source for your items, and you wonder why you have the whole queryset displayed on each page ? Maybe you should read the doc and examples more carefully...
type: Comment

http://stackoverflow.com/a/50533717
type: Answer
has body: The parameters really depend upon the data, so there is no general guideline. However, at least trying the "rbf" kernel is worth the effort I think. Also, I would first start by changing the C parameter, as that usually has the largest effect. But again, it depends on the data a lot.
has comment: http://stackoverflow.com/comment/88079540
score: 0
answers question: http://stackoverflow.com/q/50533102

http://stackoverflow.com/comment/87857918
comment on: http://stackoverflow.com/q/50421361
type: Comment
score: 4
has text: We call this the [XY Problem](https://meta.stackexchange.com/q/66377/347908). What are you actually trying to solve?
type: QuestionComment

http://stackoverflow.com/comment/87922179
score: 0
comment on: http://stackoverflow.com/q/50454068
type: Comment
has text: Since you're newbie I would recommend using a syntax highlighter UI. Using a Sublime Text or Atom as this will help you learn and find little nuances like this.
type: QuestionComment

http://stackoverflow.com/comment/127524216
comment on: http://stackoverflow.com/a/50497315
has text: FYI to anybody searching here. You can find some examples of doing this here: https://www.programcreek.com/python/example/89823/win32gui.MoveWindow
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50505370
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88338564
has body: I have a large pandas DataFrame that looks like this: OrderID OrderedItems ItemsQuantity 10052009 I0 2 10052009 I1 1 10052009 I2 1 10052009 I3 1 10448900 I4 5 10448900 I5 5 10189322 I2 1 10189322 I2 1 Now, I want to find out what all items are ordered together and prevailing bundles.
upvote count: 0
has title: Market basket and clustering in Python
answer count: 1
downvote count: 1
tagged with: cluster-analysis
tagged with: market-basket-analysis
has answer: http://stackoverflow.com/a/50505447
favorite count: 0
type: Question

http://stackoverflow.com/a/50457661
answers question: http://stackoverflow.com/q/50457604
type: AcceptedAnswer
has body: You can use a list comprehension to create your new data structure: data = [{'author': authors[b], 'title': titles[b], 'length': length[b]} for b in books] &gt;&gt;&gt; [{'author': 'sum_author', 'title': 'sum_title', 'length': 100}, {'author': 'other_author', 'title': 'other_title', 'length': 200}] Or a dict comprehension for a "dict of dicts": data = {b: {'author': authors[b], 'title': titles[b], 'length': length[b]} for b in books} &gt;&gt;&gt; {1: {'author': 'sum_author', 'title': 'sum_title', 'length': 100}, 2: {'author': 'other_author', 'title': 'other_title', 'length': 200}}
has comment: http://stackoverflow.com/comment/87942989
score: 10
upvote count: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/50457604
has comment: http://stackoverflow.com/comment/87930562
downvote count: 0

http://stackoverflow.com/comment/88133563
type: Comment
has text: Hi thanks for your answer, I didn't know that! But the problem remains, on my laptop the network location are added by the IT department, so I can't change the method they use. It seems that they just add network locations and not network drives (Now on Windows 10). But still it's good to know that in theory nothing changed ;)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50560876

http://stackoverflow.com/comment/87891921
comment on: http://stackoverflow.com/q/50438904
score: 0
type: QuestionComment
type: Comment
has text: Please provide a [mcve] and format your code nicely

http://stackoverflow.com/a/50481070
answers question: http://stackoverflow.com/q/50402801
has body: I believe the arguments of subprocess.call get passed straight to the command line, so you need to escape your quotation marks as such "\"C:/Program Files/R/R-3.4.3/Rscript\"". That being said, I get a [WinError 5] Access violation error when I use this. A workaround is to use the executable argument: import sys import subprocess if True is True: subprocess.call(["C:/Program Files/R/R-3.4.3/Rscript.exe", "./testing.r"], executable="C:/Program Files/R/R-3.4.3/Rscript.exe") sys.exit() Also, make sure that C:/Program Files/R/R-3.4.3/Rscript.exe is the location of your Rscript.exe. Mine is C:/Program Files/R/R-3.4.3/bin/Rscript.exe.
upvote count: 2
has comment: http://stackoverflow.com/comment/87994612
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50402801

http://stackoverflow.com/q/50534829
tagged with: python
tagged with: active-directory
has title: Attempting to connect to LDAP using django-python3-ldap but the target machine is actively refusing it
accepted answer: http://stackoverflow.com/a/50536918
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50536918
has body: I am working on a django app and attempting to use django_python3_ldap to connect to my company's LDAP and AD. I followed the docs basic settings in my settings.py but when I try doing python manage.py ldap_sync_users I get this error LDAP connect failed: ('unable to open socket', [(datetime.datetime(2018, 5, 25, 12, 25, 36, 77877), &lt;class 'ldap3.core.exceptions.LDAPSocketOpenError'&gt;, LDAPSocketOpenError('socket connection error while opening: [WinError 10061] No connection could be made bec ause the target machine actively refused it',), ('::1', 389, 0, 0)), (datetime.datetime(2018, 5, 25, 12, 25, 37, 78809), &lt;class 'ldap3.core.exceptions.LDAPSocketOpenError'&gt;, LDAPSocketOpenError('socket connection error while opening: [WinError 10061] No connect ion could be made because the target machine actively refused it',), ('127.0.0.1', 389))]) CommandError: Could not connect to LDAP server Here is my settings.py file import os import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, NestedActiveDirectoryGroupType # Baseline configuration. AUTH_LDAP_SERVER_URI = "ldap://***.**.***.**" LDAP_AUTH_CONNECTION_USERNAME = 'usr@ab.com' LDAP_AUTH_CONNECTION_PASSWORD = '*******' # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "ou=people,dc=example,dc=com" # The LDAP class that represents a user. LDAP_AUTH_OBJECT_CLASS = "user" # Keep ModelBackend around for per-user permissions and maybe a local # superuser. AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) DEBUG = True LDAP_AUTH_USE_TLS = False # User model fields mapped to the LDAP # attributes that represent them. LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory_principal" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "ab.com" LDAP_AUTH_USER_LOOKUP_FIELDS = ("usern…
answer count: 1
tagged with: django
type: Question
tagged with: ldap

http://stackoverflow.com/comment/87990790
has text: @Vinny Is there no other way ? How does the IPython `%whos` do the job ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50488912
type: QuestionComment

http://stackoverflow.com/a/61867761
downvote count: 0
upvote count: 1
type: Answer
has body: Adding to the answers given above by @karan-singla and @vijay-jangir given in pyspark show dataframe as table with horizontal scroll in ipython notebook, a handy one-liner to comment out the white-space: pre-wrap styling can be done like so: $ awk -i inplace '/pre-wrap/ {$0="/*"$0"*/"}1' $(dirname `python -c "import notebook as nb;print(nb.__file__)"`)/static/style/style.min.css This translates as; use awk to update inplace lines that contain pre-wrap to be surrounded by */ -- */ i.e. comment out, on the file found in styles.css found in your working Python environment. This, in theory, can then be used as an alias if one uses multiple environments, say with Anaconda. REFs: https://stackoverflow.com/a/24884616/4521950 Save modifications in place with awk
answers question: http://stackoverflow.com/q/50523950
score: 1

http://stackoverflow.com/comment/88001831
type: QuestionComment
comment on: http://stackoverflow.com/q/50494388
score: 2
type: Comment
has text: or `idx = np.s_[i, 0, :, 7]`, `a[idx]`, etc.

http://stackoverflow.com/q/50426661
has answer: http://stackoverflow.com/a/58817125
downvote count: 0
answer count: 1
tagged with: tensorflow
has title: tf.nn.conv2d_transpose gives InvalidArgumentError: Conv2DCustomBackpropInput: input and filter must have the same depth
has comment: http://stackoverflow.com/comment/87868353
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87868442
tagged with: convolution
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/35488717
has body: I'm facing issues with getting tf.nn.conv2d_transpose to work correctly. Here is a small reproduction of what I'm trying to do: import tensorflow as tf import numpy as np # Shape (2, 3, 3, 1) == (batch_sz, height, width, channels) inp = tf.Variable(np.array( [ [ [[1], [2], [3]], [[2], [3], [4]], [[7], [8], [9]] ], [ [[3], [2], [1]], [[2], [7], [2]], [[3], [2], [0]] ] ], dtype = np.float32 )) # Shape (5, 5, 3, 1) == (kH, kW, out_channels, in_channels) ker = tf.Variable(np.array( [ [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]], [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]], [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]], [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]], [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]] ], dtype = np.float32 )) out = tf.nn.conv2d_transpose(inp, ker, (2, 7, 7, 1), (1, 1, 1, 1), padding='SAME', data_format='NHWC', name='conv_transpose') with tf.Session() as sess: sess.run(tf.global_variables_initializer()) output, kernel, input = sess.run([out, ker, inp]) What I want is to perform a transposed convolution on a 3x3x1 input using three 5x5x1 filters. I expect the output to be of shape 7x7x3 - but instead, I get an error saying: InvalidArgumentError: Conv2DCustomBackpropInput: input and filter must have the same depth [[Node: conv_transpose_2 = Conv2DBackpropInput[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], padding="SAME", strides=[1, 1, 1, 1], use_cudnn_on_gpu=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv_transpose_2/output_shape, Variable_21/read, Variable_20/read)]] Aren't the input and filter depth both equal to 1? I don't see what I'm doing wrong - any hints would be really appreciated. I specifically want to use tf.nn.conv2d_transpose and not tf.layers.conv2d_transpose.
score: 2
tagged with: deconvolution
tagged with: conv-neural-network
upvote count: 2

http://stackoverflow.com/comment/87806517
has text: In the python terminal prompt, you have to hit enter again between when you define the function and when you call it. Python thinks `rev("just")` is part of the function definition otherwise.
type: Comment
comment on: http://stackoverflow.com/a/50395070
type: AnswerComment
score: 0

http://stackoverflow.com/q/50449082
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50455259
has title: Tkinter: Updating GUI from subprocess output in realtime
tagged with: subprocess
has answer: http://stackoverflow.com/a/50455259
answer count: 1
has body: I've searched the whole internet to answer my problem, but nobody seems to have the same one: I'm trying to update my tkinter GUI dynamically from a subprocess output, which works fine, if I'm starting my GUI inside eclipse. BUT if I'm running it in the file explorer or in visual studio, the 'stdout.readline' command waits, until the subprocess is finished. Only then the complete output is printed to my textarea... I am working with a thread and I've tried 2 ways: one is shown in 'App.py', the other one is threading the 'read_update' method instead (and not using 'reader_thread' and 'update' methods). Interesting sidenote: the sys.argv command in Test.py does not return my string "var_test". Can anyone tell me why? My Classes are: GUI.py import Tkinter as tk from App import App if __name__ == '__main__': root = tk.Tk() app = App(root) root.protocol("WM_DELETE_WINDOW", app.quit) root.mainloop() App.py #App.py import Tkinter as tk import tkFont as tkfont import subprocess from subprocess import Popen from subprocess import PIPE from itertools import islice from threading import Thread from ttk import Scrollbar from Tkinter import * from Queue import Queue, Empty class App(): def __init__(self, root): self.root = root self.root.title_font = tkfont.Font(family = "Helvetica", size = 18, weight = "bold", slant = "italic") Grid.columnconfigure(self.root, 5, weight = 1) button_ok = tk.Button(self.root, text = "OK", width = 10, command = lambda: self.on_okay()) button_ok.grid(row = 7, column = 0, padx = (20,0), pady = 10, sticky = W) xscrollbar = Scrollbar(self.root, orient=HORIZONTAL) xscrollbar.grid(row=8, column=1, columnspan=4, sticky=E + W) yscrollbar = Scrollbar(self.root, orient=VERTICAL) yscrollbar.grid(row=8, column=5, sticky=N + S) self.textarea = Text(self.root, wrap=NONE, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) self.textarea.grid(row=8, column=1, columnspan=4, rowspan=1, padx=0, sticky=E + W + S + N) def on_okay(self): self.textarea.de…
type: Question
tagged with: tkinter
tagged with: python-multithreading
tagged with: python

http://stackoverflow.com/comment/90661062
comment on: http://stackoverflow.com/a/51854290
type: AnswerComment
score: 0
has text: Hello! Thanks for answering, But how can I get the mapping dictionary? as you got that. I can get dict200, newerdict, but can make the dictionary like your mapping dictionary. That is the main doubt.
type: Comment

http://stackoverflow.com/comment/88088760
comment on: http://stackoverflow.com/q/50538447
has text: Can you add the output of a `pip3 freeze`? It looks like the `zbar` package on PyPI was last updated in 2009, so it's certainly possible it doesn't work under Python 3. https://pypi.org/project/zbar/
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50575240
has body: Here is the answer I got to work: Python: @app.route('/submit/', methods = ['POST']) def sumbit(): JS: $('.btn').click(function(){ $.ajax({ url: "/submit/", type: "POST", success: function(resp){ $('#results').html(resp.data); } }); });
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50539451

http://stackoverflow.com/comment/88183298
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50531898
score: 0
has text: @JeanPaul Anything is *possible*. But some things are harder than others. It's easy to translate `1 == 1` to `True`.

http://stackoverflow.com/comment/88088814
type: Comment
comment on: http://stackoverflow.com/q/50538447
type: QuestionComment
score: 0
has text: https://pastebin.com/Q3L7PgVJ

http://stackoverflow.com/q/50431637
answer count: 2
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/46749659
upvote count: 7
tagged with: scrapy
has comment: http://stackoverflow.com/comment/87877654
favorite count: 0
linked to: http://stackoverflow.com/q/9699049
has answer: http://stackoverflow.com/a/58111856
has body: I need to raise CloseSpider from a Scrapy Pipeline. Either that or return some parameter from the Pipeline back to the Spider to do the raise. For example, if the date already exists raise CloseSpider: raise CloseSpider('Already been scraped:' + response.url) Is there a way to do this?
has answer: http://stackoverflow.com/a/58758374
score: 7
has title: Raise close spider from Scrapy pipeline
tagged with: python
has comment: http://stackoverflow.com/comment/102615974
type: Question

http://stackoverflow.com/q/50427695
tagged with: list
downvote count: 0
has body: This is a chain of number inside a text file which I import and want to convert into a specific list. 3 04,24 4 04,75 4 05,11 4 05,47 4 05,78 4 06,80 3 07,25 3 07,92 3 08,23 2 09,76 Actually with my code I reach this point : [['3 04,24'], ['4 04,75'], ['4 05,11'], ['4 05,47'], ['4 05,78'], ['4 06,80'], ['3 07,25'], ['3 07,92'], ['3 08,23'], ['2 09,76']] But I want to split the elements inside the tuples in two to get something like this : [['3','04,24'], ['4','04,75']] etc... But after many research I can't find the solution, also if you could tell me how to convert these elements from string to int that would be very helpful ! Here's my code : with open("myfile.txt") as f: mylist = [line.rstrip('\n') for line in f] mylist = [mylist[x:x+1] for x in range(0, len(mylist), 1)] print(mylist) Thanks.
accepted answer: http://stackoverflow.com/a/50427720
favorite count: 0
has answer: http://stackoverflow.com/a/50427830
type: Question
has title: Split a string which is inside a list of a list in two elements which stay in the same list
tagged with: python-3.x
tagged with: tuples
has answer: http://stackoverflow.com/a/50427955
has answer: http://stackoverflow.com/a/50427738
possible better answer: http://stackoverflow.com/a/50427738
tagged with: python
has answer: http://stackoverflow.com/a/50427720
answer count: 4
upvote count: 2
type: AnsweredQuestion
tagged with: int
score: 2

http://stackoverflow.com/q/50432564
has comment: http://stackoverflow.com/comment/87879374
has answer: http://stackoverflow.com/a/75277322
has comment: http://stackoverflow.com/comment/87879629
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: if-statement
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87879329
has title: TypeError: unsupported operand type(s) for %: 'range' and 'int'
has answer: http://stackoverflow.com/a/55996733
tagged with: range
has answer: http://stackoverflow.com/a/50432582
tagged with: python
answer count: 6
has body: Write a Python program to find numbers between 120 and 200 which are divisible by 7 and multiples of 5 without using a "for loop". I tried to work it out this way... x = range(120, 200) if x % 7 == 0 and x % 5 == 0: print(x) But rather I do get this error. What could I be missing out? Traceback (most recent call last): File "C:\Users\User\Desktop\skillshare-code\if else statements\4.py", line 11, in &lt;module&gt; if x % 7 == 0 and x % 5 == 0: TypeError: unsupported operand type(s) for %: 'range' and 'int'
has answer: http://stackoverflow.com/a/50432750
has answer: http://stackoverflow.com/a/50432814
has answer: http://stackoverflow.com/a/50432621
score: 1
upvote count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/87879385
has comment: http://stackoverflow.com/comment/87879608

http://stackoverflow.com/q/50448198
score: 1
answer count: 1
has title: How can I crawl the specific content in this html with Beautifulsoup?
has comment: http://stackoverflow.com/comment/87909867
upvote count: 1
tagged with: web-crawler
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50448355
tagged with: beautifulsoup
downvote count: 0
tagged with: python
has body: I have a html like this： Power law exponent (estimated) with dmin 2.1310 (dmin = 49) Besides, I have many other html almost same as this one but have different numbers in the third line from the bottom. I want to crawl these numbers like 2.1310 in this html but don't know what to do. Here is my code: def getLinks(Url): html=urlopen(Url) s = ' Power law exponent (estimated) with ' \ 'dmin 2.1310(dmin = 49) ' soup = BeautifulSoup(s, 'html.parser') print(soup.find_all('td')[1].contents[0][:-2]) I can get 2.1310 using this code. But when the number is changed, I don't know how to define an unified 's' when facing other html. There are so many similar htmls that I can not copy everyone when codeing.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50448355

pandas
tags question: http://stackoverflow.com/q/50522146
tags question: http://stackoverflow.com/q/50498645
tags question: http://stackoverflow.com/q/50504354
tags question: http://stackoverflow.com/q/50419135
tags question: http://stackoverflow.com/q/50538811
tags question: http://stackoverflow.com/q/50523745
tags question: http://stackoverflow.com/q/50525864
tags question: http://stackoverflow.com/q/50391640
tags question: http://stackoverflow.com/q/50511318
tags question: http://stackoverflow.com/q/50539458
tags question: http://stackoverflow.com/q/50455797
tags question: http://stackoverflow.com/q/50476198
tags question: http://stackoverflow.com/q/50394099
tags question: http://stackoverflow.com/q/50523537
tags question: http://stackoverflow.com/q/50394519
tags question: http://stackoverflow.com/q/50389096
tags question: http://stackoverflow.com/q/50476875
tags question: http://stackoverflow.com/q/50486767
tags question: http://stackoverflow.com/q/50429170
tags question: http://stackoverflow.com/q/50476392
tags question: http://stackoverflow.com/q/50447230
tags question: http://stackoverflow.com/q/50457545
tags question: http://stackoverflow.com/q/50537020
tags question: http://stackoverflow.com/q/50464684
tags question: http://stackoverflow.com/q/50494451
tags question: http://stackoverflow.com/q/50441751
tags question: http://stackoverflow.com/q/50529955
tags question: http://stackoverflow.com/q/50387775
tags question: http://stackoverflow.com/q/50418627
tags question: http://stackoverflow.com/q/50413291
tags question: http://stackoverflow.com/q/50505784
tags question: http://stackoverflow.com/q/50442500
tags question: http://stackoverflow.com/q/50497274
tags question: http://stackoverflow.com/q/50399074
tags question: http://stackoverflow.com/q/50480156
tags question: http://stackoverflow.com/q/50417688
tags question: http://stackoverflow.com/q/50492185
tags question: http://stackoverflow.com/q/50413993
tags question: http://stackoverflow.com/q/50428119
tags question: http://stackoverflow.com/q/50510865
tags question: http://stackoverflow.com/q/50412290
tags question: http://stackoverflow.com/q/50491499
tags question: http://stackoverflow.com/q/50418511
tags question: http://stackoverflow.com/q/50457329
tags question: http://stackoverflow.com/q/50512866
tags question: http://stackoverflow.com/q/50453774
tags question: http://stackoverflow.com/q/50411641
tags question: http://stackoverflow.com/q/50430914
tags question: http://stackoverflow.com/q/50485754
tags question: http://stackoverflow.com/q/50414552
tags question: http://stackoverflow.com/q/50511640
tags question: http://stackoverflow.com/q/50430404
tags question: http://stackoverflow.com/q/50510407
tags question: http://stackoverflow.com/q/50418645
tags question: http://stackoverflow.com/q/50471777
tags question: http://stackoverflow.com/q/50415083
tags question: http://stackoverflow.com/q/50503290
tags question: http://stackoverflow.com/q/50470813
tags question: http://stackoverflow.com/q/50409408
tags question: http://stackoverflow.com/q/50447683
tags question: http://stackoverflow.com/q/50509481
tags question: http://stackoverflow.com/q/50478913
tags question: http://stackoverflow.com/q/50407447
tags question: http://stackoverflow.com/q/50459602
tags question: http://stackoverflow.com/q/50464135
tags question: http://stackoverflow.com/q/50463929
tags question: http://stackoverflow.com/q/50401241
tags question: http://stackoverflow.com/q/50425973
tags question: http://stackoverflow.com/q/50418102
tags question: http://stackoverflow.com/q/50500453
tags question: http://stackoverflow.com/q/50414136
tags question: http://stackoverflow.com/q/50462844
tags question: http://stackoverflow.com/q/50467459
tags question: http://stackoverflow.com/q/50513964
tags question: http://stackoverflow.com/q/50414180
tags question: http://stackoverflow.com/q/50386566
tags question: http://stackoverflow.com/q/50421457
tags question: http://stackoverflow.com/q/50422052
tags question: http://stackoverflow.com/q/50497646
tags question: http://stackoverflow.com/q/50426654

http://stackoverflow.com/q/50456087
has comment: http://stackoverflow.com/comment/87925946
has title: pandas way to get list of indexes using iloc?
tagged with: vectorization
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
tagged with: python
has body: I have data sorted the way I want. I'm about to put in something like: series_data = [] for count,x in enumerate(df): series_data.append(list(range(count))) df['up_to_row'].iloc(count)= series_data so the column would be: df['up_to_row'] = Series([0], [0,1], [0,1,2], [0,1,2,3]...) Then I need to translate this iloc locations to indexes. Is there a more pandas specific way to do this? I would do this with pandas operators but I'm not sure how to get the current iloc (which is why the enumerate was needed) Edit* Found the final answer using some of the tools from @wen. Thank you. data['ind']=data.index.astype(str)+',' data['cumsum_indexes']=data['ind'].cumsum().str[:-1].str.split(',')
type: Question
accepted answer: http://stackoverflow.com/a/50456276
has answer: http://stackoverflow.com/a/50456276

http://stackoverflow.com/q/50499894
has answer: http://stackoverflow.com/a/50501037
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50501553
downvote count: 0
score: 4
has title: How should I load file on s3 using Spark?
favorite count: 0
type: Question
tagged with: apache-spark
tagged with: amazon-s3
tagged with: pyspark
tagged with: python
has body: I installed spark via pip install pyspark I'm using following code to create a dataframe from a file on s3. from pyspark.sql import SparkSession spark = SparkSession.builder \ .config('spark.driver.extraClassPath', '/home/ubuntu/spark/jars/aws-java-sdk-1.11.335.jar:/home/ubuntu/spark/jars/hadoop-aws-2.8.4.jar') \ .appName("cluster").getOrCreate() df = spark.read.load('s3a://bucket/path/to/file') However I got an error: --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) in () ----> 1 df = spark.read.load('s3a://bucket/path/to/file') ~/miniconda3/envs/audience/lib/python3.6/site-packages/pyspark/sql/readwriter.py in load(self, path, format, schema, **options) 164 self.options(**options) 165 if isinstance(path, basestring): --> 166 return self._df(self._jreader.load(path)) 167 elif path is not None: 168 if type(path) != list: ~/miniconda3/envs/audience/lib/python3.6/site-packages/py4j/java_gateway.py in call(self, *args) 1158 answer = self.gateway_client.send_command(command) 1159 return_value = get_return_value( -> 1160 answer, self.gateway_client, self.target_id, self.name) 1161 1162 for temp_arg in temp_args: ~/miniconda3/envs/audience/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---> 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() ~/miniconda3/envs/audience/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 318 raise Py4JJavaError( 319 "An error occurred while calling {0}{1}{2}.\n". --> 320 format(target_id, ".", name), value) 321 else: 322 raise Py4JError( Py4JJavaError: An error occurred while calling o220.load. : java.lang.NoClassDefFoundError: org/apache/hadoop/fs/StorageStatistics at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Confi…
upvote count: 4
answer count: 2

http://stackoverflow.com/comment/87839987
type: QuestionComment
comment on: http://stackoverflow.com/q/50412165
type: Comment
has text: @Jaxi ! Yeap! For loop inside a for loop is what I am looking for. But first for loop should iterate over distinct items instead of rows
score: 0

http://stackoverflow.com/comment/87812264
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50398188
has text: @abarnert Python 3

http://stackoverflow.com/q/50418448
has comment: http://stackoverflow.com/comment/87852547
has body: All I could find is this statement: The easiest way to create a text stream is with open(), optionally specifying an encoding: f = open("myfile.txt", "r", encoding="utf-8") In-memory text streams are also available as StringIO objects: f = io.StringIO("some initial text data") But this gives no insight at all on when I should use open() over io.StringIO and vice-versa. I know that they do not work exactly the same behind the scene. But why would someone go for open() in Python 3 ?
score: 10
tagged with: python
has comment: http://stackoverflow.com/comment/87854094
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87853098
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50418544
upvote count: 12
has comment: http://stackoverflow.com/comment/87854050
downvote count: 2
has answer: http://stackoverflow.com/a/50418544
answer count: 1
has comment: http://stackoverflow.com/comment/87854179
has title: io.StringIO vs open() in Python 3
has comment: http://stackoverflow.com/comment/87854395
favorite count: 0
type: Question

http://stackoverflow.com/a/50484194
accepted answer of: http://stackoverflow.com/q/50484145
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50484145
type: Answer
has body: I suggest use ffill with bfill for back filling if possible some NaNs in first row: X_train = X_train.ffill().bfill().astype(int) If not: X_train = X_train.ffill().astype(int)
upvote count: 2
score: 2

http://stackoverflow.com/comment/88017337
score: 0
has text: Thanks for the reply. let me try
comment on: http://stackoverflow.com/q/50484943
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50533239
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50533838
favorite count: 0
type: Question
has body: I am trying to calculate a series of Gaussian curves for peak coordinates in an IR spectrum. The script to calculate a single peak over a frequency range (X) of 0 to 4000 1/cm functions normally. However when I try to iterate over a range of 75 Frequency and Intensity coordinates I get a broadcast shape conflict between the 4001 'x' values and the 75 peak coordinate pairs. Is there a way to isolate the calculation so that it behaves like a series of independent calculations and thereby avoids the conflict? Here is my code and error traceback: import numpy as np def gaussian(intens, mu): x = np.arange(4001) sig = 50 return intens*np.exp(-np.power(x-mu, 2.)/(2*np.power(sig, 2.))) results = np.empty((4001, 1), float) for i in range(75): mu = np.array([106.2516, 169.2317, 179.4433, 210.1843, 225.1875, 237.6963, 261.1454, 290.3952, 298.8429, 383.1141, 394.5482, 415.7989, 474.0785, 522.2687, 555.9868, 571.7233, 617.1713, 646.9524, 712.1052, 757.1555, 839.7896, 862.2479, 874.9923, 927.4888, 948.9697, 951.0036, 964.3596, 969.371, 1008.6015, 1039.7932, 1044.8249, 1063.0541, 1107.298, 1127.9082, 1155.2848, 1180.83, 1196.411, 1225.1961, 1234.4729, 1256.5558, 1278.3917, 1284.0116, 1311.6421, 1338.709, 1346.252, 1360.011, 1434.1602, 1439.0059, 1455.3892, 1490.6434, 1512.7327, 1517.3906, 1521.4376, 1525.9011, 1531.1185, 1540.3454, 1546.1395, 1554.7932, 1841.6486, 3045.7824, 3050.0779, 3053.1525, 3064.5046, 3070.2651, 3073.4956, 3094.2865, 3097.3753, 3101.0081, 3107.7236, 3108.5122, 3115.0888, 3117.7676, 3123.2296, 3127.9553, 3141.7127]) intens = np.array([3.609400e+00, 6.870000e-02, 1.425000e-01, 1.908000e-01, 2.848000e-01, 9.040000e-01, 7.114000e-01, 3.850000e-01, 1.899100e+00, 7.697000e-01, 1.484000e-01, 1.223400e+00, 5.366000e-01, 4.554700e+00, 2.007100e+00, 8.798000e-01, 9.361000e-01, 1.767700e+00, 4.380000e-01, 6.543100e+00, 4.705000e-01, 1.423900e+00, 5.475000e-01, 1.230200e+00, 3.059800e+00, 4.872000e-01, 1.293400e+00, 2.782900e+00, 5.430000e-02, 1.592800e+00, 2.582030e+01…
tagged with: python
accepted answer: http://stackoverflow.com/a/50533838
linked to: http://stackoverflow.com/q/35461477
tagged with: numpy
type: AnsweredQuestion
has title: How do I isolate a calculation of a function within a python 'for loop' to avoid a broadcasting shape conflict?
tagged with: for-loop

python
tags question: http://stackoverflow.com/q/50395170
tags question: http://stackoverflow.com/q/50492185
tags question: http://stackoverflow.com/q/50454068
tags question: http://stackoverflow.com/q/50449876
tags question: http://stackoverflow.com/q/50474790
tags question: http://stackoverflow.com/q/50489916
tags question: http://stackoverflow.com/q/50428376
tags question: http://stackoverflow.com/q/50508591
tags question: http://stackoverflow.com/q/50452324
tags question: http://stackoverflow.com/q/50498575
tags question: http://stackoverflow.com/q/50502781
tags question: http://stackoverflow.com/q/50498884
tags question: http://stackoverflow.com/q/50443180
tags question: http://stackoverflow.com/q/50393604
tags question: http://stackoverflow.com/q/50438326
tags question: http://stackoverflow.com/q/50521716
tags question: http://stackoverflow.com/q/50439908
tags question: http://stackoverflow.com/q/50499894
tags question: http://stackoverflow.com/q/50495961
tags question: http://stackoverflow.com/q/50516416
tags question: http://stackoverflow.com/q/50515960
tags question: http://stackoverflow.com/q/50440066
tags question: http://stackoverflow.com/q/50421427
tags question: http://stackoverflow.com/q/50397954
tags question: http://stackoverflow.com/q/50477206
tags question: http://stackoverflow.com/q/50493901
tags question: http://stackoverflow.com/q/50511034
tags question: http://stackoverflow.com/q/50522799
tags question: http://stackoverflow.com/q/50457589
tags question: http://stackoverflow.com/q/50400621
tags question: http://stackoverflow.com/q/50436658
tags question: http://stackoverflow.com/q/50426015
tags question: http://stackoverflow.com/q/50438334
tags question: http://stackoverflow.com/q/50504425
tags question: http://stackoverflow.com/q/50492494
tags question: http://stackoverflow.com/q/50443388
tags question: http://stackoverflow.com/q/50452336
tags question: http://stackoverflow.com/q/50482147
tags question: http://stackoverflow.com/q/50421590
tags question: http://stackoverflow.com/q/50505440
tags question: http://stackoverflow.com/q/50494385
tags question: http://stackoverflow.com/q/50474848
tags question: http://stackoverflow.com/q/50445179
tags question: http://stackoverflow.com/q/50490990
tags question: http://stackoverflow.com/q/50499628
tags question: http://stackoverflow.com/q/50432866
tags question: http://stackoverflow.com/q/50419091
tags question: http://stackoverflow.com/q/50497327
tags question: http://stackoverflow.com/q/50535964
tags question: http://stackoverflow.com/q/50401550
tags question: http://stackoverflow.com/q/50533122
tags question: http://stackoverflow.com/q/50463202
tags question: http://stackoverflow.com/q/50521031
tags question: http://stackoverflow.com/q/50456840
tags question: http://stackoverflow.com/q/50428329
tags question: http://stackoverflow.com/q/50474302
tags question: http://stackoverflow.com/q/50497212
tags question: http://stackoverflow.com/q/50393145
tags question: http://stackoverflow.com/q/50528274
tags question: http://stackoverflow.com/q/50532819
tags question: http://stackoverflow.com/q/50391209
tags question: http://stackoverflow.com/q/50414144
tags question: http://stackoverflow.com/q/50498525
tags question: http://stackoverflow.com/q/50415579
tags question: http://stackoverflow.com/q/50497398
tags question: http://stackoverflow.com/q/50430216
tags question: http://stackoverflow.com/q/50453301
tags question: http://stackoverflow.com/q/50520306
tags question: http://stackoverflow.com/q/50461126
tags question: http://stackoverflow.com/q/50418511
tags question: http://stackoverflow.com/q/50488327
tags question: http://stackoverflow.com/q/50402758
tags question: http://stackoverflow.com/q/50538118
tags question: http://stackoverflow.com/q/50522480
tags question: http://stackoverflow.com/q/50510560
tags question: http://stackoverflow.com/q/50459540
tags question: http://stackoverflow.com/q/50410165
tags question: http://stackoverflow.com/q/50432546
tags question: http://stackoverflow.com/q/50442760
tags question: http://stackoverflow.com/q/50474244

http://stackoverflow.com/comment/88032727
has text: Or enumerate over the list: `docs = { doc_format.format(index+1): f for index, f in enumerate(Finance.documents)}`
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50510176

http://stackoverflow.com/comment/88066780
has text: Matplotlib just plots your data using a `LineCollection` and displays this in 2D. If you want to have a matrix representing the points in the 2D image as a matrix, you need to define the same point spacing and axes properties for each timeseries.
comment on: http://stackoverflow.com/q/50526033
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50428661
has comment: http://stackoverflow.com/comment/87872131
has answer: http://stackoverflow.com/a/50428967
answer count: 2
tagged with: python-import
has comment: http://stackoverflow.com/comment/87872527
has answer: http://stackoverflow.com/a/50428732
has comment: http://stackoverflow.com/comment/87872551
downvote count: 0
has comment: http://stackoverflow.com/comment/87872158
tagged with: python-3.6
possible better answer: http://stackoverflow.com/a/50428732
has comment: http://stackoverflow.com/comment/87872967
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87873349
score: 3
tagged with: importerror
has comment: http://stackoverflow.com/comment/87872325
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/87872160
upvote count: 3
has comment: http://stackoverflow.com/comment/87872342
tagged with: python
has comment: http://stackoverflow.com/comment/87872146
has body: In my terminal, I wanted to test something with asyncio. Here's what I did: $ python3.6 Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import asyncio And this threw an error as follows: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/__init__.py", line 42, in &lt;module&gt; tasks.__all__ + AttributeError: module 'asyncio.tasks' has no attribute '__all__' Why does it throw this error, and how can I fix it? (I checked in my python 3.5 interpreter the same way and got no error, so maybe the library got corrupted?) I've run Python with the -v switch, the output produced after running import asyncio at the prompt is rather large, so it is available in this GitHub gist.
has comment: http://stackoverflow.com/comment/87873442
has title: Importing asyncio throws error
accepted answer: http://stackoverflow.com/a/50428967
has comment: http://stackoverflow.com/comment/87872125
has comment: http://stackoverflow.com/comment/87872386
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87872307

http://stackoverflow.com/q/50450129
has body: I have this code for Python, but it searches for actual page and not the source of the page. import requests from bs4 import BeautifulSoup def count_words(url, the_word): r = requests.get(url, allow_redirects=False) soup = BeautifulSoup(r.content, 'lxml') words = soup.find(text=lambda text: text and the_word in text) print(words) return len(words) def main(): url = 'google.com' word = 'google' count = count_words(url, word) print('\nUrl: {}\ncontains {} occurrences of word: {}'.format(url, count, word)) if __name__ == '__main__': main() How do I make it to search for the page's source too? I don't want to count. Yes, I know I have to remove the count {} part. But, how do I make it load a website list from a text file and if x word is found to print "X Found on this website" Any help is appreciated!
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/50450588
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/50450588
type: AnsweredQuestion
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has title: Scrape website source and search for word
favorite count: 0

http://stackoverflow.com/a/50415423
has comment: http://stackoverflow.com/comment/87956559
answers question: http://stackoverflow.com/q/50412736
has body: You can wait till the element become clickable and then try to click on it.This may solve your issue. submit = WebDriverWait(self.webdriver, 10).until( EC.element_to_be_clickable((By.NAME, "_save"))) submit.click()
score: 0
has comment: http://stackoverflow.com/comment/87955991
has comment: http://stackoverflow.com/comment/87956296
type: Answer
has comment: http://stackoverflow.com/comment/87940104
has comment: http://stackoverflow.com/comment/87938277
has comment: http://stackoverflow.com/comment/87956508

http://stackoverflow.com/a/60620190
answers question: http://stackoverflow.com/q/50450655
has body: I've done it! The trick for me was just to wait the entire loading of the page. Not the DOM ready state page for me continues loading. There is a way to remove the arbitrary sleep and ask the driver for the real complete loading of the page. I do not recall the code... I've to search. from browsermobproxy import Server import json from selenium import webdriver import time urle = "https://www.yoururl.com"; server = Server(path="./browsermob-proxy-2.1.4/bin/browsermob-proxy") server.start() proxy = server.create_proxy() profile = webdriver.FirefoxProfile() profile.set_proxy(proxy.selenium_proxy()) driver = webdriver.Firefox(firefox_profile=profile, executable_path='./geckodriver') proxy.new_har(urle, options={'captureHeaders': True, 'captureContent':True}) driver.get(urle) time.sleep(10) result = json.dumps(proxy.har, ensure_ascii=False) print result proxy.stop() driver.quit()
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87932554
type: AnswerComment
comment on: http://stackoverflow.com/a/50431627
type: Comment
has text: In my case, I came across it years ago learning about Reed Solomon coding. I forgot everything else about that stuff, but the Vandermonde matrix keeps popping up!
score: 0

http://stackoverflow.com/q/50476102
has title: Saving data from multiple text files to a single file
score: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/50484399
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87969634
has body: I was trying to open multiple files using tkinter. I want to see the contents in these multiple files and put these text files to a single file but on different cells, so that i can treat all the data together. I was not able to find ant tutorial to understand more about tkinter. Can anyone suggest me an idea on how to see the contents in these files? I have an idea on how to do this on matlab, can anyone suggest a way to do the same in python? Matlab code: [filename,pathname] = uigetfile('*.txt','MultiSelect','on'); data = cell(1) Python code: import tkinter as tk from tkinter import filedialog root = tk.Tk() filez = filedialog.askopenfilenames(parent=root,title='Choose a file') print (root.tk.splitlist(filez))
tagged with: matlab
type: Question
has comment: http://stackoverflow.com/comment/87977229
tagged with: python

http://stackoverflow.com/q/50481942
answer count: 0
has comment: http://stackoverflow.com/comment/87978656
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87978754
linked to: http://stackoverflow.com/q/11977270
has comment: http://stackoverflow.com/comment/87977592
upvote count: 1
linked to: http://stackoverflow.com/q/21799210
tagged with: copy
type: Question
tagged with: performance
score: 1
has comment: http://stackoverflow.com/comment/87978987
has comment: http://stackoverflow.com/comment/87977452
tagged with: python
tagged with: shutil
has body: i use a script to copy files to a sharedrive. One of the files is usually around 3GB. The copy is quite slow, compare to manual copy. (all on Windows) How can change the buffer size in my code ? Something similar like the answer in that question: Python copy larger file too slow def copyAllFiles(): src_files = os.listdir(src) for file_name in src_files: full_file_name = os.path.join(src, file_name) if (os.path.isfile(full_file_name)): shutil.copy(full_file_name, newPath) print("copy done") or is there recommendation to use other copy method?
favorite count: 0
tagged with: python-3.x
has title: change buffer size to improve copy speed in python

http://stackoverflow.com/comment/87906127
score: 0
type: Comment
has text: ah got it. @Chris i have scheme, when submit data to `Foo`, i need update other model like `bar` related to that database so i need that `id`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50441344

http://stackoverflow.com/a/50490220
has comment: http://stackoverflow.com/comment/88860495
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88821074
has comment: http://stackoverflow.com/comment/88860987
has comment: http://stackoverflow.com/comment/88859704
score: 1
downvote count: 0
has body: The proper way to pass some extra data from view to serializer is the serializer context. In DRF class-based view, you can (and, actually, should for such purposes) override get_serializer_context() method. In the overridden method you just add to the context, which is just a dictionary, whatever you want. Simple example, how to do this in view: class YourView(generics.RetrieveAPIView): def get_serializer_context(self): context = super().get_serializer_context() context['depth'] = self.request.query_params.get('depth', 1) return context And the to access it in serializer: class YourSerializer(serializers.ModelSerializer): the_depth_from_get_param = serializers.SerializerMethodField() class Meta: model = YourModel fields = [ 'the_depth_from_get_param' ] def get_the_depth_from_get_param(self, obj): return self.context['depth']
answers question: http://stackoverflow.com/q/50487145

http://stackoverflow.com/q/50487995
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87990304
has body: I have multiple documents that together are approximately 400 GB and I want to convert them to json format in order to drop to elasticsearch for analysis. Each file is approximately 200 MB. Original file looked like: IUGJHHGF@BERLIN:lhfrjy 0t7yfudf@WARSAW:qweokm246 0t7yfudf@CRACOW:Er747474 0t7yfudf@cracow:kui666666 000t7yf@Vienna:1йй2ц2й2цй2цц3у It has the characters that are not only English. key1 is always separated with @, where city was separated either by ; or : After I have parsed it with code: #!/usr/bin/env python # coding: utf8 import json with open('2') as f: for line in f: s1 = line.find("@") rest = line[s1+1:] if rest.find(";") != -1: if rest.find(":") != -1: print "FOUND BOTH : ; " s2 = -0 else: s2 = s1+1+rest.find(";") elif rest.find(":") != -1: s2 = s1+1+rest.find(":") else: print "FOUND NO : ; " s2 = -0 key1 = line[:s1] city = line[s1+1:s2] description = line[s2+1:len(line)-1] All file looks like: RRS12345 Cracow Sunflowers RRD12345 Berin Data After that parsing I want to have the output: { "location_data":[ { "key1":"RRS12345", "city":"Cracow", "description":"Sunflowers" }, { "key1":"RRD123dsd45", "city":"Berlin", "description":"Data" }, { "key1":"RRD123dsds45", "city":"Berlin", "description":"1йй2ц2й2цй2цц3у" } ] } How can I convert it to the required json format quickly, where we do not have only English characters?
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50488072
upvote count: 2
accepted answer: http://stackoverflow.com/a/50488201
downvote count: 2
has comment: http://stackoverflow.com/comment/87988841
has answer: http://stackoverflow.com/a/50488201
has comment: http://stackoverflow.com/comment/87988844
tagged with: python
has comment: http://stackoverflow.com/comment/87990232
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87989642
has title: converting text file to json in python
has answer: http://stackoverflow.com/a/50488072

apache-kafka
tags question: http://stackoverflow.com/q/50501936
tags question: http://stackoverflow.com/q/50392699
type: Tag
tags question: http://stackoverflow.com/q/50443755
tags question: http://stackoverflow.com/q/50453189
tags question: http://stackoverflow.com/q/50388349
tags question: http://stackoverflow.com/q/50477948
tags question: http://stackoverflow.com/q/50492820
tags question: http://stackoverflow.com/q/50477711
tag name: apache-kafka
tags question: http://stackoverflow.com/q/50405509
tags question: http://stackoverflow.com/q/50514137
tags question: http://stackoverflow.com/q/50508379

http://stackoverflow.com/a/50502271
has comment: http://stackoverflow.com/comment/88017501
score: 1
has body: Using collections Module. Demo: import collections d = collections.defaultdict(int) with open(filename, "r") as infile: for line in infile: if 'RT' not in line and 'DM' not in line: d[line.strip().split()[0]] += 1 d = sorted(d.items(), key=lambda x: x[1], reverse=True) for k,v in d: print(v, k) Output: 2 andrew 2 fred 1 judy
has comment: http://stackoverflow.com/comment/88017788
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88017268
has comment: http://stackoverflow.com/comment/88016993
has comment: http://stackoverflow.com/comment/88016955
answers question: http://stackoverflow.com/q/50502148
type: Answer
has comment: http://stackoverflow.com/comment/88017606

http://stackoverflow.com/q/50506175
has comment: http://stackoverflow.com/comment/88040771
has title: Google App Engine Instance Memory Error
type: Question
has comment: http://stackoverflow.com/comment/88030423
has answer: http://stackoverflow.com/a/50508906
has comment: http://stackoverflow.com/comment/88041303
tagged with: google-app-engine
tagged with: memory-leaks
tagged with: python
has comment: http://stackoverflow.com/comment/88041180
accepted answer: http://stackoverflow.com/a/50508906
type: AnsweredQuestion
score: 0
has body: I have a simple python App Engine application with low traffic (3 hours of instance activity per day more or less). I'm using everything below the free tier provided and I have: F1 Instances with auto-scaling 1/2 MB of Memcache I make "heavy" use of ndb.get_multi() (with 400 entities per request only for a small amount of requests, but these 400 entities weigh only 3MB) The problem is that I get the Exceeded soft private memory limit of 128 MB with 131 MB after servicing 93 requests total error randomly once every 2/3 days but there is no request the app can't process singularly. I've tried to call gc.collect() at the end of each request but the amount of memory keeps increasing event after servicing the request. How can I solve this without upgrading to higher performing instances (F2)? Thanks!
linked to: http://stackoverflow.com/q/45026920
answer count: 1

azure
tags question: http://stackoverflow.com/q/50496835
tags question: http://stackoverflow.com/q/50525765
tags question: http://stackoverflow.com/q/50531852
type: Tag
tags question: http://stackoverflow.com/q/50478121
tags question: http://stackoverflow.com/q/50398246
tags question: http://stackoverflow.com/q/50481522
tags question: http://stackoverflow.com/q/50528704
tags question: http://stackoverflow.com/q/50446620
tag name: azure
tags question: http://stackoverflow.com/q/50532205
tags question: http://stackoverflow.com/q/50470090
tags question: http://stackoverflow.com/q/50520129
tags question: http://stackoverflow.com/q/50462334
tags question: http://stackoverflow.com/q/50521738
tags question: http://stackoverflow.com/q/50476811

http://stackoverflow.com/comment/88051080
has text: I have the queryset as a variable. ps = Pastry.objects.values('pastry').annotate(total=Count('pastry')) I want to retrieve this in the pastry_list.html template.
comment on: http://stackoverflow.com/q/50518889
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87877840
comment on: http://stackoverflow.com/q/50431585
type: Comment
type: QuestionComment
score: 0
has text: It is for school project, I just wanted to upload json format to {} dic format.

http://stackoverflow.com/comment/88086814
type: QuestionComment
has text: @user8371915 it is not a duplicate, as noted on my post, after edition
score: 0
comment on: http://stackoverflow.com/q/50535772
type: Comment

http://stackoverflow.com/comment/87949725
type: AnswerComment
comment on: http://stackoverflow.com/a/50467926
has text: Sorry for that!
score: 0
type: Comment

http://stackoverflow.com/comment/87946240
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50466557
has text: You need to open the file in append mode, I guess (use a instead of r+)

http://stackoverflow.com/a/60202712
score: 1
downvote count: 1
has body: Uninstall Python32 bit and install Python 64 bit.. Worked for me!
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50483235

http://stackoverflow.com/comment/87920943
comment on: http://stackoverflow.com/a/50427423
has text: just finished running it now. It is the 'tmp =chunk...' line that is crashing it
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50386595
type: UnansweredQuestion
has body: I just tried to run MS's example face API python code. But my code cannot get response from HTTPs. I wrote my collect api key and end point. This end point-face_api_url only response { "error": { "code": "ResourceNotFound", "message": "The requested resource was not found." } } What should I do? Please help me!! here is my source code: subscription_key = 'I wrote my KEY' assert subscription_key face_api_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0' image_url = 'https://how-old.net/Images/faces2/main007.jpg' import requests from IPython.display import HTML headers = { 'Ocp-Apim-Subscription-Key': subscription_key } params = { 'returnFaceId': 'true', 'returnFaceLandmarks': 'false', 'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', } response = requests.post(face_api_url, params=params, headers=headers, json={"url": image_url}) faces = response.json() print(faces)
tagged with: python
has answer: http://stackoverflow.com/a/56795084
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50397492
upvote count: 1
score: 1
has title: FACE API : Resource Not Found for end point url
favorite count: 0
type: Question

http://stackoverflow.com/q/50413693
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/50414088
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50414088
accepted answer: http://stackoverflow.com/a/50414890
has answer: http://stackoverflow.com/a/50414890
type: Question
tagged with: python-3.x
answer count: 2
has title: Detect URL and add anchor tags using BeautifulSoup
score: 2
upvote count: 2
downvote count: 0
tagged with: python
has body: I am parsing html using BeautifulSoup. Given following HTML: An absolute URL: https://www.w3schools.com I wish to convert it to: An absolute URL: https://www.w3schools.com Code written so far: def detect_urls_and_update_target(self, root): //root is the soup object for tag in root.find_all(True): if tag.name == 'a': if not tag.has_attr('target'): tag.attrs['target'] = '_blank' elif tag.string is not None: for url in re.findall(self.url_regex, tag.string): //regex which detects URLS which works new_tag = root.new_tag("a", href=url, target="_blank") new_tag.string = url tag.append(new_tag) This adds the required anchor tag but I am not able to figure out how do I remove the original URL from the tag.
favorite count: 0

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/50496008
tags question: http://stackoverflow.com/q/50525301
tags question: http://stackoverflow.com/q/50487655
tags question: http://stackoverflow.com/q/50506305
tags question: http://stackoverflow.com/q/50463123
tags question: http://stackoverflow.com/q/50412820
tags question: http://stackoverflow.com/q/50418200
tags question: http://stackoverflow.com/q/50501420
tags question: http://stackoverflow.com/q/50472247
tags question: http://stackoverflow.com/q/50436596
tags question: http://stackoverflow.com/q/50490273
tags question: http://stackoverflow.com/q/50502537
tags question: http://stackoverflow.com/q/50441663
tags question: http://stackoverflow.com/q/50431810
tags question: http://stackoverflow.com/q/50509126
tags question: http://stackoverflow.com/q/50427289
tags question: http://stackoverflow.com/q/50488424
tags question: http://stackoverflow.com/q/50539540
tags question: http://stackoverflow.com/q/50515725
tags question: http://stackoverflow.com/q/50445889
tags question: http://stackoverflow.com/q/50518388
tags question: http://stackoverflow.com/q/50435338
tags question: http://stackoverflow.com/q/50396023
tags question: http://stackoverflow.com/q/50498213
tags question: http://stackoverflow.com/q/50473197
tags question: http://stackoverflow.com/q/50524323
tags question: http://stackoverflow.com/q/50401550
tags question: http://stackoverflow.com/q/50462557
tags question: http://stackoverflow.com/q/50455962
tags question: http://stackoverflow.com/q/50418451
tags question: http://stackoverflow.com/q/50521865
tags question: http://stackoverflow.com/q/50520171
tags question: http://stackoverflow.com/q/50432243
tags question: http://stackoverflow.com/q/50460505
tags question: http://stackoverflow.com/q/50457357
type: Tag
tags question: http://stackoverflow.com/q/50388110

http://stackoverflow.com/q/50533871
downvote count: 1
favorite count: 0
has body: I have a directory with (a lot of) subdirs of the type td.0000000 td.0000050 td.0000100 etc. in each subdir I have a file called "density.cube" I would like to move all the "density.cube" in a new subdir "td" td/density0000000.cube td/density0000050.cube td/density0000100.cube etc. or at least td/density.cube0000000 td/density.cube0000050 td/density.cube0000100 etc. How could I achieve that ? I have basis in bash and python but it is obviously not enough... thanks !
type: AnsweredQuestion
score: 0
tagged with: bash
has title: move and number files with same name in a new directory
possible better answer: http://stackoverflow.com/a/50534265
tagged with: mv
has answer: http://stackoverflow.com/a/50534265
tagged with: shell
accepted answer: http://stackoverflow.com/a/50534909
type: Question
has answer: http://stackoverflow.com/a/50534909
answer count: 2
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50472076
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50471870
has body: You can join adjacent words in a list of even length with map('{} {}'.format, lst[::2], lst[1::2]). The rest is handling the odd case and mapping over the lsit of lists. lsts = [['Start', 'двигаться', 'конгресс', 'сша'], ['Start', 'двигаться', 'сторона', 'в'], ['Start', 'двигаться', 'сторона', 'признание', 'суверенитет', 'израильский'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'на'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'оккупировать'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'Голанский'], ['Start', 'двигаться', 'сторона', 'признание', 'и']] def proc_single(lst): # join adjacent words res = list(map('{} {}'.format, lst[::2], lst[1::2])) # correct for lists with odd length if len(lst) % 2: res[-1] = '{} {}'.format(res[-1], lst[-1]) return res for lst in lsts: print(proc_single(lst)) # ['Start двигаться', 'конгресс сша'] # ['Start двигаться', 'сторона в'] # ['Start двигаться', 'сторона признание', 'суверенитет израильский'] # ['Start двигаться', 'сторона признание', 'высот на'] # ['Start двигаться', 'сторона признание', 'высот оккупировать'] # ['Start двигаться', 'сторона признание', 'высот Голанский'] # ['Start двигаться', 'сторона признание и']
upvote count: 2
type: Answer

http://stackoverflow.com/q/50420637
tagged with: numerical-methods
has body: I have a complex finite difference model which is written in python using the same general structure as the below example code. It has two for loops one for each iteration and then within each iteration a loop for each position along the x array. Currently the code takes two long to run (probably due to the for loops). Is there a simple technique to use numpy to remove the second for loop? Below is a simple example of the general structure I have used. import numpy as np def f(x,dt, i): xn = (x[i-1]-x[i+1])/dt # a simple finite difference function return xn x = np.linspace(1,10,10) #create initial conditions with x[0] and x[-1] boundaries dt = 10 #time step iterations = 100 # number of iterations for j in range(iterations): for i in range(1,9): #length of x minus the boundaries x[i] = f(x, dt, i) #return new value for x[i] Does anyone have any ideas or comments on how I could make this more efficient? Thanks, Robin
has comment: http://stackoverflow.com/comment/87961987
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87961897
has answer: http://stackoverflow.com/a/50421330
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87856767
accepted answer: http://stackoverflow.com/a/50421330
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87857069
has title: speed up finite difference model
has comment: http://stackoverflow.com/comment/87856884
score: 1

http://stackoverflow.com/a/55912291
answers question: http://stackoverflow.com/q/50391868
upvote count: 3
has body: You can simply install the package again using Anaconda conda install statsmodels If there are packages that need to be adjusted, they you will be prompted automatically (see below). I was able to resolve the issue this way.
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/q/50401298
upvote count: 2
possible better answer: http://stackoverflow.com/a/50401473
has title: Pandas: filling the gap in time with certain value
downvote count: 0
has answer: http://stackoverflow.com/a/50401473
tagged with: python
accepted answer: http://stackoverflow.com/a/50401518
score: 2
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/50401518
has body: I have the following data frame: timestamp value 2018-02-26 09:13:00 0.972198 2018-02-26 09:14:00 1.008504 2018-02-26 09:15:00 1.011961 2018-02-26 09:18:00 1.018950 2018-02-26 09:19:00 1.008538 2018-02-26 09:21:00 0.988535 2018-02-26 09:22:00 0.944170 2018-02-26 09:23:00 0.940284 I want to fill all the gap in timestamp with the value = 2, so the output would be like: timestamp value 2018-02-26 09:13:00 0.972198 2018-02-26 09:14:00 1.008504 2018-02-26 09:15:00 1.011961 2018-02-26 09:16:00 2.0 2018-02-26 09:17:00 2.0 2018-02-26 09:18:00 1.018950 2018-02-26 09:19:00 1.008538 2018-02-26 09:20:00 2.0 2018-02-26 09:21:00 0.988535 2018-02-26 09:22:00 0.944170 2018-02-26 09:23:00 0.940284 I used the following code to fill the gap in timestamp first: df.reindex(index = 'timestamp') but got the following errors. I am wondering what did I miss here? Thanks! TypeErrorTraceback (most recent call last) &lt;ipython-input-5-cf75ce057c42&gt; in &lt;module&gt;() ----&gt; 1 df.reindex(index = 'timestamp') /opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/frame.pyc in reindex(self, index, columns, **kwargs) 2731 def reindex(self, index=None, columns=None, **kwargs): 2732 return super(DataFrame, self).reindex(index=index, columns=columns, -&gt; 2733 **kwargs) 2734 2735 @Appender(_shared_docs['reindex_axis'] % _shared_doc_kwargs) /opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/generic.pyc in reindex(self, *args, **kwargs) 2513 # perform the reindex on the axes 2514 return self._reindex_axes(axes, level, limit, tolerance, method, -&gt; 2515 fill_value, copy).__finalize__(self) 2516 2517 def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, /opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/frame.pyc in _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy) 2677 if index is not None: 2678 frame = frame._reindex_index(index, method, copy, level, -&gt; 2679 fill_value, limit, tolerance) 2680 2681 return fra…
tagged with: reindex
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/a/50388467
answers question: http://stackoverflow.com/q/50388069
type: Answer
has comment: http://stackoverflow.com/comment/87792712
downvote count: 0
has body: Assuming you are running some kind of linux (like raspbian), you don't need to use Python for this, the easiest way would be: iwconfig 2&gt;&amp;1 | grep ESSID from the command line or a shell script. There will be output if you are connected to a wireless network, and no output if not. You could wrap this in subprocess if you want to run it from Python: import subprocess ps = subprocess.Popen(['iwconfig'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) try: output = subprocess.check_output(('grep', 'ESSID'), stdin=ps.stdout) print(output) except subprocess.CalledProcessError: # grep did not match any lines print("No wireless networks connected")
score: 3
upvote count: 3

http://stackoverflow.com/q/50502150
tagged with: pandas
has body: I have a df of sales data. I want to add two more columns that highlight important values within the other columns. At the moment I have code that returns the values into the new columns whenever a sale is made. So if a subject appears in the Sales column, the corresponding values are indexed in the new columns. import pandas as pd import numpy as np a = 5 N = 10 df = pd.DataFrame({ 'Tom_$' : [500, 50, 10, 60, 50, 77, 30, 600, 40, 60], 'Tom_c' : [100, 20, 40, 50, 0, 67, 90, 100, 0, 0], 'Code' : ['nan', 'nan', 'Big', 'nan', 'nan', 'Small', 'nan','nan', 'nan','nan'], 'Sales' : ['nan','nan','Tom','nan','nan','Tom','nan','nan','nan','nan']}) df['Big'] = df.apply(lambda row: row.get(row['Sales']+'_$') if pd.notnull(row['Sales']) else np.nan, axis=1) df['Small'] = df.apply(lambda row: row.get(row['Sales']+'_c') if pd.notnull(row['Sales']) else np.nan, axis=1) Output: Code Julie_$ Julie_c Sales Tom_$ Tom_c Dollars Cents 0 nan 500 300 nan 500 100 NaN NaN 1 nan 40 20 nan 50 20 NaN NaN 2 Big 10 70 Tom 10 40 10.0 40.0 3 nan 10 50 nan 60 50 NaN NaN 4 nan 50 80 nan 50 0 NaN NaN 5 Small 37 67 Tom 77 67 77.0 67.0 6 nan 30 50 nan 30 90 NaN NaN 7 Big 900 100 Julie 600 100 900.0 100.0 8 nan 40 40 nan 40 0 NaN NaN 9 nan 50 0 nan 60 0 NaN NaN This works fine, but I want to add another layer by using the Code column. If the value in this column is Big I want to keep returning the salesperson values until theres a new sale. If it's Small I don't care. So the output would be: Code Julie_$ Julie_c Sales Tom_$ Tom_c Dollars Cents 0 nan 500 300 nan 500 100 NaN NaN 1 nan 40 20 nan 50 20 NaN NaN 2 Big 10 70 Tom 10 40 10.0 40.0 3 nan 10 50 nan 60 50 60.0 50.0 4 nan 50 80 nan 50 0 50.0 0.0 5 Small 37 67 Tom 77 67 77.0 67.0 6 nan 30 50 nan 30 90 NaN NaN 7 Big 900 100 Julie 600 100 900.0 100.0 8 nan 40 40 nan 40 0 40.0 0.0 9 nan 50 0 nan 60 0 60.0 0.0 I have considered using a similar method to returning the values like the Sales column df['Dollars'] = df.apply(lambda row: row.get(row['Sales']+'_$…
accepted answer: http://stackoverflow.com/a/50502639
has title: Return values to new columns in a pandas df
answer count: 1
tagged with: apply
type: Question
tagged with: python
tagged with: indexing
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50502639

port
tags question: http://stackoverflow.com/q/50415390
type: Tag
tag name: port

http://stackoverflow.com/a/50517047
has comment: http://stackoverflow.com/comment/88046802
has comment: http://stackoverflow.com/comment/88062808
has comment: http://stackoverflow.com/comment/88060603
has body: Just use another counter variable, and check if it's a multiple of 7. def main(): counter = 0 for month in range(1, 13): daymax = 32 if month == 2: daymax = 29 elif month == 4: daymax = 31 elif month == 6: daymax = 31 elif month == 9: daymax = 31 elif month == 11: daymax = 31 for day in range(1, daymax): if counter % 7 == 0: print(day,".", month,".", sep="") counter += 1
has comment: http://stackoverflow.com/comment/88046796
has comment: http://stackoverflow.com/comment/88046699
score: 0
has comment: http://stackoverflow.com/comment/88046720
type: Answer
answers question: http://stackoverflow.com/q/50517004
has comment: http://stackoverflow.com/comment/88074939

http://stackoverflow.com/comment/87914463
type: Comment
comment on: http://stackoverflow.com/a/50450350
score: 0
type: AnswerComment
has text: Sorry I should have clarified. I need two regex to extract location and timestamp separately, not one regex. Sorry for the confusion.

pyfcm
tags question: http://stackoverflow.com/q/50412058
tag name: pyfcm
type: Tag

http://stackoverflow.com/q/50464576
type: AnsweredQuestion
score: 2
has title: How to get specific system tray icon using pywinauto?
tagged with: ui-automation
tagged with: pywinauto
has body: For example the Slack icon from the notification area: And how can we get a specific icon in case of "show hidden" icons option?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50560105
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50560105
possible better answer: http://stackoverflow.com/a/54648006
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/54648006
has comment: http://stackoverflow.com/comment/88058072

http://stackoverflow.com/a/50492164
score: 0
has comment: http://stackoverflow.com/comment/88024018
type: Answer
has body: Do you have the https://... urls in your prefs? Check it at: https://console.developers.google.com/apis/credentials/consent?project={your_project}
answers question: http://stackoverflow.com/q/50490629

http://stackoverflow.com/comment/87962617
type: QuestionComment
comment on: http://stackoverflow.com/q/50474535
has text: What do you mean with "In a new variable"? a new dictionary?
score: 0
type: Comment

http://stackoverflow.com/q/50490445
has comment: http://stackoverflow.com/comment/87994130
answer count: 1
has title: Not able to fetch data from unicode between two characters
has comment: http://stackoverflow.com/comment/87994179
type: Question
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/50490752
has answer: http://stackoverflow.com/a/50490752
tagged with: python
type: AnsweredQuestion
has body: In parsing of html 05/23 13:58頃 苫小牧市 （支援）苫小牧市新富町1丁目 I have to fetch data from small bracket '( )' as 支援 in python. When I am trying to fetch data by command text = div.h3.findAll(text=True, recursive=False)[2].strip() I am getting u'（支援）苫小牧市新富町1丁目' It is the unicode data of '（支援）苫小牧市新富町1丁目', so I am unable to fetch data from small bracket as '支援'
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/101681204
score: 0
comment on: http://stackoverflow.com/a/50451354
type: Comment
type: AnswerComment
has text: This is an amazing answer. Thanks for sharing it. Even though it's a little bit late for asking, would you also know how to add a constraint to the sum of all the coefficients? For example for a stock portfolio, not only coefficients can't be negative but their sum can't be greater than 1. Thanks!

http://stackoverflow.com/a/50395189
upvote count: 1
answers question: http://stackoverflow.com/q/50393811
has comment: http://stackoverflow.com/comment/87808494
score: 1
has comment: http://stackoverflow.com/comment/87808913
downvote count: 0
has body: Okay, it seems your problem is solved. You can have all the data sequentially now. Give it a shot: from bs4 import BeautifulSoup import requests res = requests.get("https://regatta.time-team.nl/hollandia/2017/results/003.php") soup = BeautifulSoup(res.text,"lxml") for table in soup.find(class_="timeteam").find_all("tr",class_=['even','odd']): if "smallrow" not in table.get('class'): #this is the fix data = [item.get_text(strip=True) for item in table] print(data) Output you may get like: ['1.', 'PHO', 'Phocas 1 (p2)', '', '--', '', '--', '', '--', '', '06:39,86', '(1)', 'KF'] ['2.', 'PAM', 'Pampus (p4)', '', '--', '', '--', '', '--', '', '06:45,21', '(2)', 'KF'] ['3.', 'SKO', 'Skøll 1', '', '--', '', '--', '', '--', '', '06:46,23', '(3)', 'KF'] ['4.', 'NJO', 'Njord (p1)', '', '--', '', '--', '', '--', '', '06:49,44', '(4)', 'KF'] ['5.', 'GYA', 'Gyas (SB)', '', '--', '', '--', '', '--', '', '06:50,04', '(5)', 'KF'] ['6.', 'PRO', 'Proteus 1 (p7)', '', '--', '', '--', '', '--', '', '06:50,24', '(6)', 'KF']
has comment: http://stackoverflow.com/comment/88304614
type: Answer

http://stackoverflow.com/a/50418360
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Use zip method: shirts = driver.find_elements_by_xpath("//*[@id='container']/article/div/h1/a") colors = driver.find_elements_by_xpath("//*[@id='container']/article/div/p/a") for shirt, color in zip(shirts, colors): shirt_text = shirt.text color_text = color.text print shirt_text, color_text
accepted answer of: http://stackoverflow.com/q/50418044
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50418044

http://stackoverflow.com/comment/88012472
comment on: http://stackoverflow.com/q/50499868
type: Comment
type: QuestionComment
has text: Please provide some code to help you debug ;)
score: 0

http://stackoverflow.com/comment/88062080
comment on: http://stackoverflow.com/a/50523924
type: AnswerComment
score: 0
type: Comment
has text: Both of them df.loc['madvise',130] = df.loc['madvise',130] + 10 and df.loc['madvise',130] += 10 are giving error..which is TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [32] of <class 'int'>

http://stackoverflow.com/q/50490481
answer count: 0
linked to: http://stackoverflow.com/q/10763440
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88007769
upvote count: 1
has body: python 2.7 is installed at /usr/lib packages are installed at /usr/lib/python2.7/site-packages python 3 is installed at /usr/local/bin python3 command is not able to fetch the packages/modules from the above mentioned directory. $PATH looks like [PATH][1] How can i fetch or use those packages in python3 .
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87993948
has comment: http://stackoverflow.com/comment/87993945
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88010543
has title: How to use python2 modules in python3 in linux server?
has comment: http://stackoverflow.com/comment/87993990
tagged with: python-3.x
tagged with: python-2.7

pivot
tags question: http://stackoverflow.com/q/50507735
tags question: http://stackoverflow.com/q/50441995
tags question: http://stackoverflow.com/q/50500057
tags question: http://stackoverflow.com/q/50465399
tag name: pivot
tags question: http://stackoverflow.com/q/50471777
type: Tag

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/50396492
tags question: http://stackoverflow.com/q/50522042
tags question: http://stackoverflow.com/q/50477528
tags question: http://stackoverflow.com/q/50525927
tags question: http://stackoverflow.com/q/50523095
tag name: xml
tags question: http://stackoverflow.com/q/50418602
tags question: http://stackoverflow.com/q/50387482
tags question: http://stackoverflow.com/q/50489585
tags question: http://stackoverflow.com/q/50401588
tags question: http://stackoverflow.com/q/50482088
type: Tag
tags question: http://stackoverflow.com/q/50449181
tags question: http://stackoverflow.com/q/50458900
tags question: http://stackoverflow.com/q/50510639
tags question: http://stackoverflow.com/q/50399803
tags question: http://stackoverflow.com/q/50463394
tags question: http://stackoverflow.com/q/50415676
tags question: http://stackoverflow.com/q/50453543
tags question: http://stackoverflow.com/q/50539837
tags question: http://stackoverflow.com/q/50430887
tags question: http://stackoverflow.com/q/50537060
tags question: http://stackoverflow.com/q/50396265
tags question: http://stackoverflow.com/q/50498261
tags question: http://stackoverflow.com/q/50502476
tags question: http://stackoverflow.com/q/50419213
tags question: http://stackoverflow.com/q/50460562
tags question: http://stackoverflow.com/q/50447564
tags question: http://stackoverflow.com/q/50482188
tags question: http://stackoverflow.com/q/50477026
tags question: http://stackoverflow.com/q/50393860
tags question: http://stackoverflow.com/q/50513894
tags question: http://stackoverflow.com/q/50388644

parsing
tags question: http://stackoverflow.com/q/50535759
tags question: http://stackoverflow.com/q/50437375
tags question: http://stackoverflow.com/q/50441612
tags question: http://stackoverflow.com/q/50439948
tags question: http://stackoverflow.com/q/50430887
tags question: http://stackoverflow.com/q/50520408
tags question: http://stackoverflow.com/q/50401820
tags question: http://stackoverflow.com/q/50462844
tag name: parsing
tags question: http://stackoverflow.com/q/50531101
tags question: http://stackoverflow.com/q/50456445
tags question: http://stackoverflow.com/q/50539837
tags question: http://stackoverflow.com/q/50407509
tags question: http://stackoverflow.com/q/50399683
tags question: http://stackoverflow.com/q/50450694
tags question: http://stackoverflow.com/q/50387248
tags question: http://stackoverflow.com/q/50493670
tags question: http://stackoverflow.com/q/50482088
tags question: http://stackoverflow.com/q/50460562
tags question: http://stackoverflow.com/q/50455945
tags question: http://stackoverflow.com/q/50445895
tags question: http://stackoverflow.com/q/50420548
tags question: http://stackoverflow.com/q/50429371
type: Tag

http://stackoverflow.com/q/50438512
has answer: http://stackoverflow.com/a/50438554
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50438568
downvote count: 4
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/87891039
has title: Find specific word in array of strings
has body: I have two lists, one with strings and another one with words to be found. Lets say: list1 = ['Hi I am Tayyab','I am a python programmer', 'I am new To python' ] list2 = ['Tayyab','Programmer'] I want to check if list 1 contains the words present in list2. If yes then return the complete string present in list1. In the above case I want the first two items in list1 to be returned because the first two items contain the words 'Tayyab' and 'Programmer'.
has comment: http://stackoverflow.com/comment/87890962
favorite count: 0
type: Question
score: -2
tagged with: python
possible better answer: http://stackoverflow.com/a/50438554
has comment: http://stackoverflow.com/comment/87891318
has answer: http://stackoverflow.com/a/50438559
accepted answer: http://stackoverflow.com/a/50438568

pyqt
type: Tag
tags question: http://stackoverflow.com/q/50430093
tags question: http://stackoverflow.com/q/50446851
tags question: http://stackoverflow.com/q/50439086
tags question: http://stackoverflow.com/q/50419523
tags question: http://stackoverflow.com/q/50498162
tags question: http://stackoverflow.com/q/50529406
tags question: http://stackoverflow.com/q/50497926
tags question: http://stackoverflow.com/q/50534181
tags question: http://stackoverflow.com/q/50494654
tags question: http://stackoverflow.com/q/50459326
tags question: http://stackoverflow.com/q/50386120
tags question: http://stackoverflow.com/q/50525101
tags question: http://stackoverflow.com/q/50531164
tags question: http://stackoverflow.com/q/50430941
tags question: http://stackoverflow.com/q/50531797
tags question: http://stackoverflow.com/q/50415466
tags question: http://stackoverflow.com/q/50536613
tags question: http://stackoverflow.com/q/50504502
tags question: http://stackoverflow.com/q/50406779
tags question: http://stackoverflow.com/q/50517837
tags question: http://stackoverflow.com/q/50457475
tags question: http://stackoverflow.com/q/50427076
tags question: http://stackoverflow.com/q/50477815
tags question: http://stackoverflow.com/q/50476489
tags question: http://stackoverflow.com/q/50430911
tag name: pyqt
tags question: http://stackoverflow.com/q/50500479
tags question: http://stackoverflow.com/q/50468807
tags question: http://stackoverflow.com/q/50502793
tags question: http://stackoverflow.com/q/50522521
tags question: http://stackoverflow.com/q/50436562
tags question: http://stackoverflow.com/q/50454733
tags question: http://stackoverflow.com/q/50470212
tags question: http://stackoverflow.com/q/50465934

http://stackoverflow.com/q/50435931
score: -1
tagged with: decimal
type: AnsweredQuestion
tagged with: python-3.x
tagged with: fractions
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Choose if your number is a fraction or a decimal
tagged with: if-statement
has answer: http://stackoverflow.com/a/50435957
accepted answer: http://stackoverflow.com/a/50435957
has body: I'm trying to make it so if the denominator of the fraction is over 2, it prints the decimal. Else, it prints the fraction from fractions import Fraction z = float(input()) frac = (Fraction(z)) s = str(z) x = s.find("/") x1 = x + 1 segment = z[x1:] print(segment) if len(segment) &lt;= 3: print(frac) else: print(z)
tagged with: python

http://stackoverflow.com/a/50386076
has comment: http://stackoverflow.com/comment/87788092
has comment: http://stackoverflow.com/comment/87787945
score: 0
has comment: http://stackoverflow.com/comment/87788150
has comment: http://stackoverflow.com/comment/87788196
answers question: http://stackoverflow.com/q/50385976
has comment: http://stackoverflow.com/comment/87788118
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50385976
has body: Finding All Songs in Non-tokenized Sentence So, to find all the songs you iterate over the dictionary and accumulate the results: def find_verses(book_dict, target_sentence): result = [] for key, verse_list in book_dict.items(): for verse in verse_list: if verse in target_sentence: result.append((key, verse)) return result EDIT 2: Remove token searching in token list because we would loose the phrases. EDIT 3: Add code to find all verses
type: Answer
has comment: http://stackoverflow.com/comment/87787775
has comment: http://stackoverflow.com/comment/87788064
has comment: http://stackoverflow.com/comment/87788030

http://stackoverflow.com/a/50420300
score: 3
downvote count: 0
has body: Something like this: res = tuple([x if not ind % 2 else y for ind, (x,y) in enumerate(zip(list1,list2))]) print(res) #('a', 'B', 'c')
type: Answer
answers question: http://stackoverflow.com/q/50420229
upvote count: 3

http://stackoverflow.com/a/50462746
score: 2
accepted answer of: http://stackoverflow.com/q/50462670
type: Answer
answers question: http://stackoverflow.com/q/50462670
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Try this: &gt;&gt;&gt; s = 'Adam, 30 M, Husband' &gt;&gt;&gt; re.sub(r'(?is)(\d+)(\s)', '\\1, ', s) 'Adam, 30, M, Husband'

http://stackoverflow.com/comment/88000273
has text: Thanks @KlausD.. Your comment helped me.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50431921

http://stackoverflow.com/comment/88009651
comment on: http://stackoverflow.com/a/50498357
type: Comment
score: 0
has text: Thanks for your answer, but it didn't working for me actually. I try your code with https://www.jdoodle.com/python3-programming-online Check my original post to copy past my code
type: AnswerComment

http://stackoverflow.com/a/50486723
answers question: http://stackoverflow.com/q/50483439
has comment: http://stackoverflow.com/comment/87998687
has comment: http://stackoverflow.com/comment/88008119
score: 1
downvote count: 1
has body: Using the Resource method: # Iterate through list to upload objects to S3 bucket = s3.Bucket('rekognition-pictures') for image in images: bucket.upload_file(Filename='/upload/' + image[0], Key='index/' + image[0], ExtraArgs={'FullName': image[1]} ) Using the client method: import boto3 client = boto3.client('s3') ... # Iterate through list to upload objects to S3 for image in images: client.upload_file(Filename='/upload/' + image[0], Bucket='rekognition-pictures', Key='index/' + image[0], ExtraArgs={'FullName': image[1]} )
has comment: http://stackoverflow.com/comment/88008621
upvote count: 2
type: Answer

http://stackoverflow.com/comment/139263092
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50514338
has text: For people using SQLModel, use `SQLModel.metadata.drop_all(engine)`.

http://stackoverflow.com/q/50508310
has comment: http://stackoverflow.com/comment/88039923
tagged with: multiprocessing
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88039109
has body: This seems to be a python 3.6 bug When assigning a manager.Queue to a manager.Namespace attribute one gets an TypeError. To reproduce it is simple: &gt;&gt;&gt; from multiprocessing import Manager &gt;&gt;&gt; manager = Manager() &gt;&gt;&gt; np = manager.Namespace() &gt;&gt;&gt; np.shared_queue = manager.Queue() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\users\leonardo.schettini\appdata\local\programs\python\python36-32\Lib\multiprocessing\managers.py", line 1065, in __setattr__ return callmethod('__setattr__', (key, value)) File "c:\users\leonardo.schettini\appdata\local\programs\python\python36-32\Lib\multiprocessing\managers.py", line 772, in _callmethod raise convert_to_error(kind, result) multiprocessing.managers.RemoteError: --------------------------------------------------------------------------- Traceback (most recent call last): File "c:\users\leonardo.schettini\appdata\local\programs\python\python36-32\Lib\multiprocessing\managers.py", line 228, in serve_client request = recv() File "c:\users\leonardo.schettini\appdata\local\programs\python\python36-32\Lib\multiprocessing\connection.py", line 251, in recv return _ForkingPickler.loads(buf.getbuffer()) File "c:\users\leonardo.schettini\appdata\local\programs\python\python36-32\Lib\multiprocessing\managers.py", line 881, in RebuildProxy return func(token, serializer, incref=incref, **kwds) TypeError: AutoProxy() got an unexpected keyword argument 'manager_owned' --------------------------------------------------------------------------- Here, I found that manager.Queue is just an address (proxy) pointing to shared queue managed by the multiprocessing.Manager() object If one tries to assign a multiprocessing.Queue instead a RuntimeError is raised. This makes sense if you consider that the multiprocessing.Queue can't be pickled (information on provided link)
tagged with: python
has comment: http://stackoverflow.com/comment/88039830
tagged with: python-multiprocessing
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/43439194
has title: Adding a shared object to a manager.Namespace
has comment: http://stackoverflow.com/comment/88040104

http://stackoverflow.com/comment/88139986
type: Comment
comment on: http://stackoverflow.com/q/50492820
score: 0
type: QuestionComment
has text: @Paizo Fetching from db takes 2 mins 30 secs and fetching+publishing takes 4 mins 10 secs

http://stackoverflow.com/a/50908388
has body: I only managed to get this working on a Linux machine, so hope you're not on windows. Here's what worked for me. I had to do a seperate install of hte xmlsec-library first: apt-get install xmlsec1 openssl python-lxml libxmlsec1 libxmlsec1-dev and then I was able to pip install python3-saml and there were no complains anymore.
type: Answer
answers question: http://stackoverflow.com/q/50525133
score: 0

http://stackoverflow.com/q/50534767
tagged with: android
downvote count: 0
tagged with: python
tagged with: kivy
type: AnsweredQuestion
score: 3
tagged with: android-webview
upvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/50536161
has body: I am trying to make an android app for a website with Python Kivy. I am using 2nd code from here. 1) I want all external links to open in device browser and 2) Back button minimizes the app instead of exiting. Please suggest the changes I should make. Thanks For 1st problem, there are some solutions of using if_else with INTENT, but all are in Java and not Python
has title: How to make Python Kivy webview app with navigation button and open external link in browser?
favorite count: 0
has answer: http://stackoverflow.com/a/50536161
type: Question

pyqt5
tags question: http://stackoverflow.com/q/50430941
tags question: http://stackoverflow.com/q/50538953
tags question: http://stackoverflow.com/q/50415466
type: Tag
tags question: http://stackoverflow.com/q/50512391
tags question: http://stackoverflow.com/q/50413628
tags question: http://stackoverflow.com/q/50459672
tags question: http://stackoverflow.com/q/50437855
tags question: http://stackoverflow.com/q/50491134
tags question: http://stackoverflow.com/q/50391050
tags question: http://stackoverflow.com/q/50426838
tags question: http://stackoverflow.com/q/50527080
tags question: http://stackoverflow.com/q/50497926
tags question: http://stackoverflow.com/q/50433467
tags question: http://stackoverflow.com/q/50517087
tags question: http://stackoverflow.com/q/50534181
tags question: http://stackoverflow.com/q/50459326
tags question: http://stackoverflow.com/q/50535957
tags question: http://stackoverflow.com/q/50531797
tags question: http://stackoverflow.com/q/50504502
tags question: http://stackoverflow.com/q/50406779
tags question: http://stackoverflow.com/q/50457475
tags question: http://stackoverflow.com/q/50524613
tag name: pyqt5
tags question: http://stackoverflow.com/q/50427076
tags question: http://stackoverflow.com/q/50439086
tags question: http://stackoverflow.com/q/50506566
tags question: http://stackoverflow.com/q/50476489
tags question: http://stackoverflow.com/q/50419523
tags question: http://stackoverflow.com/q/50498162
tags question: http://stackoverflow.com/q/50430911
tags question: http://stackoverflow.com/q/50386223
tags question: http://stackoverflow.com/q/50500479
tags question: http://stackoverflow.com/q/50468807
tags question: http://stackoverflow.com/q/50430449
tags question: http://stackoverflow.com/q/50398483
tags question: http://stackoverflow.com/q/50426090
tags question: http://stackoverflow.com/q/50436562
tags question: http://stackoverflow.com/q/50454733

http://stackoverflow.com/comment/87890747
comment on: http://stackoverflow.com/q/50394393
type: Comment
type: QuestionComment
score: 0
has text: @chepner entry was being reused because I didn't understand that a copy was not being made. The context that (clumsily) fixed it was to reassign entry as [0.0]*2. This apparently overwrote the reference and created a new Python object. Due to reference counting, the old object still stayed alive in the 'listing' object.

http://stackoverflow.com/comment/89570833
type: AnswerComment
has text: Remove the decorator, change the signature to `on_message(self, message)` and change `bot` to `self.bot`
score: 0
comment on: http://stackoverflow.com/a/50548698
type: Comment

http://stackoverflow.com/q/50417746
has title: Python 3.6 multiprocessing.Pool intermittently fails to exit on KeyboardInturrupt
type: Question
tagged with: python
type: AnsweredQuestion
tagged with: multithreading
downvote count: 0
has body: I am trying to use multiprocessing.Pool to asynchronously dispatch some jobs to external processes, e.g.: #!/bin/env python3 ''' test.py ''' import multiprocessing.util from multiprocessing import Pool import shlex import subprocess from subprocess import PIPE multiprocessing.util.log_to_stderr(multiprocessing.util.DEBUG) def waiter(arg): cmd = "sleep 360" cmd_arg = shlex.split(cmd) p = subprocess.Popen(cmd_arg, stdout=PIPE, stderr=PIPE) so, se = p.communicate() print (f"{so}\n{se}") return arg def main1(): proc_pool = Pool(4) it = proc_pool.imap_unordered(waiter, range(0, 4)) for r in it: print (r) if __name__ == '__main__': main1() I would like it to terminate all called subprocesses, pool workers, and itself on SIGINT. Currently this works fine with a pool size of 4: $&gt; ./test.py [DEBUG/MainProcess] created semlock with handle 140194873397248 [DEBUG/MainProcess] created semlock with handle 140194873393152 [DEBUG/MainProcess] created semlock with handle 140194873389056 [DEBUG/MainProcess] created semlock with handle 140194873384960 [DEBUG/MainProcess] added worker [INFO/ForkPoolWorker-2] child process calling self.run() [DEBUG/MainProcess] added worker [INFO/ForkPoolWorker-3] child process calling self.run() [DEBUG/MainProcess] added worker [INFO/ForkPoolWorker-4] child process calling self.run() [DEBUG/MainProcess] doing set_length() [INFO/ForkPoolWorker-2] process shutting down [DEBUG/ForkPoolWorker-2] running all "atexit" [DEBUG/ForkPoolWorker-3] runni[DEBUG/ForkPoolWorker-2] running the remaining[DEBUG/ForkPoolWorker-3] running the remaining "atexit" finalizers Process ForkPoolWorker-1: Traceback (most recent call last): File "/usr/local/lib/python3.6/multiprocessing/process.py", line 249, in _bootstrap self.run() File "/usr/local/lib/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/multiprocessing/pool.py", line 119, in worker result = (True, func(*args, **kwds)) File "./test.py…
score: 7
upvote count: 7
answer count: 1
favorite count: 0
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/50420682
tagged with: python-3.x
linked to: http://stackoverflow.com/q/38271547
linked to: http://stackoverflow.com/q/1408356
has answer: http://stackoverflow.com/a/50420682

http://stackoverflow.com/comment/88684509
type: QuestionComment
score: 0
has text: The time should be almost the same. I have done several tests and for me it is the same. Did you run the both pieces of code several times? It would be better, as said by @AlexeyMaloletkin to see the entire code you are using. If you used a batch query or you were doing a lot of queries or you had network issues at that time could explain a difference in this sense but is difficult to say without more information.
comment on: http://stackoverflow.com/q/50430604
type: Comment

http://stackoverflow.com/q/50426842
has comment: http://stackoverflow.com/comment/87868357
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50427238
upvote count: 2
has answer: http://stackoverflow.com/a/50427238
downvote count: 0
has title: python3.4 twitter data scrape error: KeyError: 'user'
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/87868285
answer count: 1
tagged with: twitter
has body: I have extracted 4gb from twitter in a json txt file. Now i am trying to go through the file and extract user locations. When i run the script below i get the error: File "filepath/test.py", line 18, in if tweet['user']['id']: KeyError: 'user' Is it possible that a user id is missing from the tweets collected? I thought it cannot be null. I have collected smaller samples, in 3 out of 4 i get the same error, it works only for one dataset in which i didn't spot any json structure differences import json # Tweets are stored in in file "fname". In the file used for this script, # each tweet was stored on one line fname = 'test_with_sample.json' with open(fname, 'r') as f: # Create dictionary to later be stored as JSON. All data will be included # in the list 'data' users_with_geodata = { "data": [] } all_users = [] total_tweets = 0 geo_tweets = 0 for line in f: tweet = json.loads(line) if tweet['user']['id']: total_tweets += 1 user_id = tweet['user']['id'] if user_id not in all_users: all_users.append(user_id) # Give users some data to find them by. User_id listed separately # to make iterating this data later easier user_data = { "user_id": tweet['user']['id'], "features": { "name": tweet['user']['name'], "id": tweet['user']['id'], "screen_name": tweet['user']['screen_name'], "tweets": 1, "location": tweet['user']['location'], } } if tweet['place']: user_data["features"]["primary_geo"] = tweet['place']['full_name'] + ", " + tweet['place'][ 'country'] user_data["features"]["geo_type"] = "Tweet place" else: user_data["features"]["primary_geo"] = tweet['user']['location'] user_data["features"]["geo_type"] = "User location" # Add only tweets with some geo data to .json. Comment this if you want to include all tweets. if user_data["features"]["primary_geo"]: users_with_geodata['data'].append(user_data) geo_tweets += 1 # If user already listed, increase their tweet count elif user_id in all_users: for user in users_with_geodata["data"]: if user_id == user["user_id"]: user["f…

http://stackoverflow.com/q/50499418
has title: Djengo Error trying to run python manage.py test
answer count: 3
has answer: http://stackoverflow.com/a/50499449
has answer: http://stackoverflow.com/a/50499451
has body: Why am I getting this error from the end of my manange.py file? I'm trying to run python manage.py test. I get this error even if the tests.py is blank. The project works fine and I'm trying to add tests. Error I'm getting Sorry about the late getback, I do have django_rest in my installed apps. here's my settings.py - """ Django settings for djangorest project. Generated by 'django-admin startproject' using Django 2.0.2. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Serer datails for password reset by email EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' #STATICFILES_DIR = ( # os.path.join(BASE_DIR, 'staticfiles') #) #STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media') ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'djangorest/media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '04u+3)m+%o+in*5iorg*h9ze1p(tat9en8#6qkfb3#a8xty24(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } # Custom redirect for login LOGIN_REDIRECT_URL = '/home' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'django.contrib.auth.forms', 'rest_framework', 'api', 'cg', 'djangorest', 'multiselectfield…
tagged with: python
type: Question
score: 0
type: UnansweredQuestion
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/50499474

http://stackoverflow.com/comment/88018691
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50487396
has text: @MikeVlad post your actual code please, and what you expect of it

http://stackoverflow.com/q/50417731
has comment: http://stackoverflow.com/comment/87853472
has comment: http://stackoverflow.com/comment/87852951
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87919582
tagged with: ngrok
tagged with: dialogflow-es
upvote count: 1
has body: Issue with Dialogflow ,carried out below steps Enabled Webhook requeston dialogflow and its request Connected with ngrok Calling webhook method from flask Below are the images: Intent Webhook: Fullfillment Enabled: Ngrok: Flask Method: @app.route("/webhook",methods=['POST']) def main(): Req = request.get_json(silent=True, force=True) print(Req.get('queryResult')) Resp='test' return make_response(jsonify({'fulfillmentText': Resp}))
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87851598
downvote count: 0
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/112891791
has title: Dialog Flow Webhook not working with ngrok
has comment: http://stackoverflow.com/comment/87851305

http://stackoverflow.com/comment/88096795
score: 0
has text: Please have a look into my code and let me know how can I make it right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50540475

http://stackoverflow.com/comment/87880619
has text: Yes, I saw those. Ideally I would prefer to use only imageio, but if it does not have the features I look for I will use one of the other solutions mentioned there. I will wait a bit for other answers though.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50433100

http://stackoverflow.com/a/50469147
has body: You can avoid computing all pairwise distances by observing that the two points which are furthest apart will occur as vertices in the convex hull. You can then compute pairwise distances between fewer points. For example, with 100,000 points distributed uniformly in a unit square, there are only 22 points in the convex hull in my instance. import numpy as np from scipy import spatial # test points pts = np.random.rand(100_000, 2) # two points which are fruthest apart will occur as vertices of the convex hull candidates = pts[spatial.ConvexHull(pts).vertices] # get distances between each pair of candidate points dist_mat = spatial.distance_matrix(candidates, candidates) # get indices of candidates that are furthest apart i, j = np.unravel_index(dist_mat.argmax(), dist_mat.shape) print(candidates[i], candidates[j]) # e.g. [ 1.11251218e-03 5.49583204e-05] [ 0.99989971 0.99924638] If your data is 2-dimensional, you can compute the convex hull in O(N*log(N)) time where N is the number of points. By concentration of measure, this method deteriorates in performance for many common distributions as the number of dimensions grows.
answers question: http://stackoverflow.com/q/50468643
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50468643
score: 16
upvote count: 16

tensorflow
tags question: http://stackoverflow.com/q/50417166
tags question: http://stackoverflow.com/q/50493836
tags question: http://stackoverflow.com/q/50460475
tags question: http://stackoverflow.com/q/50437382
tags question: http://stackoverflow.com/q/50495878
tags question: http://stackoverflow.com/q/50492715
tags question: http://stackoverflow.com/q/50488410
type: Tag
tags question: http://stackoverflow.com/q/50506088
tags question: http://stackoverflow.com/q/50507571
tags question: http://stackoverflow.com/q/50467151
tags question: http://stackoverflow.com/q/50483577
tags question: http://stackoverflow.com/q/50533610
tags question: http://stackoverflow.com/q/50385660
tags question: http://stackoverflow.com/q/50537971
tags question: http://stackoverflow.com/q/50536721
tags question: http://stackoverflow.com/q/50417129
tags question: http://stackoverflow.com/q/50539213
tags question: http://stackoverflow.com/q/50436134
tags question: http://stackoverflow.com/q/50387465
tags question: http://stackoverflow.com/q/50479619
tags question: http://stackoverflow.com/q/50444920
tags question: http://stackoverflow.com/q/50435336
tags question: http://stackoverflow.com/q/50517334
tags question: http://stackoverflow.com/q/50474028
tags question: http://stackoverflow.com/q/50423095
tags question: http://stackoverflow.com/q/50477280
tags question: http://stackoverflow.com/q/50474336
tags question: http://stackoverflow.com/q/50524897
tags question: http://stackoverflow.com/q/50514298
tags question: http://stackoverflow.com/q/50451456
tags question: http://stackoverflow.com/q/50518758
tags question: http://stackoverflow.com/q/50472023
tags question: http://stackoverflow.com/q/50391080
tags question: http://stackoverflow.com/q/50470735
tags question: http://stackoverflow.com/q/50457863
tags question: http://stackoverflow.com/q/50452476
tags question: http://stackoverflow.com/q/50434183
tags question: http://stackoverflow.com/q/50477443
tags question: http://stackoverflow.com/q/50538822
tags question: http://stackoverflow.com/q/50518926
tags question: http://stackoverflow.com/q/50498755
tags question: http://stackoverflow.com/q/50426661
tags question: http://stackoverflow.com/q/50448897
tags question: http://stackoverflow.com/q/50484453
tags question: http://stackoverflow.com/q/50474674
tags question: http://stackoverflow.com/q/50445553
tags question: http://stackoverflow.com/q/50458964
tags question: http://stackoverflow.com/q/50434710
tags question: http://stackoverflow.com/q/50418963
tags question: http://stackoverflow.com/q/50518622
tags question: http://stackoverflow.com/q/50408243
tags question: http://stackoverflow.com/q/50448601
tags question: http://stackoverflow.com/q/50397321
tags question: http://stackoverflow.com/q/50470437
tags question: http://stackoverflow.com/q/50507165
tags question: http://stackoverflow.com/q/50449114
tags question: http://stackoverflow.com/q/50391464
tags question: http://stackoverflow.com/q/50456251
tags question: http://stackoverflow.com/q/50391357
tags question: http://stackoverflow.com/q/50503065
tags question: http://stackoverflow.com/q/50420359
tags question: http://stackoverflow.com/q/50428040
tags question: http://stackoverflow.com/q/50473474
tags question: http://stackoverflow.com/q/50420711
tags question: http://stackoverflow.com/q/50454806
tags question: http://stackoverflow.com/q/50448034
tags question: http://stackoverflow.com/q/50426462
tags question: http://stackoverflow.com/q/50431942
tags question: http://stackoverflow.com/q/50447649
tags question: http://stackoverflow.com/q/50425850
tags question: http://stackoverflow.com/q/50439395
tags question: http://stackoverflow.com/q/50387105
tags question: http://stackoverflow.com/q/50457247
tags question: http://stackoverflow.com/q/50483962
tags question: http://stackoverflow.com/q/50512019
tags question: http://stackoverflow.com/q/50433155
tags question: http://stackoverflow.com/q/50417709
tags question: http://stackoverflow.com/q/50447786
tags question: http://stackoverflow.com/q/50386210

http://stackoverflow.com/q/50448154
tagged with: pandas
downvote count: 2
answer count: 1
has body: I have 200 files in 2 parts. eg. (aapl-BAL-Q.csv and aapl-CAS-Q.csv) and I merged them to aapl-ALL.csv with pandas: import pandas as pd a = pd.read_csv('.../aapl-BAL-Q.csv') b = pd.read_csv('.../aapl-CAS-Q.csv') c = pd.concat([a,b], join='outer', axis=0, ignore_index=True, join_axes=None) c.to_csv('...aapl-ALL.csv', index=False) now I need to do it for the rest of files (eg. aa-BAL-Q.csv and aa-CAS-Q.csv) and so on.. I'm wondering how do that easiest way, instead of renaming filenames in code, tnx.
upvote count: 1
accepted answer: http://stackoverflow.com/a/50448429
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50448429
has title: Merge 2 csv files to one for multiple files
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
type: AnsweredQuestion

http://stackoverflow.com/comment/88057043
comment on: http://stackoverflow.com/q/50520683
score: 0
has text: Did you forget `del: True` in the first element of `d3`?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50432383
accepted answer of: http://stackoverflow.com/q/50432300
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50432300
has body: You have used m for both dict and also maths score. You can update your code to it and try this: print('welcome to the marklist of the students program') def student(dict1): for name,marks in dict1.items(): if marks&gt;60: print(f'student {name} has got a total of {marks} marks in exam and\n passed the exam with distinction ') elif marks&gt;40: print(f'student {name} has got a total of {marks} marks in exam and\n passed the exam with first class ') elif marks&gt;20: print(f'student {name} has got a total of {marks} marks in exam and\n passed the exam with second class ') else: print(f'student {name} has got a total of {marks} marks in exam and\n ha failed his exam ') m={} while True: student_name=input('enter student\'s name:') maths_score=int(input('enter students marks in maths:')) chemistry_score=int(input('enter student\'s marks in chemistry:')) physics_score=int(input('enter student\'s marks in physics:')) cs_score=int(input('enter student\'s marks in computer science:')) t=maths_score+chemistry_score+physics_score+cs_score m[student_name]=t b=input('want to add another students details?? enter yes or no:') if b=="yes": continue else: break student(m) And also: Use words for defining variables Output: welcome to the marklist of the students program enter student's name:hari enter students marks in maths:100 enter student's marks in chemistry:100 enter student's marks in physics:100 enter student's marks in computer science:100 want to add another students details?? enter yes or no:no student hari has got a total of 400 marks in exam and passed the exam with distinction

http://stackoverflow.com/q/50495686
type: AnsweredQuestion
has body: My while loop is not working. I am trying to have it check to see if the player is dead or the enemy and if so the fight is over. If they are alive then fight again until someone is dead. With my code now even if one or both are dead the fight still goes on. I tried to make then if else statement and still does the same thing. def fight(): Monster.reduce_health(Player.weapon) Monster_check_dead() Player.reduce_health(Monster.damage) Player_check_dead() while Monster_check_dead == True or Player_check_dead == True: print ("Your fight is over") break else: fight_again() Complete Code: import random import time class Player: def __init__(self, name, weapon, health, armor): self.name = name self.weapon = weapon self.health = health self.armor = armor def reduce_health(self): Player.health = Player.health - Monster.damage class Monster: def __init__(self, name, health, damage, armor): self.name = name self.health = health self.armor = armor self.damage = damage def reduce_health(self): Monster.health = Monster.health - Player.weapon def Monster_check_dead(): if Monster.health &lt; 1 == True : print(Monster.name, "has been killed") else: print (Monster.name, "current health: ", Monster.health) def Player_check_dead(): if Player.health &lt; 1 == True : print(Player.name, "You have died") else: print (Player.name, "current health: ", Player.health) def fight(): Monster.reduce_health(Player.weapon) Monster_check_dead() Player.reduce_health(Monster.damage) Player_check_dead() while Monster_check_dead == True or Player_check_dead == True: print ("Your fight is over") break else: fight_again() def fight_again(): if ask("Do you wish to attack again"): fight() else: print ("You have ran away") def ask(question): answer = input(question + " [Y/N]") return answer in ["y", "Y", "Yes", "YES", "yes"] print("Welcome to Nadia adventures the Nadia text adventure game!") if ask("Do you wish to play the game?"): print ("Lets the great adventure start!") Player.name = "Nadia" Player.health …
has comment: http://stackoverflow.com/comment/88004146
answer count: 1
has comment: http://stackoverflow.com/comment/88004217
has comment: http://stackoverflow.com/comment/88004158
has comment: http://stackoverflow.com/comment/88004457
has comment: http://stackoverflow.com/comment/88004611
score: -1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88004182
has comment: http://stackoverflow.com/comment/88004661
accepted answer: http://stackoverflow.com/a/50495779
has answer: http://stackoverflow.com/a/50495779
downvote count: 2
has comment: http://stackoverflow.com/comment/88004145
upvote count: 1
tagged with: python
has title: While loop not working - Text adventure python game

http://stackoverflow.com/comment/87900688
comment on: http://stackoverflow.com/q/50443357
type: QuestionComment
has text: Well, the tasks are highly related, so you can probably start from there and adapt the technique to your case.
type: Comment
score: 0

http://stackoverflow.com/comment/87970721
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50472531
type: AnswerComment
has text: @Hei Ah okay; I understand but I don't know Python as of yet... so my help is limited and stops there at C++ portion, but yes you need to fix the C++ compiler errors first. Oh and I made an edit to my post in the second class's definition for the function `blah` I added the `override` specifier. This is also useful when working with purely virtual classes, abstract classes and polymorphism.

http://stackoverflow.com/a/50394523
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50393802
type: Answer
has body: How about something like this? I'm assuming these are dictionaries you're looking at (that's what they look like). First, let keys be the set of keys you want to look for. Suppose D and E are the events you're looking at. found = False for k in keys: if D[k] == E[k]: keys2 = copy(keys) keys2.remove(k) for l in keys2: if D[l] == E[l]: found = True break if found: break There's probably a better "Python way" to do this but it's been a while and I don't have time to look it up. At least this works on examples I've tried. EDIT: Notice that if you only have those two keys you want to look for, you can discard both keys and the loop, and just test for them directly.
has comment: http://stackoverflow.com/comment/87806435
answers question: http://stackoverflow.com/q/50393802
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87805686

http://stackoverflow.com/q/50418926
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87854137
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/87854132
has answer: http://stackoverflow.com/a/50419141
has comment: http://stackoverflow.com/comment/87853610
tagged with: python
has comment: http://stackoverflow.com/comment/87853872
has title: python big integer multiplication doesn't calculate most significant digits
has comment: http://stackoverflow.com/comment/87853373
tagged with: biginteger
linked to: http://stackoverflow.com/q/3877765
has body: I have a python program which should multiply 2 big integers. The problem is I get a different result in java with BigInteger class with same input. I have tried DecInt library for python but gives the same answer as using pure python. Here are my variables: d = 372049305848826709205673800090501485720867768816 r = 5452188953055713107393819158892374332916586527736541041226026450382 Result I get in python from d * r: 2028483115341019294875069650745272851135156323450218238187883716036516369477015140871224045070868977706272670887712 Result I get in java with BigInteger class: 9530687378863294988874153740700860249994095546182028483115341019294875069650745272851135156323450218238187883716036516369477015140871224045070868977706272670887712 Here is my java code: BigInteger d = new BigInteger("372049305848826709205673800090501485720867768816"); BigInteger r = new BigInteger("5452188953055713107393819158892374332916586527736541041226026450382"); BigInteger tmp1 = d.multiply(r); System.out.println(tmp1); As you can see, there are some most significant digits that are missed in python's result. Is there any solution for that?
tagged with: java
tagged with: multiplication
has comment: http://stackoverflow.com/comment/87853454
has comment: http://stackoverflow.com/comment/87854086
answer count: 1
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/87853957

http://stackoverflow.com/q/50450622
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87915659
answer count: 1
has title: Urllib3 HTTP Error 502: Bad Gateway
tagged with: bad-gateway
type: Question
tagged with: urllib3
has comment: http://stackoverflow.com/comment/87915150
has body: I am trying to scrape zk.fm in order to download music, but it's giving me some trouble. I'm using urllib3 to generate a response, but this always yields a Bad Gateway error. Accessing the website through a browser works perfectly fine. This is my code (with a random fake user-agent). I'm trying to access "http://zk.fm/mp3/search?keywords=" followed by some keywords which indicate the song name and artist, for example "http://zk.fm/mp3/search?keywords=childish+gambino+heartbeat". from bs4 import BeautifulSoup from random import choice import urllib3 desktop_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'] def random_headers(): return {'User-Agent': choice(desktop_agents)} ua = random_headers() http = urllib3.PoolManager(10,headers=user_agent) response = http.request('GET',"http://zk.fm/mp3/search? keywords=childish+gambino+heartbeat") soup = BeautifulSoup(response.data) Is there a way to work …
tagged with: python
accepted answer: http://stackoverflow.com/a/50451358
linked to: http://stackoverflow.com/q/2422922
favorite count: 0
has answer: http://stackoverflow.com/a/50451358
has comment: http://stackoverflow.com/comment/87916559
score: 2
upvote count: 2

http://stackoverflow.com/comment/87957112
type: Comment
has text: oh that is cool, just out of curiosity, how would a vector operation work for a non-binary value, i.e. label can equal 0,1, or 2. Would it be like this: `((age_new <= 42) && (age_new > 7)).astype(int).tolist()`
type: AnswerComment
comment on: http://stackoverflow.com/a/50471539
score: 0

http://stackoverflow.com/comment/87972802
comment on: http://stackoverflow.com/q/50478410
type: QuestionComment
has text: Apologies. This was my first post and I think the font I used to copy paste from my word doc created this problem. Will take care. Thanks for showing interest. :)
type: Comment
score: 0

http://stackoverflow.com/comment/87898912
has text: yes, you need to. Also, please accept the answer, if it solves it.
type: Comment
comment on: http://stackoverflow.com/a/50404315
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87956229
type: AnswerComment
has text: one more question - how can I check if `scrapyd` is currently running or not, without accessing it in url?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50453629

http://stackoverflow.com/comment/87789528
type: AnswerComment
has text: This does the work. I wonder what am I doing wrong because I used `drop('A', axis=1)` . I thought it would delete column 'A'
comment on: http://stackoverflow.com/a/50386786
score: 1
type: Comment

http://stackoverflow.com/comment/87971832
type: Comment
type: QuestionComment
has text: @wim OK, that’s true; using `FunctionType` avoids people saying “Why don’t you just make a subclass”. So I guess it’s a tradeoff; to avoid one source of irrelevant answers and comments, you have to pick a different source of irrelevant answers and comments. (Although if PEP 575 goes through, you’ll need a different example anyway…)
score: 0
comment on: http://stackoverflow.com/q/50478162

http://stackoverflow.com/q/50441839
type: Question
tagged with: python-3.x
has body: i'm new to Python and working on my exercise. i have list of two columns, first column contains date value and second column contains numeric values. so i need to calculate how many months from the first column and sort the first column from oldest to newest date based on the date value. this is what i have so far: import os import csv source_csv = os.path.join("..","C:/Users/Desktop/","data.csv") with open(source_csv,newline="") as csvfile: csvreader = csv.reader(csvfile,delimiter=",") next(csvreader) # skip the headers sortedlist = sorted(csvreader, key=lambda row: row[0], reverse = True) print(sortedlist)
has title: Python - How to Count How Many Month of a List of Date Value
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50442102
upvote count: 0
has answer: http://stackoverflow.com/a/50442102
answer count: 1
has comment: http://stackoverflow.com/comment/87898103
downvote count: 1
has comment: http://stackoverflow.com/comment/87897840
favorite count: 0

http://stackoverflow.com/comment/87973313
type: Comment
type: QuestionComment
has text: Are those `https` sites, self singed ?
score: 0
comment on: http://stackoverflow.com/q/50479969

http://stackoverflow.com/comment/87970984
type: AnswerComment
has text: I found a different way to solve my Problem. Apparently it is not possibly to open my link in a new window/tab. The website is javascript generated and the link is in a dynamic javascript table. I think maybe the only way to have it open the link in a new window/tab, would be to send a javascript script.
score: 0
comment on: http://stackoverflow.com/a/50462811
type: Comment

http://stackoverflow.com/comment/87964249
type: Comment
type: QuestionComment
has text: then is there a way to have matplotlib convert epoch times to dates on the labels only so I could use epoch values for the graphing but have it display month values on the x axis?
comment on: http://stackoverflow.com/q/50474104
score: 0

http://stackoverflow.com/a/50449691
has body: EdChum's setup df = pd.DataFrame({'date':pd.to_datetime(['2018-05-20 10:20:00','2018-05-20 10:30:00'])}) df date 0 2018-05-20 10:20:00 1 2018-05-20 10:30:00 list and map list(map(str, df.date)) ['2018-05-20 10:20:00', '2018-05-20 10:30:00']
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50449453

http://stackoverflow.com/q/50497280
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/88014814
type: Question
has answer: http://stackoverflow.com/a/50497538
has comment: http://stackoverflow.com/comment/88040596
tagged with: memory-leaks
score: 1
has comment: http://stackoverflow.com/comment/88017237
tagged with: memory
has comment: http://stackoverflow.com/comment/88049441
favorite count: 0
has comment: http://stackoverflow.com/comment/104218115
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/104184953
has title: Python raspberry Pi timelapse memory leak?
downvote count: 0
has body: I am using my raspberry Pi3 to create timelapse videos. I have a cron that runs a python script every minute that decides how many photos to take and then imports a function from another python script that takes the actual photos. The problem is that after running for about 4 hours the camera stops taking photos- if I try and take one manually it says it is out of memory, and top confirms this. If I watch top while the timelapse is running the memory usage steadily climbs. I think I have narrowed the problem down to the python script that takes the photos. I can run this on its own, and if I start up the pi and run it a few times I see that the memory used climbs by about 10MB the first run and about 1MB every subsequent run (screenshot at the bottom of the post). This is the script import time import picamera import os def ShutterTS(dirname): with picamera.PiCamera() as cam: cam.resolution=(1920,1440) cam.rotation=180 cam.hflip=True # camera warm up time time.sleep(2) FNfmt = "%4d%02d%02d_%02d:%02d:%02d.JPG" Fname = FNfmt % time.localtime()[0:6] framename = os.path.join(dirname, Fname) cam.capture(framename) return def main(): dirname = [insert path here, my path hidden] ShutterTS(dirname) return if __name__ == '__main__': import sys sys.exit(main()) I'm not a good coder, I basically cobble stuff together from bits I find on the internet so I'm hoping this is something really simple that I've missed. The with is the raspberry pi recommended way of calling the camera. I know this should close the camera instance on exit but I'm guessing something is hanging around in memory? I tried adding close.cam() at the end of the function and it made no difference (didn't think it would). I've tried del on all the variables at the end of the function and it made no difference. I think the return at the end of the function is redundant but adding it made no difference. This website https://www.linuxatemyram.com/ suggests that top showing the memory climbing is normal and free -…
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50532291
has comment: http://stackoverflow.com/comment/88076842
answers question: http://stackoverflow.com/q/50531873
has body: You can use pd.DataFrame.applymap with your function. However, I suggest you refactor your logic to check for float first as, if your data is representative, many values are already in an acceptable format. Here's an example. def converter(num): try: return float(num) except ValueError: try: num = num.replace('-', '0.0').replace(',', '') return float(num) except ValueError: return np.nan cols = ['rpks', 'asks', 'pax'] df[cols] = df[cols].applymap(converter) print(df) rpks asks pax 0 9.74 194.72 1752.48 1 19.47 82.74 700.85 2 0.00 360.16 3679.45 3 127.03 994.14 7306.93 4 53.54 612.75 5770.53 5 0.00 7.02 666.43 6 34.52 197.28 784.19 7 0.00 460.31 5466.80 8 0.00 108.63 1128.90 9 0.00 16.54 913.49 10 10.52 368.06 3054.90 11 93.93 784.55 5646.55
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87929315
type: QuestionComment
comment on: http://stackoverflow.com/q/50424946
has text: Pylzma is a good suggestion
score: 0
type: Comment

http://stackoverflow.com/comment/87916171
has text: @TomDalton. No worries! I know that one of them is low- and high- because these are specific registers in the CPU. Basically, one register will always hold the low-part of the value and the other is always the high-part.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50451184
type: Comment

http://stackoverflow.com/a/50512137
type: Answer
upvote count: 4
has body: I pass the field names in a list to parse_dates when I invoke pd.read_sql with: df= pd.read_sql(query, connection, parse_dates=['Date_of_creation', 'Date_of_termination'] ) You mentioned doing it with a dictionary for custom formatting: fmt='%Y%m%d %H:%M:%S' df= pd.read_sql(query, connection, parse_dates={'Date_of_creation':fmt, 'Date_of_termination':fmt} )
downvote count: 0
answers question: http://stackoverflow.com/q/50510698
score: 4

http://stackoverflow.com/q/50470803
tagged with: numpy
has answer: http://stackoverflow.com/a/50670112
has answer: http://stackoverflow.com/a/56219542
upvote count: 8
linked to: http://stackoverflow.com/q/43877692
has answer: http://stackoverflow.com/a/76401131
tagged with: python
accepted answer: http://stackoverflow.com/a/50670112
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/52665628
answer count: 4
type: AnsweredQuestion
has body: I am trying upload my python code into AWS Lambda. I have been following this guide to create the deployment package (https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html). I have created a folder 'project-dir' on my desktop and moved my python file 'Twilio_Alerts_AWS.py' into the folder. I have used the command: pip install module-name -t /path/to/project-dir to install all my libraries into the folder. Next I highlighted everything and hit 'compress' by right clicking on the highlighted files in the folder. This produces one zipped file called 'archive' I put the 'archive.zip' in a S3 bucket on AWS and called it into AWS Lambda. I keep getting error Unable to import module 'Twilio_Alerts_AWS': Missing required dependencies ['numpy'] even though I have installed numpy into the folder. Not sure what I am doing wrong. Code I am trying to upload: from twilio.rest import Client import time import datetime import requests import pandas as pd from pandas.io.json import json_normalize def lambda_handler(event, context): # Your Account SID from twilio.com/console account_sid = "xxx" # Your Auth Token from twilio.com/console auth_token = "xxx" client = Client(account_sid, auth_token) current_datetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'x-api-key': 'xxx', 'x-organization-id': 'xxx', 'x-facility-id': 'xxx', 'x-user-id': 'xxx', } orders_staging_api_call = requests.get('URL', headers=headers, verify=False) consumers_staging_api_call = requests.get('URL', headers=headers, verify=False) inventory_staging_api_call = requests.get('URL', headers=headers, verify=False) lst = ["+1234567890"] ##Consumers API Alert if consumers_staging_api_call.status_code !=200: for i in lst: message = client.messages.create( to=i, from_="+1234567890", body="API connection between A and B has failed for: Consumers.Datetime of check:{}".format(current_datetime)) …
has title: Missing required dependencies ['numpy'] in AWS Lambda after installing numpy into directory, how to fix?
downvote count: 0
possible better answer: http://stackoverflow.com/a/52665628
score: 8
tagged with: aws-lambda
favorite count: 0
type: Question

http://stackoverflow.com/q/50511059
score: 1
has comment: http://stackoverflow.com/comment/88034643
answer count: 1
has comment: http://stackoverflow.com/comment/88034472
tagged with: google-chrome
linked to: http://stackoverflow.com/q/18483087
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: How to update Chrome browser using python on Windows?
has answer: http://stackoverflow.com/a/50511216
has body: I have written a python script to open few pages with chrome, but sometimes I have issue with compatibility with chrome driver and chrome browser. And I want to have updated version of both chrome browser and driver for my requirement. So is there a way I can update Chrome browser using python ? EDIT : I want it for Windows.

http://stackoverflow.com/comment/88007322
score: 0
comment on: http://stackoverflow.com/q/50497155
type: QuestionComment
type: Comment
has text: I assume you mean `pandas`, not `numpy` in your tags, right? Your dataframe looks like a `pandas` dataframe and not like a `numpy` array. Let me know if I'm wrong, I'll delete my answer

http://stackoverflow.com/q/50525864
upvote count: 1
accepted answer: http://stackoverflow.com/a/50525907
favorite count: 0
type: Question
has title: Create a binary matrix from 2 dataframe columns in Python
possible better answer: http://stackoverflow.com/a/50526200
has body: I need to create a binary matrix Example Data in a pandas DataFrame ID P 2 1 1 2 3 2 1 3 1 4 2 5 3 5 Using A = pd.DataFrame(index=df.ID.values, columns=df.P.values, data=(df.P.values == df.P.values[:,None]).astype(int)) My current output Which is correct in terms of where the '1's' hit, but I just want to have the column / row numbers consolidated and the row numbers in order as in: index 1 2 3 4 5 6 7 1 0 1 1 1 0 1 0 2 1 0 0 0 1 0 1 3 0 1 0 1 1 1 0 If that's not clear, feel free to question!
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50525907
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50526200
downvote count: 0
tagged with: pandas
tagged with: matrix
score: 1

django
tags question: http://stackoverflow.com/q/50394250
tags question: http://stackoverflow.com/q/50386926
tags question: http://stackoverflow.com/q/50505347
tags question: http://stackoverflow.com/q/50436341
tags question: http://stackoverflow.com/q/50434728
tags question: http://stackoverflow.com/q/50409054
tags question: http://stackoverflow.com/q/50396023
tags question: http://stackoverflow.com/q/50394650
tags question: http://stackoverflow.com/q/50523484
tags question: http://stackoverflow.com/q/50462306
tags question: http://stackoverflow.com/q/50417385
tags question: http://stackoverflow.com/q/50539695
tags question: http://stackoverflow.com/q/50431700
tags question: http://stackoverflow.com/q/50492626
tags question: http://stackoverflow.com/q/50510554
tags question: http://stackoverflow.com/q/50497871
tags question: http://stackoverflow.com/q/50401494
tags question: http://stackoverflow.com/q/50437355
tags question: http://stackoverflow.com/q/50418200
tags question: http://stackoverflow.com/q/50451570
tags question: http://stackoverflow.com/q/50464303
tags question: http://stackoverflow.com/q/50412539
tags question: http://stackoverflow.com/q/50473197
tags question: http://stackoverflow.com/q/50429243
tags question: http://stackoverflow.com/q/50487145
tags question: http://stackoverflow.com/q/50466289
tags question: http://stackoverflow.com/q/50423659
tags question: http://stackoverflow.com/q/50449103
tags question: http://stackoverflow.com/q/50474753
tags question: http://stackoverflow.com/q/50397954
tags question: http://stackoverflow.com/q/50419091
tags question: http://stackoverflow.com/q/50401550
tags question: http://stackoverflow.com/q/50492017
tags question: http://stackoverflow.com/q/50458956
tags question: http://stackoverflow.com/q/50501420
tags question: http://stackoverflow.com/q/50531619
tags question: http://stackoverflow.com/q/50430663
tags question: http://stackoverflow.com/q/50480583
tags question: http://stackoverflow.com/q/50493132
tags question: http://stackoverflow.com/q/50432712
tags question: http://stackoverflow.com/q/50498744
tags question: http://stackoverflow.com/q/50506516
tags question: http://stackoverflow.com/q/50502552
tags question: http://stackoverflow.com/q/50444879
tags question: http://stackoverflow.com/q/50534202
tags question: http://stackoverflow.com/q/50516006
tags question: http://stackoverflow.com/q/50413511
tags question: http://stackoverflow.com/q/50391047
tags question: http://stackoverflow.com/q/50436596
tags question: http://stackoverflow.com/q/50401385
tags question: http://stackoverflow.com/q/50490273
tags question: http://stackoverflow.com/q/50418451
tags question: http://stackoverflow.com/q/50468969
tags question: http://stackoverflow.com/q/50530059
tags question: http://stackoverflow.com/q/50502537
tags question: http://stackoverflow.com/q/50436833
tags question: http://stackoverflow.com/q/50502337
tags question: http://stackoverflow.com/q/50540770
tags question: http://stackoverflow.com/q/50471952
tags question: http://stackoverflow.com/q/50507550
tags question: http://stackoverflow.com/q/50481800
tags question: http://stackoverflow.com/q/50413481
tags question: http://stackoverflow.com/q/50450106
tags question: http://stackoverflow.com/q/50504567
tags question: http://stackoverflow.com/q/50390108
tags question: http://stackoverflow.com/q/50436151
tags question: http://stackoverflow.com/q/50407780
tags question: http://stackoverflow.com/q/50441663
tags question: http://stackoverflow.com/q/50493467
tags question: http://stackoverflow.com/q/50447987
tags question: http://stackoverflow.com/q/50422560
tags question: http://stackoverflow.com/q/50478708
tags question: http://stackoverflow.com/q/50494064
tags question: http://stackoverflow.com/q/50482507
tags question: http://stackoverflow.com/q/50413239
tags question: http://stackoverflow.com/q/50422261
tags question: http://stackoverflow.com/q/50426104
tags question: http://stackoverflow.com/q/50486478
tags question: http://stackoverflow.com/q/50479052
tags question: http://stackoverflow.com/q/50439624

http://stackoverflow.com/q/50488912
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87990971
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50488990
has title: Python List ONLY the variables I have created
upvote count: 1
tagged with: variables
has answer: http://stackoverflow.com/a/50488990
favorite count: 0
type: Question
has body: I have run my Python script that created 22 variables according to %whos IPython command. I want to be able to list MY variables from within a Python (not IPython) script. So far, I tried dir(), vars().keys(), locals().keys() and globals().keys() : In [2]: len( [v for v in dir() if not v.startswith('_')] ) Out[2]: 1015 In [3]: len( [v for v in vars().keys() if not v.startswith('_')] ) Out[3]: 1015 In [4]: len( [v for v in locals().keys() if not v.startswith('_')] ) Out[4]: 1015 In [5]: len( [v for v in globals().keys() if not v.startswith('_')] ) Out[5]: 1015 I ONLY want MY variables that I created, how can I do that ?
has comment: http://stackoverflow.com/comment/87990696
tagged with: python
has comment: http://stackoverflow.com/comment/87992360
has comment: http://stackoverflow.com/comment/87990790

http://stackoverflow.com/comment/87971647
type: QuestionComment
has text: The error is that `saver.restore(model_dir)` cannot find `model_dir` which is `dri//colab//mod//model.ckpt`. You can check the contents of this directory by executing say `!ls -l dri//colab//mod//` to make sure you model is there. You can get your model into the colab environment in various ways, e.g. checkout https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb. You can also mount your google drive on your local machine and read/write to it. See second answer in https://stackoverflow.com/questions/49675374/write-out-file-with-google-colab
comment on: http://stackoverflow.com/q/50469878
score: 0
type: Comment

http://stackoverflow.com/a/50492829
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88021011
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88001817
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50492652
has body: You need 2 extra commas: cur.execute("INSERT INTO tweet (textt) VALUES (%s)", (tweet,)) The first separates the query string from the arguments, the second turns the value in brackets into the first element in a 1 element tuple (it actually would work if you just used a single string instead of a tuple, assuming you only have one argument, but this isn't officially supported from the look of things). But this error that you mentioned in the comments: UnicodeEncodeError: 'latin-1' codec can't encode character '\u201c' in position 97: ordinal not in range(256) means you are trying to interpret unicode text containing a character from the extended character set into latin-1. If the field is already internally defined (in your mysql database) as unicode, you may need to specify the character set to use when connecting e.g.: conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='admin1234', db='mysql', use_unicode=True, charset="utf8") If the field in mysql is not already something like utf-8 then I recommend you alter or otherwise redefine the database to use a unicode character se tfor this column. https://dev.mysql.com/doc/refman/8.0/en/charset-mysql.html
answers question: http://stackoverflow.com/q/50492652
type: Answer

http://stackoverflow.com/q/50422261
has title: Recommended way to find the source of a query when using Django?
has comment: http://stackoverflow.com/comment/87860170
type: Question
upvote count: 9
type: AnsweredQuestion
tagged with: sql
has comment: http://stackoverflow.com/comment/87917673
accepted answer: http://stackoverflow.com/a/50452057
has body: I'm having difficulties with locating the source of the queries which I see in my database logs. I'm using Django, so the actual queries are generated automatically which makes a simple "grep" ineffective. I'm thinking of patching the database cursors to append the current stacktrace to the query, something like: for conn in connections.all(): with conn.cursor() as c: ctype = type(c.cursor) orig_execute = ctype.execute def _patchedExecute(self, query, params=None): query = query + ' -- ' + traceback.format_stack() return orig_execute(self, query, params) ctype.execute = _patchedExecute orig_execute_many = ctype.executemany def _patchedExecuteMany(self, query, params=None): query = query + ' -- ' + traceback.format_stack() return orig_execute_many(self, query, params) ctype.executemany = _patchedExecuteMany What I'm wondering: is there a ready made solution for this? (seems like a somewhat common problem to have) if not, are there better solutions than the one presented above? (I'm not all that familiar with the Django internals) Edit: thank you for everyone who suggested Django Debug Toolbar. I'm already aware of that (and similar tools like Django Silk) and already using it, however in this particular case I'm more interested in the reverse problem. That is: starting from the database where I see that a particular kind of query is executed frequently or that it takes a long time and I would like to know where in my Django application am I generating those queries?
favorite count: 0
has answer: http://stackoverflow.com/a/50452057
score: 9
downvote count: 0
tagged with: django
tagged with: python
answer count: 1

http://stackoverflow.com/a/75766163
score: 0
type: Answer
has body: I had this issue and had to post my answer, for all the long and way too complicated responses. If you have pyninstaller (or don't), activate your conda environment conda activate "envName" You can get your environment name in many ways, an easy one is just opening Anaconda (the UI) > Environment (on the left) and your enviornment name is listed in the middle column right next to where you clicked. Pip install pyinstaller. If you have it, the first like will be like "Requirement already satisfied: pyinstaller in [Path]" If you don't have it installed, it will simply install it and the same logic applies, take the path from there. Make sure it says ":pyinstaller in" then copy that path. To run pyinstaller from your conda environment: python [Full library path\pyinstaller] –onefile [your script] The idea is it needs the main function NOT pyinstaller.py so don't bother looking for that specifically. Hope this helps.
answers question: http://stackoverflow.com/q/50411931

http://stackoverflow.com/comment/87959218
has text: What does the error say? You should always post the error
type: Comment
comment on: http://stackoverflow.com/a/50472474
score: 0
type: AnswerComment

http://stackoverflow.com/q/50420401
tagged with: django-tables2
favorite count: 0
type: Question
has title: can i make a two dimensional table in django-tables2?
has answer: http://stackoverflow.com/a/50464548
has body: Edited: Hi guys, I have been looking for a solution to my problem for some days without an answer I am trying to make a two-dimensional table with data obtained from the same model. The idea is to list the students in rows, the data in columns and the status in their respective cells, a two dimensional table. class DailyAttendanceStudent(models.Model): ATTENDANCE_CHOICES = ( (None,''), (True,'Presente'), (False, 'Ausente') ) date = models.DateField(default=datetime.datetime.now) status = models.NullBooleanField(choices=ATTENDANCE_CHOICES) student = models.ForeignKey('perfiles.Student') These are my table: class StudentAttendanceTable(tables.Table): nombres = tables.Column('nombres', accessor='Student.first_name') apellidos = tables.Column('apellidos', accessor='Student.last_name') date = tables.Column('fecha', accessor='date')#LinkColumn status = tables.Column('status', accessor='status') class Meta: model = DailyAttendanceStudent fields = ('nombres', 'apellidos', 'date', 'status') graphically this is what I want to do:
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: html-table
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/50464548
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50539618
has body: i want to use fabric control my remote host i want to fabric input shell command line to Code branch example： the shell code: root@debian:~# cd /root the fabric: con.run('cd /root') i want input shell code like this : root@debian:~# cd \ root@debian:~# /root how can i write my fabric code i have a shell command with a long parameter， so i need to code branch
answer count: 1
downvote count: 3
tagged with: shell
upvote count: 1
accepted answer: http://stackoverflow.com/a/50539630
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/952914
has title: python fabric how to input \ into code branch
has answer: http://stackoverflow.com/a/50539630
duplicate of: http://stackoverflow.com/q/952914
score: -2
tagged with: fabric
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50397694
has body: You can try so: df['desc_L1'] = df['desc_L0'] df['desc_L1'] = np.where(df['L0'].isna(), df['desc_L0'], np.NaN) df['desc_L0'] = np.where(df['L0'].isna(), np.NaN, df['desc_L0']) Input: L0 desc_L0 0 10.0 hi 1 NaN I am 2 20.0 Here 3 NaN where are u? Output: L0 desc_L0 desc_L1 0 10.0 hi NaN 1 NaN NaN I am 2 20.0 Here NaN 3 NaN NaN where are u?
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50397060

http://stackoverflow.com/q/50425700
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/87867627
type: UnansweredQuestion
has title: image preprocessing error in tensorflow
has comment: http://stackoverflow.com/comment/87867334
tagged with: python
tagged with: image
score: 0
has body: I have input function that reads all lines from the filename argument. Then it applies parser function to each line. Every line in my .csv file is as following: "path_to_img, label_num". Here is the code: def input_fn(filename): def parser(column): d = tf.decode_csv(column, record_defaults=[[''], [-1]]) img, label = d img = tf.read_file(img) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize_images(img, (300, 200)) img = tf.cast(img, tf.float32) return {'image': img}, label dataset = tf.data.TextLineDataset(filename).map(parser) dataset = dataset.repeat(None).shuffle(5000).batch(500) return dataset.make_one_shot_iterator().get_next() Then I create classifier and train: feat_cols = [tf.feature_column.numeric_column('image', shape=(300, 200))] model = tf.estimator.DNNClassifier([4028, 1024, 512], feature_columns=feat_cols, model_dir=OUTDIR, n_classes=5) model.train(input_fn=lambda: input_fn('data.csv'), steps=1000) But eventually I'm getting an error relate to decode operation and still can't understand what's wrong tensorflow.python.framework.errors_impl.InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with '\"\"\"\n flickr.p' [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=3, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false](ReadFile)]] [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[?,300,200,1], [?]], output_types=[DT_FLOAT, DT_INT32], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator)]]
answer count: 0
has comment: http://stackoverflow.com/comment/87884477
tagged with: image-processing
tagged with: machine-learning

http://stackoverflow.com/q/50452608
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87922160
has answer: http://stackoverflow.com/a/50462811
has comment: http://stackoverflow.com/comment/87918677
has comment: http://stackoverflow.com/comment/87918424
score: 0
answer count: 2
tagged with: selenium
has body: I am currently trying to crawl a website using selenium. I have a table with elements and I want to click on each element, open the link in a new window/tab, process this window/tab, close it and click on the next element etc. So far I can click on the elements of the table, open the link and process the page. Unfortunately I can not open the link in a new window or tab. I can not send keyboard commands to the elements. I have also tried action = ActionChains(self.driver) action.move_to_element(ele)\ .key_down(Keys.SHIFT)\ .click(ele)\ .key_up(Keys.SHIFT)\ .perform() This somehow does only open the link in the current window (I dont't get a new window handle, still just one). I would be very grateful for any help. Edit: Also I am not able to open the link in a new window/tab manually with the browser.
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/87919132
has title: Selenium not able to open new Window/Tab
has comment: http://stackoverflow.com/comment/87919601
type: Question
has answer: http://stackoverflow.com/a/65288497

http://stackoverflow.com/comment/88053403
score: 0
has text: 1) you have no customise code in rc.local to run your script. 2) rc.local does get run upon boot, it just not log to your log file, check `/var/log/boot.log`, you will see the log about IP address upon boot.
comment on: http://stackoverflow.com/q/50495330
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87833647
type: Comment
type: QuestionComment
has text: Description: Ubuntu 16.04.4 LTS
score: 0
comment on: http://stackoverflow.com/q/50408845

http://stackoverflow.com/q/50539030
score: 1
has body: Setup I am running on windows 10 Have python 3.6 and Java 8 description I have a Java program which calls and passes an argument to a python program and then receives its output using system commands and cmd. Question How do I convert it into a single exe file that is the user can run it without installing java(jdk or jre) and python. Both are a part of my system variable Thank you
tagged with: executable-jar
has comment: http://stackoverflow.com/comment/88089968
tagged with: integration
has answer: http://stackoverflow.com/a/50548694
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88089934
has answer: http://stackoverflow.com/a/50539385
tagged with: java
has title: Converting a jar file to exe file
tagged with: python
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/a/51987141
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/50441453
downvote count: 0
has body: Preface My solution was tested for correctness. I need to be able to search on a list of objects and that is the solution that worked for me. However, my solution was not tested for performance, nor do I care about it since my data sets are rather small. For large datasets I strongly recommend using a 3rd party tool, probably some cloud based search tool will be scalable and with reasonable performance. Solution fuzzywuzzy process.extract apparently can handle a dictionary where only values are being searched and the result is a list of tuples with the following structure (query, score, key) Where query and score are the same as using extract with lists and key is the key that matched the string value (values must still be strings only). So, you will need to create a processed issuer names dictionary with keys as indexes like so issuer_names_dict = dict(enumerate([issuer.name for issuer in issuers])) Then you can pass this dictionary to process.extract (I think you should use extractBests since you are using a cutoff threshold) best_issuers = process.extractBests(word, issuer_names_dict, score_cutoff=threshold, limit=5) Finally you will need to assemble the result list res = [issuers[z] for (x,y,z) in best_issuers]
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50441453

http://stackoverflow.com/comment/88103173
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50455643
has text: After a few days of research, I decided to not modify `m1` and instead use `np.linalg.pinv()` to calculate the Moore-Penrose Pseudoinverse of `m1`, which doesn't require a non-singular matrix and mathematically allows me to find `m2`. I'm validating your answer as it can prove useful in some other cases ; and it also helped me with understanding why it didn't work quite well. Thanks for helping !

http://stackoverflow.com/q/50514409
has comment: http://stackoverflow.com/comment/88041544
tagged with: pandas
has comment: http://stackoverflow.com/comment/88041528
score: 1
answer count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has title: Convert list of strings into pandas DataFrame based on values in string
has comment: http://stackoverflow.com/comment/88041450
has comment: http://stackoverflow.com/comment/88041414
has comment: http://stackoverflow.com/comment/88041458
has body: I have a list of strings like the following: input = ["number__128_alg__hello_min_n__7_max_n__9_full_seq__True_random_color__False_shuffle_shapes__False.pkl", "k__9_window__10_number__128_overlap__True_alg__hi_min_n__7_max_n__9_full_seq_embedding__False_random_color__False_shuffle_shapes__False.pkl", "k__9_window__10_number__128_overlap__True_alg__what_random_color__False_shuffle_shapes__False.pkl"] The format of these strings is parameter name followed by "__", then parameter value. After the parameter value, there is a _ before the next parameter name. It is worth noting that some parameter names contain _ in them (such as "random_shape". Each string has different parameters, but there is overlap. Therefore, I would like to make a data frame with each parameter name as a column, and each row being the values corresponding to each element of the input list. If the particular value in the list does not have a parameter, the data frame should contain NA or NaN or anything. How can this be done? Thanks! EDIT: If it cannot be done for the original list, what about: input = ["number__128_alg__hello_min.n__7_max.n__9_full.seq__True_random.color__False_shuffle.shapes__False.pkl", "k__9_window__10_number__128_overlap__True_alg__hi_min.n__7_max.n__9_full.seq__False_random.color__False_shuffle.shapes__False.pkl", "k__9_window__10_number__128_overlap__True_alg__what_random.color__False_shuffle.shapes__False.pkl"]
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/88041632
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50514913
accepted answer: http://stackoverflow.com/a/50514913

http://stackoverflow.com/q/50533079
has comment: http://stackoverflow.com/comment/88078345
accepted answer: http://stackoverflow.com/a/50533689
favorite count: 0
has comment: http://stackoverflow.com/comment/88078672
type: AnsweredQuestion
has title: How to properly access a StringVar() of a class from another class - Python - tkinter
has body: (I'm using mac 10.8.5 and Python3 with PyCharm) I have a tkinter GUI TestMain() class plus one PageOne() class and a PageTwo() class. I need PageOne() and PageTwo() to be different GUI windows cause they will handle different data. I minimized the code in order to set it as readable as possible. After many tests I tried to place the tk.StringVar() and a simple function in the global scope as you can see below, but there's still a problem. import tkinter as tk page1_label = tk.StringVar() page2_entry = tk.StringVar() def set_ebdata(): data = page2_entry.get() page1_label.set(data) class TestMain(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, 'TEST GUI') container = tk.Frame(self) container.pack(side='top') container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame frame.configure(background='lightgrey') frame.grid(row=0, column=0, sticky='nswe') self.show_frame(PageOne) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) frame_eb_data = tk.Frame(self, width=100, height=100, bg="orange", colormap="new") frame_eb_data.grid(row=0, column=0, sticky='w', padx=5, pady=5) frame_but_right = tk.Frame(self, width=240, height=60, bg="yellow", colormap="new") frame_but_right.grid(row=0, column=1, padx=5, pady=5, rowspan=2) lab_eb_data = tk.Label(frame_eb_data, background='#DDD4EF', textvariable=page1_label) lab_eb_data.grid(row=0, column=0, sticky='n') b_ebdata = tk.Button(frame_but_right, text="Page 2", width=10, height=2, command=lambda: controller.show_frame(PageTwo)) b_ebdata.grid(row=3, column=0) class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) frame_buttons = tk.Frame(self, width=455, bg="#DDD4EF", colormap="new") frame_buttons.grid(row=…
tagged with: python
has answer: http://stackoverflow.com/a/50533689
linked to: http://stackoverflow.com/q/33646605
has comment: http://stackoverflow.com/comment/88078453
type: Question
tagged with: python-3.x
tagged with: tkinter
duplicate of: http://stackoverflow.com/q/33646605
upvote count: 0
score: -2
downvote count: 2
answer count: 1

http://stackoverflow.com/q/50445608
has comment: http://stackoverflow.com/comment/87905313
has answer: http://stackoverflow.com/a/50445946
duplicate of: http://stackoverflow.com/q/23852480
has title: Why do changes to a nested dict inside dict2 affect dict1?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50445973
has comment: http://stackoverflow.com/comment/87905260
has comment: http://stackoverflow.com/comment/87905085
type: Question
tagged with: mutability
has comment: http://stackoverflow.com/comment/87905499
answer count: 3
has comment: http://stackoverflow.com/comment/87905512
has answer: http://stackoverflow.com/a/50446296
score: 7
downvote count: 3
linked to: http://stackoverflow.com/q/2465921
tagged with: nested
tagged with: python
tagged with: dictionary
upvote count: 10
has body: I don't understand these cases: content = {'a': {'v': 1}, 'b': {'v': 2}} d1 = {'k1': {}} d2 = {'k2': {}} d1['k1'].update(content) print(d1) content['a']['v'] = 3 content['b']['v'] = 4 d2['k2'].update(content) print(d2) print(d1) &gt;&gt;&gt; {'k1': {'a': {'v': 1}, 'b': {'v': 2}}} &gt;&gt;&gt; {'k2': {'a': {'v': 3}, 'b': {'v': 4}}} &gt;&gt;&gt; {'k1': {'a': {'v': 3}, 'b': {'v': 4}}} In the case above the content of d1 is changed after the variable content is updated. content = {'a': 1, 'b': 2} d1 = {'k1': {}} d2 = {'k2': {}} d1['k1'].update(content) print(d1) content['a'] = 3 content['b'] = 4 d2['k2'].update(content) print(d2) print(d1) &gt;&gt;&gt; {'k1': {'a': 1, 'b': 2}} &gt;&gt;&gt; {'k2': {'a': 3, 'b': 4}} &gt;&gt;&gt; {'k1': {'a': 1, 'b': 2}} However in this case d1 is not altered even if the variable content was changed. I don't understand why... any idea?
linked to: http://stackoverflow.com/q/23852480
favorite count: 0
has comment: http://stackoverflow.com/comment/87905605

http://stackoverflow.com/q/50526926
tagged with: awk
has comment: http://stackoverflow.com/comment/88068064
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50541103
accepted answer: http://stackoverflow.com/a/50541103
tagged with: sed
possible better answer: http://stackoverflow.com/a/50527146
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88067227
has comment: http://stackoverflow.com/comment/88065479
has title: Best expression using Regex for extracting Email-Preference from large text files
type: AnsweredQuestion
score: 0
has body: Currently I am trying to parse a large text file with mixed content. However am interested in filtering only lines which satisfy this requirement. Email-Preference I am able to find the regex for email however the preceding ":" followed by preference in text is currently my challenge. Single character matching with "?" doesnt help much though. Any suggestions on this would be much appreciated. Sample from text source: Warning: You are using an old IOS image for this router. Sending 5, 100-byte ICMP Echos to abacus, timeout is 2 seconds: Sending 5, 100-byte ICMP Echos to abacus, timeout is 2 seconds: timeout xlate 3:00:00 timeout conn 1:00:00 half-closed 0:10:00 udp 0:02:00 icmp 0:00:02 timeout sunrpc 0:10:00 h323 0:05:00 h225 1:00:00 mgcp 0:05:00 mgcp-pat 0:05:00 timeout sip 0:30:00 sip_media 0:02:00 sip-invite 0:03:00 sip-disconnect 0:02:00 timeout sip-provisional-media 0:02:00 uauth 0:05:00 absolute timeout tcp-proxy-reassembly 0:01:00 myemail@gmail.com-prefmenuonly timeout floating-conn 0:00:00 destination address http https://tools.cisco.com/its/service/oddce/services/DDCEService Cryptochecksum:checksum : end Sending 5, 100-byte ICMP Echos to abacus, timeout is 2 seconds: Sending 5, 100-byte ICMP Echos to abacus, timeout is 2 seconds: secondmail@gmail.com-selectedprefonly Output should be : myemail@gmail.com-prefmenuonly secondmail@mail.com-selectedprefonly
answer count: 2
tagged with: bash
upvote count: 1
has answer: http://stackoverflow.com/a/50527146

http://stackoverflow.com/comment/87796196
comment on: http://stackoverflow.com/a/50389960
type: Comment
has text: I'm using Python 3.6.5 on windows 10 and chrom-driver version is 2.38 and chrome version is 66
score: 0
type: AnswerComment

http://stackoverflow.com/q/50440568
tagged with: http://stackoverflow.com/tag/html
tagged with: selenium
has comment: http://stackoverflow.com/comment/87898595
downvote count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/44724185
has answer: http://stackoverflow.com/a/50442913
type: Question
has answer: http://stackoverflow.com/a/50441483
has title: Python selenium "Not Clickable at point error."
answer count: 2
upvote count: 1
tagged with: python
type: UnansweredQuestion
has body: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC import os Game_Pin = input('Enter your PIN: ') NickNAME = input('Enter your nickname: ') driver = webdriver.Chrome(executable_path=r"C:\WebDriver\bin\chromedriver.exe") def Enter_Press(driver): driver.find_element_by_xpath("//*[contains(text(), 'Enter')]").click() def OK_GO(driver): driver.find_element_by_xpath("//*[@class='btn btn-greyscale join ng-binding']").click() def Kahoot_Spammer(Game_Pin, NickNAME, driver): driver.get('https://kahoot.it/') driver.maximize_window() #For maximizing window driver.implicitly_wait(2) #gives an implicit wait for 2 seconds game_pin = driver.find_element_by_xpath("//*[@id='inputSession']") game_pin.send_keys(Game_Pin) Enter_Press(driver) driver.implicitly_wait(2) Name = driver.find_element_by_xpath("//*[@id='username']") Name.send_keys(NickNAME) OK_GO(driver) Kahoot_Spammer(Game_Pin, NickNAME, driver) The program works fine until you get to a certain point. Then selenium cannot click a button. It gives me this error. selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (1279, 741). Other element would receive the click: ... Here is the code for the button I am trying to click. OK, go!
score: 0
has comment: http://stackoverflow.com/comment/87899157

http://stackoverflow.com/q/50489552
score: 1
has title: Path name format - Windows - Python
possible better answer: http://stackoverflow.com/a/50489884
tagged with: python
has answer: http://stackoverflow.com/a/50489884
has comment: http://stackoverflow.com/comment/88001690
type: Question
has body: I am working on a code that takes the path of a file and the reads it. The code is, import sys import os user_input = input("Enter the path of your file: ") assert os.path.exists(user_input), "I did not find the file at, "+str(user_input) However, I am on a Windows machine in which, the path names come with a \, like, C:\your\path\and\file.xlsx Each time I enter the file name to the prompt, I need to manually replace all \ with / and then run the code. Is there a solution such that I enter C:\your\path\and\file.xlsx but the code takes it as, C:/your/path/and/file.xlsx Regards.
answer count: 2
has comment: http://stackoverflow.com/comment/87992797
downvote count: 0
has comment: http://stackoverflow.com/comment/87992688
accepted answer: http://stackoverflow.com/a/50489964
upvote count: 1
has comment: http://stackoverflow.com/comment/87998926
has answer: http://stackoverflow.com/a/50489964
has comment: http://stackoverflow.com/comment/87991989
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/88074507
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50531183
has text: Possible duplicate of [How do I connect to a MySQL Database in Python?](https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python)

http://stackoverflow.com/q/50432745
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87879844
has comment: http://stackoverflow.com/comment/87879887
has comment: http://stackoverflow.com/comment/87879736
type: Question
has comment: http://stackoverflow.com/comment/87880685
upvote count: 2
score: 0
linked to: http://stackoverflow.com/q/61106297
duplicate of: http://stackoverflow.com/q/59977052
downvote count: 2
answer count: 0
has body: I'm trying to make a game using pygame module I've already imported my pictures and can move the helicopter but I'm not able to shoot. The commented lines are the things that I've done so far for the shooting part. When pressing the button for shooting, nothing happens. It seems that the code does not run for the second if statement and I don't know the reason. Thank you for your help! import pygame white=(255,255,255) black=(0,0,0) pygame.init() surface = pygame.display.set_mode((1000,1000)) pygame.display.set_caption("AI Game") clock = pygame.time.Clock() def helicopter(x , y, image): surface.blit(helicopterPicture ,(x,y)) def bulletshape(x, y, image): surface.blit(bulletPicture ,(x,y)) bullets=[] helicopterPicture = pygame.image.load('helicoptter.png') bulletPicture = pygame.image.load('bullet.png') x_helicopter= 150 y_helicopter= 200 x_bullet= 260 y_bullet= 240 y_move = 0 x_move = 0 y_bullet_move = 0 x_bullet_move = 0 Game_Over=False def GameOver(): pygame.quit() quit() while not Game_Over: for event in pygame.event.get(): if (event.type == pygame.QUIT): Game_Over=True if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_UP): y_move = -5 x_move = 0 y_bullet_move = -5 x_bullet_move = 0 if (event.type == pygame.KEYDOWN): if(event.key == pygame.K_SPACE): y_bullet_move = -20 x_bullet_move = 0 if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_DOWN): y_move = 5 x_move = 0 # y_bullet_move = 5 # x_bullet_move = 0 # if (event.key == pygame.K_KP_ENTER): # y_bullet_move = 10 # x_bullet_move = 0 if(event.type == pygame.KEYDOWN): if(event.key == pygame.K_RIGHT): x_move = 5 y_move = 0 x_bullet_move = 5 y_bullet_move = 0 #if(event.key == pygame.K_KP_ENTER): # x_bullet_move = 10 # y_bullet_move = 0 if(event.type == pygame.KEYDOWN): if(event.key == pygame.K_LEFT): x_move = -5 y_move = 0 # x_bullet_move = -5 # y_bullet_move = 0 # if(event.key == pygame.K_KP_ENTER): # x_bullet_move = -100 # y_bullet_move = 0 y_helicopter+=y_move x_helicopter+=x_move x_bullet+=x_…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87880847
has title: Shooting helicopter in pygame
duplicate of: http://stackoverflow.com/q/61106297
linked to: http://stackoverflow.com/q/45665784
has comment: http://stackoverflow.com/comment/87880534
has comment: http://stackoverflow.com/comment/87880915
has comment: http://stackoverflow.com/comment/87880776
has comment: http://stackoverflow.com/comment/87879848
tagged with: python
tagged with: pygame

http://stackoverflow.com/q/50448377
downvote count: 1
has title: Almost the same duplicates but only different in length
has comment: http://stackoverflow.com/comment/87912574
favorite count: 0
has comment: http://stackoverflow.com/comment/87912438
type: Question
has answer: http://stackoverflow.com/a/50449182
has answer: http://stackoverflow.com/a/50450218
has comment: http://stackoverflow.com/comment/87912662
has body: I want to do remove the almost the same duplicates, but only keep the longest one. I am thinking first comparing the first word or first few word to filter out the candidate for comparison. Then compare the length of the remaining elements. If it is the longest, I will write it into a new text file. Here is the test file https://drive.google.com/file/d/1tdewlNtIqBMaldgrUr02kbCKDyndXbSQ/view?usp=sharing Input I am Harry. I am Harry. I like I am Harry. I like to eat apple. I am Garry. I am Garry. I am Hap I am Garry. I am Happy. Output I am Harry. I like to eat apple. I am Garry. I am Happy. I am doing it with Python, but the thing just won't work. Code f1 = open('a.txt','r') # Read from file ListofLine = f1.readlines() # Read the line into list f2 = open('n.txt','w') # Open new file to write # Iterate all the sentences to compare for x in len(ListofLine): # Comparing first word of the sentences if(ListofLine[x].split()[0] = ListofLine[x+1].split()[0]): # Comparing the length and keep the longest length sentences if(len(ListofLine[x])&gt;len(ListofLine[x+1])): f2.write(ListofLine[x]) f1.close() f2.close()
tagged with: duplicates
tagged with: python
has comment: http://stackoverflow.com/comment/87912682
has comment: http://stackoverflow.com/comment/87912738
tagged with: text
accepted answer: http://stackoverflow.com/a/50449182
score: 2
has comment: http://stackoverflow.com/comment/87912727
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/50449455
answer count: 3
has answer: http://stackoverflow.com/a/50449455

http://stackoverflow.com/q/50457475
has comment: http://stackoverflow.com/comment/87929512
linked to: http://stackoverflow.com/q/40877516
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/26140428
tagged with: python
score: 0
tagged with: python-import
answer count: 0
tagged with: pyqt
has body: I would like to use this line QtGui.QFileDialog.getOpenFileName(self) to open a file dialogue such as this post but from PyQt5 rather than PyQt4. My import statement currently is from PyQt5 import QtCore, QtWidgets, uic, QtGui. What am I doing wrong? Traceback (most recent call last): File "H:/4-Programming/OpenTester/OpenTester.py", line 136, in MenuNew fileToOpen = QtGui.QFileDialog.getOpenFileName(self) AttributeError: module 'PyQt5.QtGui' has no attribute 'QFileDialog'
tagged with: pyqt5
upvote count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/46554746
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87928874
has comment: http://stackoverflow.com/comment/87928748
has title: How to open a file browser dialog with PyQt5

http://stackoverflow.com/comment/87801525
comment on: http://stackoverflow.com/q/50392879
score: 2
type: Comment
has text: Doesn't seem overkill to me. That's the point of a library
type: QuestionComment

http://stackoverflow.com/q/50401977
tagged with: python
has title: How can I scrape jquery code with python 3.6?
has answer: http://stackoverflow.com/a/50402316
has body: I need help, I want to scrape this site. I was using BeautifulSoup and requests but I can't get the value from the picture. import requests from bs4 import BeautifulSoup my_url = 'https://partneredge.sap.com/content/partnerfinder/search.html#/' page = requests.get(my_url) page_soup = BeautifulSoup(page.content, "lxml") trazenje = page_soup.find_all('header.search-result__head') print(trazenje) I get empty list as result and no error! Link to site
score: 0
has comment: http://stackoverflow.com/comment/87819826
upvote count: 1
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python-requests
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87820491
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87819701
type: Question
has comment: http://stackoverflow.com/comment/87820004
has comment: http://stackoverflow.com/comment/87820072

http://stackoverflow.com/a/61860268
score: 0
has body: You can use the built-in magic %%bash as first line in your cell: %%bash python script1.py &amp; python script2.py &amp;
answers question: http://stackoverflow.com/q/50467077
type: Answer

http://stackoverflow.com/q/50425064
upvote count: 2
score: 2
tagged with: stream
downvote count: 0
has body: I would like to be able to capture a video stream in Python from a internet address. For my example I am streaming from VLC to this node.js app via http: https://github.com/sinclairzx81/vlc.web.stream And then this node app exposes this live stream to localhost:5000/stream. Now I would like to capture this stream and show it realtime using opencv for instance.
favorite count: 0
type: Question
tagged with: video-streaming
type: UnansweredQuestion
tagged with: python
tagged with: node.js
has title: Capture video stream in python
answer count: 0

http://stackoverflow.com/q/50419778
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87857722
tagged with: scipy
tagged with: sparse-matrix
type: Question
has comment: http://stackoverflow.com/comment/87855375
has answer: http://stackoverflow.com/a/50425139
has body: What is a good way of identifying the unique columns of a sparse matrix represented in csc_matrix format and the times each column is repeated? I have no information a priori about the elements of the matrix. It is the result of a sampling with replacement of the columns of another matrix, so I can have duplicated columns both due to the fact that a column is sampled many times either there are duplicated columns in the original matrix. Therefore I cannot apply numpy.unique to the indices of the sampled columns and I think it is not a good choice to convert the entire matrix to a dense format and then apply numpy.unique to it.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87861624
has title: Unique column of a sparse matrix in Python

http://stackoverflow.com/q/50485154
downvote count: 2
has answer: http://stackoverflow.com/a/50485323
has comment: http://stackoverflow.com/comment/87983409
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50485364
has answer: http://stackoverflow.com/a/50485307
possible better answer: http://stackoverflow.com/a/50485307
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/50485323
has body: My regex is horrendous. I have list items that look like this device = ['1U1abc'] device = ['18U12def'] I want to split the item out that it will look like this device = ['1','U1','abc'] device = ['18','U12','def'] So i have an entry for the first number in the string, the code with a letter and number, and the second code containing all letters. Is regex a good method to get this?
tagged with: regex
has comment: http://stackoverflow.com/comment/87983435
answer count: 3
has title: Regex in a python script
upvote count: 1

aws-cli
tags question: http://stackoverflow.com/q/50392646
tag name: aws-cli
type: Tag
tags question: http://stackoverflow.com/q/50416093

http://stackoverflow.com/a/50521011
answers question: http://stackoverflow.com/q/50520215
type: Answer
score: 0
has body: It is also possible to just select the right values from np.eye or the identity matrix: a = np.array([1,3,2]) b = np.eye(max(a))[a-1] This would probably be the most straight forward.

http://stackoverflow.com/q/50421457
tagged with: mysql
has body: Having issues with inserting pandas dataframe to MySQL db.Have listed the sample data and code used along with errors that follow. How to insert data with pandas dataframe to mysql? Packages used Pandas - 0.22.0 sqlalchemy - 1.2.1 Dataframe used: Out[135]: P_ID S_ID Action Timestamp \ 0 Harold 1 Extensions 2017-11-07 03:17:27.342295+00:00 1 Harold 1 Extensions 2017-11-07 03:17:27.447234+00:00 2 Harold 1 Extensions 2017-11-07 03:17:27.552406+00:00 3 Harold 1 Extensions 2017-11-07 03:17:27.657676+00:00 4 Harold 1 Extensions 2017-11-07 03:17:27.762737+00:00 Value 0 -0.096083 1 -0.003894 2 -0.004779 3 0.131210 4 0.161990 dtypes : P_ID object S_ID int64 Action object Timestamp datetime64[ns, UTC] Value float64 dtype: object The following code snippets were used with the errors followed Also pd.to_datetime() did not seem to have any effect. Code used (1) without index engine = create_engine('mysql+pymysql://xxxx:3306/xxxx') test.to_sql(name='table1', con=engine, if_exists = 'append',index=False) conn.close() Error : ValueError: Cannot cast DatetimeIndex to dtype datetime64[us] Code used (2) with timestamp column indexed engine = create_engine('mysql+pymysql://xxxx:3306/xxxx') test.to_sql(name='table1', con=engine, if_exists = 'append',index=True, index_label='Timestamp', dtype={'Timestamp':typeTIMESTAMP(timezone=True)}) conn.close() Error : ValueError: duplicate name in index/columns: cannot insert Timestamp, already exists
possible better answer: http://stackoverflow.com/a/50459595
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53682848
upvote count: 2
has answer: http://stackoverflow.com/a/77920199
has title: issues with pandas dataframe insert to mysql with timestamp
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50459595
accepted answer: http://stackoverflow.com/a/50505361
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50505361
tagged with: pandas
score: 2
downvote count: 0

http://stackoverflow.com/q/50440889
has comment: http://stackoverflow.com/comment/87928683
has comment: http://stackoverflow.com/comment/87923231
has body: I have the python interpreter location in my path environment variable so that I don't need to explicitly call the python interpreter from the command line. However, when I use the argparse module to read command line arguments, it only works if I explicitly call the python interpreter. import argparse parser = argparse.ArgumentParser() parser.add_argument('w') cmd_args = parser.parse_args() print(cmd_args.w) when I don't explicitly call the interpreter, this occurs: C:\Users\nheme\Desktop&gt; command_line_parse.py test_argument usage: command_line_parse.py [-h] w command_line_parse.py: error: the following arguments are required: w When I explicitly call the interpreter, the code works as expected: C:\Users\nheme\Desktop&gt; python command_line_parse.py test_argument test_argument Why do I need to explicitly call the interpreter?
favorite count: 0
tagged with: command-line
type: Question
has comment: http://stackoverflow.com/comment/87896405
has comment: http://stackoverflow.com/comment/87923308
has title: Why does argparse only work if the python interpreter is called explicitly?
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87927373
score: 3
answer count: 0
tagged with: argparse
upvote count: 3
tagged with: windows

http://stackoverflow.com/comment/87867837
comment on: http://stackoverflow.com/q/50426050
has text: Et[i,j] = (E1[i,j]**2+E2[i,j]**2)**(0.5) needs to be indented by one. otherwise it will only update after each j loop is completed.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/50440821
type: Answer
has body: First, you need to know that over-fitting is a low loss function on the training set, but a high loss function on the test set. Second, you need to know if MSE is a loss function you use or an evaluation indicator for your regression task. I think you may have drawn a curve for the evaluation indicator here. You should actually look at the curve for the loss function. Finally, with regard to the selection of activation functions, the upper floor is quite right. It would be nice to use a linear activation function.
score: 1
has comment: http://stackoverflow.com/comment/87896080
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50440696
has comment: http://stackoverflow.com/comment/87901498

http://stackoverflow.com/q/50527404
score: 1
upvote count: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88066292
has comment: http://stackoverflow.com/comment/88067193
has comment: http://stackoverflow.com/comment/88067058
has body: I'm getting the following error:- AttributeError: PageOne instance has no attribute 'scann' I'm trying to run a bash script (runfocus). Still not being able to figure out why I'm getting this error. My code is as follow:- class PageOne(tk.Frame): def __init__(self, parent, controller): running = False # Global flag tk.Frame.__init__(self, parent) self.controller = controller button = tk.Button(self, text="Go to the start page", command=lambda: controller.show_frame("StartPage")) strt = tk.Button(self, text="Start Scan", command=self.start) stp = tk.Button(self, text="Stop", command=self.stop) button.pack() strt.pack() stp.pack() self.after(1000, self.scann) # After 1 second, call scanning def scann(self): if running: sub.call(['./runfocus'], shell=True) self.after(1000, self.scann) def start(self): """Enable scanning by setting the global flag to True.""" global running running = True def stop(self): """Stop scanning by setting the global flag to False.""" global running running = False Please provide your valuable suggestions.
has comment: http://stackoverflow.com/comment/88067362
favorite count: 0
has comment: http://stackoverflow.com/comment/88066675
type: Question
has answer: http://stackoverflow.com/a/50528104
accepted answer: http://stackoverflow.com/a/50528104
tagged with: attributeerror
has title: Python AttributeError instance has no attribute
tagged with: python
has comment: http://stackoverflow.com/comment/88066376
has comment: http://stackoverflow.com/comment/88069231
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88066291
has comment: http://stackoverflow.com/comment/88067167

http://stackoverflow.com/q/50470997
score: 0
tagged with: lxml
answer count: 1
tagged with: elementtree
has body: I am attempting to parse Open XML from a Microsoft Word document. However, whenever i go to look at any tag or attribute i receive the tag i want, preceded by the openxmlformats namespace. Examples below. Does anybody know how i can remove this, and only receive my tag id and value? Current format: for content in root.iter(): print(content.tag) returns: '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tag' and for content in root.iter('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tag'): print(content.attrib) returns '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': 'Orange' Desired Output: for content in root.iter(): print(content.tag) returns tag and for content in root.iter('tag'): print(content.attrib) returns val : 'Orange'
type: Question
has comment: http://stackoverflow.com/comment/87955621
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50471355
has title: OpenXML Tag Formatting
tagged with: python
tagged with: openxml

http://stackoverflow.com/comment/87845628
comment on: http://stackoverflow.com/a/50414875
type: AnswerComment
has text: I think this is the better answer. (Well, I think you should use `pd.get_dummies`, but asides from that, this is the better answer.)
score: 1
type: Comment

http://stackoverflow.com/a/50479526
has comment: http://stackoverflow.com/comment/87973302
has comment: http://stackoverflow.com/comment/87973168
type: Answer
score: -1
upvote count: 0
has body: one way to do it is the set_xticklabels function, though Mr. T's answer is the proper way to go ax = plt.subplot(111) df["msft"].plot(grid = True) ax.set_xticklabels(df['date']) plt.xticks(np.arange(4)) with the data provided:
downvote count: 1
answers question: http://stackoverflow.com/q/50479425

http://stackoverflow.com/a/50425021
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87931060
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50424151
upvote count: 1
answers question: http://stackoverflow.com/q/50424151
has body: It seems, your problem is that you mix numpy arrays with a scalar math function. Don't do this. Substitute it with the appropriate numpy function: import numpy as np import matplotlib.pyplot as plt r = 50 V = np.linspace(0,10,r) print(V) def current(): current = [] for t in V: i = np.zeros(r) Ipv = 3 Rs = 0.221 Rsh = 415 n = 2 m = 1.5 T = 302 Eg = 1.14 K = 1.3 Vt = T/11600 Io = K*(T**m)*np.exp(-Eg/(n*Vt)) i = Ipv - Io *(np.exp((t + Rs*i)/(n*Vt)) - 1) - (t + Rs * i)/Rsh current.append(i) return np.array(current) Icurrent = current() plt.plot(V,Icurrent) plt.show() Output: I would have suggested using scipy.fsolve, but seemingly your approach is working.

http://stackoverflow.com/q/50506667
upvote count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/88026009
favorite count: 0
type: Question
has body: I get the bellow error when I query my instances: (1052, "Column 'name' in field list is ambiguous") If I use: http://localhost:8000/api/physicalserver/list/?switchesport__id=5 I can get the right results. but if I use: http://localhost:8000/api/physicalserver/list/?switchesport__bandwidth=10 I will get the error. My list API view is bellow: class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [AllowAny] filters = {'{}__contains'.format(key): value for key, value in query_params.items()} return PhysicalServer.objects.filter(**filters) How can I use the switchesport__bandwidth as the query param?
has title: (1052, "Column 'name' in field list is ambiguous")
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88026241
type: UnansweredQuestion
downvote count: 0
tagged with: django
score: 1

http://stackoverflow.com/q/50431138
upvote count: 2
downvote count: 0
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/50571605
type: AnsweredQuestion
has title: how to make objects move smoothly tkinter
has answer: http://stackoverflow.com/a/50571605
possible better answer: http://stackoverflow.com/a/50431299
has answer: http://stackoverflow.com/a/50431299
has comment: http://stackoverflow.com/comment/87876736
has body: When you press a button to move the "tank", it starts, but then it stops and starts again. Any way to make it not do that? from tkinter import * from tkinter.constants import LEFT root = Tk() c = Canvas(root, width=400, height=400) tank = c.create_rectangle(200,200,250, 250, outline = 'dark green', fill='dark green') c.pack() class Tank: def move_left(self): c.move(tank, -5, 0) def move_right(self): c.move(tank, 5,0) def move_up(self): c.move(tank, 0, -5) def move_down(self): c.move(tank, 0, 5) c.bind('&lt;Left&gt;', Tank.move_left) c.bind('&lt;Right&gt;', Tank.move_right) c.bind('&lt;Up&gt;', Tank.move_up) c.bind('&lt;Down&gt;', Tank.move_down) c.focus_set() root.mainloop()
type: Question
tagged with: tkinter
answer count: 2
has comment: http://stackoverflow.com/comment/87876907
score: 2

http://stackoverflow.com/a/50391388
has comment: http://stackoverflow.com/comment/87799228
has comment: http://stackoverflow.com/comment/87799120
score: 1
answers question: http://stackoverflow.com/q/50391156
has body: Your SomAprilMay has 13 elements so I added one. Here is a one liner: SomAprilMay=[0,0,0,1,0,1,2,3,4,5,15,12,14,1] XposMay=[[50,51,52,53,54,55,56,57,58,59,60,61,62,63], [50,51,52,53,54,55,56,57,58,59,60,61,62,63], [50,51,52,53,54,55,56,57,58,59,60,61,62,63]] mask = [e &lt; 3 for e in SomAprilMay] Xpos1May = [[0 if mask[i] else item for i, item in enumerate(sub) ] for sub in XposMay]
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/87964523
comment on: http://stackoverflow.com/a/50475273
score: 1
type: Comment
type: AnswerComment
has text: For the purpose of iterating over the keys, calling `keys()` is not even necessary.

http://stackoverflow.com/a/50482909
has body: I believe need change: moving_avg = pd.rolling_mean(ts_log,12) to: moving_avg = ts_log.rolling(12).mean() because old pandas version code below pandas 0.18.0
answers question: http://stackoverflow.com/q/50482884
has comment: http://stackoverflow.com/comment/112482162
upvote count: 120
score: 120
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50482884
downvote count: 0
type: Answer

http://stackoverflow.com/q/50443955
tagged with: selenium
has title: How to load extension within chrome driver in selenium with python
tagged with: google-chrome
has body: All my efforts to open chrome browser with Browsec extension enabled are failing. Here is what i tried in last - # Configure the necessary command-line option. options = webdriver.ChromeOptions() options.add_argument(r'--load- extension=C:\Users\lap0042\AppData\Local\Google\Chrome\User Data\Default\Extensions\omghfjlpggmjjaagoclmmobgdodcjboh') # Initalize the driver with the appropriate options. driver = webdriver.Chrome(chrome_options=options) driver.get("http://stackoverflow.com") This results in error "Failed to load extension from . Manifest files is missing or unreadable" After search for this error I get that Manifest.json file should be renamed to manifest.json.txt but doing this resulted in same error. Any help will be highly appreciated
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/34222412
has answer: http://stackoverflow.com/a/78525782
has answer: http://stackoverflow.com/a/66217641
linked to: http://stackoverflow.com/q/59954995
type: UnansweredQuestion
tagged with: python
answer count: 6
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/56276541
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/72419897
linked to: http://stackoverflow.com/q/54754945
downvote count: 0
tagged with: google-chrome-extension
has answer: http://stackoverflow.com/a/50446602
has answer: http://stackoverflow.com/a/50444048

http://stackoverflow.com/a/50431094
answers question: http://stackoverflow.com/q/50402092
has body: Turns out I was using the wrong Visual C++ prompt, changing to the correct one solved the problem
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50402092
type: AcceptedAnswer

http://stackoverflow.com/q/50440987
downvote count: 0
favorite count: 0
tagged with: multiprocessing
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50441472
has comment: http://stackoverflow.com/comment/87929804
has body: Running the below code and then doing Ctrl+C can leave p1, p2, p3 and p4 running in the background (where Ctrl+C does nothing). How to use KeyboardInterrupt from the main process such that it also stops all child processes? import time from multiprocessing import Process def process(proc_n): while True: try: pass except KeyboardInterrupt: break except Exception as e: print(e) time.sleep(0.5) def main(): p1 = Process(target=process, args=(1,)) p2 = Process(target=process, args=(2,)) p3 = Process(target=process, args=(3,)) p4 = Process(target=process, args=(4,)) p1.start() p2.start() p3.start() p4.start() if __name__ == '__main__': main()
tagged with: python
accepted answer: http://stackoverflow.com/a/50458435
tagged with: python-multiprocessing
type: AnsweredQuestion
has title: How to use KeyboardInterrupt from the main process to stop child processes?
has answer: http://stackoverflow.com/a/50458435
answer count: 2
has answer: http://stackoverflow.com/a/50441472
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87896573
tagged with: signals

http://stackoverflow.com/a/50445009
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50444958
score: 2
has body: Validated_data doesn't contain first_name data directly. It's included into nested user dictionary. So you should first get user data in create method: def create(self, validated_data): user_data = validated_data.pop('user') first_name = user_data.pop('first_name') user = User.objects.create_user(username='test', first_name=first_name, last_name='test') app_user = AppUser.objects.create(**validated_data, user=user) return app_user
answers question: http://stackoverflow.com/q/50444958

http://stackoverflow.com/comment/87921331
has text: So you want us to solve your school assignment?
type: Comment
comment on: http://stackoverflow.com/q/50453982
type: QuestionComment
score: 0

http://stackoverflow.com/q/50475815
favorite count: 0
has comment: http://stackoverflow.com/comment/87967290
tagged with: python-3.x
has body: I am trying to generate the result from given JSON data and it's generating some partial result. The JSON data is preformatted to understand and dictionary consist of key-value pair most of it. My code is running and but don't understand how to get a particular value to print from the dictionary. Given JSON data : { "aggregates": [{ "services_count": 9, "service_name": "S3", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 0.3200019691, "ytd_spends": 0.3200019691, "account_id": "136981853693" }, { "services_count": 5, "service_name": "RDS", "business_unit": "Customer Service", "last_month_costs": 0, "total_cost": 297.6462777693, "ytd_spends": 297.6462777693, "account_id": "136981853693" }, { "services_count": 38, "service_name": "EBS", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 49.7080945265006, "ytd_spends": 49.7080945265006, "account_id": "136981853693" }, { "services_count": 3, "service_name": "ELB", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 1.5519276537, "ytd_spends": 1.5519276537, "account_id": "136981853693" }, { "services_count": 22, "service_name": "EC2", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 442.70678455851, "ytd_spends": 442.70678455851, "account_id": "136981853678" } ] } My code is: Note - at the beginning of the program pass row = JSON data as it is. from itertools import groupby def format_account_details(rows): result = {} total_accounts = 0 total_account_cost = 0 for k,v in groupby(rows,key=lambda x:x["account_id"]): result[k] = {} for k2,v2 in groupby(v,key=lambda x:x["business_unit"]): result[k][k2] = list(v2) for k3 in result[k][k2]: total_account_cost = total_account_cost + k3['total_cost'] resp = [] resp.append('total_accounts:{}'.format(len(result.keys()))) resp.append('total_cost:{}'.format(total_account_cost)) for k,v in result.items(): for k2,v2 in v.items(): resp.append({'account_id':k,'business_unit':k2,'top_utilized':v2}) return resp result.update(resp) pri…
has title: dictionary generation using list
has comment: http://stackoverflow.com/comment/87965264
tagged with: python
type: Question
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/88077923
score: 0
comment on: http://stackoverflow.com/q/50531940
type: Comment
type: QuestionComment
has text: You know your algorithm best. How would you assert that your answers are correct? Hint: you can pick known input and output values across a range and assert your code honours those. This is why even simple programs should have functions that can be fed data from the calling application.

http://stackoverflow.com/q/50540460
tagged with: python-3.x
answer count: 2
has body: I have a file .txt that contains a specific line, like this file.txt . . T - Python and Matplotlib Essentials for Scientists and Engineers . A - Wood, M.A. . . . I would like to extract lines that contain a string, I tried with a simple script: with open('file.txt','r') as f: for line in f: if "T - " in line: o_t = line.rstrip('\n') elif "A - " in line: o_a = line.rstrip('\n') o_T = o_t.split('T - ') print (o_T) o_A = o_a.split('A - ') #o_Fname = #o_Lname = print (o_A) my output: ['', 'Python and Matplotlib Essentials for Scientists and Engineers'] ['', 'Wood, M.A.'] and my desired output: Python and Matplotlib Essentials for Scientists and Engineers Wood, M.A. moreover, for the second ("Wood, M.A.") can I also extract the last name and first name. So the final results will be: Python and Matplotlib Essentials for Scientists and Engineers Wood M.A.
possible better answer: http://stackoverflow.com/a/50540543
has comment: http://stackoverflow.com/comment/88092430
tagged with: python
upvote count: 1
has answer: http://stackoverflow.com/a/50540543
downvote count: 1
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88092371
accepted answer: http://stackoverflow.com/a/50541050
has comment: http://stackoverflow.com/comment/88092414
has answer: http://stackoverflow.com/a/50541050
has title: How to read the line that contains a string then extract this line without this string
has comment: http://stackoverflow.com/comment/88092356
favorite count: 0
type: Question

http://stackoverflow.com/a/50518393
upvote count: 6
type: AcceptedAnswer
downvote count: 0
score: 6
has body: The other answers are right about the basic facts: Everything, including functions, is an object, and can be assigned to a variable. But def is a statement, not an expression, so it doesn't have the function value, it has no value at all. But def isn't the only way to define functions in Python. There's also lambda.1 Which is an expression, and has the function value as a value. Because it's an expression, its body has to be an expression, which can only contain other expressions, and it returns the value of that expression. But in your example, that isn't a limitation; your whole function body is just returning an expression. So: add = lambda a, b: a+b This is considered bad style in Python. The whole point of lambda is (a) it doesn't give the function a name, and (b) it can be used inside an expression. That's great if you're just writing a throwaway callback for, e.g., a GUI button—but here, the only thing we're doing with it here is using it in an assignment expression to give it a name. In other words, this is just a less-clear version of: def add(a, b): return a+b That already does exactly what you want: defines a function, and assigns it to the variable name add in the current namespace. Plus, the def version gives you better introspection/reflection capabilities (e.g., add.__name__ will be add instead of something useless like __main__.&lt;lambda&gt;). And, because it's a statement, you can put complex statements inside the body. And, since add is just a normal variable name, and the function is just a normal value, of course you can also do this: def _add(a, b): return a+b add = _add del _add … but again, there's no point; it's just a less clear and more verbose version of def add (and with the wrong __name__ and possibly other attributes). 1. For completeness, there's also a third way: you can use the types.FunctionType constructor, giving it a code object representing the compiled body, a globals environment, and optionally some other stuff like default v…
accepted answer of: http://stackoverflow.com/q/50518218
type: Answer
answers question: http://stackoverflow.com/q/50518218

http://stackoverflow.com/q/50390301
tagged with: django
tagged with: python
has title: Django queryset: Build a dictionary from a queryset, with common elements
tagged with: django-queryset
score: 0
answer count: 1
tagged with: loops
type: Question
has body: I'm trying to construct a dictionary from my database, that will separate my data into values with common time stamps. data_point: time: &lt;timestamp&gt; value: integer I have 66k data points, out of which around 7k share timestamps (meaning the measurement was taken at the same time. I need to make a dict that would look like: { "data_array": [ { "time": "2018-05-11T10:34:43.826Z", "values": [ 13560465, 87856595, 78629348 ] }, { "time": "2018-05-11T10:34:43.882Z", "values": [ 13560689, 78237945, 92378456 ] } ] } There are other keys in the dictionary, but I'm just having a bit of a struggle with this particular key. The idea is, look at my data queryset, and group up objects that share a timestamp, then add a key "time" to my dict, with the value being the timestamp, and an array "values" with the value being a list of those data.value objects I'm not experienced enough to build this without looping a lot and probably being very innefficient. Some kind of "while timestamp doesn't change: append value to list", though I'm not sure how to go about that either. Ideally, if I can do this with queries (should be faster, right?) I would prefer that.
has answer: http://stackoverflow.com/a/50390541
type: UnansweredQuestion

http://stackoverflow.com/q/50448857
has comment: http://stackoverflow.com/comment/87911076
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/14571099
has comment: http://stackoverflow.com/comment/87911053
duplicate of: http://stackoverflow.com/q/14571099
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87910949
has title: Assert that all values are negative or all values are non-negative
has answer: http://stackoverflow.com/a/50448974
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has body: I need to assert that all numeric values in an array are either negative or non-negative. I wrote this: def check(arr): return all([i &lt; 0 for i in arr]) or all([i &gt;= 0 for i in arr]) And this, which is slightly more efficient I suppose: def check(arr): temp = [i &lt; 0 for i in arr] return all(temp) or not any(temp) I would like to know if there's a cleaner / more pythonic way, or perhaps some arithmetic trick which I can use instead.

http://stackoverflow.com/a/50496477
score: 30
has comment: http://stackoverflow.com/comment/88006186
upvote count: 30
type: Answer
has body: In [17]: df[df.index.get_level_values('time') &gt; 1] Out[17]: val id time 1 2 3 2 2 4 @piRSquared's solution is more idiomatic though...
downvote count: 0
has comment: http://stackoverflow.com/comment/114013428
answers question: http://stackoverflow.com/q/50496433

http://stackoverflow.com/a/50542015
has comment: http://stackoverflow.com/comment/88109682
has comment: http://stackoverflow.com/comment/88124015
type: Answer
accepted answer of: http://stackoverflow.com/q/50539213
has comment: http://stackoverflow.com/comment/88146718
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88116303
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50539213
has body: I've found a related issue on github, and it seems that tf.metrics are still not supported by Keras models. However, in case you are very interested in using tf.metrics.specificity_at_sensitivity, I would suggest the following workaround (inspired by BogdanRuzh's solution): def specificity_at_sensitivity(sensitivity, **kwargs): def metric(labels, predictions): # any tensorflow metric value, update_op = tf.metrics.specificity_at_sensitivity(labels, predictions, sensitivity, **kwargs) # find all variables created for this metric metric_vars = [i for i in tf.local_variables() if 'specificity_at_sensitivity' in i.name.split('/')[2]] # Add metric variables to GLOBAL_VARIABLES collection. # They will be initialized for new session. for v in metric_vars: tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, v) # force to update metric values with tf.control_dependencies([update_op]): value = tf.identity(value) return value return metric model.compile(loss='mean_squared_error', optimizer='sgd', metrics=[metrics.mae, metrics.categorical_accuracy, specificity_at_sensitivity(0.5)]) UPDATE: You can use model.evaluate to retrieve the metrics after training.

vlookup
tag name: vlookup
tags question: http://stackoverflow.com/q/50501829
type: Tag

http://stackoverflow.com/comment/88085780
type: Comment
has text: `print("{}{}".format('B', row))`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50536494

http://stackoverflow.com/comment/87822065
type: AnswerComment
has text: @OlivierMelançon. Thanks for the catch. Time to get some sleep :)
comment on: http://stackoverflow.com/a/50403209
score: 1
type: Comment

http://stackoverflow.com/q/50504523
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88032068
answer count: 1
tagged with: javascript
tagged with: flask
has title: Dynamically change image source in Flask
type: Question
score: 0
has body: I am using Flask to make a small face detection app. I want to achieve when faces are detected, they will be updated in the HTML page. In javascript part, I am using getUserMedia to stream camera images from the client to a server. In Flask part, I receive images and process them using this function: @app.route('/image.jpeg', methods=['POST']) def on_image_captured(): data = request.data image_file = request.files['image'] image = Image.open(image_file) image = np.array(image) image = image[..., :3] # faces is a list of detected faces (a list of numpy array) faces = system.detect_faces(image) return '' My HTML has two things to render: first one is the streamed video, the other is the detected faces. My question is, how do I send the detected faces (the faces variable) to HTML so that it will render variable numbers of faces on the page dynamically?
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/52095229
has comment: http://stackoverflow.com/comment/88022361
has comment: http://stackoverflow.com/comment/88033219

http://stackoverflow.com/a/50420595
type: Answer
score: 0
has body: If you are interested in calculating the number of 1's in the list, there is an easier way using list comprehensions: n_ones = sum([num == 1 for num in rolled_dice]) Then, you can decide how to perform the score based on the number of ones. Thus, you could imagine restructuring your code in this way instead of looping through rolled_dice. As for getting situations where the score is incremented when there's no 1, it doesn't look like this happens. If we modify your code to include a return statement def dices(): score1 = 0 a = 0 score_total1 = 0 score_total2 = 0 dice1 = randint(1, 6) dice2 = randint(1, 6) dice3 = randint(1, 6) dice4 = randint(1, 6) dice5 = randint(1, 6) dice6 = randint(1, 6) rolled_dice = [dice1, dice2, dice3, dice4, dice5, dice6] for number in rolled_dice: if number == 1: score_total1 += number if score_total1 == 1: score1 += 100 elif score_total1 == 2: score1 += 200 elif score_total1 == 3: score1 += 300 elif score_total1 == 4: score1 += 1000 return rolled_dice, score1 Then, the following code never prints anything for i in range(1000): rolled_dice, score1 = dices() # Check if the score is nonzero when there is a 1 in rolled_dice if not (1 in rolled_dice) and score != 0: print(rolled_dice, score1) Indicating that the described situation never happens.
answers question: http://stackoverflow.com/q/50420528

http://stackoverflow.com/comment/88155934
type: QuestionComment
has text: Use the variable `self.input_imgs` only for the tf.placeholders. Dont use the same tensor variable for other ops.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50539277

http://stackoverflow.com/q/50494385
has comment: http://stackoverflow.com/comment/88001697
has title: Why am I getting a KeyError after reading values from .txt file?
tagged with: keyerror
type: Question
has answer: http://stackoverflow.com/a/50494579
tagged with: degrees
score: 0
has comment: http://stackoverflow.com/comment/88001945
type: UnansweredQuestion
answer count: 1
tagged with: vertex
tagged with: python
has comment: http://stackoverflow.com/comment/88001791
has body: So I'm trying to change an already-working program to read from a .txt file, but I only see a KeyError. #V = ([1,2,3,4,5]) #E = ([(1,2),(1,3),(2,3),(3,5),(5,4)]) import ast with open('v.txt') as V: A = ast.literal_eval(V.read()) with open('e.txt') as E: B = ast.literal_eval(E.read()) print(A) print(B) indegree = {} outdegree = {} for x in A: indegree[x] = 0 outdegree[x] = 0 for x,y in B: outdegree[x] += 1 indegree[y] += 1 for x in A: print("Outdegree for vertex", x,"=", outdegree[x]) print("Indegree for vertex", x,"=", indegree[x]) The output is: [(1, 2, 3, 4, 5)] [(1, 2), (1, 3), (2, 3), (3, 5), (5, 4)] line 21, in outdegree[x] += 1 KeyError: 1 When I run it with values from #V and #E and the beginning of the code, it runs completely fine.

http://stackoverflow.com/comment/88028719
type: AnswerComment
comment on: http://stackoverflow.com/a/50502699
score: 0
type: Comment
has text: oh i meant, it was just in case there was some major tweak that made it work for you that was not in the solution. yes, your edits made it clearer.

http://stackoverflow.com/q/50458964
upvote count: 1
has answer: http://stackoverflow.com/a/60822677
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has title: Changing optimizer or lr after loading model yields strange results
has answer: http://stackoverflow.com/a/50811220
answer count: 2
linked to: http://stackoverflow.com/q/47523841
type: UnansweredQuestion
has body: I'm using the latest Keras with Tensorflow backend (Python 3.6) I'm loading a model that had a training accuracy at around 86% when I last trained it. The orginal optimizer that I used was : r_optimizer = optimizer=Adam(lr=0.0001, decay = .02) model.compile(optimizer= r_optimizer, loss='categorical_crossentropy', metrics = ['accuracy']) If I load the model and continue training without recompiling, my accuracy would stay around 86% (even after 10 or so more epochs). So I wanted to try changing the learning rate or optimizer. If I recompile the model and try to change the learning rate or the optimizer as follows: new_optimizer = optimizer=Adam(lr=0.001, decay = .02) or to this one: sgd = optimizers.SGD(lr= .0001) and then compile: model.compile(optimizer= new_optimizer , loss='categorical_crossentropy', metrics = ['accuracy']) model.fit .... The accuracy would reset to around 15% - 20%, instead of starting around 86%, and my loss would be much higher. Even if I used a small learning rate, and recompiled, I would still start off from a very low accuracy. From browsing the internet it seems some optimizers like ADAM or RMSPROP have a problem with resetting weights after recompiling (can't find the link at the moment) So I did some digging and tried to reset my optimizer without recompiling as follows: model = load_model(load_path) sgd = optimizers.SGD(lr=1.0) # very high for testing model.optimizer = sgd #change optimizer #fit for training history =model.fit_generator( train_gen, steps_per_epoch = r_steps_per_epoch, epochs = r_epochs, validation_data=valid_gen, validation_steps= np.ceil(len(valid_gen.filenames)/r_batch_size), callbacks = callbacks, shuffle= True, verbose = 1) However, these changes don't seem to be reflected in my training. Despite raising the lr significantly, I'm still floundering around 86% with the same loss. During each epoch, I'm seeing very little loss or accuracy movement. I would expect the loss to be a lot more volatile. This leads me to bel…
tagged with: neural-network
tagged with: python
tagged with: deep-learning
downvote count: 0
score: 1

linux
tags question: http://stackoverflow.com/q/50490018
tags question: http://stackoverflow.com/q/50515109
tags question: http://stackoverflow.com/q/50537131
tags question: http://stackoverflow.com/q/50437484
tags question: http://stackoverflow.com/q/50442675
tags question: http://stackoverflow.com/q/50519802
tag name: linux
tags question: http://stackoverflow.com/q/50406598
tags question: http://stackoverflow.com/q/50404731
tags question: http://stackoverflow.com/q/50433301
tags question: http://stackoverflow.com/q/50470014
tags question: http://stackoverflow.com/q/50395613
tags question: http://stackoverflow.com/q/50507807
tags question: http://stackoverflow.com/q/50540709
tags question: http://stackoverflow.com/q/50393741
tags question: http://stackoverflow.com/q/50446061
tags question: http://stackoverflow.com/q/50503913
tags question: http://stackoverflow.com/q/50430479
type: Tag
tags question: http://stackoverflow.com/q/50424572
tags question: http://stackoverflow.com/q/50475847
tags question: http://stackoverflow.com/q/50533119
tags question: http://stackoverflow.com/q/50532593
tags question: http://stackoverflow.com/q/50515911
tags question: http://stackoverflow.com/q/50502266
tags question: http://stackoverflow.com/q/50456093

http://stackoverflow.com/a/50404772
accepted answer of: http://stackoverflow.com/q/50399438
answers question: http://stackoverflow.com/q/50399438
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87846727
downvote count: 0
has body: Redis PUB/SUB does not store messages that were published. It sends them to who was listening at the moment. If you need to have access to old messages, you can: Use Redis Streams. They are in beta now and coming for version 5. Use another PUBSUB system, for example nats.io
has comment: http://stackoverflow.com/comment/87846952
upvote count: 5
type: Answer

http://stackoverflow.com/a/50407537
score: 0
answers question: http://stackoverflow.com/q/50407467
type: Answer
has body: v = [c[1] for c in list(readCSV)] # don't overcomplicate things. Hope this helps..

http://stackoverflow.com/a/50425967
score: 4
has comment: http://stackoverflow.com/comment/87867737
has comment: http://stackoverflow.com/comment/87867845
has comment: http://stackoverflow.com/comment/87866605
upvote count: 4
has comment: http://stackoverflow.com/comment/87867054
has comment: http://stackoverflow.com/comment/87866738
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87867680
downvote count: 0
has comment: http://stackoverflow.com/comment/87867238
has comment: http://stackoverflow.com/comment/99554729
has comment: http://stackoverflow.com/comment/99477138
has comment: http://stackoverflow.com/comment/87867060
has comment: http://stackoverflow.com/comment/99468668
has comment: http://stackoverflow.com/comment/87867193
accepted answer of: http://stackoverflow.com/q/50425739
has comment: http://stackoverflow.com/comment/87867595
has comment: http://stackoverflow.com/comment/87866821
has comment: http://stackoverflow.com/comment/87867499
type: Answer
answers question: http://stackoverflow.com/q/50425739
has comment: http://stackoverflow.com/comment/87867626
has body: Try like that: mkdir test_torch cd test_torch python3 -m venv .venv source .venv/bin/activate pip install torch torchvision python3 &gt;&gt;&gt; import torch Works for me. MacOS 10.13.4, Python 3.6.4 Or like that: mkdir test_torch cd test_torch virtualenv .venv source .venv/bin/activate pip install --upgrade pip pip install torch torchvision python2 &gt;&gt;&gt; import torch Works for me. MacOS 10.13.4, Python 2.7.10 If you don't need to use torch then you can install only torchvision pip install --no-deps torchvision

http://stackoverflow.com/a/50488396
type: Answer
has body: In the second version you set list new_a = [] in every iteration. You set it to [] and then append the element. In the first version you keep appending to the previous iteration.
score: 0
answers question: http://stackoverflow.com/q/50488300

http://stackoverflow.com/comment/87912445
comment on: http://stackoverflow.com/q/50449602
type: Comment
has text: the chances of getting answers relate to the quality of code provided. See [minimal verifyable complete example](https://stackoverflow.com/help/mcve). - we do not need 500 colors to see the behavior. Also : you are lacking your imports (f.e. cv2)? Please edit and shrink your code, thanks.
score: 1
type: QuestionComment

matplotlib
tags question: http://stackoverflow.com/q/50497990
tags question: http://stackoverflow.com/q/50537296
tags question: http://stackoverflow.com/q/50430266
tags question: http://stackoverflow.com/q/50430490
tags question: http://stackoverflow.com/q/50452455
tags question: http://stackoverflow.com/q/50498091
tags question: http://stackoverflow.com/q/50495298
tags question: http://stackoverflow.com/q/50500873
tags question: http://stackoverflow.com/q/50497922
tags question: http://stackoverflow.com/q/50504447
tags question: http://stackoverflow.com/q/50491707
tags question: http://stackoverflow.com/q/50412224
tags question: http://stackoverflow.com/q/50491223
tags question: http://stackoverflow.com/q/50415578
tags question: http://stackoverflow.com/q/50420553
tags question: http://stackoverflow.com/q/50521914
tags question: http://stackoverflow.com/q/50527658
tags question: http://stackoverflow.com/q/50540653
tags question: http://stackoverflow.com/q/50399802
tags question: http://stackoverflow.com/q/50411976
tags question: http://stackoverflow.com/q/50468874
tags question: http://stackoverflow.com/q/50538327
tags question: http://stackoverflow.com/q/50414326
tags question: http://stackoverflow.com/q/50394519
tags question: http://stackoverflow.com/q/50395392
tags question: http://stackoverflow.com/q/50416785
tags question: http://stackoverflow.com/q/50489505
tags question: http://stackoverflow.com/q/50495998
tags question: http://stackoverflow.com/q/50468643
tags question: http://stackoverflow.com/q/50514176
tags question: http://stackoverflow.com/q/50460322
tags question: http://stackoverflow.com/q/50499196
tags question: http://stackoverflow.com/q/50524188
tags question: http://stackoverflow.com/q/50460719
tags question: http://stackoverflow.com/q/50458837
tags question: http://stackoverflow.com/q/50398858
tags question: http://stackoverflow.com/q/50472448
tags question: http://stackoverflow.com/q/50522230
tags question: http://stackoverflow.com/q/50495528
tags question: http://stackoverflow.com/q/50446668
tags question: http://stackoverflow.com/q/50516862
tags question: http://stackoverflow.com/q/50517777
tags question: http://stackoverflow.com/q/50530617
tags question: http://stackoverflow.com/q/50496088
tags question: http://stackoverflow.com/q/50510757
tags question: http://stackoverflow.com/q/50533422
tags question: http://stackoverflow.com/q/50535457
tags question: http://stackoverflow.com/q/50455551
tags question: http://stackoverflow.com/q/50506200
tags question: http://stackoverflow.com/q/50540317
tags question: http://stackoverflow.com/q/50472921
tags question: http://stackoverflow.com/q/50533934
tags question: http://stackoverflow.com/q/50505256
tags question: http://stackoverflow.com/q/50469843
tags question: http://stackoverflow.com/q/50516094
tags question: http://stackoverflow.com/q/50413680
tags question: http://stackoverflow.com/q/50474104
tags question: http://stackoverflow.com/q/50536645
tags question: http://stackoverflow.com/q/50539942
tags question: http://stackoverflow.com/q/50421933
tags question: http://stackoverflow.com/q/50440837
tags question: http://stackoverflow.com/q/50434278
tags question: http://stackoverflow.com/q/50408327
tags question: http://stackoverflow.com/q/50504053
tags question: http://stackoverflow.com/q/50396479
tag name: matplotlib
tags question: http://stackoverflow.com/q/50464140
tags question: http://stackoverflow.com/q/50391555
tags question: http://stackoverflow.com/q/50418855
tags question: http://stackoverflow.com/q/50416872
tags question: http://stackoverflow.com/q/50445511
tags question: http://stackoverflow.com/q/50454476
tags question: http://stackoverflow.com/q/50385463
tags question: http://stackoverflow.com/q/50452919
tags question: http://stackoverflow.com/q/50492555
tags question: http://stackoverflow.com/q/50536916
tags question: http://stackoverflow.com/q/50488251
tags question: http://stackoverflow.com/q/50484817
tags question: http://stackoverflow.com/q/50415667
tags question: http://stackoverflow.com/q/50438077

http://stackoverflow.com/q/50499536
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88012531
downvote count: 0
score: 1
has title: Can't restore model immediately after it's saved
has comment: http://stackoverflow.com/comment/88013218
tagged with: python
has comment: http://stackoverflow.com/comment/88014928
has comment: http://stackoverflow.com/comment/88012348
tagged with: tensorflow
type: Question
has body: I'm trying to immediately restore a model I just saved for debugging purposes but I end up getting the following error all the time: venv2/local/lib/python2.7/site-packages/tensorflow/python/framework/meta_graph.py:636: RuntimeWarning: Unexpected end-group tag: Not all data was converted 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 "src/python/kmer/learning.py", line 269, in &lt;module&gt; TensorflowTrainingJob.launch(resume_from_reduce = c.resume_from_reduce) File "src/python/kmer/learning.py", line 66, in launch job.execute() File "kmer/map_reduce.py", line 71, in execute self.distribute_workload() File "kmer/map_reduce.py", line 107, in distribute_workload self.run_batch(self.batch[index]) File "kmer/map_reduce.py", line 121, in run_batch batch[track] = self.transform(batch[track], track) File "src/python/kmer/learning.py", line 110, in transform saver.restore(session, tf.train.latest_checkpoint(os.path.join("model save location"))) AttributeError: 'NoneType' object has no attribute 'restore' Seems like the model has not been completely saved by the time I try to restore it. Here is the code: with tf.Session() as session: session.run(init) for epoch in range(5): o, c = session.run([optimizer, cost], feed_dict = {x: X, y: Y}) saver.save(session, "model save location") time.sleep(10) graph = tf.Graph() session = tf.Session(graph = graph) with graph.as_default(): saver = tf.train.import_meta_graph("model save location") saver.restore(session, tf.train.latest_checkpoint("model save location"))) I've tried adding calls to sleep in between just in case the save operation is async but that doesn't seem to help. The exact same codes work when run later as part of a different script so there definitely has to be some timing issues.
answer count: 0
upvote count: 1

http://stackoverflow.com/a/52389922
answers question: http://stackoverflow.com/q/50500023
has body: You need to create your virtualenv with the option --system-site-packages to get access to the system (and site) packages: virtualenv -p python3 --system-site-packages myvenv
type: Answer
score: 0

http://stackoverflow.com/comment/88082773
score: 0
has text: @MegaIng: nope, not a bug.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50535182

http://stackoverflow.com/a/50545446
has comment: http://stackoverflow.com/comment/88110340
has comment: http://stackoverflow.com/comment/88110623
has body: The usual way would be to utilise imshow for this task. You could of course create a patch in the size of your area and fill it with a gradient colour. Or you just plot first the gradient, and then all of your elements: import matplotlib from matplotlib import cm import matplotlib.pyplot as plt import numpy as np matplotlib.rcParams['font.sans-serif'] = "Arial" matplotlib.rcParams['font.family'] = "sans-serif" #points for the three lines x_1=[0.00,1.00,2.00,3.00,4.00,5.00,6.00,6.50] y_1=[3.00,2.80,2.40,2.20,1.80,1.00,0.20,0.00] x_2 = [0.00,1.00,2.00,2.80] y_2 = [7.00,8.00,9.00,10.00] x_3=[2.80,2.80,3.00,4.00] y_3=[10.00,6.00,4.00,1.80] #create comparison arrays for fill_between y_1_compare=[] for item in x_1: y_1_compare.append(0) y_2_compare=[] for item in x_2: y_2_compare.append(10) f=plt.figure(figsize=(5,5)) ax=plt.gca() #define size of the graph xl = 0 xh = 8 yl = 0 yh = 10 #array for gradient creation arr = [[0, 1], [0, 1]] #plot a gradient picture first in the desired size, which will also autoscale the graph #set interpolation to "nearest" to see the underlying grid structure im1 = plt.imshow(arr, cmap = cm.Oranges, extent = [xl, xh, yl, yh], interpolation = "bicubic", alpha = .6, aspect = "auto") plt.plot(x_1,y_1,'o',linestyle='-', color='k',linewidth=0.7) plt.plot(x_2,y_2,'s',linestyle='-',color='k',linewidth=0.7) plt.plot(x_3,y_3,'^',linestyle='--',color='k',linewidth=0.7) #fill the areas with white, so we won't see the underlying picture, when we plot a colour with a reduced alpha ax.fill_between(x_1, y_1, y_1_compare, where=y_1 &gt;= y_1_compare, facecolor='white', interpolate=True,alpha=1) ax.fill_between(x_2, y_2, y_2_compare, where=y_2 &lt;= y_2_compare, facecolor='white', interpolate=True,alpha=1) #now plot again color with reduced alpha ax.fill_between(x_1, y_1, y_1_compare, where=y_1 &gt;= y_1_compare, facecolor='tab:cyan', interpolate=True,alpha=.4) ax.fill_between(x_2, y_2, y_2_compare, where=y_2 &lt;= y_2_compare, facecolor='green', interpolate…
has comment: http://stackoverflow.com/comment/88110524
type: Answer
accepted answer of: http://stackoverflow.com/q/50541390
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/88110632
answers question: http://stackoverflow.com/q/50541390
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50511689
downvote count: 1
has body: I am using the newest version of Tensorflow and Keras. I have seen the example where datasets like the MNIST ist loaded and used. But how do I do this with local images?
has answer: http://stackoverflow.com/a/50513216
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50512664
has title: How do I Feed local Data (Images) into my Keras Network in Python?
tagged with: python
accepted answer: http://stackoverflow.com/a/50513216
possible better answer: http://stackoverflow.com/a/50512664
upvote count: 2
type: AnsweredQuestion
answer count: 2
score: 1
tagged with: feed

http://stackoverflow.com/q/50434132
has answer: http://stackoverflow.com/a/50434237
tagged with: for-loop
has title: How could I add list in list in code
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87882741
downvote count: 2
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/87882759
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87882415
has body: I was trying to scrape Instagram and I have already achieved my goal of scraping, but the result I get is perfect but I want it to be stored in the list in a list. Code:- Post links = ['https://www.instagram.com/p/BesW08pHfUt', 'https://www.instagram.com/p/BQZyTtej4yj'] for post_link in post_links: _ = API.getMediaComments(get_media_id(post_link), max_id = 100) for c in reversed(API.LastJson['comments']): comment.append(c["user"]["username"]) The comments I get from each post links from Instagram 'https://www.instagram.com/p/BesW08pHfUt':- 'headhotel', 'famegalore', 'motivationpoem', 'malicioussatan' 'https://www.instagram.com/p/BQZyTtej4yj':- 'monarch_motivation', 'headhotel', 'motivationpoem' The output I get ['headhotel', 'famegalore', 'motivationpoem', 'malicioussatan', 'monarch_motivation', 'headhotel', 'motivationpoem'] The output I want [['headhotel', 'famegalore', 'motivationpoem', 'malicioussatan'], ['monarch_motivation', 'headhotel', 'motivationpoem']] I know this is kind of easy but I have been coded this scraper in 2 days so I have got a bit of confused!
has comment: http://stackoverflow.com/comment/87882782
answer count: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/87882518
has comment: http://stackoverflow.com/comment/87883181
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/88116260
has text: The error you get points to invalid file path. Can you double-check? Preferably verify with absolute path.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50535637

http://stackoverflow.com/comment/87822195
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50403318
has text: My point is debug handler will also include levels above (info, warn, err) so you don't need others too. Probably, they are interfering with each other.

http://stackoverflow.com/comment/87821220
comment on: http://stackoverflow.com/a/50389564
score: 0
has text: Hi, is 'FLASK_RUN_HOST' a default commands? I just want to find other default commands.
type: Comment
type: AnswerComment

pygame
tags question: http://stackoverflow.com/q/50434460
tags question: http://stackoverflow.com/q/50538367
tags question: http://stackoverflow.com/q/50510090
tags question: http://stackoverflow.com/q/50476367
tags question: http://stackoverflow.com/q/50522161
tags question: http://stackoverflow.com/q/50536362
tag name: pygame
tags question: http://stackoverflow.com/q/50439611
tags question: http://stackoverflow.com/q/50503609
tags question: http://stackoverflow.com/q/50474457
tags question: http://stackoverflow.com/q/50420969
tags question: http://stackoverflow.com/q/50427489
tags question: http://stackoverflow.com/q/50538826
tags question: http://stackoverflow.com/q/50432745
tags question: http://stackoverflow.com/q/50533105
tags question: http://stackoverflow.com/q/50438206
tags question: http://stackoverflow.com/q/50457855
tags question: http://stackoverflow.com/q/50386229
tags question: http://stackoverflow.com/q/50527763
tags question: http://stackoverflow.com/q/50534617
tags question: http://stackoverflow.com/q/50396713
tags question: http://stackoverflow.com/q/50454159
tags question: http://stackoverflow.com/q/50430140
tags question: http://stackoverflow.com/q/50396624
tags question: http://stackoverflow.com/q/50392215
tags question: http://stackoverflow.com/q/50497212
tags question: http://stackoverflow.com/q/50433453
tags question: http://stackoverflow.com/q/50420306
tags question: http://stackoverflow.com/q/50426629
tags question: http://stackoverflow.com/q/50451897
type: Tag
tags question: http://stackoverflow.com/q/50395216

http://stackoverflow.com/comment/88032847
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50505347
type: QuestionComment
has text: That's it @Alasdair, it was a namespace issue. Sorted out!

http://stackoverflow.com/comment/87808622
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50396404
type: Comment
has text: `def D(x):return sum(i**2 for i in range(1,x+1) if not x%i)`, that is one

http://stackoverflow.com/q/50413910
answer count: 1
downvote count: 0
upvote count: 1
has body: The "IDF Converter" program is lost, SMI website doesn't include the programs. Any way to open the *.idf files or convert them into any other format readable by python or MATLAB?
has title: How to open *.idf eye tracker data that was created wih "i view X" system from "SMI"
tagged with: iview
favorite count: 0
accepted answer: http://stackoverflow.com/a/52244360
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/122385304
has answer: http://stackoverflow.com/a/52244360
score: 1
tagged with: python
tagged with: eye-tracking
type: Question
has comment: http://stackoverflow.com/comment/87899468

http://stackoverflow.com/q/50488424
accepted answer: http://stackoverflow.com/a/50813772
has title: Expected type 'str', got 'CharField' instead
downvote count: 0
answer count: 1
tagged with: python
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87995344
tagged with: type-hinting
has body: In my Django project in PyCharm, I have enabled type hinting. In a Django model, I have defined a CharField. In a method in the model, I want to use that as an argument in a function that expects a string. I get the following warning however: Expected type 'str', got 'CharField' instead I realize that the two types are not the same. What would be the best way to not get the field itself, but the contents of the field as argument to that function. Note that behaviorly, everything is correct already, the receiving function already treats the argument as a string.
tagged with: django-models
upvote count: 4
has comment: http://stackoverflow.com/comment/87991897
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50813772

http://stackoverflow.com/q/50463602
has body: I have simple, but tricky question about regex (using in python), which i have did not find answer for anywhere here on google. Is there any "trick" how to make two capture groups in optional order? Let's say we have following: .*abc.* What i want is to match also this: .*acb.* I know i could use .*abc|acb.* but the problem is, that if we have something more complicated then abc, code is very long. Is not there any workaround to say e.g. "match last two capturing groups (or symbols, etc.) in any order?
score: 2
answer count: 2
downvote count: 0
has title: Regex optional order of capturing group
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50464936
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: regex-group
has answer: http://stackoverflow.com/a/50465305
tagged with: regex

http://stackoverflow.com/comment/87938623
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50461772
has text: If the text appears more than one, can I find all the divs that contains the text?
type: AnswerComment

http://stackoverflow.com/a/50984021
type: Answer
answers question: http://stackoverflow.com/q/50524674
has body: The token that Google issued is a short-live token which will expire at a short time. The ServiceAccountCredentials has a refresh method to fetch the new token. In your case, since it is called every 2 minutes, you can call gc.login() every 2 minutes. while True: gc.login() I'm not sure why it doesn't refresh by itself (it should). FYI, oauth2client is deprecated, consider using other things. Here is a tip on how to use it with Authlib: https://blog.authlib.org/2018/authlib-for-gspread
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50524674

http://stackoverflow.com/comment/87906285
type: QuestionComment
comment on: http://stackoverflow.com/q/50446224
has text: _Note that newlines are not added._ Does that tell you anything?
score: 0
type: Comment

http://stackoverflow.com/q/50503489
has body: I have just started to learn coding. This is a simple number guessing game that I created with Python. It works fine but I feel like the code can be simplified/optimized so it looks more neat. Another thing is that every time I try to input a non-integer, an error occurred. Is there a way to check if the user input is an integer or not and then proceed to the next step only if it is an integer. Thank you in advance! from random import randint random_number = randint(1, 10) guesses_taken = 0 print ("Hello! What is your name?") guess_name = input() print ("Well, " + guess_name + ", I am thinking of a number between 1-10.") while guesses_taken &lt; 4: print ("Take a guess!") guess = int(input()) if guess not in range(1, 11): print ("Oops! That's not an option!") elif guess == random_number: print ("You're right! Congratulations!") break else: guesses_taken += 1 if guesses_taken &lt; 4: print ("Nope! Try again,") else: print ("Out of chances. You lose.")
type: UnansweredQuestion
tagged with: input
tagged with: python
linked to: http://stackoverflow.com/q/5424716
score: -3
tagged with: integer
has title: A beginner-made python number guessing game. Please help optimize and resolve issues
has answer: http://stackoverflow.com/a/50503636
upvote count: 0
duplicate of: http://stackoverflow.com/q/5424716
downvote count: 3
answer count: 1
tagged with: python-requests
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/88045330
comment on: http://stackoverflow.com/q/50515911
has text: @Zak, thank you. Yes, with the full path it works. But the problem is that in my local I will have one path and, when I upload it, it will be replaced and the problem will come back...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88052000
score: 0
has text: @RoryDaulton I just used the variable explorer and double-clicked at the variable.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50519090

http://stackoverflow.com/comment/87958928
score: 0
comment on: http://stackoverflow.com/a/50472284
has text: First of all, thank you very much for your help. I tried to remove the file and tried to change the destination directory, but the problem persists.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87996528
has text: @Zekii Thanks so much! BAM! It works.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50485436

http://stackoverflow.com/comment/87948710
comment on: http://stackoverflow.com/a/50416990
has text: thank you for the answer. I was looking for a solution for python not for R. i get this error when i run "h2o.download_mojo..." : AttributeError: module 'h2o' has no attribute 'download_mojo' H2O session _sid_81cf closed.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/87882538
comment on: http://stackoverflow.com/a/50433500
type: Comment
score: 0
has text: I actually do that. I monitor on val_acc. I am now setting verbose to 1 to se what happens
type: AnswerComment

http://stackoverflow.com/q/50448897
accepted answer: http://stackoverflow.com/a/50476322
has comment: http://stackoverflow.com/comment/87931506
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87911033
has title: TensorFlow and word embeddings - TypeError: unhashable type: 'numpy.ndarray'
answer count: 1
tagged with: tensorflow
type: Question
has body: I wish to modify the code at http://www.brightideasinanalytics.com/rnn-pretrained-word-vectors/, which is about predicting the next word, to have code that predicts answers to questions. Here is an excerpt of the code I'm having trouble with: import tensorflow.contrib as ct def NHIDDEN(): return 1 g = tf.Graph() tf.reset_default_graph() with g.as_default(): # lines 97-104 of original code # RNN output node weights and biases weights = { 'out': tf.Variable(tf.random_normal([NHIDDEN(), embedding_dim])) } biases = { 'out': tf.Variable(tf.random_normal([embedding_dim])) } with tf.name_scope("embedding"): W = tf.Variable(tf.constant(0.0, shape=[vocab_size, embedding_dim]), trainable=False, name="W") embedding_placeholder = tf.placeholder(tf.float32, [vocab_size, embedding_dim]) embedding_init = W.assign(embedding_placeholder) preimage = tf.nn.embedding_lookup(W, x2) # lines 107-119 of original # reshape input data x_unstack = tf.unstack(preimage) # create RNN cells rnn_cell = ct.rnn.MultiRNNCell([ct.rnn.BasicLSTMCell(NHIDDEN()), ct.rnn.BasicLSTMCell(NHIDDEN())]) outputs, states = ct.rnn.static_rnn(rnn_cell, x_unstack, dtype=tf.float32) # capture only the last output pred = tf.matmul(outputs[-1], weights['out']) + biases['out'] # Create loss function and optimizer cost = tf.reduce_mean(tf.nn.l2_loss(pred-y)) optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) # lines 130, 134 and 135 of original step = 0 acc_total = 0 loss_total = 0 with tf.Session(graph = g) as sess: # lines 138, 160, 162, 175, 178 and 182 of original while step &lt; 1: # training_iters: _,loss, pred_ = sess.run([optimizer, cost, pred], feed_dict = {x: tf.nn.embedding_lookup(W, x2), y: tf.nn.embedding_lookup(W, y)}) loss_total += loss print("loss = " + "{:.6f}".format(loss_total)) step += 1 print ("Finished Optimization") The error I get is: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-7-7a72d8…
tagged with: numpy
has answer: http://stackoverflow.com/a/50476322

http://stackoverflow.com/q/50399889
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50458356
score: -2
tagged with: ibpy
has answer: http://stackoverflow.com/a/50414099
tagged with: python
has title: Getting IB historical option data
type: AnsweredQuestion
answer count: 2
downvote count: 3
accepted answer: http://stackoverflow.com/a/50458356
tagged with: api
upvote count: 1
possible better answer: http://stackoverflow.com/a/50414099
has body: In the following program, I am able to get the contract details, but I get no historical data. Not sure what I am doing wrong. from ib.ext.Contract import Contract from ib.ext.ContractDetails import ContractDetails from ib.opt import ibConnection, message import time import datetime from time import sleep, strftime twsPort = 7496 gatewayPort = 4001 def watcher(msg): print("[watcher: ", msg, " ]") def contractDetailsHandler(msg): print("[contractDetailsHandler:]") contractDetails = msg.contractDetails contract = msg.contractDetails.m_summary print(contractDetails.m_cusip, contractDetails.m_underConId, contractDetails.m_longName, contractDetails.m_industry, contractDetails.m_category, contractDetails.m_subcategory, contract.m_symbol, contract.m_secType, contract.m_strike, contract.m_right, contract.m_exchange, contract.m_currency, contract.m_secIdType, contract.m_secId, "\n") contracts.append(contractDetails.m_summary) def contractDetailsEndHandler(msg): print("[contractDetailsEndHandler:]") def contractHistDetailsHandler(msg): global DataWait print("[contractHistDetailsHandler:]") contracts.append(msg.historicalData) DataWait = False con = ibConnection() con.host = "127.0.0.1" con.port = gatewayPort con.clientId = 5 con.registerAll(watcher) con.register(contractDetailsHandler, 'ContractDetails') con.register(contractDetailsEndHandler, 'ContractDetailsEnd') con.register(contractHistDetailsHandler, message.historicalData) con.connect() contract = Contract() contract.m_exchange = "SMART" contract.m_secType = "OPT" contract.m_symbol = "SPY" contract.m_currency = "USD" contract.m_strike = 260 contract.m_right = "PUT" contract.m_expiry = "20180615" #contract.m_includeExpired = True endtime = strftime('%Y%m%d %H:%M:%S') #endtime = '20170102 01:00:00' con.reqContractDetails(1, contract) con.reqHistoricalData(2,contract,endtime,"14 D","30 min","MIDPOINT",0,1) contracts = [] DataWait = True ; i = 0 while DataWait and i &lt; 90: i += 1 ; print(i), time.sleep(1) time.sleep(1) co…

http://stackoverflow.com/a/50508710
has body: You can convert every character of string public class StringUnicode { public static void main(String[] args) { String foreignText = "برنامه نویسی"; String unicodevalue=""; for (int i = 0; i < foreignText.length(); i++) { unicodevalue= unicodevalue+"\\u" + Integer.toHexString(foreignText.charAt(i) | 0x10000).substring(1); } System.out.println( unicodevalue ); // System.out.println(response); } } output: \u0628\u0631\u0646\u0627\u0645\u0647\u0020\u0646\u0648\u06cc\u0633\u06cc in Python Python 3 renamed the unicode type to str, the old str type has been replaced by bytes. if isinstance(unicode_or_str, str): text = unicode_or_str decoded = False else: text = unicode_or_str.decode(encoding) decoded = True You may want to read the Python 3 porting HOWTO for more such details. There is also Lennart Regebro's Porting to Python 3: An in-depth guide, free online. Last but not least, you could just try to use the 2to3 tool to see how that translates the code for you. NameError: global name 'unicode' is not defined - in Python 3
score: 0
answers question: http://stackoverflow.com/q/50508574
type: Answer

http://stackoverflow.com/q/50439948
tagged with: parsing
type: Question
tagged with: python-3.x
tagged with: tkinter
has title: Tkinter entry returns ValueError: invalid literal for int() with base 10: ''
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/5767228
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87894127
downvote count: 1
has comment: http://stackoverflow.com/comment/87896782
has answer: http://stackoverflow.com/a/50440019
has comment: http://stackoverflow.com/comment/87894098
score: 0
has comment: http://stackoverflow.com/comment/87894350
has comment: http://stackoverflow.com/comment/87894202
tagged with: python
linked to: http://stackoverflow.com/q/5767228
has comment: http://stackoverflow.com/comment/87894315
has body: So today I've been working on a new GUI with tkinter and came across and issue with parsing a string from an entry into an int and I get this error. Traceback (most recent call last): File "/Users/g.shiner21/Desktop/Python/P2PFile/P2PFileServer.py", line 47, in &lt;module&gt; bStartServer = Button(f1, text="Start Server", command=startServer(host)) File "/Users/g.shiner21/Desktop/Python/P2PFile/P2PFileServer.py", line 28, in startServer intport = int(port) ValueError: invalid literal for int() with base 10: '' Here is the function, def startServer(host): port = ePort.get() intport = int(port) s = socket.socket() s.bind((host, intport)) s.listen(4) The most confusing part is that when I test something like this, strTest = "10000" intTest = int(strTest) I get no errors. So I don't think I'm doing my parsing wrong. But at this point I'm not too sure. Any help would be greatly appreciated! :) Edit: For those that it helps here is the full program(or at least what I have so far. I commented out the second part of it while I was building the GUI because I didn't want to have to deal with any interferences. # server.py import socket # Import socket module import sys from tkinter import * from tkinter import ttk port = 0 # Reserve a port for your service. s = socket.socket() # Create a socket object host = "0.0.0.0" root=Tk() root.title("Test Window") c = '#ececec' n = ttk.Notebook(root) #Create notebook f1 = ttk.Frame(n) #Create frames for notebook f2 = ttk.Frame(n) f3 = ttk.Frame(n) n.add(f1, text='Server') #Add frames to notebook n.add(f2, text='File') n.add(f3, text='Playback') n.pack(expand=1, fill='both') #Pack notebook def startServer(host): port = ePort.get() intport = int(port) s = socket.socket() s.bind((host, intport)) s.listen(4) lservType = Label(f1, text="Select Server Type: ", bg=c) lservType.grid(columnspan=2, row=0) R1 = Radiobutton(f1, text="Local Host", variable=host, value="localhost", bg=c) R1.grid(row=1, column=0) R2 = Radiobutton(f1, text="Wireless Ho…
favorite count: 0

http://stackoverflow.com/a/50434877
has comment: http://stackoverflow.com/comment/87884521
has body: To calculate the number of unique items in a pandas series (column), you should use pd.Series.nunique: res = df['quality'].nunique() Your code does not work because pd is not an attribute of your dataframe. It is in fact, a reference to a library. You might find import pandas as pd near the beginning of your code.
answers question: http://stackoverflow.com/q/50434855
has comment: http://stackoverflow.com/comment/87884721
score: 3
upvote count: 3
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87872194
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50426245
has text: @user3689574 This code is the first part of calculating tfidf. when ngram line called it causes the above error. Please let me know if I should provide further info regarding the code or the error.

http://stackoverflow.com/comment/87854579
comment on: http://stackoverflow.com/q/50419505
score: 3
type: Comment
has text: You cannot have duplicate keys in a `dict` so when you're creating the `names` dictionary your `Tom` and `Bernie` keys get overwritten by the latter entries. Store the entries as tuples in a `list` (or a `set` if you don't care for order) if you want to keep the duplicate entries.
type: QuestionComment

numpy
tags question: http://stackoverflow.com/q/50432927
tags question: http://stackoverflow.com/q/50536713
tags question: http://stackoverflow.com/q/50473057
tags question: http://stackoverflow.com/q/50440398
tags question: http://stackoverflow.com/q/50453437
tags question: http://stackoverflow.com/q/50536490
tags question: http://stackoverflow.com/q/50516590
tags question: http://stackoverflow.com/q/50397126
tags question: http://stackoverflow.com/q/50529250
tags question: http://stackoverflow.com/q/50439217
tags question: http://stackoverflow.com/q/50463366
tags question: http://stackoverflow.com/q/50457074
tags question: http://stackoverflow.com/q/50435357
tags question: http://stackoverflow.com/q/50426238
tags question: http://stackoverflow.com/q/50519583
tags question: http://stackoverflow.com/q/50437942
tags question: http://stackoverflow.com/q/50468792
tags question: http://stackoverflow.com/q/50468953
tags question: http://stackoverflow.com/q/50517089
tags question: http://stackoverflow.com/q/50437426
tags question: http://stackoverflow.com/q/50438066
tags question: http://stackoverflow.com/q/50494092
tags question: http://stackoverflow.com/q/50448837
tags question: http://stackoverflow.com/q/50476198
tags question: http://stackoverflow.com/q/50427337
tags question: http://stackoverflow.com/q/50430493
tags question: http://stackoverflow.com/q/50411583
tags question: http://stackoverflow.com/q/50390081
tags question: http://stackoverflow.com/q/50517794
tags question: http://stackoverflow.com/q/50401028
tags question: http://stackoverflow.com/q/50477318
tags question: http://stackoverflow.com/q/50484936
tags question: http://stackoverflow.com/q/50505250
tags question: http://stackoverflow.com/q/50401885
tags question: http://stackoverflow.com/q/50472095
tags question: http://stackoverflow.com/q/50431584
tags question: http://stackoverflow.com/q/50459009
tags question: http://stackoverflow.com/q/50500808
tags question: http://stackoverflow.com/q/50421590
tags question: http://stackoverflow.com/q/50426405
tags question: http://stackoverflow.com/q/50399189
tags question: http://stackoverflow.com/q/50411092
tags question: http://stackoverflow.com/q/50430404
tags question: http://stackoverflow.com/q/50452908
tags question: http://stackoverflow.com/q/50516717
tags question: http://stackoverflow.com/q/50463929
tags question: http://stackoverflow.com/q/50490070
tags question: http://stackoverflow.com/q/50472136
tags question: http://stackoverflow.com/q/50497987
tags question: http://stackoverflow.com/q/50424766
tags question: http://stackoverflow.com/q/50532266
tags question: http://stackoverflow.com/q/50416848
tags question: http://stackoverflow.com/q/50389840
tags question: http://stackoverflow.com/q/50393581
tags question: http://stackoverflow.com/q/50452635
tags question: http://stackoverflow.com/q/50537287
tags question: http://stackoverflow.com/q/50414077
tags question: http://stackoverflow.com/q/50394748
tags question: http://stackoverflow.com/q/50444346
tags question: http://stackoverflow.com/q/50446949
tags question: http://stackoverflow.com/q/50509623
tags question: http://stackoverflow.com/q/50532583
tags question: http://stackoverflow.com/q/50408327
tags question: http://stackoverflow.com/q/50456945
tags question: http://stackoverflow.com/q/50431401
tags question: http://stackoverflow.com/q/50437384
tags question: http://stackoverflow.com/q/50459256
tags question: http://stackoverflow.com/q/50469710
tags question: http://stackoverflow.com/q/50462707
tags question: http://stackoverflow.com/q/50479355
tags question: http://stackoverflow.com/q/50493478
tags question: http://stackoverflow.com/q/50395610
tags question: http://stackoverflow.com/q/50481372
tags question: http://stackoverflow.com/q/50436267
tags question: http://stackoverflow.com/q/50475636
tags question: http://stackoverflow.com/q/50478326
tags question: http://stackoverflow.com/q/50525525
tags question: http://stackoverflow.com/q/50400456
tags question: http://stackoverflow.com/q/50483587
tags question: http://stackoverflow.com/q/50468494

http://stackoverflow.com/q/50386332
has comment: http://stackoverflow.com/comment/87788537
favorite count: 0
type: Question
has body: I have a dictionary with key values, But I want to rearrange/change the type of the keys/values in the dict so as per my like. How can I do it? for Example: Dict = {'a':19,'b':30, 'c':"New", 'd': 6} I want to make b as key at position 1 and/or I want to make a key as a list and so on. NOTE: I dont not want to sort the dict! But decide myself : Example: If this key is present in dict then put this Key,value in Position 1 So my final result would be, Dict = {'b':30, 'a':[19], 'd':6, 'c':"new"}
has comment: http://stackoverflow.com/comment/87788304
tagged with: python
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87788348
has answer: http://stackoverflow.com/a/50386415
has comment: http://stackoverflow.com/comment/87788279
has comment: http://stackoverflow.com/comment/87788284
tagged with: python-2.7
has title: How can Rearrange/change type in the dictionary key values in dictionary , I do not want to sort it
linked to: http://stackoverflow.com/q/1867861
answer count: 2
has answer: http://stackoverflow.com/a/50386382
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87811201
downvote count: 1
has comment: http://stackoverflow.com/comment/87788238
duplicate of: http://stackoverflow.com/q/1867861
has comment: http://stackoverflow.com/comment/88066089

http://stackoverflow.com/q/50413785
accepted answer: http://stackoverflow.com/a/50414199
has answer: http://stackoverflow.com/a/50413944
favorite count: 0
has title: Python: Split CSV with character count
type: Question
answer count: 2
downvote count: 0
tagged with: input
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50414199
tagged with: http://stackoverflow.com/tag/csv
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50413944
score: 1
has body: Need help in importing CSV file into python. My CSV file 0,Donc, 2 jours, je me suis rendu compte que Musikfest est le lendemain de voir dmb, quel problème. Signifie que je ne peux pas aller ... 0,Le son est définitivement gâché.Noooooo mon bb 0,Il est le mien! Haha il me suit: ') m'aime et me veut.haha.i wana vivre en Amérique annie I want to split the above file into 2 columns Column1 ---- Column2 0 ---- Donc, 2 jours, je me suis rendu compte que Musikfest est le lendemain de voir dmb, quel problème. Signifie que je ne peux pas aller ... 0 ---- Le son est définitivement gâché.Noooooo mon bb 0 ---- Il est le mien! Haha il me suit: ') m'aime et me veut.haha.i wana vivre en Amérique annie Since my text has commas embedded and my value for the text is always the first character. Is it possible to read my CSV file with splitting first character and rest of the text?

http://stackoverflow.com/comment/87912662
type: Comment
type: QuestionComment
has text: Can you provide input file here?
comment on: http://stackoverflow.com/q/50448377
score: 0

http://stackoverflow.com/comment/88033415
score: 0
type: Comment
type: AnswerComment
has text: @DJ_Tth3jtr - it seems that `pip` on its own cannot install numpy before tulipy. Please seem my edit. Something like that could be written in a bash script, but it is a one-liner.
comment on: http://stackoverflow.com/a/50510258

http://stackoverflow.com/comment/87819928
type: QuestionComment
has text: Also, when I created the .lib file it showed a message as follows: 'C:\Users\Germano\nlopt>lib /def:libnlopt-0.def Microsoft (R) Library Manager Version 14.00.24210.0 Copyright (C) Microsoft Corporation. All rights reserved. LINK : warning LNK4068: /MACHINE not specified; defaulting to X86 Creating library libnlopt-0.lib and object libnlopt-0.exp'
score: 0
comment on: http://stackoverflow.com/q/50402092
type: Comment

http://stackoverflow.com/q/50541773
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I have made two entry widgets: account_number_entry and pin_number_entry and button 0-9 # Account number entry here account_number_entry = tk.Entry(f, textvariable=account_number_var, width=12, font=('Helvetica 15'), bd=10) account_number_entry.grid(row=45, column=1) # Account pin entry here account_pin_entry = tk.Entry(f, text='PIN Number', textvariable=pin_number_var, show=('*'), width=8, font=('Helvetica 15'), bd=10) account_pin_entry.grid(row=45, column=2) and I have created button as b1 = tk.Button(f, text='1', font=('Helvetica 12 '), width=15, height=6,command=lambda: set_text("1")) b1.grid(row=50, column=0) set_text function is like this def set_text(text): account_number_entry.insert(tk.END, text) return but I can't add data pin Entry. Please help me
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50543062
tagged with: tkinter
score: 1
has title: Set input in 2 Entry using button in python

http://stackoverflow.com/q/50433094
linked to: http://stackoverflow.com/q/50392027
has body: I've been trying to add some hopefully useful intermediate calculations used to derive my loss function to the eval_metric_ops dictionary for my evaluation EstimatorSpec. I have wrapped these in a call to tf.metrics.mean as it seemed to fit my needs. The return type of this function is a tuple of (mean, update_op), where mean is ostensibly the current mean and update_op is an operation that computes the new mean and returns it. However, when I try to evaluate it I see that the value and update_op fields seem to be different. The documentation doesn't provide an explanation for this as far as I can see. For example, take the following snippet of code: test_tensor = tensorflow.constant([[1, 2, 3], [4, 5, 6]]) test_mean = tensorflow.metrics.mean(test_tensor) sess = tensorflow.Session() sess.run(tensorflow.global_variables_initializer()) sess.run(tensorflow.local_variables_initializer()) print sess.run(test_mean) print sess.run(test_mean) print sess.run(test_mean) print sess.run(test_mean) print sess.run(test_mean[0]) print sess.run(test_mean)[1] This returns the following: (0.0, 3.5) (1.75, 3.5) (2.3333333, 3.5) (2.625, 3.5) 3.5 3.5 The second value of the tuple is obviously an overall average of the input value, but the left hand side values seem to be asymptoting towards 3.5, while the taking the zero-index of test_mean and evaluating it results in 3.5 directly, as opposed to the value that I get by evaluating the whole operation and then taking the index. What is happening here?
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50433993
accepted answer: http://stackoverflow.com/a/50433993
type: AnsweredQuestion
score: 0
tagged with: tensorflow
type: Question
has title: What do the return values of tf.metrics mean?

http://stackoverflow.com/q/50466289
type: Question
has body: I'm trying to send PDF via email: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return pdf return None in my views: pdf = render_to_pdf('expenses/pdf_report.html', data) mail.attach_file(pdf) mail.send() I get this error: expected str, bytes or os.PathLike object, not pisaContext How can I get str or bytes instead of pisaContext?
downvote count: 0
upvote count: 1
has title: expected str, bytes or os.PathLike object, not pisaContext
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50466589
accepted answer: http://stackoverflow.com/a/50466589
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87945902
has comment: http://stackoverflow.com/comment/87946097
score: 1
has comment: http://stackoverflow.com/comment/87945841

http://stackoverflow.com/a/76640273
upvote count: 1
has body: I would recommend using Socket.io along with Flask to perform real-time event handling without needing to refresh the page. The Python imports will look something like this: from flask_socketio import SocketIO, emit from flask import Flask, redirect, render_template, request, session Note that the second line contains just a few important features of the Flask library that I use within my own projects. On the HTML side, make sure you include a reference to Socket.io (and jQuery) so that the following code will actually work. This creates an event handler to execute the inline function whenever the button in question is clicked (in this specific instance, when any button is clicked--this can be changed by using $('td button'), or even better, $('#socks.shirts.pants')). This function simply calls emit() to transmit the data to the Python backend using a websocket. The data you transmit is in a dictionary format. namespace = 'namespace' var socket = io(); $('button').on('click', function() { socket.emit('event_name', { 'data_name' : $(this).attr('id') }) }); Over in the backend, we need to create an event listener to wait for this specific call to emit(). At this point, you can do whatever you want with the data! @socketio.on('event_name', namespace='namespace') def function_name(message): print(message['data_name']) From here, you can also store it in the session variables (which is also a dictionary) so that you can use it throughout your application across different routes by simply writing session['variable_name'] = message['data_name'] in your socket handler function_name(). Hope this helps!
type: Answer
answers question: http://stackoverflow.com/q/50417461
downvote count: 0
score: 1

http://stackoverflow.com/comment/87817184
type: QuestionComment
has text: can't you just check for ';;' and skip them?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50399683

http://stackoverflow.com/comment/87878624
comment on: http://stackoverflow.com/q/50426462
score: 0
type: Comment
type: QuestionComment
has text: [This](https://wiki.helionet.org/Solving_Internal_Server_Errors) could help.

http://stackoverflow.com/q/50431164
tagged with: one-hot-encoding
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/43618245
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
has body: I would like to encode my input letters of strings for machine learning methods. Let's assume that my train data looks in this way: score text 1 show photos 1 show my photos 2 who are you? At the moment I do something like this: for index, row in train_set.iterrows(): list2 = [] list2 = list(row.text.lower()) for n, key in enumerate(list2): if key in dictionary: list2[n] = dictionary[key] else: dictionary[key] = i list2[n] = i i += 1 train_set.set_value(index,'text', list2) And as a result for this example data I get: score text 1 [0, 1, 2, 3, 4, 5, 1, 2, 6, 2, 0] 1 [0, 1, 2, 3, 4, 7, 8, 4, 5, 1, 2, 6, 2, 0] 2 [3, 1, 2, 4, 10, 13, 9, 4, 8, 2, 19, 21] As you know for instance for neural networks it is not a proper way to use this values, so it seems to me that the one hot encoding will be the best solution in this case. I wonder what will be the most efficient way to convert these values in text column of test_set dataframe and also column text in train_set dataframe which looks like test_set but obviously doesn't have first column with expected values. I think that in both cases I should have the same size of columns after using one hot encoding and the same index and row should correspond to the same character in both test_set and train_set dataframe. I hope that you understand what I mean. If not please just let me know. I will try to explain it in a more clear way. Any ideas how can I do this?
has title: How can I encode my data for machine learning methods?
has comment: http://stackoverflow.com/comment/87876964
has answer: http://stackoverflow.com/a/50431273
score: 2
upvote count: 3
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50476122
has body: You seem to be quoting from the book <a href="https://books.google.be/books?id=y6FLBQAAQBAJ&amp;pg=PA136&amp;lpg=PA136&amp;dq=%22A+postings+list+is+a+singly+linked+list+with+an+additional+jump+field+at+each+node.%22&amp;source=bl&amp;ots=AtJtcLu3zg&amp;sig=vxzBY_yxozzGQiiWU_6cRzQ8kAo&amp;hl=nl&amp;sa=X&amp;ved=0ahUKEwibidXtlJrbAhWGyKQKHfwdBYAQ6AEIKDAA#v=onepage&amp;q=%22A%20postings%20list%20is%20a%20singly%20linked%20list%20with%20an%20additional%20jump%20field%20at%20each%20node.%22&amp;f=false" rel="nofollow noreferrer">Elements of Programming Interviews: The Insiders' Guide, section 9.5. It correctly states that the time complexity of this algorithm is O(n). When it speaks of a worst case it is about the space complexity, not the time complexity (for which there is no particular worst case as you correctly reasoned): The recursive implementation has maximum call stack depth of n, ... A worst case input is one where every node's jump and next node are equal. Note the context of this quote: this is a worst case for the stack size (space).
has comment: http://stackoverflow.com/comment/87965867
type: Answer
has comment: http://stackoverflow.com/comment/87965998
accepted answer of: http://stackoverflow.com/q/50470110
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50470110

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

http://stackoverflow.com/comment/87955055
has text: I have posted the complete error. :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50448342
score: 0

http://stackoverflow.com/q/50398444
downvote count: 0
answer count: 1
score: 6
tagged with: logging
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87816225
accepted answer: http://stackoverflow.com/a/50401350
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50401350
has body: I have been trying to create a new class of Logger by subclassing logging.Logger . Python version is 3.5 I have several modules in my application and I configure the logging only in the main module where I set the logger class using logging.setLoggerClass(...) However when I retrieve the same Logger instance from some other module, it still creates a new instance of the Logger class and not the child class instance that I defined. For example my code is : # module 1 import logging class MyLoggerClass(logging.getLoggerClass()): def __init__(name): super(MyLoggerClass, self).__init__(name) def new_logger_method(...): # some new functionality if __name__ == "__main__": logging.setLoggerClass(MyLoggerClass) mylogger = logging.getLogger("mylogger") # configuration of mylogger instance # module 2 import logging applogger = logging.getLogger("mylogger") print(type(applogger)) def some_function(): applogger.debug("in module 2 some_function") When this code is executed, I expect the applogger in module 2 to be of type MyLoggerClass. I intend to use the new_logger_method for some new functionality. However since applogger is turning out to be of type logging.Logger, when the code is run it throws Logger has no attribute named new_logger_method. Has anyone ever faced this issue? Thanks in advance for any help! Pranav
tagged with: python
has comment: http://stackoverflow.com/comment/87815937
has title: extending logging.Logger module in python 3.5
upvote count: 6
tagged with: python-3.x
tagged with: python-3.5

http://stackoverflow.com/a/50453833
accepted answer of: http://stackoverflow.com/q/50453490
type: Answer
has body: In the following code snippet copied from your question: def rl(): q_table = build_q_table(N_STATES, ACTIONS) for episode in range(MAX_EPISODES): step_counter = 0 S = 0 is_terminated = False update_env(S, episode, step_counter) while not is_terminated: # ... # &lt;snip&gt; # ... return q_table your rl() function has a return statement after the while loop going through the timesteps for a single episode, inside the for loop going through the episodes. This means that your function will effectively complete only a single episode, and then already return (meaning, the rl() function is terminated) before it gets a chance to start the second episode. Concerning this update to the question: CHANGES: updated the return statement and the algorithm now works so that it goes through 13 episodes!!! HOWEVER, I cannot seem to implement the player token (agent) so that it doesn't leave a trail of all steps taken and I would like it to reset after each episode. This maybe an issue to do with scope I am not 100% sure, since I'm not familiar with the turtle-graphics framework. However, I did notice that update_env() is implemented to call player_set(coords[S]) whenever the position of the player needs to be updated. This function has the following implementation: def player_set(S): player = turtle.Turtle() player.color("blue") player.shape("circle") player.penup() player.speed(0) player.setposition(S) player.setheading(90) It looks to me like that function is creating a fresh, new player object in the new location whenever it's called, rather than updating the location of a player object that already exists. So, it looks like a completely new player object is created whenever the state is updated, and the old player object will still remain where it was. A solution would probably consist of only creating a player object once, and creating a separate function to update its position without creating a new object again.
answers question: http://stackoverflow.com/q/50453490
has comment: http://stackoverflow.com/comment/87946814
has comment: http://stackoverflow.com/comment/87947537
upvote count: 2
has comment: http://stackoverflow.com/comment/87946882
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87945632
score: 2

http://stackoverflow.com/a/50423599
score: 0
has body: You might have used list as a variable before in the code. here is an example code a = list() a.append(2) print(a) list = 1 print(type(list)) #Here you would see that the type of list is integer #To get back the type list,just delete the reference as below del list print(type(list)) #Now it will print that its of type list
answers question: http://stackoverflow.com/q/50417688
type: Answer

http://stackoverflow.com/comment/120546159
comment on: http://stackoverflow.com/a/50413182
score: 0
has text: @AnthonyTuininga thanks a lot for the example. Also, the link in the comment seems not to work (404). Cheers!
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87976950
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50480556
has text: You can sniff your browser's HTTP request to see what's goin' on. Go to the login page and press F12. Go to Network, check "Persist logs", then login and watch the fireworks. Click on the relevant request and you can see if there's any extra data you need.
type: Comment

http://stackoverflow.com/a/50500803
downvote count: 0
has comment: http://stackoverflow.com/comment/91686482
accepted answer of: http://stackoverflow.com/q/50483003
type: Answer
answers question: http://stackoverflow.com/q/50483003
has comment: http://stackoverflow.com/comment/91665347
score: 2
upvote count: 2
has body: A common way to do an object turnaround is to add an empty and make it the parent of the camera, animating the z-rotation of the empty will then rotate the camera around the object, you can give the camera a trackto constraint so that the camera always points at the target object. You can use the objects bound_box to find its outer limits, then add a bit more so the object stays inside the view and position the camera with that. Making the extra distance proportional to the object size should work for most objects. The addon I made for this answer shows how to make a bounding box around multiple objects, which may be helpful if you have multiple objects at once. To do that in python - import bpy scn = bpy.context.scene bpy.ops.import_scene.obj(filepath='obj1.obj') target = bpy.context.selected_objects[0] scn.objects.active = target # centring the origin gives a better bounding box and rotation point bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY') cam_x_pos = max([v[0] for v in target.bound_box]) * 2.5 cam_y_pos = max([v[1] for v in target.bound_box]) * 2.5 cam_z_pos = max([v[2] for v in target.bound_box]) * 2.5 rot_centre = bpy.data.objects.new('rot_centre', None) scn.objects.link(rot_centre) rot_centre.location = target.location camera = bpy.data.objects.new('camera', bpy.data.cameras.new('camera')) scn.objects.link(camera) camera.location = (cam_x_pos, cam_y_pos, cam_z_pos) camera.parent = rot_centre m = camera.constraints.new('TRACK_TO') m.target = target m.track_axis = 'TRACK_NEGATIVE_Z' m.up_axis = 'UP_Y' rot_centre.rotation_euler.z = 0.0 rot_centre.keyframe_insert('rotation_euler', index=2, frame=1) rot_centre.rotation_euler.z = radians(360.0) rot_centre.keyframe_insert('rotation_euler', index=2, frame=101) # set linear interpolation for constant rotation speed for c in rot_centre.animation_data.action.fcurves: for k in c.keyframe_points: k.interpolation = 'LINEAR' scn.frame_end = 100
type: AcceptedAnswer

http://stackoverflow.com/comment/87812220
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50397818
score: 0
has text: @IljaEverilä this is the output from print psycopg2. <module 'psycopg2' from '/usr/local/lib/python2.7/dist- packages/psycopg2/__init_

http://stackoverflow.com/comment/88029579
type: Comment
comment on: http://stackoverflow.com/q/50508332
score: 0
type: QuestionComment
has text: https://github.com/MicrosoftDocs/azure-docs/issues/9101 Nothing we can do.

http://stackoverflow.com/q/50520310
has body: I am confused as I see different ways to implement the elbow method to identify the correct number of clusters in Kmean and they produce slightly different results. One method is described here Sklearn kmeans equivalent of elbow method and is using kmeans_inertia_ the other methos is described here https://pythonprogramminglanguage.com/kmeans-elbow-method/ and is using the following command. distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0]) I am wondering what does Kmeans_inertia_ does ? and are both implementation correct ?
downvote count: 0
has title: Comparison of different way of implementing the elbow method
has answer: http://stackoverflow.com/a/54639181
has answer: http://stackoverflow.com/a/50534423
has answer: http://stackoverflow.com/a/67184526
answer count: 4
favorite count: 0
linked to: http://stackoverflow.com/q/41540751
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: k-means
tagged with: cluster-analysis
tagged with: scikit-learn
tagged with: python
has answer: http://stackoverflow.com/a/60049707
score: 2

http://stackoverflow.com/q/50387950
answer count: 1
has answer: http://stackoverflow.com/a/50388104
has body: If I click "Run 'Unittest for ..'" in PyCharm it prints: Launching unittests with arguments python -m unittest /home/sfalk/workspace/git/m-search/python/tests/cluster/pipeline/preprocessing.py in /home/sfalk/workspace/git/m-search/python/tests/cluster/pipeline and reports No tests were found. However, if I copy this exact line which PyCharm claims to run, namely python -m unittest /home/sfalk/workspace/git/m-search/python/tests/cluster/pipeline/preprocessing.py then I get my expected output. $ python -m unittest /home/sfalk/workspace/git/m-search/python/tests/cluster/pipeline/preprocessing.py .. +---+------------+ | _1| _2| +---+------------+ | 1|Hello World!| +---+------------+ . ---------------------------------------------------------------------- Ran 1 test in 4.998s OK The run configuration says: Script path: /home/sfalk/workspace/git/m-search/python/tests/cluster/pipeline/preprocessing.py Working directory: /home/sfalk/workspace/git/m-search/python/tests/cluster/pipeline I don't get this .. It should not matter imho but here's the code of the unit test: import unittest from pyspark import SparkContext, SparkConf, SQLContext class TestPreprocessingText(unittest.TestCase): def test_preprocessingText(self): conf = SparkConf() conf.setMaster('local') conf.setAppName('MyApp') sc = SparkContext.getOrCreate() sql = SQLContext(sc) df = sql.createDataFrame( [ (1, 'Hello World!') ] ) df.show() if __name__ == '__main__': unittest.main()
has title: Getting "No tests were found" when running unittest
type: Question
has comment: http://stackoverflow.com/comment/87791747
accepted answer: http://stackoverflow.com/a/50388104
score: 1
favorite count: 0
tagged with: pycharm
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87792272
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87890518
comment on: http://stackoverflow.com/q/50438288
type: Comment
type: QuestionComment
score: 0
has text: I want to fill a form that has a captcha underneath.

http://stackoverflow.com/q/50452625
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87920006
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50452792
answer count: 4
has comment: http://stackoverflow.com/comment/113128534
has answer: http://stackoverflow.com/a/56730129
has title: No output displays when execute python file
has answer: http://stackoverflow.com/a/50454576
score: 0
linked to: http://stackoverflow.com/q/49519052
has body: Getting a blank screen on executing the python program. Please help. It may be a duplicate question, but I don't know Python very much, because I am an Android developer. Here is my code: import sys import requests from bs4 import BeautifulSoup, SoupStrainer home_url = 'https://parivahan.gov.in/rcdlstatus/' post_url = 'https://parivahan.gov.in/rcdlstatus/vahan/rcDlHome.xhtml' # Everything before the last four digits: GJ03KA first = sys.argv[1] # The last four digits: 0803 second = sys.argv[2] r = requests.get(url=home_url) cookies = r.cookies soup = BeautifulSoup(r.text, 'html.parser') viewstate = soup.select('input[name="javax.faces.ViewState"]')[0]['value'] data = { 'javax.faces.partial.ajax':'true', 'javax.faces.source': 'form_rcdl:j_idt32', 'javax.faces.partial.execute':'@all', 'javax.faces.partial.render': 'form_rcdl:pnl_show form_rcdl:pg_show form_rcdl:rcdl_pnl', 'form_rcdl:j_idt32':'form_rcdl:j_idt32', 'form_rcdl':'form_rcdl', 'form_rcdl:tf_reg_no1': first, 'form_rcdl:tf_reg_no2': second, 'javax.faces.ViewState': viewstate, } r = requests.post(url=post_url, data=data, cookies=cookies) soup = BeautifulSoup(r.text, 'html.parser') table = SoupStrainer('tr') soup = BeautifulSoup(soup.get_text(), 'html.parser', parse_only=table) print(soup.get_text())
upvote count: 1
has comment: http://stackoverflow.com/comment/87918679
downvote count: 1
has comment: http://stackoverflow.com/comment/87918752
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50453236
tagged with: beautifulsoup

http://stackoverflow.com/a/50465299
accepted answer of: http://stackoverflow.com/q/50464273
answers question: http://stackoverflow.com/q/50464273
type: Answer
has body: You can try this, I am printing the value and it's corresponding result. firstArray=[[1,10],[11,31],[32,40],[41,61],[62,78]] secondArray=[[1,10],[12,32],[33,39],[41,78]] foundYou=[] for second in secondArray: for firstindex,first in enumerate(firstArray): if second == first: foundYou.append(first) print(second,":",first) else: if second[0] &gt;= first[0] and second[1] &lt;= first[1]: foundYou.append(first) print(second,":",first) else: try: if second[0] &gt;= first[0] and second[1] &lt;= firstArray[firstindex+1][1] and second[0] &lt; first[1]: foundYou.append(first) foundYou.append(firstArray[firstindex+1]) print(second,":",first,firstArray[firstindex+1]) except IndexError: pass Output: [1, 10] : [1, 10] [12, 32] : [11, 31] [32, 40] [33, 39] : [32, 40] [41, 78] : [41, 61] [62, 78]
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50389061
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I am using tf.estimator.Estimator to train my model. I would now like to try a pre-trained inception_v3 in place of my current model. I stumbled upon this repository that seems to have all the models I could ever need: https://github.com/tensorflow/models/tree/master/research/slim Loading the graph and training seems to work just fine. Now it would also like to use the pre-trained weights that I downloaded from here: http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz I tried multiple variants that I found online, but nothing seems to work thus far. Most of the time I am getting the following error: Tensor name "model/InceptionV3/AuxLogits/Conv2d_1b_1x1/BatchNorm/beta" not found in checkpoint files This is how I build the graph right now: sys.path.insert(0, "./models/research/slim") from nets import nets_factory # ... params.network_name = "inception_v3", params.pre_logits = "PreLogits", params.checkpoint = "inception_v3.ckpt" # ... network_fn = nets_factory.get_network_fn(params.network_name, num_classes=(1001), weight_decay=0.00004, is_training=is_training) logits, end_points = network_fn(images) pre_logits = end_points[params.pre_logits] pre_logits = tf.layers.flatten(inputs=pre_logits) # ... loss = ... train_op = optimizer.minimize(loss, global_step=global_step) model_fn = tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op) estimator = tf.estimator.Estimator(model_fn, params=params, config=config) # ... I tried tensorflow versions v.1.6.0 and v.1.8.0. Both seem to have the same issues. Any ideas? Thank you very much!
tagged with: tf-slim
score: 2
answer count: 0
has title: Tensorflow - Load pre-trained inception_v3 to use with tf.estimator

http://stackoverflow.com/q/50415666
type: Question
upvote count: 4
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50416247
possible better answer: http://stackoverflow.com/a/78401815
answer count: 2
has title: Generic logging function wrapper
has answer: http://stackoverflow.com/a/50416247
has answer: http://stackoverflow.com/a/78401815
has body: So what I'm trying to do is essentially take a bunch of pre-existing functions from commonly used libraries (such as subprocess,shutil,etc...) and wrap them in a function that will ouput what the function is doing as well as errors if any occur. My current code looks something like this. def copytree(self,*args, **kwargs): self.debug(f":- Copying tree from \"{args[0]}\" to \"{args[1]}\"") try: shutil.copytree(*args,**kwargs) except Exception as e: self.error(f":- Failed to copy tree from \"{args[0]}\" to \"{args[1]}\" ; \"{e}\"") return False self.debug(f":- Done") return True I feel like there is probably a better way to do this in which there is a generic wrapper that can be used on any function but I am having trouble conceptualizing it. I'm also not sure if there is a way to account for functions that don't raise exceptions within said generic wrapper. Also: self.debug and self.error are both just from the logging module
downvote count: 0
tagged with: python
score: 4
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/q/50419277
has title: Convert string "02-04-20189.45" into datetime type in pandas dataframe
possible better answer: http://stackoverflow.com/a/50419346
tagged with: string
has answer: http://stackoverflow.com/a/50419346
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87854446
tagged with: pandas
tagged with: datetime
has body: I tried too hard but couldn't do string column - "**02-04-20189.45**" format = **day-month-yearhour(24).minutes** to **datetime** type
tagged with: python
has comment: http://stackoverflow.com/comment/87854358
has comment: http://stackoverflow.com/comment/87855540
has comment: http://stackoverflow.com/comment/87854033
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50419344
has answer: http://stackoverflow.com/a/50419344

http://stackoverflow.com/q/50515772
tagged with: mathematical-optimization
has title: Generating function derivative as Python callable function
downvote count: 0
tagged with: sympy
upvote count: 1
tagged with: function
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/14178101
answer count: 1
favorite count: 0
has body: I was reading this question and I was trying to do the same, but I want the function to have a single parameter say x. And that parameter is an array of "values" to be filled by an optimization solver. For instance: def f(x): return x[0]**2 + 3*x[1] That function will refer to: f(x)=x^2 + 3y, meaning x is an array of variables. Those variables will be present on the current function or not, because they are all the variables in the whole optimization problem, meaning they can be present on the constraints. So I will like to find that functions partial derivatives of all variables. So,in this case, i will need 2 callable functions so I can use it to form a new array that is the Jacobian of the function. Is there a way to do that? How?
type: Question
score: 1
tagged with: python
tagged with: nonlinear-optimization
has answer: http://stackoverflow.com/a/50564568

http://stackoverflow.com/a/50407493
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50394519
upvote count: 1
answers question: http://stackoverflow.com/q/50394519
score: 1
has body: I understand that you want something like #3. This might lead to problems, if some values are similar within the same row. But otherwise, you can create your own sorting of the columns to prevent that larger values cover smaller ones. import matplotlib.pyplot as plt import pandas as pd from matplotlib import cm from itertools import cycle df = pd.read_csv("test.csv", index_col = "weekday") def pyplot_chart(df): #create dictionary for colors by cycling through a predefined colour list color_cycle = cycle([ 'k', 'b', 'r', 'y', 'c', 'm', 'g']) col_dic = {col: next(color_cycle) for col in df} #alternatively, extract colours along a defined colormap #see color maps reference https://matplotlib.org/examples/color/colormaps_reference.html #col_dic = {col: cm.tab20c(1 - i / len(df.columns)) for i, col in enumerate(df)} #cycle through each row of the dataframe for yvalue, row in df.iterrows(): #sort the values within the row, plot largest values first for index, value in row.sort_values(ascending = False).iteritems(): plt.barh(y=yvalue, width=value, color=col_dic[index], height=0.8) #plot invisible columns for labels for col in df.columns: plt.barh(y=df.index, width=0, color=col_dic[col], label = col, height=0) plt.legend() plt.grid(axis="x") plt.show() pyplot_chart(df) Output: As you can see, on Tuesday, where two values are 0.3, you can't distinguish, whether LinkedIn exists or not. You could try to overcome this problem by modifying the width parameter as well, i.e., smaller values have also a smaller width to show similar values behind them.
type: AcceptedAnswer

http://stackoverflow.com/q/50459602
has answer: http://stackoverflow.com/a/50459742
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50460651
has answer: http://stackoverflow.com/a/50460058
has title: How to select dataframe rows between two datetimes?
tagged with: python
possible better answer: http://stackoverflow.com/a/50460651
answer count: 4
has body: I am having trouble selecting rows from a dataframe with a datetime column from a CSV file. I have my code and my sample data. There are no rows returned. import pandas as pd import numpy as np col_names = ['date','msft','nok','aapl','ibm','amzn'] stockprices = pd.read_csv('./stockdata.csv', skiprows=1, names=col_names) stockprices.loc['2018-01-01 9:00:00':'2018-01-01 11:00:00'] CSV file data: date msft nok aapl ibm amzn 2018-01-01 08:00:00 107 2 161 140 1295 2018-01-01 09:00:00 112 1 143 130 1298 2018-01-01 10:00:00 109 10 185 137 1647 2018-01-01 11:00:00 98 11 146 105 1331 2018-01-01 12:00:00 83 3 214 131 1355 Basically, trying to select the 3 rows with 9:00:00, 10:00:00 and 11:00:00 times in the dataframe. Is using the .loc the best way to do this? Thank you.
type: AnsweredQuestion
score: 3
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/50460025
accepted answer: http://stackoverflow.com/a/50459742
downvote count: 0

http://stackoverflow.com/q/50490629
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has comment: http://stackoverflow.com/comment/88824051
has answer: http://stackoverflow.com/a/50490794
score: 3
upvote count: 3
answer count: 2
downvote count: 0
favorite count: 0
type: Question
has title: Oauth redirects me to http instead of https
has answer: http://stackoverflow.com/a/50492164
has body: I work on a python3.6 app that uses flask and oauth2client and I deploy in flexible environment. The command: gcloud app browse outputs the link: https://xxx.appspot.com When I access it, I get redirected to the default route, which requires auth, then redirected to choose my google account after which I get redirected again to the default route but instead this time it's http instead of https. This is the code for setting the default route: @app.route("/") def index(): return redirect(url_for('crud.home')) And this is the controller method for the default route: @crud.route('/home') @oauth2.required def home(): return render_template('home.html') Why is that? How can I make it redirect me back to https?

http://stackoverflow.com/q/50528578
has answer: http://stackoverflow.com/a/50556591
tagged with: python
type: UnansweredQuestion
tagged with: scapy
has answer: http://stackoverflow.com/a/68445637
has title: pdfdump in python not working using scapy
score: 0
answer count: 3
tagged with: parrot-os
has body: #!/bin/bash/python3 from scapy3k.all import *`` import subprocess import os def ifac111(): pkts = sniff(filter="tcp", iface="tun0", count=100) inp = input('want to see a \'pdfdump?\' \n Y/N--&gt; ') fag = pkts.summary() print('-' * 60) what_df = pkts.show() print("^^^ Here you got {} packets {}.".format("100", "scanned")) print("The {} ones are {} and second ones are just {} command".format("first", "summary", "show" )) print(inp) if inp == 'Y': pkts[0].pdfdump() else: print("got ya \f hex0") while 1 &gt; 0: SSS = input('enter your command\'s here:-&gt; \t ') #\t moves 4 spaces if SSS == 'packets': ifac111() elif SSS == 'nworkscan': os.system('sudo nmap localhost/24') elif SSS == 'Virusscan': os.system('sudo chkrootkit') elif SSS == 'clear': subprocess.call('clear') when i run the pdfdump i get this error Traceback (most recent call last): File "scapy2.py", line 27, in &lt;module&gt; ifac111() File "scapy2.py", line 16, in ifac111 pkts[0].pdfdump() File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 418, in pdfdump canvas = self.canvas_dump(**kargs) File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 428, in canvas_dump canvas = pyx.canvas.canvas() NameError: name 'pyx' is not defined sorry if the question is stupid I'm new with coding and been trying to do some research with no result I used ICMP instead of TCP also before on my old os but its not working after changing to parrot os and when I run pdfdump I get that error above
has answer: http://stackoverflow.com/a/50529123
type: Question

http://stackoverflow.com/comment/88082327
score: 0
has text: @MichaelGoldshteyn See my comment on the question itself
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50535001

http://stackoverflow.com/q/50537388
has body: In the following function f, we can either loop on a first or on b first. How to make its code less redundant? def myfunction(a): pass def f(first_loop_on_a=True): if first_loop_on_a: for a in range(10): A = "%010i" % a myfunction(a) for b in range(5): print A, b else: for b in range(5): for a in range(10): A = "%010i" % a myfunction(a) print A, b f(True) f(False) I was thinking about product, but still, we would have: def myfunction2(a, b): A = "%010i" % a myfunction(a) print A, b def f(first_loop_on_a=True): if first_loop_on_a: for a, b in product(range(10), range(5)): myfunction2(a, b) else: for b, a in product(range(5), range(10)): myfunction2(a, b) which is still a bit redundant.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50537692
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88087514
has answer: http://stackoverflow.com/a/50537692
tagged with: loops
possible better answer: http://stackoverflow.com/a/50537697
has title: How to make these two alternatives about looping on cartesian product less redundant?
type: Question
has comment: http://stackoverflow.com/comment/88087495
has answer: http://stackoverflow.com/a/50537697
has answer: http://stackoverflow.com/a/50537726
tagged with: cartesian-product
tagged with: python

http://stackoverflow.com/q/50467040
has answer: http://stackoverflow.com/a/50467091
has comment: http://stackoverflow.com/comment/87947257
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87947145
has comment: http://stackoverflow.com/comment/87947301
possible better answer: http://stackoverflow.com/a/50467091
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50467056
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50467056
has title: convert an array into a list of objects
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50467082
favorite count: 0
type: Question
tagged with: python-3.x
has body: All, I have a dataframe which I am using to extract all unique identifiers as follows: myTradeFrame['coll_cusip'].unique() the output is: array(['BRSUJX0F8', 'BRSU17NB8', '010831BE4', ..., '912828J84', '912828R36', '912810RC4'], dtype=object) How can I convert that array into something that looks like this: ('BRSUJX0F8', 'BRSU17NB8', '010831BE4', ..., '912828J84', '912828R36', '912810RC4') Many Thanks

http://stackoverflow.com/comment/87919628
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50418988
has text: Thank you very much for helping me solving the problem. I have fixed it by changing the way to process the documents, instead of using a `GeneratorType` I load it in a `list`.
type: Comment

http://stackoverflow.com/comment/87902002
type: Comment
type: QuestionComment
has text: @fuglede: Expansion stops for me on sqrt(2) at 54 digits (1.4142135623730951454746218587388284504413604736328125)
score: 0
comment on: http://stackoverflow.com/q/50443970

http://stackoverflow.com/comment/87939310
type: Comment
comment on: http://stackoverflow.com/a/50389624
type: AnswerComment
has text: thank you for your answer, it's very helpful, just want to get something straight, so when you are parsing the row with this formula, is it just formating it in a dictionary format ? or converting it actually ?
score: 0

http://stackoverflow.com/a/50493066
score: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/50493027
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50493027
has body: You can use: df.A = df.A.map({'+': 1, '-': -1})
upvote count: 10

fragmentation
tags question: http://stackoverflow.com/q/50416915
type: Tag
tag name: fragmentation

virtualenv
tags question: http://stackoverflow.com/q/50510139
tag name: virtualenv
tags question: http://stackoverflow.com/q/50391617
tags question: http://stackoverflow.com/q/50412823
tags question: http://stackoverflow.com/q/50511109
tags question: http://stackoverflow.com/q/50404212
tags question: http://stackoverflow.com/q/50467920
tags question: http://stackoverflow.com/q/50456390
tags question: http://stackoverflow.com/q/50427087
type: Tag
tags question: http://stackoverflow.com/q/50456360
tags question: http://stackoverflow.com/q/50482306
tags question: http://stackoverflow.com/q/50509868
tags question: http://stackoverflow.com/q/50533119
tags question: http://stackoverflow.com/q/50477348

http://stackoverflow.com/q/50536736
favorite count: 0
type: Question
tagged with: tuples
score: 2
type: AnsweredQuestion
tagged with: list
has title: Create a list from a list of tuples
has comment: http://stackoverflow.com/comment/88085849
accepted answer: http://stackoverflow.com/a/50536847
tagged with: python
has body: I have a list like this: mylist = [(20, 'Start', '2008-10-10', 'TBS'),...,(20, 'End', '2008-11-09', 'NG'), (21, 'Start', '2008-12-10', 'TBS'),...,(21, 'End', '2008-12-15', 'G'), (22, 'Start', '2009-01-10', 'TBS'),...,(22, 'End', '2009-12-10', 'B'),..] I put '...' in the example above to say there are other items for each id like 20, 21 and 22 in the list but I don't want them. The only items that I want are the items that include 'Start' or 'End'.(Other items have different words than these two words.) I want to create a nested list like this: [[20, 'Start', '2008-10-10', 'End', '2008-11-09', 'NG'] , [21, 'Start', '2008-12-10', 'End', '2008-12-15', 'G'], [22, 'Start', '2009-01-10', 'End', '2009-12-10', 'B']] Here is my code: code = 0 brr = [] for row in myList: if row[1] == "Start": arr = [] code = row[0] arr.append([row[0], row[1], row[2]]) continue if row[0] == code and row[1] == "End": arr.append([row[1], row[2], row[3]]) brr.append(arr) for k in brr: print(k) But the problem is that it creates something like this: [[[20, 'Start', '2008-10-10', 'End'], ['2008-11-09', 'NG']] , [[20, 'Start', '2008-10-10', 'End'], ['2008-11-09', 'NG']] , [[20, 'Start', '2008-10-10', 'End'], ['2008-11-09', 'NG']] , [[21, 'Start', '2008-12-10', 'End'], ['2008-12-15', 'G']], [[21, 'Start', '2008-12-10', 'End'], ['2008-12-15', 'G']], [[22, 'Start', '2009-01-10', 'End'], ['2009-12-10', 'B']]] And for each items I have multiple rows in the list. I don't know why? Sorry if my question is too long.
has answer: http://stackoverflow.com/a/50538171
answer count: 4
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50536793
has comment: http://stackoverflow.com/comment/88085740
possible better answer: http://stackoverflow.com/a/50536793
has answer: http://stackoverflow.com/a/50582342
has comment: http://stackoverflow.com/comment/88085866
has comment: http://stackoverflow.com/comment/88085685
has answer: http://stackoverflow.com/a/50536847
has comment: http://stackoverflow.com/comment/88085769
has comment: http://stackoverflow.com/comment/88085756

http://stackoverflow.com/q/50534429
type: Question
has body: I made a FC neural network with numpy based on the video's of welch's lab but when I try to train it I seem to have exploding gradients at launch, which is weird, I will put down the whole code which is testable in python 3+. only costfunctionprime seem to break the gradient descent stuff going but I have no idea what is happening. Can someone smarter than me help? EDIT: the trng_input and trng_output are not the one I use, I use a big dataset import numpy as np import random trng_input = [[random.random() for _ in range(7)] for _ in range(100)] trng_output = [[random.random() for _ in range(2)] for _ in range(100)] def relu(x): return x * (x &gt; 0) def reluprime(x): return (x&gt;0).astype(x.dtype) class Neural_Net(): def __init__(self, data_input, data_output): self.data_input = data_input self.trng_output = trng_output self.bias = 0 self.nodes = np.array([7, 2]) self.LR = 0.01 self.weightinit() self.training(1000, self.LR) def randomweight(self, n): output = [] for i in range(n): output.append(random.uniform(-1,1)) return output def weightinit(self): self.weights = [] for n in range(len(self.nodes)-1): temp = [] for _ in range(self.nodes[n]+self.bias): temp.append(self.randomweight(self.nodes[n+1])) self.weights.append(temp) self.weights = [np.array(tuple(self.weights[i])) for i in range(len(self.weights))] def forward(self, data): self.Z = [] self.A = [np.array(data)] for layer in range(len(self.weights)): self.Z.append(np.dot(self.A[layer], self.weights[layer])) self.A.append(relu(self.Z[layer])) self.output = self.A[-1] return self.output def costFunction(self): self.totalcost = 0.5*sum((self.trng_output-self.output)**2) return self.totalcost def costFunctionPrime(self): self.forward(self.data_input) self.delta = [[] for x in range(len(self.weights))] self.DcostDw = [[] for x in range(len(self.weights))] for layer in reversed(range(len(self.weights))): Zprime = reluprime(self.Z[layer]) if layer == len(self.weights)-1: self.delta[layer] = np.multiply(-(self.trn…
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/88248302
tagged with: python
accepted answer: http://stackoverflow.com/a/50636183
downvote count: 0
tagged with: neural-network
has answer: http://stackoverflow.com/a/50636183
has comment: http://stackoverflow.com/comment/88278354
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/50621383
tagged with: backpropagation
upvote count: 3
has answer: http://stackoverflow.com/a/50621383
has title: backpropagation trouble; getting higher and higher total cost up until its infinity
favorite count: 0

http://stackoverflow.com/a/67875978
upvote count: 1
answers question: http://stackoverflow.com/q/50398622
score: 1
has body: pip3 uninstall pyautogui pip3 uninstall Pillow then reinstall the modules and restart you editor.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/87914398
score: 0
comment on: http://stackoverflow.com/q/50450198
type: QuestionComment
has text: I am new so just trying various cut & paste ideas from Google.
type: Comment

http://stackoverflow.com/q/50453772
tagged with: django-2.0
has comment: http://stackoverflow.com/comment/87920741
has comment: http://stackoverflow.com/comment/87920928
has body: I just have started my first project by using Django 2.0 in which I need to define a URL in a way as: http://localhost:8000/navigator?search_term=arrow But I couldn't know how to define a string parameter for a URL in Django 2.0 Here's what I have tried: From ulrs.py: from Django.URLs import path from. import views urlpatterns = [ path('navigator/&lt;str:search_term&gt;', views.GhNavigator, name='navigator'), ] Any help?
score: 6
upvote count: 6
tagged with: django
has comment: http://stackoverflow.com/comment/87920839
tagged with: django-urls
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87920945
answer count: 2
has title: URL patterns in Django 2
has answer: http://stackoverflow.com/a/65409413
possible better answer: http://stackoverflow.com/a/65409413
has answer: http://stackoverflow.com/a/50453870
downvote count: 0
accepted answer: http://stackoverflow.com/a/50453870
has comment: http://stackoverflow.com/comment/87920792
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87920813

access-denied
tags question: http://stackoverflow.com/q/50454896
tag name: access-denied
type: Tag

infinite-loop
tags question: http://stackoverflow.com/q/50424493
type: Tag
tag name: infinite-loop
tags question: http://stackoverflow.com/q/50408226

http://stackoverflow.com/comment/87884200
has text: Hello again. This is a gist with the code and result - https://gist.github.com/aktan4uk/b6f6f93d18d29d585099f1087bda065e
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50434493
type: AnswerComment

http://stackoverflow.com/comment/121123763
comment on: http://stackoverflow.com/a/50410256
type: Comment
has text: The rpm repo has been moved to https://repo.ius.io/ius-release-el7.rpm
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87830038
score: 0
comment on: http://stackoverflow.com/q/50392372
has text: I find the question unclear. Do you need to cut somehow the colorbar between 2k and 10k?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/138468744
comment on: http://stackoverflow.com/a/59887400
score: 0
has text: Just a supplement to this answer. I get this warning by having 2 jupyter notebooks imported with tensorflow, even if only one notebook is running the model and the other one is not doing anything.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50396533
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50396359
has body: g.to_csv('C:\Users\egagne\Downloads\'n+'stars'+'.csv'') needs to be g.to_csv('C:\\Users\\egagne\\Downloads\\'+n+'stars.csv'). There were two things wrong -- the backslash is an escape character so if you put a ' after it, it will be treated as part of your string instead of a closing quote as you intended it. Using \\ instead of a single \ escapes the escape character so that you can include a backslash in your string. Also, you did not pair your quotes correctly. n is a variable name but from the syntax highlighting in your question it is clear that it is part of the string. Similarly you can see that stars and .csv are not highlighted as part of a string, and the closing '' should be a red flag that something has gone wrong. Edit: I addressed what is causing the problem but Ami Tavory's answer is the right one -- though you know this is going to run on windows it is a better practice to use os.path.join() with directory names instead of writing out a path in a string. str(n) is also the right way to go if you are at all unsure about the type of n.
score: 1
upvote count: 1

http://stackoverflow.com/comment/87990246
has text: Not only the path is incorrect, the `prefix` parameter is also necessary, but that's not documented in the `WhiteNoise` documentation. Also useful maybe, the `stable` WhiteNoise documentation is even more outdated, you have to use the `WhiteNoise latest` documentation: http://whitenoise.evans.io/en/latest/flask.html . Still, it does not mention the `prefix` requirement. And no, `whitenoise.compress` is not needed. I tried with and without present `.gz` files and seems `whitenoise`generates it on its own. At least that's what happened for my app on Heroku.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50487527
type: AnswerComment

http://stackoverflow.com/q/50499936
downvote count: 1
has title: python: use strptime() for object that is not zero padding
accepted answer: http://stackoverflow.com/a/50500116
favorite count: 0
tagged with: timestamp
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50500116
score: 0
possible better answer: http://stackoverflow.com/a/50500033
has answer: http://stackoverflow.com/a/50500033
has body: I have a pandas data frame that has two columns both of them in object format. They contain year (4 means 2004) and month. I want to subtract them. start end 4-oct 12-nov dec-3 11-oct jan-5 16-dec 12-oct 17-apr I tried: data['end'].apply(lambda x: datetime.strptime(repr(x), "'%y-%b'")) data['end'].apply(lambda x: datetime.strptime(repr(x), "b'%y-%b'")) But they did not work. How can I deal with the different format and non zero padding in the first column ('%y-%b' and '%b-%y') How can I apply strptime() to object format? (can repr() convert them to string)?
tagged with: python
has comment: http://stackoverflow.com/comment/88012729
has comment: http://stackoverflow.com/comment/88012877
answer count: 2
tagged with: time-series
has comment: http://stackoverflow.com/comment/88012777
tagged with: data-mining
tagged with: data-cleaning
upvote count: 1

http://stackoverflow.com/comment/88044486
score: 0
has text: You never use the `pat_match` flag.
comment on: http://stackoverflow.com/q/50515266
type: Comment
type: QuestionComment

jupyter-notebook
tags question: http://stackoverflow.com/q/50517478
tags question: http://stackoverflow.com/q/50469213
tags question: http://stackoverflow.com/q/50428304
tags question: http://stackoverflow.com/q/50414527
tags question: http://stackoverflow.com/q/50437329
tags question: http://stackoverflow.com/q/50439371
tags question: http://stackoverflow.com/q/50509148
tags question: http://stackoverflow.com/q/50439035
tags question: http://stackoverflow.com/q/50467077
tags question: http://stackoverflow.com/q/50473417
tags question: http://stackoverflow.com/q/50405012
tags question: http://stackoverflow.com/q/50454470
tags question: http://stackoverflow.com/q/50518825
tags question: http://stackoverflow.com/q/50486598
tags question: http://stackoverflow.com/q/50474244
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/50399751
tags question: http://stackoverflow.com/q/50488803
tags question: http://stackoverflow.com/q/50474070
tags question: http://stackoverflow.com/q/50409078
tags question: http://stackoverflow.com/q/50494230
tags question: http://stackoverflow.com/q/50479247
type: Tag
tags question: http://stackoverflow.com/q/50442324
tags question: http://stackoverflow.com/q/50484397
tags question: http://stackoverflow.com/q/50493837
tags question: http://stackoverflow.com/q/50507321
tags question: http://stackoverflow.com/q/50507404
tags question: http://stackoverflow.com/q/50392372
tags question: http://stackoverflow.com/q/50411947
tags question: http://stackoverflow.com/q/50497374
tags question: http://stackoverflow.com/q/50416710
tags question: http://stackoverflow.com/q/50485997

http://stackoverflow.com/comment/87918264
type: Comment
type: QuestionComment
has text: maybe posting the input csv data would be a good idea then
score: 0
comment on: http://stackoverflow.com/q/50452290

http://stackoverflow.com/q/50436833
tagged with: django
has answer: http://stackoverflow.com/a/50443149
tagged with: django-rest-framework
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87887791
tagged with: rest
has comment: http://stackoverflow.com/comment/87887729
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87887924
has title: Django Rest Framework - object of type 'type' is not json serializable error
has body: I am creating rest api using Django Rest Framework. I am using Djanfo 2.0.5 and python 3. I am getting error "Object of type 'type' is not JSON serializable." at the time of submitting form in browser. I tried with POSTMAN and also getting same error. I have attached snaps of my code of model, serializers and view classes. from django.db import models # Create your models here. class User(models.Model): full_name = models.CharField(max_length=255, blank=False) email = models.EmailField(blank=False, unique=True) password = models.CharField(max_length=100, blank=False) profile_pic = models.FileField() age = models.CharField(max_length=3, blank=False) location_lat = models.CharField(max_length=100, blank=False) location_long = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=255, blank=False) experience_level = models.CharField(max_length=50, blank=False) utr_rating = models.CharField(max_length=50, blank=False) match_price = models.IntegerField auth_token = models.CharField(max_length=100, blank=False, unique=True) fb_token = models.CharField(max_length=100, unique=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.full_name) from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'full_name', 'email', 'password', 'profile_pic', 'age', 'location_lat', 'location_long', 'address', 'experience_level', 'utr_rating', 'match_price', 'auth_token', 'fb_token', 'date_created', 'date_modified') read_only_fields = ('date_created', 'date_modified', 'profile_pic') from rest_framework import generics from .serializers import UserSerializer from .models import User class CreateUser(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer def perform_create(self, serializer): serializer.save() Traceback
has comment: http://stackoverflow.com/comment/87887970
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87887861
has comment: http://stackoverflow.com/comment/87887754
downvote count: 0
has comment: http://stackoverflow.com/comment/87887707
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87887769
answer count: 1

http://stackoverflow.com/q/50479589
downvote count: 0
has title: common value in python dictionaries
has answer: http://stackoverflow.com/a/50480740
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50479667
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50479603
tagged with: python
tagged with: dictionary
score: 2
answer count: 3
has body: map1 = { 1: "Sam", 2: "Rich", 3 : "Mike", 4: "Bob", 6: "Donald"} map2 = { 5: "Sally", 6 : "Donald", 7: "Roger", 1: "Sam"} I want to print common names in both dicts, Can anyone help me out

http://stackoverflow.com/q/50507990
answer count: 2
has answer: http://stackoverflow.com/a/50509063
tagged with: python
type: UnansweredQuestion
tagged with: lambda
has body: poly1 and poly2 are both lists containing coordinates (x,y). Now this function is pre-implemented, which I find hard to understand: def interpolate(): # This function returns a list of tuples (x, y). return map(lambda a, b: (a[0] + b[0], a[1] + b[1]), poly_1, [(time * x[0], time * x[1]) for x in map(lambda p, q: (q[0] - p[0], q[1] - p[1]), poly_1, poly_2)]) But can you actually explain what happens in interpolate? All I can extract from this is (as far as the lambdas go) def func_a(a, b): return (a[0] + b[0], a[1] + b[1]) and def func_b(p, q): return (q[0] - p[0], q[1] - p[1]), poly_1, poly_2) But all that mapping is confusing to me.
has comment: http://stackoverflow.com/comment/88027976
has comment: http://stackoverflow.com/comment/88029040
has comment: http://stackoverflow.com/comment/88028160
has answer: http://stackoverflow.com/a/50508939
score: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88028033
tagged with: interpolation
tagged with: geometry
has title: Interpolation lambda hard to understand
type: Question
upvote count: 2

http://stackoverflow.com/comment/88047649
has text: @mr_burathi last comment: You should checkout the answer and if it works, accept it. It is probably a bit better than the answer I would give you (which would involve https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50515596
type: Comment

http://stackoverflow.com/q/50524179
type: AnsweredQuestion
score: 0
has title: HttpWebRequest to upload docx file to curl python from c#
has answer: http://stackoverflow.com/a/50597935
tagged with: http://stackoverflow.com/tag/docx
tagged with: c#
type: Question
tagged with: python
answer count: 1
tagged with: httpwebrequest
accepted answer: http://stackoverflow.com/a/50597935
has body: This is what i use to call from ubuntu: curl -X POST http://192.168.XX.XX:XXXX -F 'file[]=@file1.docx' -i I want to execute this from c#. Note: I tried other stackoverflow answers/solutions, but i always get : internal server error : 505

http://stackoverflow.com/q/50470557
tagged with: subclass
tagged with: python
has body: Here's my general problem space: I have a byte/bit protocol with a device over I2C. I've got a "database" of the commands to fully describe all the bitfields types and values and enumerations. I have a class to consume the database and a i2c driver/transactor so that I can then call commands and get responses. MyProtocol = Protocol('database.xml',I2CDriver()) theStatus = MyProtocol.GET_STATUS() creates the proper byte stream for the GET_STATUS command, sends it over the i2c and returns the response as a byte array currently. I can get it to pretty print the response inside of the GET_STATUS() implementation, but I want to move that behavior to return object, rather than in the command. I want my return object to be 'smart': theStatus needs to have the list/array of bytes plus a reference to its field definitions. I want theStatus to act like an list/bytearray, so I can directly inspect the bytes. I don't care if slices are anything other than lists of bytes or bytearray. Once they've been sliced out they're just bytes. I want 'theStatus' to be able to be printed print(theStatus) and have it pretty print all the fields in the status. I'm comfortable on how to make this happen once I settle on a workable data structure that allows me to access the bytes and the data base. I want to inspect theStatus by field name with something like theStatus.FIELDNAME or maybe theStatus['FIELDNAME']'. Same thing: once I have a workable data structure that has the byte array and database as members, I can make this happen. The problem is I don't know the "right" data structure to cause the least amount of problems. Any suggestions on the most pythonic way to accomplish this? My initial thought was to subclass list and add the field definitions as a member, but it seems like python doesn't like that idea at all. Composition seems like the next bet, but getting it to act like a proper list seems like that might be a bunch of work to get it 'right'.
upvote count: 4
type: AnsweredQuestion
has title: Pythonic way of subclassing a list
answer count: 3
has answer: http://stackoverflow.com/a/50470725
accepted answer: http://stackoverflow.com/a/50470705
downvote count: 0
tagged with: data-structures
has answer: http://stackoverflow.com/a/50470705
score: 4
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50470725
has answer: http://stackoverflow.com/a/50470675

http://stackoverflow.com/a/50503279
has comment: http://stackoverflow.com/comment/88019066
accepted answer of: http://stackoverflow.com/q/50503246
type: Answer
score: 3
answers question: http://stackoverflow.com/q/50503246
upvote count: 3
has body: I believe need pop with DataFrame contructor and join to original: df = df.join(pd.DataFrame(df.pop('var_map').values.tolist(), index=df.index)) print (df) id feature_1 feature_2 feature_3 feature_4 0 7068 2 4.0 8.0 8.0 1 7116 2 5.0 7.0 NaN 2 7154 1 8.0 17.0 NaN But if input is json better should be use json_normalize.
has comment: http://stackoverflow.com/comment/88018920
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87967000
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50476632
has text: You can't do what you want because the `ser` global is created **when you import**. There is no point in putting that `global ser; ser = ...` code in a `class` definition anyway, you may as well just use `ser = ...` *at the module level*.
score: 0

http://stackoverflow.com/comment/88104831
score: 0
type: Comment
has text: No print output was being returned, which made me look into the template for the CreateView itself to see if the 'action' of the form was being sent elsewhere. Low-and-behold, I found my problem. Thanks for brainstorming with me, sir.
type: AnswerComment
comment on: http://stackoverflow.com/a/50518583

http://stackoverflow.com/comment/88072652
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50530401
has text: Is this syntax proper to python ?
score: 0

http://stackoverflow.com/comment/87986731
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50486478
has text: Sorry, I don't know Django, but at least we've identified the encoding, which is half the battle.
score: 0

http://stackoverflow.com/comment/87795096
type: Comment
has text: Is it storing as simple string of hexadecimal representation or is it actually hexadecimal values of the data? I mean can I do any math operations on the data?
comment on: http://stackoverflow.com/a/50385323
score: 0
type: AnswerComment

http://stackoverflow.com/a/62966572
answers question: http://stackoverflow.com/q/50483235
has body: Cause It usually happened when your installation accidently stop , some of the data remain in cache which causes the problem . Note: this type of error can also be occured in other packages. Solution Go to that directory C:\Users\User_Name\AppData\Local\pip\cache Delete cache file Then upgrading the pip python -m pip install --upgrade pip Install the package you want python -m pip install spacy
type: Answer
score: 0

http://stackoverflow.com/comment/124437005
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51890271
has text: this link can be helpful if above answers are not understood https://www.pythonpool.com/pip-vs-pip3/
type: Comment

http://stackoverflow.com/q/50482810
has answer: http://stackoverflow.com/a/50484880
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: python-requests
has title: How to extract table from a webpage
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has body: I have been trying to extract the table from a webpage. I don't know what to do next here is what I wrote. import requests from bs4 import BeautifulSoup page= requests.get('http://www.moneycontrol.com/financials/nmdc/ratios/NMD02') soup = BeautifulSoup(page.text, 'html.parser') table = soup.find(class_='tabns MR10') and now I don't know what to do. I can't find table.
possible better answer: http://stackoverflow.com/a/50483680
accepted answer: http://stackoverflow.com/a/50484880
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/50483680

http://stackoverflow.com/q/50493081
tagged with: css
has body: I am working on building a website with python Django. I want to do the following project. First, I get the input values from the website. Then I use the input values to produce a plot and save it in one place of the server. After that, I want to send the location of the plot back to the website. My codes are given below In views.py from django.shortcuts import render import trip.forms #First define to Django form.Forms form_class = trip.forms.AdHocTripReportRequestForm graphurl_form=trip.forms.Graphurl #Then define a "get" function def get(self, request): encoded_cabinets, id_dirserved = self._encoded_page_precache() ctx = { 'CABINETS': encoded_cabinets, 'ID_DIRSERVED': id_dirserved, 'form': self.form_class(), 'graph': self.graphurl_form(), } # add adhoc settings profile = get_profile(request.user) if profile: ctx.update(defaults=profile.get_settings('adhoctrip')) context = RequestContext(request, ctx) return render_to_response("adhoc-trip.html", context) #after that, there is a post function def post(self, request): #1) read the input values form = self.form_class(request.POST) if form.is_valid(request.user): # update adhoc settings profile = get_profile(request.user) if profile: settings_form = DateRangeDowEmailForm(request.POST) if settings_form.is_valid(): profile.set_settings('adhoctrip', settings_form.cleaned_data) profile.save() # 2) some functions to get the link string graphurl=trip.tasks.TripReportTask().delay(trr, recipients, server, save_as, trr1) # 3) set this information to the html file graphurl_form_tmp=trip.forms.Graphurl(request.POST or None, initial={'name': graphurl}) return render(request, "adhoc-trip.html", {'graph' : graphurl_form_tmp,}) In the adhop-trip.html &lt;script type="text/javascript"&gt; var TripButtonBase = Backbone.Model.extend({ initialize: function(options) { options = options || {}; this.waypoints = options.waypoints; this.dateInput = options.dateInput; this.corridorType = options.corridorType; this.compareYear=options.compareY…
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/88001128
tagged with: django
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88009868
has title: python django how to send parameters to website in Post request
has answer: http://stackoverflow.com/a/50495419
tagged with: python
score: -1

http://stackoverflow.com/q/50443298
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm fairly new to Python programming and am seeking assistance to use Python 3 to interface into Ideal Software's Virtual Print Engine DLL on Windows 7, 8 and 10. I've searched everywhere for a solution and contacted the DLL's author without any luck. He doesn't use Python and his Python example doesn't work. Goal I want to convert to Python 3 Ideal Software's simple C example from their Programmer's Manual as follows... void MakeDoc(HWND hWndParent) { // hWndParent is the window handle of your application window VpeHandle hDoc = VpeOpenDoc(hWndParent, "Test", 0); VpeWriteBox(hDoc, 1, 1, 5, 1.5, "Hello World!"); VpeLine(hDoc, 1.5, 3, 5, 6.5); VpeWriteDoc(hDoc, "hello world.pdf"); VpePreviewDoc(hDoc, NULL, VPE_SHOW_NORMAL); } You may open as many documents simultaneously as you like. The documents are identified by a unique handle (VpeHandle, which is a 32-bit integer on 32-bit platforms and a 64-bit integer on 64-bit platforms) with a value different from NULL, which is returned by VpeOpenDoc(). Use this handle in successive calls to the output functions. Each document might send messages. The messages are received by the window, which is specified as parent-window in the first parameter of VpeOpenDoc(). From the DLL reference guide the VpeOpenDoc function is described as... 3.2 VpeOpenDoc Creates a new document with one initial blank page. VpeHandle VpeOpenDoc(HWND hwndParent, LPCSTR title, long flags) HWND hwndParent----a window of your calling application that will be the parent window of the VPE Preview Window. VPE exchanges messages with it. If the Preview is embedded, this will also be the host window of the Preview. This parameter may be NULL, for example to use VPE in windowless applications like server processes or batch jobs. In this case you can install a message callback function, in order to receive events generated by VPE. For details, see VpeSetMsgCallback(). For non-Windows platforms this parameter must be NULL. LPCSTR title ----title of the Preview …
has title: Trying to access functions in Virtual Print Engine dll using python 3 ctypes in windows
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: dll

http://stackoverflow.com/q/50455653
has title: can output file be modified to generate blocks of data?
has comment: http://stackoverflow.com/comment/87926367
type: Question
has body: i am in need of assistance...i have written out code in python to determine all combinations of a set base...however, the output file is enormous depending on the length of the base is it possible to add code which would enable it to create output files in blocks of say 5gbs which could then be deleted from the total output but still allow the program to continue where it left off? this is my biggest concern...i'm unsure how to approach this without losing what it has already generated but i fear it may not be feasible...any suggestions would be greatly appreciated...thanks. wendy current code: import itertools BASE = "stayreadytokeepfromgettingready" REPEAT = 4 def repetitions_for_letter(letter): return [letter * count for count in range(1, REPEAT + 1)] def repetitions_for_word(word): return [repetitions_for_letter(letter) for letter in word] def generate(word): length = len(word) repetitions = repetitions_for_word(word) file_object = open('possibilities.txt', 'w') print("Begining generation...") for pick_indexes in itertools.product(range(REPEAT),repeat=length): parts = [repetitions[idx][pick] for idx, pick in enumerate(pick_indexes)] file_object.write("".join(parts) + "\n") file_object.close() print("Finished...") generate(BASE)
has comment: http://stackoverflow.com/comment/87925235
tagged with: algorithm
has comment: http://stackoverflow.com/comment/87925038
tagged with: python
has comment: http://stackoverflow.com/comment/87926364
score: 0
tagged with: list
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50457247
tagged with: tensor
has body: I'm trying to find variables that end in train_step from tf.report_uninitialized_variables(), but you can't iterate over tensors without eager execution. I get that you need to use tf.map_fn, but I do not understand it well enough. This is what I have: variables = [] for s, t in zip(tf.report_uninitialized_variables().eval(session=sess), tf.report_uninitialized_variables()): if 'train_step' in s: variables.append(t) train_step_init = tf.variables_initializer(variables, name='train_step_init')
answer count: 1
has title: Tensorflow finding matching strings in tensor
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87930922
type: Question
linked to: http://stackoverflow.com/q/44268206
has comment: http://stackoverflow.com/comment/87931867
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50519032
accepted answer: http://stackoverflow.com/a/50519032

http://stackoverflow.com/a/50518583
answers question: http://stackoverflow.com/q/50518388
has comment: http://stackoverflow.com/comment/88080742
has comment: http://stackoverflow.com/comment/88081752
score: 0
has body: I think your error is trying to call the super method. Essentially, if you look into what form_valid does: def form_valid(self, form): """If the form is valid, save the associated model.""" self.object = form.save() return super().form_valid(form) So in other words, after you save your post with the group and user added in, the form then saves again without that, overwriting your first save. Here's what I'd recommend: self.object = form.save(commit = False) self.object.group = self.form_group self.object.user = self.request.user self.object.save() And then use return redirect() to redirect to wherever you need to go
has comment: http://stackoverflow.com/comment/88104831
has comment: http://stackoverflow.com/comment/88068503
has comment: http://stackoverflow.com/comment/88081648
type: Answer
has comment: http://stackoverflow.com/comment/88080826
has comment: http://stackoverflow.com/comment/88068119

save
tags question: http://stackoverflow.com/q/50453911
tags question: http://stackoverflow.com/q/50411516
tag name: save
tags question: http://stackoverflow.com/q/50457943
type: Tag
tags question: http://stackoverflow.com/q/50419162

http://stackoverflow.com/q/50427760
possible better answer: http://stackoverflow.com/a/50427962
has answer: http://stackoverflow.com/a/50427846
accepted answer: http://stackoverflow.com/a/50427846
has answer: http://stackoverflow.com/a/50427962
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87871122
has title: Sum categorical feature labels across columns for given row, pandas
favorite count: 0
type: Question
tagged with: python-3.x
has body: What would be a pythonic way of summing (same) label counts of categorical variables for each instance in a df? For eg: qualityOfLife_df = pd.DataFrame([['A', 'Up', 'Up', 'Same'], ['B', 'Up', 'Down', 'Up'], ['C', 'Down', 'Down', 'Down']], columns = ['City', 'Crime', 'Pollution', 'Jobs']) should give, after adding in the label count columns: City Crime Pollution Jobs nUp nDown nSame 0 A Up Up Same 2 0 1 1 B Up Down Up 2 1 0 2 C Down Down Down 0 3 0 Thanks
tagged with: counter
tagged with: python
has answer: http://stackoverflow.com/a/50428041
score: 4
upvote count: 4

http://stackoverflow.com/a/50398080
has comment: http://stackoverflow.com/comment/87812517
downvote count: 0
has body: The reason you could use classes like BoxLayout and GridLayout even without explicitly importing them is because they are parts of the library anyway. As for your question on when is it necessary to explicitly import libraries, I think it's a good programming practice to always do so. This way, you'll be able to avoid confusion in referring to classes or functions.
upvote count: 1
answers question: http://stackoverflow.com/q/50397890
score: 1
type: Answer

http://stackoverflow.com/q/50515596
has comment: http://stackoverflow.com/comment/88046901
has answer: http://stackoverflow.com/a/50529564
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50518585
has answer: http://stackoverflow.com/a/50515863
has answer: http://stackoverflow.com/a/50517741
has comment: http://stackoverflow.com/comment/88044366
has comment: http://stackoverflow.com/comment/88044450
has comment: http://stackoverflow.com/comment/88045673
has comment: http://stackoverflow.com/comment/88047950
tagged with: key
has comment: http://stackoverflow.com/comment/88047429
downvote count: 1
has comment: http://stackoverflow.com/comment/88046527
favorite count: 0
has comment: http://stackoverflow.com/comment/88047424
has comment: http://stackoverflow.com/comment/88047209
has comment: http://stackoverflow.com/comment/88047160
answer count: 4
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/88046940
tagged with: python
tagged with: sorting
tagged with: lambda
has comment: http://stackoverflow.com/comment/88046930
has title: Sort list of strings by very special key
has body: I must implement sorting the list of strings in a way which is much similar to sorted function, but with one important distinction. As you know, the sorted function accounts space character prior digits character, so sorted(['1 ', ' 9']) will give us [' 9', '1 ']. I need sorted that accounts digit character prior space chars, so in our example the result will be ['1 ', ' 9']. Update As I understand, by default the sorted behaviour relies on the order of chars in ascii 'alphabet' (i.e. ''.join([chr(i) for i in range(59, 127)])), so I decided to implement my own ascii 'alphabet' in the my_ord function. I planned to use this function in junction with simple my_sort function as a key for sorted, def my_ord(c): punctuation1 = ''.join([chr(i) for i in range(32, 48)]) other_stuff = ''.join([chr(i) for i in range(59, 127)]) my_alphabet = string.digits + punctuation1 + other_stuff return my_alphabet.find(c) def my_sort(w): return sorted(w, key=my_ord) like this: sorted([' 1 ', 'abc', ' zz zz', '9 '], key=my_sort). What I'm expecting in this case, is ['9 ', ' 1 ', ' zz zz', 'abc']. Unfortunately, the result not only doesn't match the expected - moreover, it differs from time to time.
score: -1
has comment: http://stackoverflow.com/comment/88045176
has comment: http://stackoverflow.com/comment/88047649
accepted answer: http://stackoverflow.com/a/50529564
has comment: http://stackoverflow.com/comment/88047369
linked to: http://stackoverflow.com/q/265960
possible better answer: http://stackoverflow.com/a/50515863
has comment: http://stackoverflow.com/comment/88047260
has comment: http://stackoverflow.com/comment/88043771
has comment: http://stackoverflow.com/comment/88047832

http://stackoverflow.com/q/50460222
downvote count: 1
tagged with: console
favorite count: 0
type: Question
has body: I have defined a list in Python code. list = ['kumar','satheesh','rajan'] BOLD = '\033[1m' for i, item in enumerate(list): list[i] = BOLD + item print (list) But I am getting the output as ['\x1b[1mfsdfs', '\x1b[1mfsdfsd', '\x1b[1mgdfdf'] But the required output is ['kumar','satheesh','rajan'] How to format the list elements in bold using python?
has answer: http://stackoverflow.com/a/50460572
linked to: http://stackoverflow.com/q/37340049
has comment: http://stackoverflow.com/comment/87933795
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87933651
tagged with: python
has answer: http://stackoverflow.com/a/50460287
has title: Bold formatting in Python console
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/87933792
tagged with: ansi-escape
has answer: http://stackoverflow.com/a/50460344
answer count: 3
tagged with: output-formatting

http://stackoverflow.com/comment/87976650
type: QuestionComment
score: 0
has text: yeah, company I am working with is using python2.7
comment on: http://stackoverflow.com/q/50481242
type: Comment

http://stackoverflow.com/comment/88186753
has text: @max9111 I was also looking at the same github package. Got a bit confused on exactly which part of the package achieves that, and how. But, thanks.
type: QuestionComment
comment on: http://stackoverflow.com/q/50537967
type: Comment
score: 0

http://stackoverflow.com/comment/88085192
has text: do I have to add `requirements=webbrowser` in p4a build command?
type: AnswerComment
comment on: http://stackoverflow.com/a/50536161
score: 0
type: Comment

http://stackoverflow.com/comment/87918122
score: 0
type: AnswerComment
has text: @DatCra, only if you want to limit your output matrix with those values belonging to vocabulary. If you omit parameter `vocabulary` - you will have one column for __each__ unique word
comment on: http://stackoverflow.com/a/50452393
type: Comment

http://stackoverflow.com/comment/87856517
has text: So one of those unknown are probably what you need. Another option then, SAS Universal Viewer is free and can access SAS data sets, it should be able to get you that information if this is a one time task, if not, a different solution is needed.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50419361

http://stackoverflow.com/q/50478046
tagged with: python
tagged with: gensim
has answer: http://stackoverflow.com/a/50496705
has answer: http://stackoverflow.com/a/65179935
answer count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/87969686
has comment: http://stackoverflow.com/comment/87976755
has answer: http://stackoverflow.com/a/60834707
score: 6
has body: I am using gensim library for loading pre-trained word vectors from GoogleNews dataset. this dataset contains 3000000 word vectors each of 300 dimensions. when I want to load GoogleNews dataset, I receive a memory error. I have tried this code before without memory error and I don't know why I receive this error now. I have checked a lot of sites for solving this issue but I cant understand. this is my code for loading GoogleNews: import gensim.models.keyedvectors as word2vec model=word2vec.KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin",binary=True) and this is the error I received: File "/home/mahsa/PycharmProjects/tensor_env_project/word_embedding_DUC2007/inspect_word2vec-master/word_embeddings_GoogleNews.py", line 8, in &lt;module&gt; model=word2vec.KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin",binary=True) File "/home/mahsa/anaconda3/envs/tensorflow_env/lib/python3.5/site-packages/gensim/models/keyedvectors.py", line 212, in load_word2vec_format result.syn0 = zeros((vocab_size, vector_size), dtype=datatype) MemoryError can anybody help me? thanks.
has comment: http://stackoverflow.com/comment/87980155
has title: memory error when using gensim for loading word2vec
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61265145
type: UnansweredQuestion
tagged with: word-embedding
upvote count: 6
tagged with: word2vec
tagged with: google-news

http://stackoverflow.com/comment/88034394
comment on: http://stackoverflow.com/q/50510875
score: 0
type: Comment
type: QuestionComment
has text: How are these IP addresses formatted? Are they IPv4? IPv6? That doesn't seem like a well-thought-out requirement. Nevermind the design - or rather the lack of one.

http://stackoverflow.com/q/50454439
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87922372
has body: I have this operation on a large Pandas DataFrame, and of course, is extremely slow. def get_last_status_in_range(df, created_dt, created_id, window_size=15, gap_size=5): since = created_dt - timedelta(days=(window_size + gap_size)) until = created_dt - timedelta(days=gap_size) try: status = df[(df.created_dt &gt;= since) &amp; (df.created_dt &lt; until) &amp; (df.number_id == created_id)]['status'].iloc[-1] except IndexError: # Not found status = None return status idx = 0 last_status_in_range = np.array([None] * len(df), dtype=str) for row in df.itertuples(): created_dt = row.created_dt created_id = row.number_id last_status_in_range[idx] = get_last_status_in_range(df, created_dt, created_id) idx += 1 My goal is to given a DF with columns "created_dt", "number_id", and "status", obtain for each row the last "status" for the same "number_id" but in a specified range of dates in the past. By now the only way I find is doing the operation as described above, but for a large DataFrame it is extremely slow, and I couldn't find a vectorise way to do that. How can I vectorize an operation using some values in the same DataFrame? EDIT: Given the following DF: In [120]: df Out[120]: number_id created_dt status 20 BBB 2018-05-18 20:28:51.388001 u 12 BBB 2018-05-19 12:28:51.388001 u 2 CCC 2018-05-19 23:28:51.388001 u 27 CCC 2018-05-20 22:28:51.388001 a 1 CCC 2018-05-21 05:28:51.388001 u 14 BBB 2018-05-21 12:28:51.388001 r 17 AAA 2018-05-24 21:28:51.388001 a 28 CCC 2018-05-30 16:28:51.388001 a 0 AAA 2018-05-31 23:28:51.388001 r 24 CCC 2018-06-01 00:28:51.388001 r 4 BBB 2018-06-01 11:28:51.388001 r 23 BBB 2018-06-01 19:28:51.388001 r 6 AAA 2018-06-03 14:28:51.388001 a 3 CCC 2018-06-04 15:28:51.388001 u 19 AAA 2018-06-05 06:28:51.388001 u 5 AAA 2018-06-05 20:28:51.388001 r 21 AAA 2018-06-06 04:28:51.388001 a 9 BBB 2018-06-06 18:28:51.388001 r 25 AAA 2018-06-07 15:28:51.388001 r 11 BBB 2018-06-08 09:28:51.388001 r 10 BBB 2018-06-08 21:28:51.388001 u 13 BBB 2018-06-09 04:28:51.38…
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/50456173
tagged with: vectorization
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50456173
has comment: http://stackoverflow.com/comment/87923124
has title: Vectorize operation in Pandas
type: Question
has comment: http://stackoverflow.com/comment/87924099
tagged with: pandas
has comment: http://stackoverflow.com/comment/87923762
tagged with: python
tagged with: numpy

http://stackoverflow.com/a/50410305
score: 1
type: Answer
has body: Use Gunicorn with Flask to manage the WSGI requests. Here are the small scripts which can help you start and stop Flask Server running with Gunicorn. Flask's built-in server is not made to be used in production. It crashes with time. Therefore look into the Gunicorn: Start Script: #!/bin/bash stat=0 COUNTER=0 swait() { echo -ne "Waiting for service to start" until $stat -ge 1 do stat=$(netstat -lnt | awk '$4 ~ /:5001$/' |wc -l) COUNTER=$((COUNTER+1)) if [ $COUNTER == 5 ] ; then echo -e '\nError-Service start failed' exit; fi echo -ne "." sleep 2 done } service_start() { echo "Starting Service" /&lt;project_path&gt;/venv/bin/gunicorn --reload -b 0.0.0.0:5001 api:app --access-logfile=/var/log/&lt;project_name&gt;.log --error-logfile=/var/log/&lt;project_name&gt;_error.log -D -w 2 --access-logformat='%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s' --log-level=info } service_start swait echo -e "\nService started Successfully" Stop Script #!/bin/bash echo "Stopping Service" stat=1 COUNTER=0 swait() { echo -ne "Waiting for service to stop" until $stat -eq 0 do stat=$(netstat -lnt | awk '$4 ~ /:5001$/' |wc -l) COUNTER=$((COUNTER+1)) if [ $COUNTER == 8 ] ; then echo -e '\nService stop failed' exit; fi echo -ne "." sleep 2 done } service_stop() { for pid in `ps augx | grep gunicorn | grep -E ':5001' | grep -v grep | awk '{print $2}'`; do echo "Killing PID" $pid kill $pid done } service_stop swait echo -e "\nService Stopped Successfully"
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50409865

http://stackoverflow.com/comment/87886458
type: Comment
has text: Doesn't using `count` actually give the wrong answer? e.g. 4 sentences starting like `'zac', 'zac', 'bob', 'bob'` would report `{'zac': 2, 'bob': 4}`.
comment on: http://stackoverflow.com/a/50435813
score: 0
type: AnswerComment

http://stackoverflow.com/q/50524246
answer count: 1
favorite count: 0
has body: I am on Windows 10, 64 bit, using CPython, Release 3.6.5. The above quoted documentation states in section Surprises that s.value is s.value returns False. But on my machine it returns True: Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; s = c_char_p &gt;&gt;&gt; s.value = 'abc def ghi' &gt;&gt;&gt; s.value 'abc def ghi' &gt;&gt;&gt; s.value is s.value True &gt;&gt;&gt; Is the relevant documentation outdated or am I missing something? My original post has a crucial bug. I am missing the trailing parentheses in s = c_char_p. Here is the corrected version, also taking into account the difference between byte strings and Unicode strings. from ctypes import * s = c_char_p() # bytes string # s = c_wchar_p() # Unicode string s.value = b'abc def ghi' # if bytes string # s.value = 'abc def ghi' # if Unicode string # print(s.value) print(s.value is s.value)
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88080972
has comment: http://stackoverflow.com/comment/88064420
has comment: http://stackoverflow.com/comment/88062268
has answer: http://stackoverflow.com/a/50540251
accepted answer: http://stackoverflow.com/a/50540251
tagged with: python
has comment: http://stackoverflow.com/comment/88081302
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/88061131
has comment: http://stackoverflow.com/comment/88060496
upvote count: 2
tagged with: ctypes
score: 0
downvote count: 2
has title: Is the The Python Library Reference, Release 3.6.5, paragraph 16.16 ctypes — A foreign function library for Python partially outdated?
has comment: http://stackoverflow.com/comment/88081256

http://stackoverflow.com/comment/87928773
has text: Whoops, that is true. Involving the original values is merely redundant rather than outright incorrect, then.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50457458

http://stackoverflow.com/q/50531732
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has body: I've trained models in Keras and I need to load this models in code made in Tflearn. I can save the Keras trained models with the line: model.save('my_model.hdf5') #keras It saves the architecture and weights of the trained model. or the line: model.save_weights('my_model.hdf5') #keras It saves only the weights of the trained model. The purpose is to load the model into tflearn using for example this line: model.load ('example.tflearn') #tflearn This line just load the weights, requires that the architecture be passed before. I tried loading the files generated by .save and .save_weights from Keras with .load of tflearn but it did not work.
tagged with: tflearn
tagged with: python
has title: Load keras model with tflearn
upvote count: 2
score: 2

http://stackoverflow.com/q/50507702
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/88037648
has answer: http://stackoverflow.com/a/50512774
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/88028460
tagged with: python
has title: How to vary the value of argument parser in a certain range?
favorite count: 0
has body: I am trying to run this piece of code. I want to assign different values to FLAGS.Ncolor as given is x. But when I run this code it is picking the default value of Ncolor that is 2. `p=argparse.ArgumentParser() passes to add_argument() p.add_argument('--Ncolor','-nc', default=2, type=int, help='Number of colors') FLAGS=p.parse_args() x = [ i+1 for i in range(5)] for FLAGS.NCOLOR in x: print ("value is %d" % (FLAGS.Ncolor))`
has comment: http://stackoverflow.com/comment/88027884
has comment: http://stackoverflow.com/comment/88027491
tagged with: argparse
has comment: http://stackoverflow.com/comment/88029226
has comment: http://stackoverflow.com/comment/88028615
has answer: http://stackoverflow.com/a/50507975
score: -2
has comment: http://stackoverflow.com/comment/88027751
has comment: http://stackoverflow.com/comment/88037707
type: Question

http://stackoverflow.com/comment/87804012
type: Comment
type: QuestionComment
has text: BTW, check out https://codereview.stackexchange.com. Your question would be much more acceptable there.
comment on: http://stackoverflow.com/q/50394119
score: 3

http://stackoverflow.com/a/50514842
type: Answer
answers question: http://stackoverflow.com/q/50514763
score: 4
has body: You can use: In [43]: df.set_index('ID').stack().reset_index(level=1, drop=True).to_frame('Merged').reset_index() Out[43]: ID Merged 0 1001 B 1 1001 A 2 1002 C 3 1002 D 4 1003 E 5 1003 E 6 1004 G 7 1004 H
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/88003253
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50494923
has text: Would this give the exact same probabilities as what Keras computed immediately after training on that epoch? I could not find verification of this which is why I ask.
score: 0

http://stackoverflow.com/comment/88760178
type: AnswerComment
has text: Could you maybe check out this similar question as well? https://stackoverflow.com/questions/50878441/python3-tcp-server-not-seeing-incoming-messages-from-external-device
comment on: http://stackoverflow.com/a/50604764
type: Comment
score: 0

http://stackoverflow.com/comment/87839308
type: Comment
score: 0
type: AnswerComment
has text: hmmm, then it is problem, because [limits](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#timestamp-limitations). One possible solution should be convert to `PeriodIndex`
comment on: http://stackoverflow.com/a/50411668

list
tags question: http://stackoverflow.com/q/50443257
tags question: http://stackoverflow.com/q/50439355
tags question: http://stackoverflow.com/q/50505418
type: Tag
tags question: http://stackoverflow.com/q/50406182
tags question: http://stackoverflow.com/q/50499290
tags question: http://stackoverflow.com/q/50458200
tags question: http://stackoverflow.com/q/50416872
tags question: http://stackoverflow.com/q/50501480
tags question: http://stackoverflow.com/q/50486328
tags question: http://stackoverflow.com/q/50470991
tags question: http://stackoverflow.com/q/50536736
tags question: http://stackoverflow.com/q/50428095
tags question: http://stackoverflow.com/q/50527685
tags question: http://stackoverflow.com/q/50520133
tags question: http://stackoverflow.com/q/50479128
tags question: http://stackoverflow.com/q/50501346
tags question: http://stackoverflow.com/q/50418506
tags question: http://stackoverflow.com/q/50538887
tags question: http://stackoverflow.com/q/50440426
tags question: http://stackoverflow.com/q/50443144
tags question: http://stackoverflow.com/q/50442942
tags question: http://stackoverflow.com/q/50440848
tags question: http://stackoverflow.com/q/50508975
tags question: http://stackoverflow.com/q/50428029
tags question: http://stackoverflow.com/q/50492150
tags question: http://stackoverflow.com/q/50422074
tags question: http://stackoverflow.com/q/50403205
tags question: http://stackoverflow.com/q/50428346
tags question: http://stackoverflow.com/q/50441385
tags question: http://stackoverflow.com/q/50442155
tags question: http://stackoverflow.com/q/50455653
tags question: http://stackoverflow.com/q/50482527
tags question: http://stackoverflow.com/q/50444378
tags question: http://stackoverflow.com/q/50537927
tags question: http://stackoverflow.com/q/50420229
tags question: http://stackoverflow.com/q/50427501
tags question: http://stackoverflow.com/q/50534051
tags question: http://stackoverflow.com/q/50533629
tags question: http://stackoverflow.com/q/50421361
tags question: http://stackoverflow.com/q/50486492
tags question: http://stackoverflow.com/q/50521716
tags question: http://stackoverflow.com/q/50493901
tags question: http://stackoverflow.com/q/50463202
tags question: http://stackoverflow.com/q/50479077
tags question: http://stackoverflow.com/q/50457685
tags question: http://stackoverflow.com/q/50536919
tags question: http://stackoverflow.com/q/50480175
tags question: http://stackoverflow.com/q/50423965
tags question: http://stackoverflow.com/q/50419476
tags question: http://stackoverflow.com/q/50432185
tags question: http://stackoverflow.com/q/50456182
tags question: http://stackoverflow.com/q/50527187
tags question: http://stackoverflow.com/q/50470825
tags question: http://stackoverflow.com/q/50512696
tags question: http://stackoverflow.com/q/50467040
tags question: http://stackoverflow.com/q/50418044
tags question: http://stackoverflow.com/q/50517559
tags question: http://stackoverflow.com/q/50517752
tags question: http://stackoverflow.com/q/50437159
tags question: http://stackoverflow.com/q/50424659
tags question: http://stackoverflow.com/q/50493655
tags question: http://stackoverflow.com/q/50426378
tags question: http://stackoverflow.com/q/50474908
tags question: http://stackoverflow.com/q/50504844
tags question: http://stackoverflow.com/q/50532977
tags question: http://stackoverflow.com/q/50435896
tags question: http://stackoverflow.com/q/50464123
tags question: http://stackoverflow.com/q/50403632
tags question: http://stackoverflow.com/q/50455821
tags question: http://stackoverflow.com/q/50400487
tags question: http://stackoverflow.com/q/50435737
tags question: http://stackoverflow.com/q/50403041
tags question: http://stackoverflow.com/q/50473499
tags question: http://stackoverflow.com/q/50531729
tags question: http://stackoverflow.com/q/50460523
tags question: http://stackoverflow.com/q/50398603
tags question: http://stackoverflow.com/q/50397260
tags question: http://stackoverflow.com/q/50498997
tags question: http://stackoverflow.com/q/50413341

http://stackoverflow.com/comment/87977218
has text: Were your paths the same when the error did and did not occur? Perhaps you tried to access a file that was admin protected?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50482122
score: 0

http://stackoverflow.com/a/60647166
has body: For those who want a "numpy-like" cumsum where the top-left corner is smallest: def multidim_cumsum(a): out = a.cumsum(-1) for i in range(2,a.ndim+1): np.cumsum(out, axis=-i, out=out) return out Modified from @Divakar (thanks to him!)
answers question: http://stackoverflow.com/q/50463366
upvote count: 5
has comment: http://stackoverflow.com/comment/109234567
score: 5
downvote count: 0
type: Answer

http://stackoverflow.com/q/50468300
has comment: http://stackoverflow.com/comment/87950291
has comment: http://stackoverflow.com/comment/87950843
answer count: 2
has title: passing string arguments to filter database rows in python
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50468372
downvote count: 1
has body: i have a written the below function to filter a column in a sql query, the function takes a string argument which will be inputted in the 'where clause' def summaryTable(machineid): df=pd.read_sql(""" SELECT fld_ATM FROM [003_tbl_ATM_Tables] WHERE (LINK &lt;&gt; 1) AND (fld_ATM =('machineid')) ; """,connection) connection.close() return df the function returns an empty Dataframe. i know the query itself is correct 'cause i get the expected data when i 'hardcode' the machine id
has comment: http://stackoverflow.com/comment/87950020
has comment: http://stackoverflow.com/comment/87949858
type: AnsweredQuestion
tagged with: sql-server
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50468625
has answer: http://stackoverflow.com/a/50468625
has answer: http://stackoverflow.com/a/50468372
favorite count: 0
type: Question

http://stackoverflow.com/a/52563354
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50509677
has body: I solved this issue a time ago by using: from IPython import embed ...code... embed() # Code will enter interactive session at this line ...code... Also, the use of try: and except: has been very useful.

http://stackoverflow.com/q/50387418
has answer: http://stackoverflow.com/a/50387893
accepted answer: http://stackoverflow.com/a/50387893
has comment: http://stackoverflow.com/comment/87790459
possible better answer: http://stackoverflow.com/a/50387472
has title: Nested / serial if expressions?
type: Question
has comment: http://stackoverflow.com/comment/87790689
answer count: 2
has comment: http://stackoverflow.com/comment/87791011
has body: Can I do more complex if expressions than strict a = b if c else d. Can I string together serial expressions, or nest an if expression inside another if expression? I cannot find an answer in the docs or online. CONTEXT (some of it is only relevant to explain why I am seeking this, rather than another solution): I have two scalar variables (a and c) that either have an actual value or are set to -1. If they have a value this is always true c - a = 2 (they are list indexes, for specific items in a list, but the items are not always present. If either a or c has a value other than -1 , then I want to create a third scalar variable b that has a specific value (the value between a and c). if neither a nor c has a value, then I want to set b = -1 so would ideally write something like this: b = a+1 if a != -1 else c-1 if c != -1 else -1 I cannot figure out if this is allowed - legal. And if it is legal, does it get evaluated sequentially? An alternative specification would be hierarchical: b = (a+1 if a != -1 else c-1) if (c != -1 or a != -1) else -1 Is either of these legal? Advisable? Thanks.
tagged with: python
has answer: http://stackoverflow.com/a/50387472
has comment: http://stackoverflow.com/comment/87790392
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87901542
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50443781
has text: Why do you want to do this? I can't think of any advantage in not having a multi dimensional array?

http://stackoverflow.com/comment/88017124
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50502038
score: 0
has text: I agree @aydow. Perhaps you have only an issue with some duplicate Separators or sth. However, it's always a good idea to prove that your data is OK, otherwise you risk to loose data in the attempt to heal it not knowing what causes which artifacts.

http://stackoverflow.com/q/50524942
has comment: http://stackoverflow.com/comment/88147745
has body: I can not understand why the weights are not like normal distribution. actually I want to understand what is going on during weight changing and what is happening for gradients. but the problem is that weights in histogram are not looking like normal distribution. bellow u can find the code: iris_data_set = pd.read_csv('iris.csv') iris_data_set.head() cols_to_norm = ['Sepal.Length' , 'Sepal.Width' , 'Petal.Length' , 'Petal.Width'] iris_data_set[cols_to_norm] = iris_data_set[cols_to_norm].apply(lambda x:(x- x.min()) / (x.max() - x.min())) feat_data = iris_data_set.drop('Species', axis=1 ) label = iris_data_set['Species'] X_train, X_test, y_train, y_test = train_test_split(feat_data , label, test_size = 0.3 , random_state =101) y_train = pd.get_dummies(y_train) y_test = pd.get_dummies(y_test) n_features = 4 n_dense_neurons = 3 n_output = 3 training_steps =1000 #tf Graph input X_data = tf.placeholder(tf.float32 , shape= [None , n_features], name='Inputdata') y_target = tf.placeholder(tf.float32 , shape= [None , n_output], name='Labeldata') #Store layers weights = { 'w1': tf.Variable(tf.random_normal(shape=[n_features , n_dense_neurons]) , name = 'w1'), # Inputs -&gt; Hidden Layer 'w2': tf.Variable(tf.random_normal(shape=[n_dense_neurons , n_output]) , name = 'w2') } biases = { 'b1': tf.Variable(tf.random_normal(shape=[n_dense_neurons]) , name='b1'), # First Bias 'b2': tf.Variable(tf.random_normal(shape=[n_output]) , name='b2') } def multilayer_perceptron(x, weights, biases): # Hidden layer with RELU activation layer_1 = tf.add(tf.matmul(X_data , weights['w1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) # Create a summary to visualize the first layer ReLU activation tf.summary.histogram("relu1", layer_1) # Output layer out_layer = tf.add(tf.matmul(layer_1, weights['w2']), biases['b2']) return out_layer with tf.name_scope('Model'): pred = multilayer_perceptron(X_data, weights, biases) with tf.name_scope('Loss'): final_output = tf.nn.softmax(pred) deltas = tf.square (fi…
has comment: http://stackoverflow.com/comment/88147501
has comment: http://stackoverflow.com/comment/88066963
score: 0
answer count: 0
has title: tensorboard weight histogram is not like normal distribution
tagged with: tensorboard
tagged with: histogram
has comment: http://stackoverflow.com/comment/88447181
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88148081
tagged with: neural-network
tagged with: python

http://stackoverflow.com/q/50447865
favorite count: 0
has title: Getlist with html form and store it in database SQLalchemy Flask Python
tagged with: python
score: -1
tagged with: sqlalchemy
type: Question
has body: I try to get the list of values from HTML form with Flask and store it in the Column in the database. I tried to use getlist() but I do not know how I should do that in a proper way. Database: association_table = Table('association', Base.metadata, Column('book_id', Integer, ForeignKey('Book.id')), Column('form_id', Integer, ForeignKey('Form.id')) ) class Book(Base): __tablename__ = 'Book' name = Column(String(80), nullable = False, unique=True) id = Column(Integer, primary_key = True) author = Column(String(30)) language = Column(String(30)) category_id = Column(Integer, ForeignKey('Category.id'), nullable = False) category = relationship(Category) forms = relationship("Form", secondary=association_table, back_populates="books") def __repr__(self): return '<Book %r>' % self.name class Form(Base): __tablename__ = 'Form' name = Column(String, nullable = False) id = Column(Integer, primary_key=True) books = relationship("Book", secondary=association_table, back_populates="forms") def __repr__(self): return self.name NEW BOOK Template: Choose Form {% for form in forms %} {{ form }} " {% endfor %} Route: @app.route('/books/new/', methods=['GET', 'POST']) def newBook(): categories = session.query(Category).all() forms = session.query(Form).all() #languages = session.query(Languages).all() if request.method == 'POST': newBook = Book(name = request.form['name'], author = request.form['author'], category = Category(name=request.form.get('category')), forms = Form(name=request.form.getlist('form')), language = request.form['language']) session.add(newBook) session.commit() flash("New Book Added!") return redirect(url_for('showBooks')) else: return render_template('newBook.html', languages=languages, categories=categories, forms=forms) When I trying to add the new book I get TypeError: Incompatible collection type: Form is not list-like
has answer: http://stackoverflow.com/a/50448456
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: flask
downvote count: 1

http://stackoverflow.com/comment/88590626
has text: This did it for me as well, but at some points the package wasn't in `archives/`. I got a lot of messages about overwriting things, but afterwards `apt upgrade` completed successfully. Thanks!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50408787

http://stackoverflow.com/q/50456144
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/88197430
has body: I'm currently building a CNN-LSTM encoder-decoder anomaly detector by reconstruction on Keras, following the directions of of Malhotra et al but with the CNN encoder difference, still I'm aiming to use the loss(objective) function defined there as: Where X is a sample of a time series of L steps, and x(i) is the i-th real vector and x'(i) the reconstructed. The total training set is that s_N. I made the loss function, but I think it's not behaving well, so I appeal to you and your knowledge to see if is this my error source or I might need to find elsewhere: def mirror_loss(y_true,y_pred): diff = tf.square(tf.norm(tf.substract(y_true, y_pred), axis = 1)) return K.sum(diff, axis = -1) It bothers me that I have to use both tensorflow and keras.backend because I wasn't able to find the "norm" on keras.backend.
has comment: http://stackoverflow.com/comment/87929665
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88197484
tagged with: loss-function
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/87974885
type: UnansweredQuestion
has title: Keras, custom "how different is" loss function definition issue

http://stackoverflow.com/comment/87957002
has text: Which python version are you using ?
type: QuestionComment
comment on: http://stackoverflow.com/q/50471730
score: 0
type: Comment

http://stackoverflow.com/comment/88030414
comment on: http://stackoverflow.com/q/50509187
type: QuestionComment
has text: for `df.index` it's printing `0...500` which is number of rows . I want indexing should be on column name and for all column.
type: Comment
score: 0

http://stackoverflow.com/a/50468999
upvote count: 0
has comment: http://stackoverflow.com/comment/87951221
downvote count: 1
has body: The string library has a .count('name') function. So you could count each element in the for loop and compare them all. You need to clarify the problem because andrew and fred occur three times. "Makes sense....First have a list of unique names [names]. Then use a dictionary to store them. {name:[list_names] then len(string) . Write a function that iterates the dictionary and retrieves the dictionary with the most speakers."
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/87951665
answers question: http://stackoverflow.com/q/50468839

http://stackoverflow.com/comment/87895816
type: AnswerComment
comment on: http://stackoverflow.com/a/50422208
score: 0
type: Comment
has text: Reading trust chains is not covered by X.509. Again single certificates are all that can be encoded in a given ASN.1 structure. Chains of certificates are covered by a number of RFCs e.g. [RFC4158](https://www.ietf.org/rfc/rfc4158.txt).

http://stackoverflow.com/comment/87994593
type: Comment
comment on: http://stackoverflow.com/a/50484638
type: AnswerComment
score: 0
has text: @VivekKumar is right, it's the default. But I don't think you can set the random_state without adding the parameter explicitly

http://stackoverflow.com/comment/87992014
type: Comment
has text: You need to convert or just print "" symbols?
type: AnswerComment
comment on: http://stackoverflow.com/a/50489553
score: 0

http://stackoverflow.com/q/50523869
tagged with: python
has comment: http://stackoverflow.com/comment/88067837
has comment: http://stackoverflow.com/comment/88070636
has comment: http://stackoverflow.com/comment/88077560
has title: trouble with imports when calling a script with another script
tagged with: bash
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: pyqt4
tagged with: shell
has comment: http://stackoverflow.com/comment/88071223
has comment: http://stackoverflow.com/comment/88070133
type: Question
has body: I have several scripts perfectly working by themselves and i would like to create a big pyqt-script which launch those scripts when they are selected. My only one problem is, every import done on my scripts are not working anymore because of the path. (As the new reference is the pyqt-script and no longer themselves). I tried to make a movable path but it means changing all my scripts and I would like to be able to "copy/past" my scripts in a file without having to modify them, only the pyqt-script. I also tried to make a function which open a new terminal with gnome-terminal and launch my script but it is not successful as it keep taking my pyqt-script for reference) os.system("gnome-terminal --tab -e 'tcsh -c \"python /path/script.py; sleep 10) Do you have any idea? even if they work in the same terminal. Thank you for your help.

http://stackoverflow.com/comment/87977808
type: QuestionComment
has text: No, I'm getting this message: ssh: Could not resolve hostname D: Name or service not known
comment on: http://stackoverflow.com/q/50481939
score: 0
type: Comment

http://stackoverflow.com/comment/87880264
comment on: http://stackoverflow.com/a/50432830
type: AnswerComment
has text: There's an issue. Now when I want to use `pip` , it says `pip: command not found`.
score: 0
type: Comment

http://stackoverflow.com/comment/87798080
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50391156
type: QuestionComment
has text: Yout most definitely will get a speedup from numpy. Something like `XposMay[somAprilMay < 3,:] = 0` should do the trick.

http://stackoverflow.com/q/50406354
has comment: http://stackoverflow.com/comment/87829332
has comment: http://stackoverflow.com/comment/87829234
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87828134
downvote count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/87828136
has comment: http://stackoverflow.com/comment/87828809
tagged with: camera
score: 0
has body: I need to perform image recognition thing on real time camera feed. The video is embedded in shtml hosted on a IP. How do I access the video and process things using openCV.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50410930
has title: How do I capture a live IP Camera feed (eg: http://61.60.112.230/view/viewer_index.shtml?id=938427) to python application?
tagged with: video-streaming

http://stackoverflow.com/a/50440618
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50440487
has comment: http://stackoverflow.com/comment/87895589
type: Answer
has comment: http://stackoverflow.com/comment/87895739
accepted answer of: http://stackoverflow.com/q/50440487
has comment: http://stackoverflow.com/comment/87895674
has body: I think that you can theoretically do this whole thing in one line: finaldf = (pd.concat([pd.read_csv('data1.csv', parse_dates={'Date':['Year', 'Month', 'Day']}), pd.read_csv('data2.csv', parse_dates={'Date':['Year', 'Month', 'Day']}) 'Date', 'Tweet']) .sort_values('Date', ascending=False)) But for the sake of readability, its better to split it into a few lines: df1 = pd.read_csv('data1.csv', parse_dates={'Date':['Year', 'Month','Day']}) df2 = pd.read_csv('data2.csv', parse_dates={'Date':['Year', 'Month','Day']}) finaldf = (pd.concat([df1, df2'Date', 'Tweet']) .sort_values('Date', ascending=False)) I think that for what you're trying to do, the main things to read up about are the parse_dates argument of pandas read_csv, and pd.concat to concatenate dataframes Edit: in order to get the dates in the correct format as you have in your example output, you can call this after the code above, using Series.dt.strftime(): finaldf['Date'] = finaldf['Date'].dt.strftime('%d-%b-%y')

http://stackoverflow.com/a/53761277
has comment: http://stackoverflow.com/comment/99645366
has body: To open a webpage through Tor Browser using Python you can use the Firefox Profile and the tor daemon and you can use the following solution: Code Block: from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile import os torexe = os.popen(r'C:\Users\AtechM_03\Desktop\Tor Browser\Browser\TorBrowser\Tor\tor.exe') profile = FirefoxProfile(r'C:\Users\AtechM_03\Desktop\Tor Browser\Browser\TorBrowser\Data\Browser\profile.default') profile.set_preference('network.proxy.type', 1) profile.set_preference('network.proxy.socks', '127.0.0.1') profile.set_preference('network.proxy.socks_port', 9050) profile.set_preference("network.proxy.socks_remote_dns", False) profile.update_preferences() driver = webdriver.Firefox(firefox_profile= profile, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe') driver.get("http://check.torproject.org") Browser Snapshot:
type: Answer
upvote count: 4
score: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50456635

http://stackoverflow.com/comment/87884638
score: 0
type: Comment
type: QuestionComment
has text: The statement `if H > T` tries to compare a list of int with a list of lists, which generates one error. In a list. `if` will compare elements but now you try to compare an `int` from H with a `list` from T.
comment on: http://stackoverflow.com/q/50434060

http://stackoverflow.com/q/50479702
answer count: 1
has title: Export a numpy matrix of complex numbers to CSV
has comment: http://stackoverflow.com/comment/87977225
has comment: http://stackoverflow.com/comment/87973180
has comment: http://stackoverflow.com/comment/88005315
accepted answer: http://stackoverflow.com/a/50484316
has comment: http://stackoverflow.com/comment/87976976
tagged with: matlab
type: Question
has answer: http://stackoverflow.com/a/50484316
tagged with: http://stackoverflow.com/tag/csv
tagged with: complex-numbers
tagged with: python
has comment: http://stackoverflow.com/comment/87976175
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87976936
has comment: http://stackoverflow.com/comment/87973295
has body: I am having the following trouble in Python. Assume a numpy.matrix A with entities of dtype to be complex128. I want to export A in CSV format so that the entries are separated by commas and each line at the output file corresponds to a row of A. I also need 18 decimal points of precision for both the real and imaginary parts and no spaces within an entry for example I need this `6.103515626000000000e+09+1.712134684679831166e+05j` instead of `6.103515626000000000e+09 + 1.712134684679831166e+05j` The following command works but only for 1-by-1 matrix numpy.savetxt('A.out', A, fmt='%.18e%+.18ej', delimiter=',') If I use: numpy.savetxt('A.out', A, delimiter=',') there are two problems. First, I don't know how many decimal points are preserved by default. Second, each complex entry is put in parentheses like (6.103515626000000000e+09+1.712134684679831166e+05j) and I cannot read the file in Matlab. What do you suggest?
score: 0

http://stackoverflow.com/comment/87904508
score: 0
comment on: http://stackoverflow.com/q/50445243
has text: You keep changing the code you are supposedly using. And it's still not even valid Python syntax. Why couldn't you have copied the actual code in the first place?
type: Comment
type: QuestionComment

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

http://stackoverflow.com/comment/87995750
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50491326
has text: @PM2Ring I may be missing something but OPs `(-100.)**(1./3)` is also not Numpy ?
score: 1

http://stackoverflow.com/comment/88069154
type: Comment
comment on: http://stackoverflow.com/a/50528391
type: AnswerComment
has text: Change `ft_analytic.real` to `np.abs(ft_analytic)` and it looks good.
score: 1

http://stackoverflow.com/comment/87996339
has text: Thanks for clarification, it would be useful for my other applications later. In this application, I need all of the dictionaries for fast lookups and as you mentioned I am willing to pay for slower start up.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50479955
type: AnswerComment

http://stackoverflow.com/comment/87859240
type: QuestionComment
comment on: http://stackoverflow.com/q/50422112
has text: Thats almost what I did with `for r in arrays:` once I had the recursion build an array of array names. The problem is I can get the value but the path is lost unless I recursively rebuild the array from the bottom...
score: 0
type: Comment

http://stackoverflow.com/q/50429325
answer count: 0
tagged with: function
has comment: http://stackoverflow.com/comment/87873446
has comment: http://stackoverflow.com/comment/87873388
has title: Can't figure out why script isn't going any further
type: Question
has comment: http://stackoverflow.com/comment/87874265
has comment: http://stackoverflow.com/comment/87874300
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87875337
tagged with: python
tagged with: python-2.7
score: 0
has body: I have this function called zms_add_bridge that calls a function called xmlbuilder. xmlbuilder creates a global variable called xml and populates it with stuff. When zms_add_bridge is called, it prints "here" to say that it's gotten at least that far in the script. Then, it calls xmlbuilder, which prints "xml1" along with the xml output to say that it's at least gotten that far in the script. The issue is that once xmlbuilder exits and returns to zms_add_bridge, the script seems to die. xml is a global variable, so it should print "yes", but it's not even printing "no". I even tried to return xml at the end of xmlbuilder to see if that would work, but it didn't (and even still, that'd be redundant since xml was declared globally, wouldn't it?) Any clues? I'm lost. def xmlbuilder(requestType,xbra): global xmlbuild global xmlbuild__request global xmlbuild__requestElement global xmlbuild__requestElementAttribute global xml xmlbuild = etree.Element("OSS", attrib={"{"+xsi+"}schemaLocation":schema}, nsmap={'xsi':xsi, None:xmlns}) xmlbuild__request = etree.SubElement(xmlbuild, "Request") etree.SubElement(xmlbuild__request, "RequestType").text = requestType etree.SubElement(xmlbuild__request, "RequestMode").text = "online" etree.SubElement(xmlbuild__request, "SessionID").text = session_id etree.SubElement(xmlbuild__request, "operName").text = apiUser etree.SubElement(xmlbuild__request, "Version").text = version etree.SubElement(xmlbuild__request, "Overwrite").text = "false" xmlbuild__requestElement = etree.SubElement(xmlbuild, "RequestElement") for index, data in xbra.items(): for key in data: xmlbuild__requestElementAttribute = etree.SubElement(xmlbuild__requestElement, "Attribute") etree.SubElement(xmlbuild__requestElementAttribute, "Name").text = "%s" % key etree.SubElement(xmlbuild__requestElementAttribute, "Value").text = "%s" % data[key] xml = etree.tostring(xmlbuild, encoding="UTF-8", pretty_print=True, xml_declaration=True) if debug >= 1: print "\nDEBUG: Generated X…
tagged with: return
has comment: http://stackoverflow.com/comment/87874217

http://stackoverflow.com/comment/88094618
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50528833
has text: @irene: I fixed your title but could you please do that in future? Otherwise SO will have lots of questions where the question as asked, the answer and the asker's intent are different things... and that's before we get to future-proofing against all the pandas version changes.
score: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/50441027
tags question: http://stackoverflow.com/q/50475185
tags question: http://stackoverflow.com/q/50537493
tags question: http://stackoverflow.com/q/50506610
tags question: http://stackoverflow.com/q/50437846
tags question: http://stackoverflow.com/q/50476265
tags question: http://stackoverflow.com/q/50447683
tag name: merge
tags question: http://stackoverflow.com/q/50432743
tags question: http://stackoverflow.com/q/50538051
tags question: http://stackoverflow.com/q/50448986
tags question: http://stackoverflow.com/q/50478159
tags question: http://stackoverflow.com/q/50480997
tags question: http://stackoverflow.com/q/50506331
tags question: http://stackoverflow.com/q/50530349
tags question: http://stackoverflow.com/q/50476327

http://stackoverflow.com/comment/88131909
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50517216
has text: The last suggestion works the best. Fast and clean :)
type: Comment

http://stackoverflow.com/comment/87996064
comment on: http://stackoverflow.com/a/50477574
type: AnswerComment
has text: Sharing the index is exactly the problem, because no two rows have the same index key. Two series extracted from the same column in a mutually exclusive way, will always have this problem.
score: 0
type: Comment

http://stackoverflow.com/comment/88003816
has text: you could brute force reflection by looking at the `__dict__` of the MSG object.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50495393
type: AnswerComment

http://stackoverflow.com/comment/87872406
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50427656
type: Comment
has text: @ALollz In this case I think it is the index so simply `df.groupby(df.index.day)`

http://stackoverflow.com/q/50398584
score: -1
has comment: http://stackoverflow.com/comment/90616598
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51994353
tagged with: sympy
has comment: http://stackoverflow.com/comment/87944949
has comment: http://stackoverflow.com/comment/87944983
has body: This occurred after upgrading sympy (1.0->1.1.1) and mpmath (0.19->1.0.0). poly_mat = eval(poly_mat_str) det = poly_mat.det(method="berkowitz") where poly_mat_str is the string repr for some complex polynomial matrix (examples at link below). The degradation is observed as vastly increased resultant det size and calculation times. Note that smaller polynomial matrices do not seem affected, see the ticket for more information. The table below shows changes on my machine to the calculation times and resultant det sizes for three polynomials, which can be found here: example polynomials
has title: Degradation of sympy det function performance when applied to large matrices of polynomials
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51994353
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87931594
downvote count: 1

http://stackoverflow.com/q/50476811
upvote count: 1
answer count: 1
has title: ImportError: No module named azure.storage.blob
tagged with: azure-storage
favorite count: 0
has body: I am trying to download a file from Azure onto my local device via python using the following code: from azure.storage.blob import BlockBlobService block_blob_service = BlockBlobService(account_name='account_name', account_key='mykey') block_blob_service.get_blob_to_path('container', 'file', 'out-test.csv') However, when I run this code I get the following error: ImportError: No module named azure.storage.blob I already have installed the azure modules as seen by the snipping of the output of pip list: C:\Users\hpfc87&gt;pip list Package Version -------------------- --------- adal 0.6.0 asn1crypto 0.24.0 azure-common 1.1.11 azure-nspkg 2.0.0 azure-storage 0.36.0 azure-storage-blob 1.1.0 azure-storage-common 1.1.0 azure-storage-file 1.1.0 azure-storage-nspkg 3.0.0 azure-storage-queue 1.1.0 I have tried following various posts about this issue like the following, but I have had no luck: ImportError: No module named azure.storage.blob (when doing syncdb) https://github.com/Azure/azure-storage-python/issues/262 Any advice?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87967520
tagged with: python-2.7
downvote count: 0
has answer: http://stackoverflow.com/a/50483133
tagged with: azure
tagged with: azure-blob-storage
accepted answer: http://stackoverflow.com/a/50483133
score: 1
has comment: http://stackoverflow.com/comment/87968178
tagged with: python
linked to: http://stackoverflow.com/q/39383741
has comment: http://stackoverflow.com/comment/87967254
type: Question
has comment: http://stackoverflow.com/comment/87968138
has comment: http://stackoverflow.com/comment/87968613

http://stackoverflow.com/q/50478574
score: 0
has comment: http://stackoverflow.com/comment/87970873
tagged with: http://stackoverflow.com/tag/json
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50478652
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87970813
tagged with: python
has title: Error when Merging Multiple Jsons & reading through python
has body: For my project i have scrapped twitter data in multiple jsonl file which needs to converted as single file and then read the single file again to extract informations. Code used to combine multiple jsons: import glob from tweepy import Cursor jsonfile = glob.glob('C:\\Users\\arun\\Desktop\\Tweets\\*.jsonl') #writejson = json.dumps('C:\\Users\\arun\\Desktop\\Tweets\\output.jsonl', 'wb') tweets = [] for files in jsonfile: with open(files, 'r') as f: for line in f: tweets.append(json.loads(line)) Above code working fine, but this appends json file as string with each line seperated by ','. But, I am getting "JSONDecodeError: Expecting value: line 2 column 1 (char 2)" from collections import Counter def get_hashtags(tweet): entities = tweet.get('entities', {}) #from tweets find entities &amp; extract it hashtags = entities.get('hashtags', []) #from entities find hastags &amp; extract it return [tag['text'].lower() for tag in hashtags] #convert as lower case and return back fname = "C:\\Users\\arun\\Desktop\\Tweets\\output.jsonl" # extracts tweets json file path with open(fname, 'r') as f: hashtags = Counter() #is a dictionary used to count hashable objects for line in f: #Reads each line at a time tweet1 = json.loads(line) Kindly suggest on this error. Thanks !!

http://stackoverflow.com/q/50486628
tagged with: python
has answer: http://stackoverflow.com/a/61662883
has comment: http://stackoverflow.com/comment/87986030
has body: I am on VS 2017 and .NET Core 2 on Win 7. Tried creating a fresh app in .NET Core 2.0 and Angular using these instructions. Running latest versions of node and npm : node -v > v10.1.0 npm -v > v6.0.1 According to the instructions, I went ahead to build the application and got Can't find Python I checked env variables the path has python. Not sure why it can't find it. The build seems to have "half worked" and got some dependencies sorted. The second go around building the app gave me a JavaScript Runtime Error .. which I think is due to crappy first build job. I also tried running "npm install" in the ClientApp folder and gave the same errors, Can't find python. Any help would be appreciated ! Build Log 1>------ Build started: Project: TestApp, Configuration: Debug Any CPU ------ 1>TestApp -> C:\Users\mohammadrauf\Desktop\Angular_Projects\TestApp\bin\Debug\netcoreapp2.0\TestApp.dll 1>v10.1.0 1>Restoring dependencies using 'npm'. This may take several minutes... 1> 1>> uws@9.14.0 install C:\Users\mohammadrauf\Desktop\Angular_Projects\TestApp\ClientApp\node_modules\uws 1>> node-gyp rebuild > build_log.txt 2>&1 || exit 0 1> 1> 1>> node-sass@4.7.2 install C:\Users\mohammadrauf\Desktop\Angular_Projects\TestApp\ClientApp\node_modules\node-sass 1>> node scripts/install.js 1> 1>Downloading binary from https://github.com/sass/node-sass/releases/download/v4.7.2/win32-x64-64_binding.node 1>Cannot download "https://github.com/sass/node-sass/releases/download/v4.7.2/win32-x64-64_binding.node": 1> 1>HTTP error 404 Not Found 1> 1>Hint: If github.com is not accessible in your location 1> try setting a proxy via HTTP_PROXY, e.g. 1> 1> export HTTP_PROXY=http://example.com:1234 1> 1>or configure npm proxy via 1> 1> npm config set proxy http://example.com:8080 1> 1>> uglifyjs-webpack-plugin@0.4.6 postinstall C:\Users\mohammadrauf\Desktop\Angular_Projects\TestApp\ClientApp\node_modules\webpack\node_modules\uglifyjs-webpack-plugin 1>> node lib/post_install.js 1> 1> 1>> node-sass@4.7.2 po…
tagged with: node.js
tagged with: asp.net-core
answer count: 3
has comment: http://stackoverflow.com/comment/87993109
has answer: http://stackoverflow.com/a/59956228
favorite count: 0
score: 8
type: Question
has answer: http://stackoverflow.com/a/50490328
has title: .NET Core 2.0 & Angular Initial app build fails - Can't find python followed by JavaScript Runtime Error
upvote count: 8
tagged with: angularjs
tagged with: npm
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87986118

dictionary
tags question: http://stackoverflow.com/q/50419505
tags question: http://stackoverflow.com/q/50493838
tags question: http://stackoverflow.com/q/50470825
tags question: http://stackoverflow.com/q/50401629
tags question: http://stackoverflow.com/q/50517559
tags question: http://stackoverflow.com/q/50427012
tags question: http://stackoverflow.com/q/50515169
tags question: http://stackoverflow.com/q/50537482
tags question: http://stackoverflow.com/q/50471236
tags question: http://stackoverflow.com/q/50484937
tags question: http://stackoverflow.com/q/50443257
tags question: http://stackoverflow.com/q/50474080
tags question: http://stackoverflow.com/q/50406182
tags question: http://stackoverflow.com/q/50491984
tags question: http://stackoverflow.com/q/50484241
tags question: http://stackoverflow.com/q/50441027
tags question: http://stackoverflow.com/q/50391949
tags question: http://stackoverflow.com/q/50441303
tags question: http://stackoverflow.com/q/50484845
tags question: http://stackoverflow.com/q/50520683
tags question: http://stackoverflow.com/q/50479589
tags question: http://stackoverflow.com/q/50460325
tags question: http://stackoverflow.com/q/50482983
tags question: http://stackoverflow.com/q/50518761
tags question: http://stackoverflow.com/q/50445608
tags question: http://stackoverflow.com/q/50538213
tags question: http://stackoverflow.com/q/50400996
tags question: http://stackoverflow.com/q/50433794
tags question: http://stackoverflow.com/q/50399494
tags question: http://stackoverflow.com/q/50531919
tags question: http://stackoverflow.com/q/50479401
tags question: http://stackoverflow.com/q/50499619
tags question: http://stackoverflow.com/q/50472520
tags question: http://stackoverflow.com/q/50425402
tags question: http://stackoverflow.com/q/50459151
tags question: http://stackoverflow.com/q/50496549
tags question: http://stackoverflow.com/q/50387826
tags question: http://stackoverflow.com/q/50506065
tags question: http://stackoverflow.com/q/50386332
tags question: http://stackoverflow.com/q/50475966
tags question: http://stackoverflow.com/q/50453437
tags question: http://stackoverflow.com/q/50434079
tags question: http://stackoverflow.com/q/50420229
tags question: http://stackoverflow.com/q/50432645
tags question: http://stackoverflow.com/q/50407301
tags question: http://stackoverflow.com/q/50519536
tags question: http://stackoverflow.com/q/50429720
tags question: http://stackoverflow.com/q/50518120
tags question: http://stackoverflow.com/q/50403717
tags question: http://stackoverflow.com/q/50500135
tags question: http://stackoverflow.com/q/50512188
tags question: http://stackoverflow.com/q/50486492
tags question: http://stackoverflow.com/q/50451558
tags question: http://stackoverflow.com/q/50480997
tags question: http://stackoverflow.com/q/50507235
tags question: http://stackoverflow.com/q/50470854
tags question: http://stackoverflow.com/q/50485754
tags question: http://stackoverflow.com/q/50419476
tags question: http://stackoverflow.com/q/50526862
tags question: http://stackoverflow.com/q/50417376
tags question: http://stackoverflow.com/q/50403196
tags question: http://stackoverflow.com/q/50417047
tags question: http://stackoverflow.com/q/50492042
tags question: http://stackoverflow.com/q/50508911
tags question: http://stackoverflow.com/q/50512696
tags question: http://stackoverflow.com/q/50517752
tags question: http://stackoverflow.com/q/50437268
tags question: http://stackoverflow.com/q/50474443
tags question: http://stackoverflow.com/q/50497930
tags question: http://stackoverflow.com/q/50405112
tags question: http://stackoverflow.com/q/50392926
tags question: http://stackoverflow.com/q/50395812
tags question: http://stackoverflow.com/q/50440937
tags question: http://stackoverflow.com/q/50474447
tags question: http://stackoverflow.com/q/50423772
tags question: http://stackoverflow.com/q/50474535
tags question: http://stackoverflow.com/q/50469989
tags question: http://stackoverflow.com/q/50535847
tags question: http://stackoverflow.com/q/50400210
tags question: http://stackoverflow.com/q/50400487

http://stackoverflow.com/a/50499096
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50498913
type: Answer
has comment: http://stackoverflow.com/comment/88011096
score: 1
has body: You must set APP_DIRS to True, i.e.: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ ...
accepted answer of: http://stackoverflow.com/q/50498913

http://stackoverflow.com/q/50474753
tagged with: python
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87964170
has comment: http://stackoverflow.com/comment/87964133
has comment: http://stackoverflow.com/comment/87964096
favorite count: 0
has answer: http://stackoverflow.com/a/69474290
type: Question
has body: I have a few models: ModelA, ModelB, ModelC each with identical attributes say x,y,z. I am trying to get them displayed in Django admin. I have registered each as @admin.register(ModelA) class ModelAAdmin(admin.ModelAdmin): list_display = ['x', 'y' , 'z'] However when I runserver, I get error which says The value of list_display[0] refers to 'x' which is not callable, an attribute of modelA, or an attribute or method on 'database.modelA' I am guessing this has got something to do with each model having identical names but I am not sure. How do I resolve this? EDIT- the models are pretty basic with class ModelA(models.Model): x = models.CharField(max_length = 30) y = models.CharField(max_length = 30) z = models.CharField(max_length = 30)
answer count: 2
tagged with: django-admin
has answer: http://stackoverflow.com/a/50474847
type: UnansweredQuestion
downvote count: 0
has title: Django: list_display is not callable
tagged with: django

http://stackoverflow.com/q/50505784
score: 3
has body: I have a DataFrame with two columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the elements of other columns in same row be values. However, entries in the first column are repeated - Keys Values 1 1 1 6 1 9 2 3 3 1 3 4 The dict I want is - {1: [1,6,9], 2: [3], 3: [1,4]} I am using the code - mydict=df.set_index('Keys').T.to_dict('list') however, the output has only unique values of keys. {1: [9], 2: [3], 3: [4]}
has title: Convert a Pandas DataFrame with repetitive keys to a dictionary
tagged with: python
has answer: http://stackoverflow.com/a/50505848
accepted answer: http://stackoverflow.com/a/50505848
type: AnsweredQuestion
answer count: 2
tagged with: pandas
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88023764
has answer: http://stackoverflow.com/a/50505886
possible better answer: http://stackoverflow.com/a/50505886
favorite count: 0
type: Question

http://stackoverflow.com/comment/87897549
has text: I found that I can use the following: i = root.winfo_children(); d = i.index(frame_for_D); for child in i[d].winfo_children():; child.destroy() This allows find the proper index number for the desired frame.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50430579
type: Comment

django-rest-framework
tags question: http://stackoverflow.com/q/50506667
tags question: http://stackoverflow.com/q/50530805
tags question: http://stackoverflow.com/q/50427289
tags question: http://stackoverflow.com/q/50415002
tags question: http://stackoverflow.com/q/50535257
tags question: http://stackoverflow.com/q/50499418
tags question: http://stackoverflow.com/q/50437901
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/50386926
tags question: http://stackoverflow.com/q/50524040
tags question: http://stackoverflow.com/q/50429243
tags question: http://stackoverflow.com/q/50487145
tags question: http://stackoverflow.com/q/50498884
tags question: http://stackoverflow.com/q/50505440
tags question: http://stackoverflow.com/q/50451152
tags question: http://stackoverflow.com/q/50468672
tags question: http://stackoverflow.com/q/50436833
tags question: http://stackoverflow.com/q/50507550
tags question: http://stackoverflow.com/q/50481800
tags question: http://stackoverflow.com/q/50485085
tags question: http://stackoverflow.com/q/50413239
tags question: http://stackoverflow.com/q/50432243
tags question: http://stackoverflow.com/q/50460505
tags question: http://stackoverflow.com/q/50465026
type: Tag
tags question: http://stackoverflow.com/q/50402446
tags question: http://stackoverflow.com/q/50477702
tags question: http://stackoverflow.com/q/50444958
tags question: http://stackoverflow.com/q/50409128
tags question: http://stackoverflow.com/q/50426285
tags question: http://stackoverflow.com/q/50458956
tags question: http://stackoverflow.com/q/50462214
tags question: http://stackoverflow.com/q/50517745
tags question: http://stackoverflow.com/q/50469182

http://stackoverflow.com/a/68319995
downvote count: 1
answers question: http://stackoverflow.com/q/50386968
type: Answer
score: -1
has body: You should use np.true_divide. x = np.arange(5) np.true_divide(x, 4)*100 [Output] array([ 0. , 25., 50. , 75., 100. ])
upvote count: 0

http://stackoverflow.com/q/50393475
accepted answer: http://stackoverflow.com/a/50393629
tagged with: python
possible better answer: http://stackoverflow.com/a/50393884
has answer: http://stackoverflow.com/a/50393884
answer count: 2
has title: Pandas select date_range with empty rows does not work
tagged with: pandas
has body: in a pandas data frame I have a column with dates and empty values like that 15 2018-04-13 13:26:54 UTC 16 ... 28 29 2018-05-15 00:00:00 UTC 30 ... 40 41 42 2018-03-24 20:32:36 UTC ... 46 2018-04-10 20:41:39 UTC 47 48 49 2018-01-26 20:30:22 UTC .... 58 2017-05-30 09:26:04 UTC 59 2010-09-09 14:09:03 UTC and I am searching for values empty and in a date range. Unfortunately nothing like that worked df[df['date_column'].loc['2017-01-01':'2018-01-01']] df['date_column']isin(pd.date_range('two_months', periods=2, freq='M')) df[df['date_column'].str.contains(regex_filters_date)] How would I correctly select dates within a given range ?
downvote count: 0
upvote count: 1
score: 1
tagged with: date-range
has answer: http://stackoverflow.com/a/50393629
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29370057
type: AnsweredQuestion

http://stackoverflow.com/comment/88000418
score: 0
comment on: http://stackoverflow.com/a/50478464
type: Comment
type: AnswerComment
has text: Don't forget to reinstall every time when you edit sources.

http://stackoverflow.com/a/67337328
type: Answer
answers question: http://stackoverflow.com/q/50541409
score: 0
has body: If all you want is to track down those custom metrics, I've managed to make it work relatively simply by inheriting from ModelCheckpoint class ModdedModelCheckpoint(keras.callbacks.ModelCheckpoint): def on_epoch_end(self, epoch, logs={}): relevantAcc = list(availableOutputs.keys()) accuracies = [logs[f"val_y_{k}_accuracy"] for k in relevantAcc] print(f"Relevant_Accuracies: {accuracies}") average = sum(accuracies) / len(relevantAcc) print(f"Average Accuracies: {average}") logs["val_y_accuracy"] = average super(keras.callbacks.ModelCheckpoint, self).on_epoch_end( epoch, logs=logs ) In this case, it decides whether to store the best model based on my "fake" val_y_accuracy entry to the logs

http://stackoverflow.com/a/50410397
answers question: http://stackoverflow.com/q/50390889
has comment: http://stackoverflow.com/comment/88020848
has body: The general solution is to not rely on overly-specific APIs like datareader and instead go to the source. You can use datareader's source code as inspiration and as a guide for how to do it. But ultimately when you need to get data from a source, you may want to directly access that source and load the data. One very popular tool for HTTP APIs is requests. You can easily use it to load JSON data from any website or HTTP(S) service. Once you have the JSON, you can load it into Pandas. Because this solution is based on general-purpose building blocks, it is applicable to virtually any data source on the Web (as opposed to e.g. pandaSDMX, which is only applicable to SDMX data sources).
has comment: http://stackoverflow.com/comment/88062152
downvote count: 0
has comment: http://stackoverflow.com/comment/88038422
has comment: http://stackoverflow.com/comment/87996529
has comment: http://stackoverflow.com/comment/87836932
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87897432
has comment: http://stackoverflow.com/comment/87910756
has comment: http://stackoverflow.com/comment/88068341
has comment: http://stackoverflow.com/comment/87837139
has comment: http://stackoverflow.com/comment/87907226
has comment: http://stackoverflow.com/comment/87846715
score: 1

http://stackoverflow.com/a/50522071
type: Answer
has comment: http://stackoverflow.com/comment/88110976
score: 0
has comment: http://stackoverflow.com/comment/88107566
answers question: http://stackoverflow.com/q/50520408
has body: You can use wrap and unwrap Demo: from bs4 import BeautifulSoup s = """ This sign is select color in color """ soup = BeautifulSoup(s, "html.parser") for t in soup.find_all('text'): if t.a: t.a.wrap(soup.new_tag("b")).find("a").unwrap() print(t) Output: This sign is select color in color wrap unwrap

http://stackoverflow.com/q/50428293
upvote count: 1
has comment: http://stackoverflow.com/comment/94652779
tagged with: python
tagged with: conv-neural-network
answer count: 0
has body: I am trying to extract features from audio files using Librosa, to feed to a CNN as Numpy arrays. Currently i save a single feature at a time to feed into the CNN. I save two dimensional (single-channel) log-scaled mel-spectrogram features in Python using Librosa: def build_features(): y, sr = librosa.load("audio.wav") mel = librosa.feature.melspectrogram( n_fft=4096, n_mels=128, #Mel-bins hop_length=2048, ) logamplitude = librosa.amplitude_to_db logspec = logamplitude(mel, ref=1.0)[np.newaxis, :, :, np.newaxis] This gives the shape (1,128,323,1). I would like to add another feature, let's say a tempogram. I can do this, using the same code, but replacing melspectrogram to tempogram', and setting the window length to 128. This gives me a tempogram shape of (1,128,323,1). Now i would like to "stack" these 2 feature layers, into a multi-channel numpy object, that i can feed into a CNN in Keras. How should i code this? EDIT: Think I figured it out, using np.vstack()
score: 1
has comment: http://stackoverflow.com/comment/94862818
has comment: http://stackoverflow.com/comment/94699309
downvote count: 0
has title: Save Audio Features extracted using Librosa in a multichannel Numpy array
tagged with: librosa
has comment: http://stackoverflow.com/comment/94659364
tagged with: keras
has comment: http://stackoverflow.com/comment/94663089
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion

http://stackoverflow.com/q/50389096
has comment: http://stackoverflow.com/comment/87793812
has title: Pandas: InvalidIndexError: Reindexing only valid with uniquely valued Index objects
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 9
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87793749
score: 9
accepted answer: http://stackoverflow.com/a/50389166
tagged with: pandas
has answer: http://stackoverflow.com/a/50389166
has body: I have two Dataframes that store data about products procured in a store. df1 stores data about the store name, product id, product name and the date when the purchase was made. df2 stores data about product id, product name and the type. I am trying to update df2 with the Date recevied value in df1 but only for products of type P. Given below are views of the dataframe and what I tried doing. df1: StoreName,ProdId,ProdName,DateReceived Store A,P1,Prod1,2018-05-01 Store A,P2,Prod2,2018-05-02 Store B,P1,Prod1,2018-05-04 df2: DateRecived,ProdId,ProdName,Type ,P1,Prod1,P ,P2,Prod2,P ,P3,Prod3,S Script: df2['DateRecived'] = df2['ProdId'].map(df1.set_index('ProdId')['StoreName']).df2['Type'] == 'P' Running this throws the below error: InvalidIndexError: Reindexing only valid with uniquely valued Index objects Could anyone help me modify the script so that I am able to filter out value by Store Name and Prod Name and get df2 populated with the DateReceived value. Thanks.
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50512302
has title: Django celery - asyncio - daemonic process are not allowed to have children
tagged with: celery
favorite count: 0
type: Question
score: 8
upvote count: 8
tagged with: python
has body: I can see similar questions have been asked before but those are running multi processors and not executors. Therefore I am unsure how to fix this. the GitHub issue also say its resolved in 4.1 https://github.com/celery/celery/issues/1709 I am using celery==4.1.1 django-celery==3.2.1 django-celery-beat==1.0.1 django-celery-results==1.0.1 My script as as follows, ive tried to cut it down to show relevant code only. @asyncio.coroutine def snmp_get(ip, oid, snmp_user, snmp_auth, snmp_priv): results=[] snmpEngine = SnmpEngine() errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( ... ) ... for varBind in varBinds: results.append(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() return results def create_link_data_record(link_data): obj = LinkData.objects.create( ... ) return 'data polled for {} record {} created'.format(link_data.hostname, obj.id) async def retrieve_data(link, loop): from concurrent.futures import ProcessPoolExecutor executor = ProcessPoolExecutor(2) poll_interval = 60 results = [] # credentials: ... print('polling data for {} on {}'.format(hostname,link_mgmt_ip)) # create link data obj link_data = LinkDataObj() ... # first poll for speeds download_speed_data_poll1 = await snmp_get(link_mgmt_ip, down_speed_oid % link_index ,snmp_user, snmp_auth, snmp_priv) download_speed_data_poll1 = await snmp_get(link_mgmt_ip, down_speed_oid % link_index ,snmp_user, snmp_auth, snmp_priv) # check we were able to poll if 'timeout' in str(get_snmp_value(download_speed_data_poll1)).lower(): return 'timeout trying to poll {} - {}'.format(hostname ,link_mgmt_ip) upload_speed_data_poll1 = await snmp_get(link_mgmt_ip, up_speed_oid % link_index, snmp_user, snmp_auth, snmp_priv) # wait for poll interval await asyncio.sleep(poll_interval) # second poll for speeds download_speed_data_poll2 = await snmp_get(link_mgmt_ip, down_speed_oid % link_index, snmp_user, snmp_auth, snmp_priv) upload_speed_data_poll2 = await sn…
accepted answer: http://stackoverflow.com/a/50587988
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39815771
has answer: http://stackoverflow.com/a/50587988
answer count: 1
tagged with: django-celery
downvote count: 0

http://stackoverflow.com/a/50450831
has body: Try doing the following: page_url = urlparse(df['Page URL']) df['query'] = parse_qs(page_url.query) Remember that parse_qs() returns a dictionary, so you will have dictionaries in your query cells.
type: Answer
answers question: http://stackoverflow.com/q/50450694
score: 0
has comment: http://stackoverflow.com/comment/87914956
has comment: http://stackoverflow.com/comment/87915714
has comment: http://stackoverflow.com/comment/87916259

http://stackoverflow.com/comment/87911310
comment on: http://stackoverflow.com/q/50447652
type: Comment
type: QuestionComment
score: 0
has text: I'll set a odoo10 code

http://stackoverflow.com/q/50471397
downvote count: 0
has comment: http://stackoverflow.com/comment/87956420
upvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/87956460
linked to: http://stackoverflow.com/q/38231591
favorite count: 0
has title: Searching and replacing in nested dictionary in a Pandas Dataframe column
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50471512
tagged with: dataframe
tagged with: python
tagged with: dictionary
has body: Have some tricky situation. The Pandas Dataframe df contains a column col which has nested dictionaries as values looking like that: {'code': 'D104', 'description': 'Error Occured', 'id': '5451235d', 'root_cause': 'Brokage'} What I need to do is to find the occurrences of certain codes in string and replace the whole string with it, in example above it will be searching for 'D104' and all the string will be just 'D104' instead of dict. I tried to apply .str.contains () on that column and use replace () function on the column but it seems to be that the trick is not working with dictionaries as values. Can you please guide me the way?
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50471512
answer count: 1

http://stackoverflow.com/q/50390255
has comment: http://stackoverflow.com/comment/87797914
tagged with: pyspark
upvote count: 1
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/87796341
has comment: http://stackoverflow.com/comment/87829642
has comment: http://stackoverflow.com/comment/87834944
has comment: http://stackoverflow.com/comment/87796881
has comment: http://stackoverflow.com/comment/87798645
has comment: http://stackoverflow.com/comment/87834536
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87796557
has comment: http://stackoverflow.com/comment/87835382
has title: Too many values to unpack in lambda function
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/87796743
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87835622
has comment: http://stackoverflow.com/comment/87796399
downvote count: 0
has comment: http://stackoverflow.com/comment/87797072
has comment: http://stackoverflow.com/comment/87796982
has body: I just started learning Python. I'm using an API to build a TFIDFs model, however I'm facing some errors with the lambda functions which I cannot resolve. This is part of the class that generates the TFIDFs: class tfidf(ModelBuilder, Model): def __init__(self, max_ngram=1, normalize = True): self.max_ngram = max_ngram self.normalize = normalize def build(self, mentions, idfs): m = mentions\ .map(lambda (target, (span, text)): (target, text))\ """error is triggered here """ .mapValues(lambda v: ngrams(v, self.max_ngram))\ .flatMap(lambda (target, tokens): (((target, t), 1) for t in tokens))\ .reduceByKey(add)\ .map(lambda ((target, token), count): (token, (target, count)))\ .leftOuterJoin(idfs)\ And here is a sample output of the mentions class (which is the input causing the error in tdfidf class): Out[24]: [{'_id': u'en.wikipedia.org/wiki/William_Cowper', 'source': 'en.wikipedia.org/wiki/Beagle', 'span': (165, 179), 'text': u'References to the dog appear before the 19th century in works by such writers as William Shakespeare, John Webster, John Dryden, Thomas Tickell, Henry Fielding, and William Cowper, as well as in Alexander Pope\'s translation of Homer\'s "Iliad".'}, {'_id': u"en.wikipedia.org/wiki/K-Run's_Park_Me_In_First", 'source': 'en.wikipedia.org/wiki/Beagle', 'span': (32, 62), 'text': u" On 12 February 2008, a Beagle, K-Run's Park Me In First (Uno), won the Best In Show category at the Westminster Kennel Club show for the first time in the competition's history."}, The error message is: .map(lambda (target, (span, text)): (target, text))\ ValueError: too many values to unpack I tried: .map(lambda ( src, target, span, text) : (target, text))\ since I only need the target and text which causes the same error in mentions\. A simple and a compilable example: import math import numpy Data = [{'_id': '333981', 'source': 'Apple', 'span': (100, 119), 'text': ' It is native to the northern Pacific.'}, {'_id': '27262', 'source': 'Apple', 'span': (4, 20), 'text': ' …
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87796784
accepted answer: http://stackoverflow.com/a/50410218
has comment: http://stackoverflow.com/comment/87796305
has comment: http://stackoverflow.com/comment/87797358
has answer: http://stackoverflow.com/a/50410218

http://stackoverflow.com/comment/88004374
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50495831
has text: Yes, this is what happens. I believe OP knows that and is asking how to get around this...

http://stackoverflow.com/comment/136254711
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/59514584
has text: Just FYI, the regular expression for the method name is actually 3-31 characters long. The first character, then 2-30 characters after that.
type: Comment

arrays
tags question: http://stackoverflow.com/q/50512432
tags question: http://stackoverflow.com/q/50506331
tag name: arrays
tags question: http://stackoverflow.com/q/50452635
tags question: http://stackoverflow.com/q/50537287
tags question: http://stackoverflow.com/q/50394748
tags question: http://stackoverflow.com/q/50531181
tags question: http://stackoverflow.com/q/50435896
tags question: http://stackoverflow.com/q/50431401
tags question: http://stackoverflow.com/q/50437384
tags question: http://stackoverflow.com/q/50500553
type: Tag
tags question: http://stackoverflow.com/q/50397260
tags question: http://stackoverflow.com/q/50416661
tags question: http://stackoverflow.com/q/50512655
tags question: http://stackoverflow.com/q/50518158
tags question: http://stackoverflow.com/q/50537646
tags question: http://stackoverflow.com/q/50499552
tags question: http://stackoverflow.com/q/50440592
tags question: http://stackoverflow.com/q/50437865
tags question: http://stackoverflow.com/q/50397016
tags question: http://stackoverflow.com/q/50537551
tags question: http://stackoverflow.com/q/50423310
tags question: http://stackoverflow.com/q/50391703
tags question: http://stackoverflow.com/q/50392879
tags question: http://stackoverflow.com/q/50493216
tags question: http://stackoverflow.com/q/50527383
tags question: http://stackoverflow.com/q/50414016
tags question: http://stackoverflow.com/q/50498421
tags question: http://stackoverflow.com/q/50435357
tags question: http://stackoverflow.com/q/50497999
tags question: http://stackoverflow.com/q/50472562
tags question: http://stackoverflow.com/q/50461634
tags question: http://stackoverflow.com/q/50472235
tags question: http://stackoverflow.com/q/50491703
tags question: http://stackoverflow.com/q/50405832
tags question: http://stackoverflow.com/q/50421590
tags question: http://stackoverflow.com/q/50491504
tags question: http://stackoverflow.com/q/50498879
tags question: http://stackoverflow.com/q/50412043
tags question: http://stackoverflow.com/q/50475183
tags question: http://stackoverflow.com/q/50459216
tags question: http://stackoverflow.com/q/50451593
tags question: http://stackoverflow.com/q/50510374
tags question: http://stackoverflow.com/q/50399782
tags question: http://stackoverflow.com/q/50442657
tags question: http://stackoverflow.com/q/50459119
tags question: http://stackoverflow.com/q/50464273
tags question: http://stackoverflow.com/q/50459578
tags question: http://stackoverflow.com/q/50499351
tags question: http://stackoverflow.com/q/50494388
tags question: http://stackoverflow.com/q/50389518
tags question: http://stackoverflow.com/q/50487164
tags question: http://stackoverflow.com/q/50428668
tags question: http://stackoverflow.com/q/50471811
tags question: http://stackoverflow.com/q/50472421
tags question: http://stackoverflow.com/q/50421182
tags question: http://stackoverflow.com/q/50410191
tags question: http://stackoverflow.com/q/50486328
tags question: http://stackoverflow.com/q/50447162
tags question: http://stackoverflow.com/q/50428368
tags question: http://stackoverflow.com/q/50520231
tags question: http://stackoverflow.com/q/50535733
tags question: http://stackoverflow.com/q/50389128
tags question: http://stackoverflow.com/q/50500369
tags question: http://stackoverflow.com/q/50515170
tags question: http://stackoverflow.com/q/50500345
tags question: http://stackoverflow.com/q/50415972
tags question: http://stackoverflow.com/q/50536713
tags question: http://stackoverflow.com/q/50516590
tags question: http://stackoverflow.com/q/50529250
tags question: http://stackoverflow.com/q/50517636
tags question: http://stackoverflow.com/q/50463366
tags question: http://stackoverflow.com/q/50392129
tags question: http://stackoverflow.com/q/50468792
tags question: http://stackoverflow.com/q/50465162
tags question: http://stackoverflow.com/q/50494092
tags question: http://stackoverflow.com/q/50415280
tags question: http://stackoverflow.com/q/50411583
tags question: http://stackoverflow.com/q/50439908

http://stackoverflow.com/a/50416804
accepted answer of: http://stackoverflow.com/q/50416663
score: 0
answers question: http://stackoverflow.com/q/50416663
has comment: http://stackoverflow.com/comment/87852580
type: AcceptedAnswer
type: Answer
has body: You are using old version of Fabric 1.8.3, Fabric (2+) has Python 3 compatibility (now support 2.7 and 3.4+) Therefore, kindly upgrade to the latest version of Fabric Module, considering the upgrade documentation http://docs.fabfile.org/en/latest/upgrading.html

http://stackoverflow.com/q/50477333
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87968303
has body: I was analyzing a doubly linked list function that deletes a node. However Im a bit confused. def remove( self, p ) : tmp = p.prev p.prev.next = p.next p.prev = tmp Why is there a tmp = p.prev and p.prev = tmp. What is the purpose of those extra line? and finally, why is no nodes being deleted with "del"? shouldn't it be "del p" at the end of the code? Thank you!
has comment: http://stackoverflow.com/comment/87968312
tagged with: doubly-linked-list
has comment: http://stackoverflow.com/comment/87968580
accepted answer: http://stackoverflow.com/a/50477437
has comment: http://stackoverflow.com/comment/87968361
has title: Doubly Linked list in python Using Del
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50477437

http://stackoverflow.com/q/50511640
score: 2
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88035845
has comment: http://stackoverflow.com/comment/88038883
downvote count: 1
has comment: http://stackoverflow.com/comment/88036492
favorite count: 0
type: Question
has body: For example issue_d column in dataframe is string, df['issue_d'] = 'Dec-2012' I want to convert the string to datetime type not string type: 2012-12, how to do that? I use [datetime.strptime(x, '%b-%Y') for x in df.issue_d] But I get as result 2012-12. How can I get a result without days, and save it into a database by using mysql and sqlalchemy? I create a column issue_d with DateTime() type in my database. I want to insert the df['issue_d'] into that table. Table created using sqlalchemy
has comment: http://stackoverflow.com/comment/88035963
has answer: http://stackoverflow.com/a/50512045
linked to: http://stackoverflow.com/q/50503290
tagged with: pandas
has answer: http://stackoverflow.com/a/50512116
has title: How to convert string to datetime without days in pandas
has answer: http://stackoverflow.com/a/50511720
linked to: http://stackoverflow.com/q/14425133
tagged with: python
tagged with: mysql
has answer: http://stackoverflow.com/a/50511724
has comment: http://stackoverflow.com/comment/88036337
answer count: 4

recursion
type: Tag
tags question: http://stackoverflow.com/q/50461333
tags question: http://stackoverflow.com/q/50470110
tags question: http://stackoverflow.com/q/50441677
tags question: http://stackoverflow.com/q/50518629
tag name: recursion
tags question: http://stackoverflow.com/q/50468156
tags question: http://stackoverflow.com/q/50498540
tags question: http://stackoverflow.com/q/50455832
tags question: http://stackoverflow.com/q/50434079
tags question: http://stackoverflow.com/q/50428376
tags question: http://stackoverflow.com/q/50508591
tags question: http://stackoverflow.com/q/50426566
tags question: http://stackoverflow.com/q/50422112
tags question: http://stackoverflow.com/q/50432450
tags question: http://stackoverflow.com/q/50532690

http://stackoverflow.com/a/65691984
score: 1
downvote count: 0
upvote count: 1
has body: when I installed the pycharm I had the same issue. for this, you really need to understand the concept of the virtual environment. this error comes because you run the file in another directory in which you do not create any virtual environment. let's say you create a virtual environment in any folder located at the desktop now you run the files in any other folder located in /user/AppData/any_folder then it will show the error that the system can't find the file specified. So be sure you run in a file in the same folder in which you created a virtual environment.
type: Answer
answers question: http://stackoverflow.com/q/50386050

http://stackoverflow.com/a/50470895
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: request = scrapy.Request(link, callback=self.parse2) request.meta['item'] = item yield request This does define a meta variable with the name item but not with pitem. So when you call function parse2 and say pitem = response.meta['pitem'] it is unable to find pitem in the request meta data. One possible solution might be to use pitem = response.meta.get('pitem') which will return a None value if it's unable to find pitem but that depends very much on your usecase.
answers question: http://stackoverflow.com/q/50467085

http://stackoverflow.com/a/50480243
score: 26
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87981222
has body: Read file first and then send it in response. from django.http import HttpResponse, HttpResponseNotFound def waprfile(request, date): ... file_location = '/path/to/file/foo.xls' try: with open(file_location, 'r') as f: file_data = f.read() # sending response response = HttpResponse(file_data, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xls"' except IOError: # handle file not exist case here response = HttpResponseNotFound(' File not exist ') return response Read docs for more info: telling browser to treat the response as a file attachment and returning errors
downvote count: 0
has comment: http://stackoverflow.com/comment/87978167
upvote count: 26
type: Answer
has comment: http://stackoverflow.com/comment/87975959
accepted answer of: http://stackoverflow.com/q/50479804
has comment: http://stackoverflow.com/comment/120683212
has comment: http://stackoverflow.com/comment/87979024
answers question: http://stackoverflow.com/q/50479804

http://stackoverflow.com/comment/87902807
comment on: http://stackoverflow.com/a/50444048
type: AnswerComment
score: 0
has text: Thanks Prany for your help. Im trying to find the CRX of Browsec or any good VPN plugin but no success yet. The app on the link http://crxextractor.com doesn't show any crx when i try to add file with extension id in it. In fact, there is no .CRX file in the folder of extension id. Can you help how i can find crx of any good VPN plugin
type: Comment

http://stackoverflow.com/a/58816007
upvote count: 6
has comment: http://stackoverflow.com/comment/134177748
has body: As noted in the Pipes and Queues documentation if a child process has put items on a queue (and it has not used JoinableQueue.cancel_join_thread), then that process will not terminate until all buffered items have been flushed to the pipe. This means that if you try joining that process you may get a deadlock unless you are sure that all items which have been put on the queue have been consumed. ... Note that a queue created using a manager does not have this issue. If you switch over to a manager queue, then the process terminates successfully: import multiprocessing as mp import queue import requests import time class ChildProcess(mp.Process): def __init__(self, q, qout): super().__init__() self.qin = qin self.qout = qout self.daemon = True def run(self): while True: try: url = self.qin.get(block=False) r = requests.get(url, verify=False) self.qout.put(r.content) self.qin.task_done() except queue.Empty: break except requests.exceptions.RequestException as e: print(self.name, e) self.qin.task_done() print("Infinite loop terminates") if __name__ == '__main__': manager = mp.Manager() qin = mp.JoinableQueue() qout = manager.Queue() for _ in range(5): qin.put('http://en.wikipedia.org') w = ChildProcess(qin, qout) w.start() qin.join() time.sleep(1) print(w.name, w.is_alive())
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50483576
score: 6

http://stackoverflow.com/q/50407953
type: UnansweredQuestion
score: 0
tagged with: python
has body: I don't understand the failure i add with my code sample below import xml.etree.ElementTree as ET with open('sheet_short.xml','r') as f: tree = ET.parse(f) # # some processing # xml_str = ET.tostring(tree) The code is failing with error message AttributeError: 'ElementTree' object has no attribute 'tag' Searching a bit I ended on a link stating I should use getroot so I replace my last line with xml_str = ET.tostring(tree.getroot()) and now it's OK but I'm not sure why it was failing originally. is it because parse returns an ElemenTree object while tostring requires an element object? Thanks for your precious feedbacks Simon
tagged with: elementtree
type: Question
has title: python ElementTree.tostring(tree) failed but ElementTree.tostring(tree.getroot()) OK, cannot picture the difference
has answer: http://stackoverflow.com/a/50408412
answer count: 2
has answer: http://stackoverflow.com/a/50409048

http://stackoverflow.com/q/50399442
has title: How to pass command line arguments to a url string
answer count: 1
downvote count: 1
has body: I have a report I'm downloading from a url using requests in python like this: dls = 'http://somepage/reporting?tags=name&amp;daysback=days' resp = requests.get(dls) What I want is for 'tag' and 'daysback' in the url above to be arguments passed in the command line using sys argv. For example, I want something like this: try: tag = sys.argv[1] daysback = sys.argv[2] except IndexError: raise IndexError('Example/ python script.py [tag] [daysback]') So if my tag name was 'produce' and 'daysback' was 10, for example: I'd expect the url to look like this: dls = 'http://somepage/reporting?tags=produce&amp;daysback=10' and command line argument to be: python script.py [produce] [10] Does anyone know how I can do this?
favorite count: 0
has comment: http://stackoverflow.com/comment/87816147
accepted answer: http://stackoverflow.com/a/50399482
type: Question
has answer: http://stackoverflow.com/a/50399482
tagged with: sys
tagged with: python
type: AnsweredQuestion
score: 0
upvote count: 1

http://stackoverflow.com/a/50429457
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50429282
has body: There is no item with class ec-table__title in the base html of that page. However, it does appear when using a dom inspector in the browser. I am afraid this is a sure sign that it has been inserted into the DOM by javascript ad indeed there is some javascript invoked by that webpage. May I suggest that you investigate using the selenium module in conjunction with BeautifulSoup?
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87970188
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50477293
type: AnswerComment
has text: Hello Sim - Appreciate it very much and the code is working. Two questions. 1>Was there anything different that struck you to find an alternate website for same data? 2> Do I assume that it is not at all possible to scrape data from insidefutures.com? If yes, could you find me in the direction on why? I am new to Python so wanted to know some nitty gritty else I will waste my time in future on scraping websites that may be futile.

http://stackoverflow.com/comment/88042321
comment on: http://stackoverflow.com/q/50476771
has text: Then that's your problem. Don't name a module the same thing as a stdlib module. If you do so, it hides the stdlib module, and some code you're using will try to `import random` and use `random.choice` and get an `ImportError` or `AttributeError`. Things can get harder to debug when that code is numpy trying to do something fancy like import a C accelerator out of a stdlib module, but the fix is the same—just rename your module to something that doesn't clash.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/50442808
upvote count: 1
favorite count: 0
tagged with: binning
tagged with: pandas
score: 1
tagged with: datetime
tagged with: python
has body: This is my dataframe: ID : A, B, C, D, ... Time: 2:44PM, 3:23AM, 5:00PM, 12:00AM, ... What I would like to do is to categorize the time into bins such as: 12:00AM to 6:00AM: 0 6:00AM to 12:00PM: 1 12:00PM to 6:00PM: 2 6:00PM to 12:00AM: 3 So the output needs to be: ID: A, B, C, D, ... T_flag: 2, 0, 2, 3, ... I have tried using pd.cut and other methods but since I am a beginner in Python I am not able to find the desired result by any method.
type: Question
has answer: http://stackoverflow.com/a/50443799
has title: How to bin timestamps in python and assign labels
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87902883
comment on: http://stackoverflow.com/q/50444378
type: QuestionComment
score: 0
has text: What about the order of `matches`? Is it always as same as the original matches passed to the function?
type: Comment

http://stackoverflow.com/comment/87858467
comment on: http://stackoverflow.com/q/50421549
type: Comment
has text: Apologies - I have updated if that helps.
type: QuestionComment
score: 0

http://stackoverflow.com/a/50449440
answers question: http://stackoverflow.com/q/50448310
score: 0
has body: I found attempt to amend Pool to be overcomplicated here. The Pool class let workers to be alive untill the whole working queue is done and thus has complex mechanism to control it. Instead, if you have not very stict requirenments on 10 second, you can use the following code: from multiprocessing import Process import time pdict = {} for fname in list_files: p = Process(target = write_file, args = (fname,)) pdict[fname] = p p.start() while pdict: to_del = [] time.sleep(10) for pname in pdict: if pdict[pname].exitcode == None or pdict[pname].is_alive(): pdict[pname].terminate() #killing old; that should also release file resource pdict[pname] = Process(target = write_file, args = (pname,)) pdict[pname].start() #simply creating new and starting else: to_del.append(pname) for pname in to_del: del pdict[pname]
type: Answer
has comment: http://stackoverflow.com/comment/87925044

http://stackoverflow.com/comment/87958081
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50467459
type: QuestionComment
has text: @piRSquared - Option #2 numpy max() times: Load 42MM elements: 0:00:02.2; Build max for 67K elements: 0:00:00.6

http://stackoverflow.com/comment/88092430
score: 0
comment on: http://stackoverflow.com/q/50540460
has text: Yes you were right, I will correct
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50523899
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/88059978
tagged with: python
possible better answer: http://stackoverflow.com/a/50524113
accepted answer: http://stackoverflow.com/a/50523928
has body: My Script is reading data from another file. I require the data as float, not as string and I am searching for an elegant/pythonic way to combine float() with the last line instead of iterating over the entire list to change the data or changing it when I need it: data = [] with open(os.path.join(path, file), "r") as f: searchlines = f.readlines() for i, line in enumerate(searchlines): data.append(line.replace('[', ' ').replace(']', ' ').split()) So far this will save the data from the file in a list in a list as string. How to combine the last line with float()? Here is an example of the data before reading it: [[ 563.15 1673.97 3078.41] [ 563.15 1066.4 26617.7] [ 563.212 778.931 59356.1]
has title: How to combine split() with float()
has comment: http://stackoverflow.com/comment/88059763
has comment: http://stackoverflow.com/comment/88060262
has answer: http://stackoverflow.com/a/50524113
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50523928

http://stackoverflow.com/comment/88609320
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50516528
type: Comment
has text: I dont understand your comment.. i added the print output of my code in the original post, so you can see what it gives me, but i also mentioned that i've already tested what you suggest and it gives me the mentioned error. i know step2 is a `IfcPropertySet` but I can't get any further info from that...

http://stackoverflow.com/a/50430268
has comment: http://stackoverflow.com/comment/87875460
type: Answer
answers question: http://stackoverflow.com/q/50430246
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87875465
has body: I'm also new to Python, but it looks like your PC variable is an int, while your I variable is a tuple, which is Python's data type for something like (2,1) or (1,2,3). If your I is just a single integer represented as a tuple like (3,), you can probably do something like: int(PR = PC + int(I[0])) which will get the 0th item in the tuple and represent it as an integer. (Or if PC is the tuple and I is the int, you switch it around)

http://stackoverflow.com/q/50498879
answer count: 4
tagged with: sublist
has body: I am working on a project and I have a list of lists containing names, monetary values, etc. I am running into trouble trying to update the individual sub-lists within the primary list when a user enters a value. For example, my list contains 4 rows (constant) and an in-determinant number of columns based on user entries. I am including the whole program just for reference in case there are questions about what it all looks like: spacing = '- ' * 45 # formatting for DONOR header data_list = [['NAMES', 'DONATION AMOUNT', 'Number of Gifts', 'Avg Gifts'], ['Rudolph S', 1500, 3, 0], ['Josef M', 250, 5, 0], ['Joye A', 5000, 2, None], ['Joni M', 2750, 1, None], ['Rachelle L', 750, 3, None], ['Vena U', 1000, 7, None], ['Efrain L', 10000, 1, None], ['Mee H', 15000, 2, None], ['Tanya E', 50000, 1, None], ['Garrett H', 800, 2, None]] def addtolist(): """Method for sending 'Thank You' messages to Donors, using names *""" while True: print("Enter the name of the person you are writing to (or enter 'list' to see a list of names or Q to quit) ") fname_prompt = input("First Name: ").strip().capitalize() if fname_prompt.upper() == "Q": break elif fname_prompt.lower() == "list": if len(data_list) - 1 % 2 != 0: for i in range(0, int(len(data_list) - 1 / 2)): cut_off = int((len(data_list)) / 2) if i == 0: print(spacing) print('{:&gt;44s}'.format(str(data_list[i][0]))) print(spacing) elif cut_off + i &gt;= len(data_list): continue else: print('{:&gt;30s}'.format(data_list[i][0]), '{:&gt;35s}'.format(data_list[cut_off + i][0])) else: if i == 0: print(spacing) print('{:&gt;20s}'.format(str(data_list[i]))) print(spacing) else: print('{:&gt;15s}'.format(data_list[i][0]), '{:&gt;30s}'.format(data_list[cut_off + i][0])) else: lname_prompt = input("Last Name: ").strip().capitalize() if lname_prompt.upper() == "Q": break elif lname_prompt.lower() == "list": if len(data_list) - 1 % 2 != 0: for i in range(0, int(len(data_list) - 1 / 2)): cut_off = int((len(data_list)) / 2) if i == 0: print(spaci…
type: Question
tagged with: python-3.x
score: 0
tagged with: nested-lists
has answer: http://stackoverflow.com/a/50499648
tagged with: arrays
accepted answer: http://stackoverflow.com/a/50501192
has answer: http://stackoverflow.com/a/50498942
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50498967
has answer: http://stackoverflow.com/a/50501192
tagged with: python
has title: How to add items to multi-dimensional arrays with expanding values
possible better answer: http://stackoverflow.com/a/50498942

http://stackoverflow.com/comment/88059163
type: QuestionComment
has text: Doing with a Class would be the best approach
type: Comment
comment on: http://stackoverflow.com/q/50523576
score: 0

http://stackoverflow.com/q/50457357
has comment: http://stackoverflow.com/comment/87928416
tagged with: django-views
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/87929124
has title: Django Users, how can a user have permission to only edit the models they own (DRY)?
has body: I am currently creating a lot of views and at each one of them only the User has permissions to access that view and create or edit the model. Depending on the view I either put a small permission IF statement in the get_context_data or get_object. While the following works I would like to make it more DRY since I have more than 20 views that need it: def get_context_data(self, **kwargs): context = super(SpaceCreate, self).get_context_data(**kwargs) house = House.objects.get(pk=self.kwargs['pk']) # CHECK IF USER HAS PERMISSION TO MAKE CHANGES TO THE MODEL if house.owner != self.request.user: raise PermissionDenied or in the get_object() , and with more permission checks: def get_object(self, *args, **kwargs): obj = super(SpaceManage, self).get_object() house = House.objects.get(pk=self.kwargs['pk']) space = Space.objects.get(pk=self.kwargs['space_pk']) if space.house.owner != self.request.user and house.pk != space.house.pk: raise PermissionDenied return space While I have read a lot on creating permissions ( https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication ), they seem to be applicable in cases where we want many users to have that permission instead of checking if the user has the permission to edit the models they have created. Another possibility (in my opinion) is the use of mixins, but I don't seem to understand how they work and how to implement them. What I'm trying to achieve is: The user is only able to create, update and delete the models they have created, without re using the same code over and over in views. EDIT 1: Based on @Lemayzeur's comments, creating a Mixin is the best approach for this. Any examples or explanations would be very helpful.
has comment: http://stackoverflow.com/comment/87932282
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: mixins
score: 1
has comment: http://stackoverflow.com/comment/87928396
tagged with: django
has comment: http://stackoverflow.com/comment/87940564
favorite count: 0
type: Question

http://stackoverflow.com/q/50525752
upvote count: 1
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88076208
tagged with: discord
has comment: http://stackoverflow.com/comment/88066983
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88069945
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/88069068
has answer: http://stackoverflow.com/a/50548698
has body: How to make below command to work if members use below command in lower or upper or mixing. If members use ping it works. but if members use Ping it not works. @bot.event async def on_message(message): message.content = message.content.lower() await bot.process_commands(message) @bot.command(pass_context=True) async def ping(ctx): msg = 'Pong {0.author.mention}'.format(ctx.message) await bot.say(msg) Update: above on_message is working correctly in single file but i splitted main file to multiple files. now how to make it work for cog in all files.
has title: Command Case Insensitve
tagged with: discord.py
has comment: http://stackoverflow.com/comment/88071740
linked to: http://stackoverflow.com/q/50359600
has comment: http://stackoverflow.com/comment/88066339

http://stackoverflow.com/q/50392879
has comment: http://stackoverflow.com/comment/87801612
possible better answer: http://stackoverflow.com/a/50393271
type: AnsweredQuestion
has body: I have a sorted integer array, e.g., [0, 0, 1, 1, 1, 2, 4, 4], and I would like to determine where the integer blocks start and how long the blocks are. The block sizes are small but the array itself can be very large, so efficiency is important. The total number of blocks is also known. numpy.unique does the trick: import numpy a = numpy.array([0, 0, 1, 1, 1, 2, 4, 4]) num_blocks = 4 print(a) _, idx_start, count = numpy.unique(a, return_index=True, return_counts=True) print(idx_start) print(count) [0 0 1 1 1 2 4 4] [0 2 5 6] [2 3 1 2] but is slow. I would assume that, given the specific structure of the input array, there's a more efficient solution. For example, something as simple as import numpy a = numpy.array([0, 0, 1, 1, 1, 2, 3, 3]) num_blocks = 4 k = 0 z = a[k] block_idx = 0 counts = numpy.empty(num_blocks, dtype=int) count = 0 while k &lt; len(a): if z == a[k]: count += 1 else: z = a[k] counts[block_idx] = count count = 1 block_idx += 1 k += 1 counts[block_idx] = count print(counts) gives the block sizes, and a simple numpy.cumsum would give index_start. Using a Python loop is slow of course. Any hints?
downvote count: 0
has answer: http://stackoverflow.com/a/50393271
has answer: http://stackoverflow.com/a/50394587
accepted answer: http://stackoverflow.com/a/50394587
has comment: http://stackoverflow.com/comment/87801727
has title: Determine blocks in sorted numpy integer array
tagged with: python
upvote count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/87801845
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/87801956
tagged with: arrays
has comment: http://stackoverflow.com/comment/87801525
score: 4

http://stackoverflow.com/comment/87904717
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50424902
has text: Thanks for this!
type: Comment

http://stackoverflow.com/comment/88067864
has text: The issue is my string is predefined, it's a text block template that is then filled in with the content. Similarly, I need to use a dictionary as input to str.format(). So, I can't simply replace what I wrote with the "properties" key. I've done this for now using regex, basically implementing this solution, but I was wondering if there was something better I could do.
comment on: http://stackoverflow.com/a/50527216
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88065688
type: QuestionComment
has text: The row can be plotted. Using z = np.array([0.05, -0.022, 0.03,...]) plt.plot(z) I get a plot looking like a plot shown above. So matplotlib does this conversion in any way too.
comment on: http://stackoverflow.com/q/50526033
score: 0
type: Comment

http://stackoverflow.com/q/50420168
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52232568
tagged with: python
has body: I'm trying to custom load some image files (JPG files) with some labels and feed them into a convolutional neural network (CNN) in PyTorch following the example here. However, there still seem to be no decent end-to-end tutorials. The problem that I am seeing is the following. RuntimeError: thnn_conv2d_forward is not implemented for type torch.ByteTensor My Dataset looks like the following. class ImageData(Dataset): def __init__(self, width=256, height=256, transform=None): self.width = width self.height = height self.transform = transform y, x = get_images() #y is a list of labels, x is a list of file paths self.y = y self.x = x def __getitem__(self, index): img = Image.open(self.x[index]) # use pillow to open a file img = img.resize((self.width, self.height)) # resize the file to 256x256 img = img.convert('RGB') #convert image to RGB channel if self.transform is not None: img = self.transform(img) img = np.asarray(img).transpose(-1, 0, 1) # we have to change the dimensions from width x height x channel (WHC) to channel x width x height (CWH) img = torch.from_numpy(np.asarray(img)) # create the image tensor label = torch.from_numpy(np.asarray(self.y[index]).reshape([1, 1])) # create the label tensor return img, label def __len__(self): return len(self.x) The CNN is taken from here and is modified to handle NCWH (batch x channel x width x height) as follows. class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 256, 256) 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 The learning loop is also taken from the same tutorial and looks like the following. for epoch in range(2): # loop over the dataset multiple times running_l…
upvote count: 6
answer count: 2
tagged with: conv-neural-network
tagged with: pytorch
has title: How do I load up an image and convert it to a proper tensor for PyTorch?
has answer: http://stackoverflow.com/a/50420914
downvote count: 0
score: 6
tagged with: image-processing
favorite count: 0
type: Question
tagged with: python-imaging-library

http://stackoverflow.com/comment/87859532
has text: Then my solution should work
comment on: http://stackoverflow.com/q/50422187
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87983385
type: Comment
has text: If your code is complete, you can post it to https://codereview.stackexchange.com/and get feedback on how to improve it. For what it's worth, I do it your way too
type: QuestionComment
comment on: http://stackoverflow.com/q/50485149
score: 1

http://stackoverflow.com/q/50439225
tagged with: dictionary
has body: This feels redundant: name = 'Isaiah' myInfo = { 'name': name } Is there a shorter, idiomatic way to do this, like in JavaScript: myInfo = { name } Edit: changed the variable name from dict to myInfo, since dict is a keyword.
favorite count: 0
type: Question
tagged with: python-2.7
downvote count: 0
has answer: http://stackoverflow.com/a/50439292
has comment: http://stackoverflow.com/comment/87892618
has comment: http://stackoverflow.com/comment/139740340
has comment: http://stackoverflow.com/comment/87892699
has answer: http://stackoverflow.com/a/56304909
possible better answer: http://stackoverflow.com/a/56304909
has answer: http://stackoverflow.com/a/50439240
type: AnsweredQuestion
has title: Use variable as key name in python dictionary
accepted answer: http://stackoverflow.com/a/50439240
answer count: 3
linked to: http://stackoverflow.com/q/783781
upvote count: 21
score: 21
linked to: http://stackoverflow.com/q/3972872
tagged with: python

http://stackoverflow.com/q/50514493
type: UnansweredQuestion
has title: Splitting user input into lists of increasing size [python]
tagged with: python
tagged with: list
downvote count: 0
has comment: http://stackoverflow.com/comment/88041584
linked to: http://stackoverflow.com/q/8370206
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50515067
has body: I am trying to produce a code that verifies whether or not a user input meets the criteria of a pascal triangle. I know how to go about inputting the number of lines and having it develop a pascal triangle, but I am having trouble figuring out how to get a user to input something like 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1, and having my program say whether it is a pascal triangle or not. values = input("Enter the numbers: ").split() pascals_triangle = list(map(list, values)) I know the first line could split the numbers, and the second line would assign the numbers into individual lists of a list. Every time I attempt to have the lists increase by 1 in every row, I get str/int errors. Once I get past this little road block, I should be able to figure out the rest of the code. data = input("Enter values: ").split() def pascal_triangle(data): size = int(data[0]) n = 2 * size + 1 grid = [[0 for x in range(n)] for y in range(size)] left = 1 for i in range(size, 0, -1): grids = data[i].split(' ') count = 0 for g in grids: grid[i - 1][left + 2 * count] = int(g) count += 1 left += 1 if count != i: return False left = 1 for i in range(size - 1, -1, -1): if i == 0: return grid[i][left] == 1 numbers = i + 1 count = 0 while count &lt; numbers: current = grid[i][left + count * 2] upper_left = grid[i - 1][left - 1 + count * 2] upper_right = grid[i - 1][left + 1 + count * 2] if current != (upper_left + upper_right): return False count += 1 left += 1 return False status = pascal_triangle(data) if status: print('It is a pascal triangle') else: print('It is not a pascal triangle') So, in this code, why am I still not getting the accurate answers?
has comment: http://stackoverflow.com/comment/88041574
has answer: http://stackoverflow.com/a/50514753
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2

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

http://stackoverflow.com/q/50426844
has comment: http://stackoverflow.com/comment/87868795
downvote count: 1
has title: How to convert time in this format to local time zone?
has body: I'd like to convert this time Sat, 19 May 2018 16:32:56 +0000 to 20180519-113256 in a local timezone (EDT in this example) in python. Could anybody show me how to do it? PS., The following example shows how to convert time to local timezone. But I am not sure how to parse Sat, 19 May 2018 16:32:56 +0000. Convert UTC datetime string to local datetime with Python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50427120
has answer: http://stackoverflow.com/a/50427119
type: UnansweredQuestion
tagged with: python
tagged with: datetime-format
tagged with: time-format
score: 0
linked to: http://stackoverflow.com/q/4770297
answer count: 2
upvote count: 1

http://stackoverflow.com/q/50429826
type: Question
has title: My single layer perceptron converges on the OR dataset, but not on the AND dataset
tagged with: perceptron
score: 1
tagged with: python
has body: I am building my first single-layer perceptron network and I am training it to mimic the behavior of the simplest kind of logic gates (AND and OR) with two inputs. The network consists of two input nodes and a bias. The delta-rule learning algorithm for single layer perceptron is used, with the tanh function as the activation function. When trained on the AND dataset, the network should give an answer close to 1 when given an input (1, 1), and 0 for any other input such as (0, 1), (1, 0), or (1, 1). When trained on the OR dataset, it should return an answer close to 1 when given any input other than (0, 0). However it is exhibiting a behavior which I could not understand. It converges well (ie., error rates are pretty low - 0.01 or less) when I trained it on the OR dataset: $ python nn.py [0 0]: (actual result = [[0.00051257]]). (expected result from training set=0, error rate=[[-0.00051257]]) [0 1]: (actual result = [[0.98865851]]). (expected result from training set=1, error rate=[[0.01134149]]) [1 0]: (actual result = [[0.98865222]]). (expected result from training set=1, error rate=[[0.01134778]]) [1 1]: (actual result = [[0.99993485]]). (expected result from training set=1, error rate=6.51512784e-05) However, it does not converge well on the AND dataset: $ python nn.py [0 0]: (actual result = [[-0.28911014]]). (expected result from training set=0, error rate=[[0.28911014]]) [0 1]: (actual result = [[0.23984154]]). (expected result from training set=0, error rate=[[-0.23984154]]) [1 0]: (actual result = [[0.28911014]]). (expected result from training set=0, error rate=[[-0.28911014]]) [1 1]: (actual result = [[0.68570095]]). (expected result from training set=1, error rate=[[0.31429905]]) I've tried adjusting the epoch to various numbers between 500-10000 to no effect. And eta to anywhere between 0.1 to 1.0. Looking at the converge plot below, you'll see how the neural network is converging much better for the OR dataset than the AND dataset as depicted by t…
has answer: http://stackoverflow.com/a/50433841
has comment: http://stackoverflow.com/comment/87875233
type: UnansweredQuestion
answer count: 1
tagged with: neural-network
downvote count: 0
tagged with: machine-learning
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/88031681
type: QuestionComment
has text: There's a ``yes_or_no()`` before your ``if(yes_or_no() == 1):``, that's why you have to input at least twice (the first input is always discarded).
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50509820

http://stackoverflow.com/comment/87855825
has text: No, this still doesn't make sense to me. depth 1 returns an ARRAY of depth 2 elements corresponding to the cons element in the xml. The id is logically associated with the depth 2 element. When I work at depth 1 even if I use the d["cons']['firstname'] syntax, I get the "list indices must be integers, not str" error. I suppose I could iterate through the list in the handler, but why should I have to? Depth 2 is what I want and I still don't understand why the attributes don't show up.
type: AnswerComment
comment on: http://stackoverflow.com/a/50419492
type: Comment
score: 0

configuration-files
type: Tag
tags question: http://stackoverflow.com/q/50533812
tags question: http://stackoverflow.com/q/50460562
tag name: configuration-files

http://stackoverflow.com/comment/88279122
type: AnswerComment
comment on: http://stackoverflow.com/a/50469331
has text: Thanks @4ur0r4 for the tip. I am a complete newbie to Python. Is there any chance that you could formulate an expression based on your suggestion please?
score: 0
type: Comment

http://stackoverflow.com/comment/87854876
has text: Or do you want something like `for x in itertools.product(*a.values()): do_something(x)`?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50419679
type: Comment

http://stackoverflow.com/a/50419346
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50419277
has body: You can use datetime.strptime with a specified format: from datetime import datetime x = '02-04-20189.45' res = datetime.strptime(x, '%d-%m-%Y%H.%M') # 2018-04-02 09:45:00 Python's strftime directives is a useful reference for deriving the appropriate format string. You can also use the above format with pandas.to_datetime, although this uses dateutil.parser.

django-views
tags question: http://stackoverflow.com/q/50523484
tags question: http://stackoverflow.com/q/50473197
tags question: http://stackoverflow.com/q/50455962
tags question: http://stackoverflow.com/q/50418451
tags question: http://stackoverflow.com/q/50512804
tags question: http://stackoverflow.com/q/50457357
tags question: http://stackoverflow.com/q/50431831
tags question: http://stackoverflow.com/q/50392498
tags question: http://stackoverflow.com/q/50529336
tags question: http://stackoverflow.com/q/50418200
tag name: django-views
tags question: http://stackoverflow.com/q/50472247
tags question: http://stackoverflow.com/q/50490273
tags question: http://stackoverflow.com/q/50439624
tags question: http://stackoverflow.com/q/50431810
tags question: http://stackoverflow.com/q/50539105
tags question: http://stackoverflow.com/q/50504441
type: Tag
tags question: http://stackoverflow.com/q/50518814
tags question: http://stackoverflow.com/q/50521577
tags question: http://stackoverflow.com/q/50515725
tags question: http://stackoverflow.com/q/50420252

http://stackoverflow.com/comment/87926008
comment on: http://stackoverflow.com/q/50456107
has text: Hard to tell what was wrong with the code without seeing it!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87962722
score: 2
type: Comment
comment on: http://stackoverflow.com/a/50474472
type: AnswerComment
has text: Any provisos about safety?

selenium
tags question: http://stackoverflow.com/q/50502451
tags question: http://stackoverflow.com/q/50403711
tags question: http://stackoverflow.com/q/50440066
tags question: http://stackoverflow.com/q/50458613
tags question: http://stackoverflow.com/q/50481172
tags question: http://stackoverflow.com/q/50491836
tags question: http://stackoverflow.com/q/50518008
tags question: http://stackoverflow.com/q/50418044
tags question: http://stackoverflow.com/q/50523197
tags question: http://stackoverflow.com/q/50450527
tags question: http://stackoverflow.com/q/50539817
tags question: http://stackoverflow.com/q/50485560
tags question: http://stackoverflow.com/q/50452608
tags question: http://stackoverflow.com/q/50467950
tags question: http://stackoverflow.com/q/50401721
tags question: http://stackoverflow.com/q/50434065
tags question: http://stackoverflow.com/q/50522769
tags question: http://stackoverflow.com/q/50513128
tags question: http://stackoverflow.com/q/50469221
tags question: http://stackoverflow.com/q/50537982
tags question: http://stackoverflow.com/q/50500304
tags question: http://stackoverflow.com/q/50456635
tags question: http://stackoverflow.com/q/50482431
tags question: http://stackoverflow.com/q/50469764
tags question: http://stackoverflow.com/q/50389926
tags question: http://stackoverflow.com/q/50417529
tags question: http://stackoverflow.com/q/50421597
tags question: http://stackoverflow.com/q/50432905
tags question: http://stackoverflow.com/q/50432033
tags question: http://stackoverflow.com/q/50436791
tags question: http://stackoverflow.com/q/50529563
tags question: http://stackoverflow.com/q/50478415
tags question: http://stackoverflow.com/q/50498809
tags question: http://stackoverflow.com/q/50416538
tags question: http://stackoverflow.com/q/50442391
tags question: http://stackoverflow.com/q/50468629
tags question: http://stackoverflow.com/q/50494495
tags question: http://stackoverflow.com/q/50397805
tags question: http://stackoverflow.com/q/50518634
tags question: http://stackoverflow.com/q/50502617
tags question: http://stackoverflow.com/q/50482796
tags question: http://stackoverflow.com/q/50532328
tags question: http://stackoverflow.com/q/50399181
tags question: http://stackoverflow.com/q/50386113
tags question: http://stackoverflow.com/q/50502348
tags question: http://stackoverflow.com/q/50503319
tags question: http://stackoverflow.com/q/50467167
tags question: http://stackoverflow.com/q/50485017
tags question: http://stackoverflow.com/q/50508171
tags question: http://stackoverflow.com/q/50522779
tags question: http://stackoverflow.com/q/50421723
tags question: http://stackoverflow.com/q/50535433
tags question: http://stackoverflow.com/q/50505540
tags question: http://stackoverflow.com/q/50452087
tags question: http://stackoverflow.com/q/50518447
tags question: http://stackoverflow.com/q/50429371
tags question: http://stackoverflow.com/q/50443955
tags question: http://stackoverflow.com/q/50422124
tags question: http://stackoverflow.com/q/50505827
type: Tag
tags question: http://stackoverflow.com/q/50483725
tags question: http://stackoverflow.com/q/50527561
tags question: http://stackoverflow.com/q/50457828
tags question: http://stackoverflow.com/q/50396393
tags question: http://stackoverflow.com/q/50487815
tags question: http://stackoverflow.com/q/50532259
tags question: http://stackoverflow.com/q/50486403
tags question: http://stackoverflow.com/q/50502711
tags question: http://stackoverflow.com/q/50424654
tags question: http://stackoverflow.com/q/50427972
tag name: selenium
tags question: http://stackoverflow.com/q/50440426
tags question: http://stackoverflow.com/q/50541597
tags question: http://stackoverflow.com/q/50413206
tags question: http://stackoverflow.com/q/50400666
tags question: http://stackoverflow.com/q/50472129
tags question: http://stackoverflow.com/q/50465491
tags question: http://stackoverflow.com/q/50420799
tags question: http://stackoverflow.com/q/50440568
tags question: http://stackoverflow.com/q/50519769

http://stackoverflow.com/q/50500473
has answer: http://stackoverflow.com/a/50500775
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88013904
type: AnsweredQuestion
score: 0
tagged with: view
accepted answer: http://stackoverflow.com/a/50500801
has answer: http://stackoverflow.com/a/50500801
has title: Trying to save POST data CLASS NAME in STUDENT model (foreign key)?
has comment: http://stackoverflow.com/comment/88013681
has body: I am trying to displaying classes in a form on a page. when enrol button is clicked i get the class name and assign it to student model (which has a foreign key to the class model).. Update: NEW ERROR: ValueError at /enrol/ Cannot assign "'guitar101'": "StudentProfile.student_class" must be a "MusicClass" instance. New to django I have no idea what I'm doing, please help! My Attempt, what's the issue? models.py class StudentProfile(models.Model): user = models.OneToOneField('Accounts', related_name='student_profile') student_class = models.ForeignKey(to=MusicClass, related_name="student_class", null=True, blank=True) is_student = models.BooleanField('student status', default=True) # more fields class MusicClass(models.Model): class_name = models.CharField(max_length=500, blank=True) # more fields views.py # enrolls student def studentEnrol(request): if request.method == "POST": musicClass = request.POST.get('musicClass', '') student_profile = StudentProfile(student_class=musicClass) student_profile.save() return HttpResponseRedirect('/') else: querySet = MusicClass.objects.all() args = {'classes': querySet } return render(request, 'accounts/enrol.html', args) forms.py class MusicClassesEnrolForm(forms.ModelForm): class Meta: model = MusicClass fields = ('class_name', 'class_level', 'class_time', 'class_room', 'instrument_taught', 'day', 'teacher') enrol.html {% extends 'base.html' %} {% block body %} Enrol into Class Class Name Instrument Class Level Time Teacher Room Register {% for class in classes %} {{ class.class_name }} {{ class.instrument_taught }} {{ class.class_level }} {{ class.class_time }} {{ class.teacher }} {{ class.class_room }} {% csrf_token %} {% endfor %} {% include "footer.html" %} {% endblock %} ideas please? UPDATE - TRACE BACK ADDED Environment: Request Method: POST Request URL: http://127.0.0.1:8000/enrol/ Django Version: 1.11.7 Python Version: 3.6.5 Installed Applications: ['accounts', 'timetable', 'django.contrib.admin', 'django.contrib.auth…
has comment: http://stackoverflow.com/comment/88013726
has comment: http://stackoverflow.com/comment/88013663
has comment: http://stackoverflow.com/comment/88013785
type: Question
tagged with: model
possible better answer: http://stackoverflow.com/a/50500775
answer count: 2

visual-studio-code
tags question: http://stackoverflow.com/q/50458542
tags question: http://stackoverflow.com/q/50541020
tags question: http://stackoverflow.com/q/50403405
tags question: http://stackoverflow.com/q/50486919
tags question: http://stackoverflow.com/q/50393869
tag name: visual-studio-code
tags question: http://stackoverflow.com/q/50541730
type: Tag
tags question: http://stackoverflow.com/q/50456360
tags question: http://stackoverflow.com/q/50389852
tags question: http://stackoverflow.com/q/50515623
tags question: http://stackoverflow.com/q/50477094
tags question: http://stackoverflow.com/q/50408796
tags question: http://stackoverflow.com/q/50385276
tags question: http://stackoverflow.com/q/50414626

http://stackoverflow.com/q/50467083
has body: I did: print(df['User Type'].value_counts()) This gives output: Subscriber 238889 Customer 61110 Dependent 1 Name: User Type, dtype: int64 Is there any way to remove the last line Name: User Type, dtype: int64.?
tagged with: series
has comment: http://stackoverflow.com/comment/87990231
tagged with: python-3.x
type: Question
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87947246
has title: Removing the last line from pd.Series.value_counts output
tagged with: pandas
has comment: http://stackoverflow.com/comment/87947249
score: 0

http://stackoverflow.com/comment/88006943
has text: thanks for removing the images of data. is roe successfully put into a dataframe? could you post the result of `roe.dtypes` then?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50458837
score: 0

http://stackoverflow.com/comment/87847193
has text: It has nothing to do with the file format. It's the fact that the Excel *program* acquires a lock (at the operating system level) that prevents other applications from writing to the same file. Some other application (such as the HxD hex editor) can happily open an Excel file without locking it.
comment on: http://stackoverflow.com/a/50414768
type: Comment
type: AnswerComment
score: 2

http://stackoverflow.com/comment/88020594
type: AnswerComment
comment on: http://stackoverflow.com/a/50501866
score: 0
has text: Since we have to check the correct answer with the selected answer if we save the answer along with the user then the check would fail
type: Comment

http://stackoverflow.com/q/50485017
possible better answer: http://stackoverflow.com/a/50486041
type: Question
upvote count: 4
tagged with: xpath
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50487941
tagged with: python
has comment: http://stackoverflow.com/comment/87990521
score: 4
has answer: http://stackoverflow.com/a/50486192
tagged with: selenium-webdriver
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/50486041
downvote count: 0
tagged with: selenium
has body: I'm trying to retrieve data from the dynamic web table in selenium python but errors in a console as ERROR as " values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+row+"]/td["+col+"]").text TypeError: must be str, not int FAILED (errors=1) class DynamicWebTable1(unittest.TestCase): @classmethod def setUpClass(cls): chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe" cls.driver=webdriver.Chrome(chrome_driver_path) cls.driver.implicitly_wait(30) cls.driver.maximize_window() # navigate to the application home page cls.driver.get("http://qavalidation.com/demo/") def test_get_table_data(self): time.sleep(10) columns = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr[1]/td")) rows = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr")) print("rows - ",rows) # rows - 3 print("columns - ",columns) #columns - 4 for row in range(rows): for col in range(columns): values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+row+"]/td["+col+"]").text print(" Dynamic web table index {row} ,{col} value is {values} ".format(row, col, values)) @classmethod def tearDownClass(cls): # close the browser window cls.driver.quit() Github sample code https://github.com/venkywarriors619/selenium_with_python/blob/master/Python_basics/SeleniumWebDriver_Advanced/DynamicWebTable1.py dynamic we table from http://qavalidation.com/demo/
accepted answer: http://stackoverflow.com/a/50487941
has title: how to retrieve data from dynamic table - selenium python
favorite count: 0

http://stackoverflow.com/q/50489970
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87993010
has comment: http://stackoverflow.com/comment/87993057
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87998559
tagged with: dictionary
has answer: http://stackoverflow.com/a/50490084
duplicate of: http://stackoverflow.com/q/33049397
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has title: how to iterate through json key,values in multiple dictionaries in python
tagged with: loops
score: 1
has body: i am trying to compare keys of different dictionaries stored in json.if keys are same then store those keys in another dictionary but i am not getting the required output. input looks like: [ { "huma":10, "sana":25 }, { "sara":12, "huma":20, " zeb:15 } ] what i tried is: def compare(): result_dictionary = {} with open('data.json') as data_file: data = json.load(data_file) for d1 in data: for key, value in d1.items(): print("key: {key} | value: {value}".format(key=key, value=value)) compare() i am confused how to compare these keys of multiple dictionaries and key which matches store them in a new dictionary? the output should be "Huma"because only that is equal in both dictionaries.
duplicate of: http://stackoverflow.com/q/1317410
has comment: http://stackoverflow.com/comment/87996903

http://stackoverflow.com/q/50503262
has body: I want to generate a large string (20MB+) every 3 seconds. Now my problem is that my string pool get larger and larger and i have no RAM for that. Anyone knows how to remove the string pool manually? Thanks.
answer count: 0
has title: Remove string pool
score: 1
downvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/88021189
favorite count: 0
type: Question
tagged with: string-pool
type: UnansweredQuestion
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/88020027

http://stackoverflow.com/q/50400963
tagged with: odoo
tagged with: windows
has title: Can't debug windows odoo, pydev debugger Process finished with exit code -1073740940
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87856201
answer count: 0
tagged with: pycharm
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87818345
has body: My company wants to implement an ERP and we've decided that Odoo is the chosen one. Odoo server (debian) is running, but we need a development environment in windows which I've already installed,from PyCharm I can Run the odoo server and navigate through the browser and watch the log fill, so I think it works. But I can't launch in Debug mode, when I try it the message in the console is: C:\python\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.3\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 57805 --file D:/devpython/vodoo/odoo-bin --config=D:\devpython\vodoo\odoo.conf pydev debugger: process 7072 is connecting Connected to pydev debugger (build 181.4892.64) Process finished with exit code -1073740940 (0xC0000374) Is there a log for this so I can try to solve the problem? or has anyone encountered the same problem? the only "weird" thing is that the python.exe path is different from the python.exe in my virtual environment is this a problem? if so, how can I change this configuration? I already set my Run configuration and selected the interpreter in my Virtual environment. when i run the Odoo server I get this: (first line): D:\devpython\vodooenv\Scripts\python.exe D:/devpython/vodoo/odoo-bin --config=D:\devpython\vodoo\odoo.conf Which as I understand means that is running python.exe from my virtual environment, but when I try to debug launches from another python.exe. Sorry if this is a noob question (I have the feeling it is), but I can't find an answer or a log to know more about the problem... also sorry if my english is not good.
score: 3
upvote count: 3

http://stackoverflow.com/q/50504502
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu
has title: Pyqt5 MySQL database connection not opening through worker thread using Python3
score: 0
tagged with: pyqt
answer count: 1
tagged with: mysql
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50506767
type: Question
has body: I am having problems connecting to my mysql database from my pyqt worker thread. I can connect to the DB manually through command line, but my pyqt5 worker thread seems to be unable to open the DB. I have the QMYSQL drivers available, and I have temporarily set full privileges for all users logging in to rule out that scenario, and I have made the username and password login as default, but still I cannot connect. Just to outline, the MySQL db resides on a Ubuntu system and I am connecting from a Windows 10 PC. Here's my code so far and the outputs. class Worker(QThread): def __init__(self): super(Worker, self).__init__() print('Opening DB') self.db = QtSql.QSqlDatabase().addDatabase("QMYSQL") print('Driver available? ', self.db.isDriverAvailable("QMYSQL")) self.db.setHostName(192.168.56.1) self.db.setDatabaseName('Automation_DB') self.db.setUserName('root') self.db.setPassword('root') self.db.open() self.query = QSqlQuery(self.db) self.qstring = None print('isopened? ',self.db.isOpen()) print('open? ',self.db.open()) print('Last Error ', self.db.lastError().text()) print('Drivers ', self.db.drivers()) try: self.db.open() print('Check open? ', self.db.open()) except Exception as e: if not self.db.open(): print('DB open error', e) else: print('Error') Command line output Below: Opening DB Driver available? True isopened? False open? False Last Error Driver not loaded Driver not loaded Drivers ['QSQLITE', 'QMYSQL', 'QMYSQL3', 'QODBC', 'QODBC3', 'QPSQL', 'QPSQL7'] Check open? False I just wanted to know if I am missing something obvious? Thanks.

http://stackoverflow.com/a/50652120
score: -1
upvote count: 0
has body: I have to agree. This is a foolproof way fo solving your problem, and it is the simplest way to circumvent dealing with rendering issues. Here is some code of mine with no sprites: import pygame pygame.init() game_display = pygame.display.set_mode((800, 800)) # fixed variables at the start x_pos = 400 y_pos = 400 current_speed = 15 def jump_coords(y_position, speed): if speed &gt;= 0: #to move up, reduce the y-coordinate y_position -= speed return y_position game_exit = False # main loop while not game_exit: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: y_pos = jump_coords(y_pos, current_speed) # 1 represents gravity value current_speed -= 1 rect_one = pygame.Rect(x_pos, y_pos, 10, 10) pygame.draw.rect(game_display, (255, 0, 0), rect_one) pygame.display.update()`enter code here`
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/50533105

http://stackoverflow.com/q/50386955
has comment: http://stackoverflow.com/comment/87790433
has comment: http://stackoverflow.com/comment/87791699
has comment: http://stackoverflow.com/comment/87793929
has answer: http://stackoverflow.com/a/50389918
favorite count: 0
has comment: http://stackoverflow.com/comment/87789681
type: Question
has comment: http://stackoverflow.com/comment/87833609
has title: Lambda function causing TypeError: 'int' object is not iterable
has comment: http://stackoverflow.com/comment/87789786
linked to: http://stackoverflow.com/q/50390255
downvote count: 0
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/50389918
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87792792
has comment: http://stackoverflow.com/comment/87791067
has comment: http://stackoverflow.com/comment/87793456
has comment: http://stackoverflow.com/comment/87791383
type: AnsweredQuestion
tagged with: python-2.7
has body: I just started learning Python. I'm using an API to build an IDFs model,however I'm facing some errors with the lambda functions which I cannot resolve. This the class that generates the IDF: class Idfs(DocumentFrequencies, Model): def build(self, corpus): log.info('Counting documents in corpus...') N = float(corpus.count()) dfs = super(Idfs, self).build(corpus) log.info('Building idf model: N=%i', N) return dfs\ .map(lambda (term, (df,rank)): (term, df))\ .mapValues(lambda df: math.log(N/df)) @staticmethod def format_item((term, idf)): return { '_id': term, 'idf': idf, } And the this is the class that count the DF: class DocumentFrequencies(ModelBuilder): def __init__(self, lowercase=False, max_ngram=1, min_df=2): self.lowercase = lowercase self.max_ngram = max_ngram self.min_df = min_df def build(self, docs): m = docs.map(lambda d: d['text']) if self.lowercase: m = m.map(lambda text: text.lower()) return m\ .flatMap(lambda text: set(ngrams(text, self.max_ngram)))\ .map(lambda t: (t, 1))\ .reduceByKey(add)\ .filter(lambda (k,v): v &gt; self.min_df) The error appears in this line .map(lambda (term, (df, rank)): (term, df))\ and this is the error message : TypeError: 'int' object is not iterable This is what I get when I call DocumentFrequencies.collect(): Out[5]: [(u'fawn', 3), (u'1,800', 31), (u'clotted', 3), (u'comically', 11), (u'Adjusting', 3), (u'O(log', 6), (u'unnecessarily', 15), (u'evangelical', 53), (u'naturopathic', 3), (u'grenadiers', 4), (u'stipulate', 4), (u'Vikrant', 3), (u'fractal', 18), I dont know which argument exactly is causing the error. I'm using python 2.7, 8 GB 1600 MHz DDR with 2 cores. These are the pyspark configs: conf = pyspark.SparkConf().setAll([('spark.executor.memory', '8g'),('spark.driver.memory','8g'),('spark.network.timeout','100000000s'),('spark.executor.heartbeatInterval','10000000s'),('spark.driver.maxResultSize','8g'),('spark.driver.cores','2')]) Thanks in advance,
has comment: http://stackoverflow.com/comment/87790829
tagged with: typeerror
tagged with: apache-spark
score: 1
has comment: http://stackoverflow.com/comment/87793682
answer count: 1
has comment: http://stackoverflow.com/comment/87793026

http://stackoverflow.com/q/50518706
has comment: http://stackoverflow.com/comment/88050135
has body: I have a dataset with two text columns and I should build a prediction model for a float column containing a probability value (a number between 0 and 1). My difficult here is to handle the target column. Every method and example that I find are for categorical target columns, with a short range of possibilities. But in my case, my target column doesn't work in that way. I already got some results using another numeric columns of the dataset and linear regression, but linear regression doesn't work with text features. I also tried to implement naive bayes, but I got stuck with the non categorical target.
has comment: http://stackoverflow.com/comment/88133370
has comment: http://stackoverflow.com/comment/88057262
type: Question
has comment: http://stackoverflow.com/comment/88053244
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88105787
score: 0
has title: How to build a text classification model based on a non categorical target?
tagged with: machine-learning
tagged with: scikit-learn

http://stackoverflow.com/q/50454068
has answer: http://stackoverflow.com/a/50454175
possible better answer: http://stackoverflow.com/a/50454175
score: 3
has answer: http://stackoverflow.com/a/50454197
has comment: http://stackoverflow.com/comment/87921605
tagged with: python
has comment: http://stackoverflow.com/comment/87922179
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88498118
answer count: 2
accepted answer: http://stackoverflow.com/a/50454197
tagged with: google-cloud-platform
upvote count: 3
has title: Invalid Syntax error on try clause in Python
downvote count: 0
tagged with: mysql
has body: First I apologize if this is formatted poorly, I've never asked a question here before. I'm running python 2.7.15 in a virtualenv on win10-64. I'm trying to upload some test strings to a MySQL database but I'm getting the dumbest error and I don't know how to get around it. The MySQL Python/Connector should be installed correctly. Same with the GCP SDK. import mysql.connector from mysql.connector import errorcode # Config info will be moved into config file(s) after testing # Google Proxy Connection (Proxy must be running in shell) # C:\Users\USER\Google Drive\Summer Education\GCP # $ cloud_sql_proxy.exe -instances="pdf2txt2sql-test"=tcp:3307 config1 = { 'user': 'USER', 'password': 'PASSWORD', 'host': 'IP', 'port': '3307', 'database': 'pdftxttest', 'raise_on_warnings': True, } # Direct Connection to Google Cloud SQL config2 = { 'user': 'USER', 'password': 'PASSWORD', 'host': 'IP', 'database': 'pdftxttest', 'raise_on_warnings': True, } try: cnx = mysql.connector.connect(**config1) except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) print("Connection not made") cursor = cnx.cursor() # Test information id = str(1) testtitle = str("Look a fake title") teststring = str('thislistis representingaveryshort pdfwithfuckedup spaces') add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring) try: cursor.execute(add_pdf) except mysql.connector.Error as err: if err.errno == errorcode.ER_BAD_TABLE_ERROR: print("no pdf for you") else: print(err) print("here") cnx.commit() cursor.close() cnx.close() After running this code I get (env) C:\Users\USER\Google Drive\Summer Education\ProjPdf2Txt&gt;python TXT2SQL.py File "TXT2SQL.py", line 47 try: ^ SyntaxError: invalid syntax I have some previous experience in java but I'm still a novice programmer. If I r…
favorite count: 0
has comment: http://stackoverflow.com/comment/87924024
type: Question

http://stackoverflow.com/q/50429887
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57956384
tagged with: python
has answer: http://stackoverflow.com/a/50430057
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50430031
tagged with: pandas
has body: I have a piece of Python code that essentially reduces to the following: import pandas as pd months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] l = [1607.8, 1688.17, 1605.66, 1469.03, 1312.65, 1451.74, 1445.26, 1350.94, 1371.27, 1201.6, 1240.59, 1291.43] # First, construct a empty DataFrame. df = pd.DataFrame(columns = months, dtype=float) # Then, keep adding rows to DataFrame given by list l. df.append([l]) print df Expected output is: Jan Feb Mar Apr May Jun Jul Aug \ 0 1607.8 1688.17 1605.66 1469.03 1312.65 1451.74 1445.26 1350.94 Sep Oct Nov Dec 0 1371.27 1201.6 1240.59 1291.43 However what I get is the following: Empty DataFrame Columns: [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec] Index: [] If I replace df.append([l]) with the following, things work fine for me. df = pd.DataFrame([l], columns = months) df.columns = months What am I doing wrong?
score: 7
downvote count: 0
upvote count: 7
has answer: http://stackoverflow.com/a/50429912
has title: Appending rows to empty DataFrame not working
favorite count: 0
has answer: http://stackoverflow.com/a/50430507
type: Question

http://stackoverflow.com/comment/87809368
has text: Unfortunately, the whole file is 20GB, my text editor can't handle that
comment on: http://stackoverflow.com/q/50396284
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50403760
tagged with: javascript
tagged with: python
has title: Flask Jinja2 Statements vs. JavaScript Use Case
has comment: http://stackoverflow.com/comment/87823285
has comment: http://stackoverflow.com/comment/87824884
score: 3
upvote count: 3
answer count: 1
downvote count: 0
has body: I am creating my first small web app using the Flask framework and I am not sure which approach is best practice to change the properties of elements (ID='#NRG') on my page based upon data defined in the Python code on the backend: Flask / Jinja2 Approach: {% if nrg_precip_probs[0] &lt;=25 and nrg_precip_probs[1] &lt;= 25 and nrg_precip_probs[2] &lt;=25 %} &lt;script&gt;$("#NRG").css("background", "#21CE99");&lt;/script&gt; {% else %} &lt;script&gt;$("#NRG").css("background", "#F45531");&lt;/script&gt; {% endif %} or a JavaScript Approach: function change_it() { if ({{nrg_precip_probs[0]}} &lt;= 25) { $("#NRG").css("background", "#21CE99"); } else { $("#NRG").css("background", "#F45531"); } } change_it();
tagged with: flask
tagged with: jinja2
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50404066
has comment: http://stackoverflow.com/comment/87823033
type: UnansweredQuestion

http://stackoverflow.com/q/50454573
has answer: http://stackoverflow.com/a/50454624
tagged with: datetime
accepted answer: http://stackoverflow.com/a/50454624
tagged with: python
answer count: 2
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/50328246
tagged with: timedelta
favorite count: 0
type: Question
has title: Getting the average from a dataframe consisting of pandas timestamp
has answer: http://stackoverflow.com/a/50454862
possible better answer: http://stackoverflow.com/a/50454862
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49757871
has body: I have two panda series, closedDate and createdDate, thats elements are pandas timestamps, class 'pandas._libs.tslib.Timestampclass 'pandas._libs.tslib.Timestamp. I have subtracted those two panda series to make a list, age, of pandas timedelta. closedDate = data.iloc[:,1] createdDate = data.iloc[:,2] age = [x-y for x,y in zip(closedDate, createdDate)] Now, I want to get the average of age but with my line of code I get an error. In: average_age = functools.reduce(lambda x, y: x + y, age) / len(age) Out: OverflowError: int too big to convert How can I fix this?? Thanks!

http://stackoverflow.com/q/50536129
type: UnansweredQuestion
answer count: 1
tagged with: bottlenose
upvote count: 1
tagged with: python
tagged with: amazon-web-services
downvote count: 1
type: Question
score: 0
has title: How to use bottlenose Python library with MWS
tagged with: amazon-mws
has answer: http://stackoverflow.com/a/50536648
has body: For MWS requests, what credentials should I provide to bottlenose to access the Amazon Product Advertising API? From the documentation, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_ASSOCIATE_TAG appear to be required. I am assuming that AWS_ASSOCIATE_TAG is from Product Advertising API, do we have to get the AWS_ACCESS_KEY_ID from Product Advertising too? Or can I use the AWS_ACCESS_KEY_ID that I got from MWS (Seller Centra) And provide the AWS_ASSOCIATE_TAG from Product Advertising API? more info: https://github.com/lionheart/bottlenose/issues/66
favorite count: 0
has comment: http://stackoverflow.com/comment/88105451

http://stackoverflow.com/q/50509990
has answer: http://stackoverflow.com/a/50516917
has title: TypeError: sqlalchemy properties -> class 'sqlalchemy.orm.attributes.InstrumentedAttribute'
favorite count: 0
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/50516917
upvote count: 1
tagged with: python
tagged with: properties
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/88036075
has comment: http://stackoverflow.com/comment/88041916
tagged with: hybrid
type: AnsweredQuestion
score: 1
answer count: 1
has body: I have the following sqlalchemy class (simplified): class Persons(Base): __tablename__ = 'm_persons' birthDate = db.Column(db.Date, nullable=True) @hybrid_property def age(self): bd = self.birthDate return relativedelta(date.today(), bd).years @age.expression def age(cls): bd = cls.birthDate return relativedelta(date.today(), bd).years when I use the property to print the value as person = Person.query.get(1) print(person.age) It correctly prints the age of the person. Now when I try to use the property into a query like: Persons.query.filter(Persons.age &gt;= min_age).all() Then I got the following error : TypeError: relativedelta only diffs datetime/date Which I understand as cls.birthDate is of type class 'sqlalchemy.orm.attributes.InstrumentedAttribute' So the question what I am missing to get the value of the property birthDate? Of course I have been 'googleing' around and read the doc but could not find the reason why it is not working or a solution. Any help would be appreciated. *** EDIT **** The trace of the error : File "/Users/ext334/Dev/python/asocio/app/members/forms.py", line 174, in __init__ self.person.choices = listPersons(gender=subscription.gender, min_age=subscription.min_age, max_age=subscription.max_age) File "/Users/ext334/Dev/python/asocio/app/members/forms.py", line 31, in listPersons print(Persons.query.join(Members).filter(Persons.age &gt;= min_age, Persons.age &lt;= max_age, extract('year',Persons.birthDate) &gt;= minBirthYear, extract('year',Persons.birthDate) &lt;= maxBirthYear, Persons.sex == gender).order_by(Members.lastname, Members.firstname)) File "/Users/ext334/Dev/python/venv36/lib/python3.6/site-packages/sqlalchemy/ext/hybrid.py", line 867, in __get__ return self._expr_comparator(owner) File "/Users/ext334/Dev/python/venv36/lib/python3.6/site-packages/sqlalchemy/ext/hybrid.py", line 1066, in expr_comparator owner, self.__name__, self, comparator(owner), File "/Users/ext334/Dev/python/venv36/lib/python3.6/site-packages/sqlalchemy…

http://stackoverflow.com/comment/87812682
has text: yes.. you are right, I need to understand it better. Just start to learn python. thank you for your help!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50397988
type: Comment

http://stackoverflow.com/q/50450985
upvote count: 3
has answer: http://stackoverflow.com/a/50452808
has comment: http://stackoverflow.com/comment/87915378
has comment: http://stackoverflow.com/comment/87916096
has comment: http://stackoverflow.com/comment/87918565
answer count: 1
has comment: http://stackoverflow.com/comment/87917024
favorite count: 0
has comment: http://stackoverflow.com/comment/87918299
type: Question
has comment: http://stackoverflow.com/comment/87915634
has comment: http://stackoverflow.com/comment/87916935
has title: python string replacing with re module
tagged with: python
has body: I am looking for a way to replace a string that can contain any type of characters but with 2 rules: This string must not be contained between opening and closing quotes or double quotes. It must not be directly preceded or followed by an alphanumeric character or an underscore. For example: myStringToBeReplaced = "any type* of (h@ra[ters –" mySourceString = """ a = any type* of (h@ra[ters –*2 print "The value of any type* of (h@ra[ters – is: ",any type* of (h@ra[ters –, " and it's like this !" b = any type* of (h@ra[ters –With alpha numeric close to it """ myReplacementString = "HELLO" theResultShouldBe =""" a = HELLO*2 print "The value of any type* of (h@ra[ters – is: ", HELLO, " and it's like this !" b = any type* of (h@ra[ters –With alpha numeric close to it """ Thanks a lot JD First attempt with simpler strings for the moment : #!/usr/bin/env python # -*- coding: latin1 -*- import re myStringToBeReplaced = "anytypeof(h@ra[ters" mySourceString = """ a = anytypeof(h@ra[ters*2 print "anytypeof(h@ra[ters is:", anytypeof(h@ra[ters , " and it's like this !" b = anytypeof(h@ra[tersWith alpha numeric close to it """ myReplacementString = "HELLO" myescape = re.escape(myStringToBeReplaced) pattern = "(?&lt;!\"|')" + myescape + "(?!\"|')" result = re.sub(pattern, myReplacementString, mySourceString) print result This gives : a = HELLO*2 print "anytypeof(h@ra[ters is:", HELLO , " and it's like this !" b = HELLOWith alpha numeric close to it
tagged with: regex
score: -1
downvote count: 4
accepted answer: http://stackoverflow.com/a/50452808
has comment: http://stackoverflow.com/comment/87915947
type: AnsweredQuestion

http://stackoverflow.com/comment/87926690
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50455417
has text: @user40551 Yes that's probably why - you can use `df["ZipCode"] = df["ZipCode"].astype(int)` to convert it to the same data type.

http://stackoverflow.com/q/50417801
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50445713
tagged with: elasticsearch
tagged with: python
has answer: http://stackoverflow.com/a/69805167
answer count: 3
has body: I am using Elasticsearch client in Python to create index for the fields below and I am stuck on creating date index that has null values. I am having very hard time seeing why the index it not setting to date instead of string when there are null values present in the data. From the online and ES documentation research, looks like you can't index on null values. So, I am following this https://www.elastic.co/guide/en/elasticsearch/reference/current/null-value.html documentation to over come the problem which uses "null_value": "NULL", however I have not been successful. I have tried changing the actual date date into format like "yyyy-MM-dd", "MM/dd/yyyy" ... etc and many other combinations. For the json mapping I have also tried {"type": "strict_date"} and {"type": "strict_date": "MM/dd/yyyy"}. Is there any way to deal with this problem? Data: id_name,team_name,team_members,date_info,date_sub 123,"Biology, Neurobiology ","Ali Smith, Jon Doe",5/1/2015,5/1/2015 234,Mathematics,Jane Smith ,8/12/2016, 345,"Statistics, Probability","Matt P, Albert Shaw",5/15/2015,5/15/2015 456,Chemistry,"Andrew M, Matt Shaw, Ali Smith",4/12/2017, 678,Physics,"Joe Doe, Jane Smith, Ali Smith ",5/12/2017,5/12/2017 JSON/PYTHON MAPPING: request_body = ''' { "settings" : { "number_of_shards": 2, "number_of_replicas": 1 }, "mappings": { "team": { "properties": { "id_name": { "type": "text"}, "team_name": { "type": "text"}, "team_members": { "type": "text"}, "date_info": {"type": "date","null_value": "NULL"}, "date_sub": {"type": "date","null_value":"NULL"} } } } } ''' res = self.es.indices.create(index=your_index_name, ignore = 400, body=request_body) ERROR: raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, 'mapper_parsing_exception', 'failed to parse [date_info]')
score: 1
has title: Elastic Search: indexing dates field that has null values
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87874878
has answer: http://stackoverflow.com/a/50447208

http://stackoverflow.com/a/50437478
answers question: http://stackoverflow.com/q/50436562
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50436562
has body: You have to use the cursor position: import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * class Widget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) lay = QVBoxLayout(self) self.te = QTextEdit() self.te.setPlainText('''Hey mr Nikhil\nHowdy you\nFunny life isn't it.''') lay.addWidget(self.te) button = QPushButton("Click Me") lay.addWidget(button) button.clicked.connect(self.on_clicked) def on_clicked(self): p = self.te.textCursor().position() result = self.te.toPlainText()[:p] print("result:\n{}".format(result)) if __name__ == '__main__': app = QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())

http://stackoverflow.com/comment/87961328
score: 0
comment on: http://stackoverflow.com/q/50463207
type: QuestionComment
has text: Yea, nothing... It's as if since the `start` is so far out and it has to check every single `row[0]`, which is the time, that it just doesn't bother and gives up. The ONLY way I am able to make it work is adding a `print row[0]` right after `for row in reader` because this way, it gives the script 'something' to do until it reaches the `start` time to start extracting.
type: Comment

http://stackoverflow.com/q/50533105
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88123418
tagged with: pygame
has comment: http://stackoverflow.com/comment/88081985
has comment: http://stackoverflow.com/comment/88081414
has body: I have a pygame game, and it works perfectly fine on my laptop, but when I move it over to my raspberry pi, a lot of the sprites don't appear. They are there because I can still click on them, but they don't seem to actually be being drawn. I thought it may have been because the pi couldn't handle hundreds of pngs, so I compressed them all, and still no different results. It's not the same sprites every time that don't appear. If I relaunch the script, or even just refresh a screen, it's different images that decide to appear. I then drew it to a capacitive tft screen from Adafruit, and it's still the same results. The mouse is also inverted which is a bit annoying, but that is a different problem I will figure out. The sprites are definitely there because I can still click them, they just aren't visible, like it can't load the image, but it doesn't give an error. import pygame class base_sprite(pygame.sprite.Sprite): def __init__(self, color=(0,0,0), width=0, height=0, image=None,x=0,y=0, scale=None): pygame.sprite.Sprite.__init__(self) if "Surface" in type(image).__name__: self.image = image else: self.image = pygame.image.load(image) if scale != None: self.image = pygame.transform.scale(self.image, (scale[0], scale[1])) pygame.draw.rect(self.image, color, [5000000,5000000,width,height]) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y pygame.init() width = 320 height = 240 s = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() gameGroup = pygame.sprite.Group() inventoryGroup = pygame.sprite.Group() back = base_sprite(width=320, height=240, image="images/back.png", x=0, y=0) headBorder = base_sprite(width=64, height=64, image="images/ItemBorder.png", x=180, y=10, scale=[50, 50]) handBorder = base_sprite(width=64, height=64, image="images/ItemBorder.png", x=250, y=94, scale=[50, 50]) bodyBorder = base_sprite(width=64, height=64, image="images/ItemBorder.png", x=180, y=94, scale=[50, 50]) feetBorder = base_sprite(width=64, height=6…
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88081337
has title: Sprites not appearing in pygame on raspberry pi
has comment: http://stackoverflow.com/comment/88082283
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88092345
has answer: http://stackoverflow.com/a/50652120
has comment: http://stackoverflow.com/comment/88078953
has comment: http://stackoverflow.com/comment/88081835
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/88080239
type: UnansweredQuestion

http://stackoverflow.com/q/50451339
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87915863
answer count: 1
has comment: http://stackoverflow.com/comment/87916174
has title: How to count bigrams in several inputs in python
type: Question
has answer: http://stackoverflow.com/a/50451645
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87915862
has body: Before I start, here are the exact instruction from my learning material (Grok Learning, Python) "Write a program to read in multiple lines of input from the user, where each line is a space-separated sentence of words. Your program should then count up how many times each of the bigrams occur across all input sentences. The bigrams should be treated in a case insensitive manner by converting the input lines to lowercase. Once the user stops entering input, your program should print out each of the bigrams that appear more than once, along with their corresponding frequencies." I am supposed to find the bigrams within several inputs and I have formulated this code. This code works by asking for inputs until the input is blank, then adding that whole line into a list called combined, where it is converted into bigrams in this format [('this', 'is'), ('is', 'a')] which equals to the list called text. Now that list called text is converted into simple bigrams in this format [('this is'), ('is a')] into another list called newlist. Then I add all repeating strings into a dictionary called my_dict and add them. I print them out in separate lines so it can produce each bigram and how frequent it is, discluding bigrams that only occur once. Here is my code: newlist = [] combined = [] a = (input("Line: ")).lower() while a: combined.append(a) text = [b for l in combined for b in zip(l.split(" ")[:-1], l.split(" ")[1:])] a = (input("Line: ")).lower() for bigram in text: newbigram = ' '.join(bigram) newlist.append(newbigram) my_dict = {i:newlist.count(i) for i in newlist} for words in sorted(my_dict): if my_dict[words] &gt; 1: print(str(words) + str(": ") + str(my_dict[words])) Here is my output: Line: The big red ball Line: The big red ball is near the big red box Line: I am near the box Line: big red: 3 near the: 2 red ball: 2 the big: 3 See this code worked fine, but whenever I set an empty a value, it comes with this error message: Line: Traceback (most recent call last): …

http://stackoverflow.com/comment/87998086
type: AnswerComment
comment on: http://stackoverflow.com/a/50473850
type: Comment
has text: Substitute the equivalent. Edited the answer to be more explicit about this.
score: 0

http://stackoverflow.com/comment/87873061
type: Comment
score: 0
type: AnswerComment
has text: If you give me a simple example I can update my answer later tonight
comment on: http://stackoverflow.com/a/50428658

http://stackoverflow.com/q/50414787
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50415054
score: -3
tagged with: python
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50415140
has body: I have a Nx3 matrix constructed as, i j val . . . . . . . . . from which I want to construct a matrix where element x_ij = val. For example position-value matrix, [[ 0 0 3 ] [ 1 1 2 ] [ 0 1 4 ] [ 1 0 1 ] [ 2 0 5 ] [ 2 1 2 ]] would result in the matrix, [[3 4] [1 2] [5 2]] What is the most simple/succinct way to do this in numpy?
answer count: 3
has answer: http://stackoverflow.com/a/50415140
upvote count: 0
has title: Numpy - construct matrix from matrix of positions and values
downvote count: 3
has answer: http://stackoverflow.com/a/50415097
has comment: http://stackoverflow.com/comment/87845294
possible better answer: http://stackoverflow.com/a/50415054

http://stackoverflow.com/q/50461876
has title: Netsuite namespace conflict (core_2017_2.platform vs accounting_2017_2.lists)
has answer: http://stackoverflow.com/a/50532439
tagged with: zeep
has body: I want to post a journal entry to Netsuite from my Python script. I am using zeep to talk to SuiteTalk. I am new to Netsuite and I am new to SOAP. Following on internet examples, I managed to add a test customer via Python script using the below code: def make_app_info(client): AppInfo = client.get_type('ns4:ApplicationInfo') app_info = AppInfo(applicationId=NS_APPID) return app_info def make_passport(client): RecordRef = client.get_type('ns0:RecordRef') Passport = client.get_type('ns0:Passport') role = RecordRef(internalId=NS_ROLE) return Passport(email=NS_EMAIL, password=NS_PASSWORD, account=NS_ACCOUNT, role=role) def login_client(): client = Client(WSDL_URL) login = client.service.login(passport=make_passport(client), _soapheaders={'applicationInfo': make_app_info(client)}) return client The WSDL_URL I am using is https://webservices.netsuite.com/wsdl/v2017_2_0/netsuite.wsdl Using the above client the below code adds the customer: def add_customer(): client = login_client() Customer = client.get_type('ns13:Customer') customer = Customer( lastName='Prasad', firstName='Vikas', email='vikasprasad@example.com', companyName='Test Company' ) client.service.add(customer) add_customer() The above adds the Customer successfully to the Netsuite account and I can see it in the list on the webapp. Continuing on the above example, I wrote this code to add JournalEntry: def get_record_by_type(client, type, internal_id): RecordRef = client.get_type('ns0:RecordRef') record = RecordRef(internalId=internal_id, type=type) response = client.service.get(record, _soapheaders={ 'applicationInfo': make_app_info(client), 'passport': make_passport(client), } ) r = response.body.readResponse if r.status.isSuccess: return r.record def add_journal_entry(): client = login_client() # get subsidiary by internal id subsidiary = get_record_by_type(client, 'subsidiary', '1') print(subsidiary) # This prints a valid subsidiary having internal id 1 # create two journal entry lines JournalEntryLine = …
type: AnsweredQuestion
downvote count: 0
tagged with: netsuite
upvote count: 1
score: 1
tagged with: suitetalk
answer count: 1
favorite count: 0
type: Question
tagged with: soap
tagged with: python
accepted answer: http://stackoverflow.com/a/50532439

tornado
tags question: http://stackoverflow.com/q/50460894
tags question: http://stackoverflow.com/q/50434462
tags question: http://stackoverflow.com/q/50516253
tags question: http://stackoverflow.com/q/50415390
tags question: http://stackoverflow.com/q/50484943
tag name: tornado
tags question: http://stackoverflow.com/q/50508556
tags question: http://stackoverflow.com/q/50488084
type: Tag

http://stackoverflow.com/comment/87988686
has text: You could split your matrices where the difference between two positions is greater than 6 (almost your domain)
comment on: http://stackoverflow.com/q/50486357
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50491499
has comment: http://stackoverflow.com/comment/87996247
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50492061
has answer: http://stackoverflow.com/a/50492061
favorite count: 0
type: Question
has body: I want to write a text file which is separated by four spaces instead of one tab: df.to_csv(file,sep= '\s\s\s\s') instead of df.to_csv(file,sep= '\t') I tried regex : df.to_csv(file,sep= r'\s{4}') which did not work either ? Is this doable without writing and the replacing the delimiter?
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has title: Write .csv file from pandas dataframe with consecutive spaces as delimiter

http://stackoverflow.com/comment/87941886
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50462470
score: 0
has text: The sleep_time is not showing in the excel file. The output for the sleep_time column in the notepad file is showing this:`vcc,device_id,temp,hum,packet_no,sleep_time 3776,0EE3C60C,26.12,62.31,3,"5} " 3853,0BD776ED,24.40,65.19,4,"3} " 3776,0EE3C60C,26.03,63.61,4,"5} " 3853,0BD776ED,24.43,65.37,5,"3} " `

http://stackoverflow.com/a/50449516
has comment: http://stackoverflow.com/comment/87916247
has comment: http://stackoverflow.com/comment/87912343
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/50444889
has body: as a complete example: import tkinter as tk # global imports are bad from tkinter import ttk from PIL import Image, ImageTk root = tk.Tk() nb = ttk.Notebook(root) nb.pack(fill='both', expand=True) f = tk.Frame(nb) tk.Label(f, text="in frame").pack() # must keep a global reference to these two im = Image.open('path/to/image') ph = ImageTk.PhotoImage(im) # note use of the PhotoImage rather than the Image nb.add(f, text="profile", image=ph, compound=tk.TOP) # use the tk constants root.mainloop() for reference i tested this to work with a gif file where the builtin PhotoImage failed, and gif is one of the supported formats.
has comment: http://stackoverflow.com/comment/87912303
has comment: http://stackoverflow.com/comment/87914074
score: 3
has comment: http://stackoverflow.com/comment/87913663
has comment: http://stackoverflow.com/comment/87912522
upvote count: 4

string
tags question: http://stackoverflow.com/q/50474426
tags question: http://stackoverflow.com/q/50511218
tags question: http://stackoverflow.com/q/50440937
tags question: http://stackoverflow.com/q/50532977
tags question: http://stackoverflow.com/q/50404202
tags question: http://stackoverflow.com/q/50452684
tags question: http://stackoverflow.com/q/50424310
tags question: http://stackoverflow.com/q/50423502
type: Tag
tags question: http://stackoverflow.com/q/50502148
tags question: http://stackoverflow.com/q/50538051
tags question: http://stackoverflow.com/q/50397744
tags question: http://stackoverflow.com/q/50534249
tags question: http://stackoverflow.com/q/50492377
tags question: http://stackoverflow.com/q/50388128
tags question: http://stackoverflow.com/q/50493492
tags question: http://stackoverflow.com/q/50482899
tags question: http://stackoverflow.com/q/50496325
tags question: http://stackoverflow.com/q/50419277
tags question: http://stackoverflow.com/q/50503569
tags question: http://stackoverflow.com/q/50433473
tags question: http://stackoverflow.com/q/50393595
tags question: http://stackoverflow.com/q/50419852
tags question: http://stackoverflow.com/q/50527383
tags question: http://stackoverflow.com/q/50539573
tags question: http://stackoverflow.com/q/50402373
tags question: http://stackoverflow.com/q/50397474
tags question: http://stackoverflow.com/q/50471397
tags question: http://stackoverflow.com/q/50449453
tags question: http://stackoverflow.com/q/50396877
tags question: http://stackoverflow.com/q/50423548
tags question: http://stackoverflow.com/q/50463669
tags question: http://stackoverflow.com/q/50396284
tags question: http://stackoverflow.com/q/50523308
tags question: http://stackoverflow.com/q/50443117
tags question: http://stackoverflow.com/q/50388786
tags question: http://stackoverflow.com/q/50510841
tags question: http://stackoverflow.com/q/50495099
tags question: http://stackoverflow.com/q/50423089
tags question: http://stackoverflow.com/q/50416915
tags question: http://stackoverflow.com/q/50459578
tags question: http://stackoverflow.com/q/50537139
tags question: http://stackoverflow.com/q/50426938
tags question: http://stackoverflow.com/q/50503262
tags question: http://stackoverflow.com/q/50414050
tags question: http://stackoverflow.com/q/50493125
tags question: http://stackoverflow.com/q/50489198
tags question: http://stackoverflow.com/q/50500095
tags question: http://stackoverflow.com/q/50504795
tags question: http://stackoverflow.com/q/50479128
tags question: http://stackoverflow.com/q/50442942
tags question: http://stackoverflow.com/q/50396355
tags question: http://stackoverflow.com/q/50456281
tags question: http://stackoverflow.com/q/50480555
tags question: http://stackoverflow.com/q/50496586
tag name: string
tags question: http://stackoverflow.com/q/50508621
tags question: http://stackoverflow.com/q/50538989
tags question: http://stackoverflow.com/q/50514078
tags question: http://stackoverflow.com/q/50493670
tags question: http://stackoverflow.com/q/50485438
tags question: http://stackoverflow.com/q/50400615
tags question: http://stackoverflow.com/q/50492150
tags question: http://stackoverflow.com/q/50409701
tags question: http://stackoverflow.com/q/50500135
tags question: http://stackoverflow.com/q/50447743
tags question: http://stackoverflow.com/q/50474344
tags question: http://stackoverflow.com/q/50412933
tags question: http://stackoverflow.com/q/50450266
tags question: http://stackoverflow.com/q/50444035
tags question: http://stackoverflow.com/q/50486927
tags question: http://stackoverflow.com/q/50480175
tags question: http://stackoverflow.com/q/50526862
tags question: http://stackoverflow.com/q/50424963
tags question: http://stackoverflow.com/q/50393316
tags question: http://stackoverflow.com/q/50517137
tags question: http://stackoverflow.com/q/50390409
tags question: http://stackoverflow.com/q/50417461
tags question: http://stackoverflow.com/q/50418496
tags question: http://stackoverflow.com/q/50394194

http://stackoverflow.com/a/55040649
has comment: http://stackoverflow.com/comment/104960360
downvote count: 0
has comment: http://stackoverflow.com/comment/104960067
has body: The issue was solved for me by installing the gihub repository version of statsmodels, pip3 install git+https://github.com/statsmodels/statsmodels.git
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/50391868
type: Answer
has comment: http://stackoverflow.com/comment/127924356

http://stackoverflow.com/q/50438738
score: 2
type: AnsweredQuestion
tagged with: deep-learning
tagged with: pytorch
upvote count: 2
downvote count: 0
answer count: 1
tagged with: machine-learning
favorite count: 0
type: Question
tagged with: python
has body: I am trying to follow the OpenAI "Sentiment Neuron" experiment by reading through the PyTorch code posted on Github for training the model from scratch. One thing I am not understanding is the byte-level embedding used in the code. I understood that the LSTM outputs a probability distribution for the value of the next byte and I assumed the "embedding" would just be a one-hot encoding of the byte value. Looking at the code, I see that the model's input goes through a (trainable) dense embedding before going into the model. Confusingly, the output of the loss is computed between the model output and the upcoming byte value, which is not embedded. My questions are: 1. How is the cross entropy loss computed? Does nn.CrossEntropyLoss take the softmax of its input and expand the target into a one-hot vector "under the hood"? 2. If we want to generate byte strings from this LSTM, how do we embed the output to feed back into the model for the next step? Do we embed the highest likelihood or take a softmax of the output and use some sort of weighted embedding? I'm new to LSTM and I'm trying to learn but I just don't get it! I appreciate any help!
has title: Byte Embedding in mLSTM Conceptual Struggle
accepted answer: http://stackoverflow.com/a/50439381
tagged with: lstm
has answer: http://stackoverflow.com/a/50439381

http://stackoverflow.com/q/50445544
has title: Python: convert datetime format
type: Question
has body: I've a string in the following date/time format: 2018-05-20T07:06:23.226 I need to convert it to the following format: 2018-05-20 06:23 AM I tried the following code, but I'm surely making some mistake here: date = "2018-05-20T07:06:23.226" d = datetime.datetime.strptime('date', '%Y-%m-%dT%H:%M:%S.%f') new_date = d.strftime('%y-%m-%d %H:%M %p') I always get the following error: ValueError: time data 'date' does not match format '%Y-%m-%dT%H:%M:%S.%f'
answer count: 2
score: 1
downvote count: 2
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50445564
accepted answer: http://stackoverflow.com/a/50445564
has comment: http://stackoverflow.com/comment/87904781
tagged with: datetime
has answer: http://stackoverflow.com/a/50445611
possible better answer: http://stackoverflow.com/a/50445611
tagged with: python

http://stackoverflow.com/comment/87796875
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50390674
type: Comment
has text: had a similar issue using django packages. running pip3 as root solved it to me. I still have no idea what caused it.

http://stackoverflow.com/q/50503698
type: AnsweredQuestion
has title: What is the runtime for this particular algorithm?
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50504762
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50504762
has body: I am thinking this particular code is (log n)^2 because each findindex function takes logn depth and we are calling it logn times? Can someone confirm this? I hope one of you can think of this as a small quiz and help me with it. Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order. # Ex # input find 5 in {15,16,19,20,25,1,3,4,5,7,10,14} # output 8 # runtime(log n) def findrotation(a, tgt): return findindex(a, 0, len(a)-1, tgt, 0) def findindex(a, low, high, target, index): if low&gt;high: return -1 mid = int((high + low) / 2) if a[mid] == target: index = index + mid return index else: b = a[low:mid] result = findindex(b, 0, len(b)-1, target, index) if result == -1: index = index + mid + 1 c = a[mid+1:] return findindex(c, 0, len(c)-1, target, index) else: return result
tagged with: algorithm
tagged with: runtime
tagged with: python
has comment: http://stackoverflow.com/comment/88021095
tagged with: big-o

http://stackoverflow.com/q/50505418
score: -2
tagged with: python
tagged with: dictionary
has body: I would need to make a union between dicts inside a list in the following way: current: [{A},{B},{C},{D},...] expected: [{A,B},{A,C},{A,D},...] I have the following code: import xlsxwriter word='Chain' def create_chain(chain_segment): chains=[] chain_lines = [line for line in chain_segment.split('\n') if line] for line in chain_lines: chain={} if word in line: chain['type'] = line.split()[1] elif line[0].isdigit(): chain['num']=line[0] chain['pkts']=line.split()[1] chain['bytes']=line.split()[2] chain['target']=line.split()[3] chain['prot']=line.split()[4] chain['opt']=line.split()[5] chain['in']=line.split()[6] chain['out']=line.split()[7] chain['source']=line.split()[8] chain['destination']=line.split()[9] chains.append(chain) chains=filter(None, chains) return chains with open('/media/sf_vboxshared/iptables-list.log') as f: log_content = f.read() host_sections = [host for host in log_content.split('---') if host] hosts = {} for host in host_sections: hostname, chains_segment = host.split('\n', 1) hostname = hostname.strip() chains=[] for segment in chains_segment.split('\n\n'): chains.extend(create_chain(segment)) chains=filter(None,chains) hosts[hostname] = chains workbook=xlsxwriter.Workbook('/media/sf_vboxshared/iptables-1st.xlsx') worksheet1=workbook.add_worksheet('Sheet1') worksheet1.write(0,0,'hostname') worksheet1.write(0,1,'chain') worksheet1.write(0,2,'num') worksheet1.write(0,3,'pkts') worksheet1.write(0,4,'bytes') worksheet1.write(0,5,'target') worksheet1.write(0,6,'prot') worksheet1.write(0,7,'opt') worksheet1.write(0,8,'in') worksheet1.write(0,9,'out') worksheet1.write(0,10,'source') worksheet1.write(0,11,'destination') row = 1 for host, chains in hosts.items(): for chain in chains: worksheet1.write(row, 1, chain.get('type')) worksheet1.write(row, 0, host) worksheet1.write(row, 2, chain.get('num')) worksheet1.write(row, 3, chain.get('pkts')) worksheet1.write(row, 4, chain.get('bytes')) worksheet1.write(row, 5, chain.get('target')) worksheet1.write(ro…
has answer: http://stackoverflow.com/a/50505569
type: AnsweredQuestion
tagged with: python-2.7
tagged with: list
answer count: 1
downvote count: 3
upvote count: 1
accepted answer: http://stackoverflow.com/a/50505569
favorite count: 0
type: Question
tagged with: python-3.x
has title: Union of dicts in a list

http://stackoverflow.com/q/50432331
has comment: http://stackoverflow.com/comment/87880330
score: 0
has title: get triplets from a string of text
linked to: http://stackoverflow.com/q/50422077
tagged with: python
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87880743
has body: Define the get_triples_dict() function which is passed a string of text as a parameter. The function first converts the parameter string to lower case and then returns a dictionary with keys which are all the unique consecutive three alphabetic characters from the text, and the corresponding values are the number of times the three consecutive alphabetic characters appear in the text. Use the isalpha() method to check if a character is alphabetic or not. The dictionary should only contain entries which occur more than once. After your dictionary has been created and populated, you need to remove any key-value pairs which have a corresponding value of 1. can someone help me fix my code so that i can get the right output? i have attempted it but it doesn't exactly work. i just need some help with the get_triples_dict function, i don't need to touch the test_get_triples_dict function. below is what i have so far along with the expected output: def get_triples_dict(text): triples_dict = {} word = "" mod_text = "" # convert the text to contain only letters and convert all letters to lowercase for i in range(0,len(text)): if text[i].isalpha(): mod_text = mod_text + text[i].lower() # if length of text &gt;= 3 letters if(len(mod_text) &gt;= 3): # loop over the text for i in range(0,len(mod_text)-2): word = mod_text[i:i+3] # extract 3 letter word from starting with the letter at i if word in triples_dict.keys(): # if word is in dictionary then increment its frequency triples_dict[word] = triples_dict[word] + 1 else: # else insert the word in dictionary with frequency 1 triples_dict[word] = 1 keys = triples_dict.keys() # get the list of keys in the dictionary # loop over the keys list for i in range(0,len(keys)): if triples_dict[keys] == 1: #if frequency of the word is 1, then remove the entry from dictionary del triples_dict[keys] i = i - 1 # decrement i return triples_dict # return the dictionary def test_get_triples_dict(): print("1.") print_dict_in_key_order(get_triples_d…

http://stackoverflow.com/a/50520282
score: 0
has body: new_list = [] for ks, vs in list.items(): for v in vs: new_list.append('.'.join([ks, v])) print(new_list) # output ['A.1', 'A.2', 'A.3', 'C.1', 'C.2', 'B.2']
answers question: http://stackoverflow.com/q/50519063
type: Answer

http://stackoverflow.com/a/50492154
answers question: http://stackoverflow.com/q/50492042
score: 0
has body: To print the images in ascending height order: for k, v in sorted(size_images.items(), lambda kv: kv[1]['height']): print (k, '--&gt;', v)
has comment: http://stackoverflow.com/comment/87998663
type: Answer
has comment: http://stackoverflow.com/comment/87998853

http://stackoverflow.com/a/50528989
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50525101
type: Answer
has body: Here's a possible solution: import sys import webbrowser import os import winreg from PyQt5.Qt import * # noqa def get_download_path(): if os.name == 'nt': sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}' with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key: location = winreg.QueryValueEx(key, downloads_guid)[0] return location else: return os.path.join(os.path.expanduser('~'), 'downloads') def main(): app = QApplication(sys.argv) fname, _ = QFileDialog.getOpenFileName( None, 'Open File', get_download_path(), 'Binary executable (*.exe)', None ) sys.exit(app.exec_()) if __name__ == "__main__": main()
answers question: http://stackoverflow.com/q/50525101
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50397067
has comment: http://stackoverflow.com/comment/87810006
has comment: http://stackoverflow.com/comment/87809977
has title: Python : issue of memory with the function map
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87811110
has comment: http://stackoverflow.com/comment/87812645
upvote count: 1
tagged with: memory
has comment: http://stackoverflow.com/comment/87810619
has body: I do not understand why the function map does not free memory after its execution even if I do not store the result in memory. I have tried to do a garbage collector, used objgraph but I don't see any object store in the memory. Basic use of map : map(lambda x:x*x,range(10**8)) As you can see in the screenshot, the memory is full. I ran the code on ubuntu 16.04, with python 2.7. Thank you for your attention.
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87811078
tagged with: python
has comment: http://stackoverflow.com/comment/87810019

http://stackoverflow.com/a/50451212
score: 2
upvote count: 3
downvote count: 1
has body: Your series contains other pd.Series objects. This is bad practice. In general, you should ensure your series is of a fixed type to enable you to perform manipulations without having to check for type explicitly. Your error is due to pd.Series objects not being hashable. One workaround is to use a function to convert pd.Series objects to a hashable type such as tuple: s = pd.Series(['one string', 'another string', pd.Series([1, 2, 3])]) def converter(x): if isinstance(x, pd.Series): return tuple(x.values) else: return x res = s.apply(converter).unique() print(res) ['one string' 'another string' (1, 2, 3)]
answers question: http://stackoverflow.com/q/50450672
type: Answer

http://stackoverflow.com/comment/88039260
score: 0
has text: Thank you for the info...this did it...!!
type: Comment
comment on: http://stackoverflow.com/a/50504030
type: AnswerComment

http://stackoverflow.com/a/50417451
has body: It isn't included in the inner group, but it's still included as part of the outer group. A non-capturing group does't necessarily imply it isn't captured at all... just that that group does not explicitly get saved in the output. It is still captured as part of any enclosing groups. Just do not put them into the () that define the capturing: import pandas as pd df = pd.DataFrame( {'a' : [1,2,3,4], 'b' : ['41u -428u', '31u - 68u', '11u - 58u', '21u - 318u'] }) df['b'].str.extract(r'- ?(\d+)u', expand=True) 0 0 428 1 68 2 58 3 318 That way you match anything that has a '-' in front (mabye followed by a aspace), a 'u' behind and numbers between the both. Where, - # literal hyphen \s? # optional space—or you could go with \s* if you expect more than one (\d+) # capture one or more digits u # literal "u"
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87850665
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50417423
type: Answer
answers question: http://stackoverflow.com/q/50417423
has comment: http://stackoverflow.com/comment/87850709
has comment: http://stackoverflow.com/comment/87850733
has comment: http://stackoverflow.com/comment/87850856
score: 5

http://stackoverflow.com/comment/87964171
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50475348
type: QuestionComment
has text: I had tried https://www.tensorflow.org/api_docs/python/tf/train/Saver and done `saver.save(estimator, 'my-model', global_step=0)` but it gives an error saying `no variables to save`

http://stackoverflow.com/comment/87867897
score: 0
type: AnswerComment
has text: Sorry, I need more information [editted](https://stackoverflow.com/posts/50423502/edit) into your question to help! Have a look at [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). A screenshot usually is *not* sufficient.
comment on: http://stackoverflow.com/a/50425619
type: Comment

http://stackoverflow.com/comment/88070246
score: 0
type: Comment
type: QuestionComment
has text: That seems to be the [unicode minus sign `−`](https://www.compart.com/en/unicode/U+2212), not the [hyphen-minus `-`](https://www.compart.com/en/unicode/U+002D) that is normally used.
comment on: http://stackoverflow.com/q/50529246

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

http://stackoverflow.com/comment/87885836
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50435725
has text: @PM2Ring, how would I change the file loading?

http://stackoverflow.com/comment/87809181
comment on: http://stackoverflow.com/q/50396666
type: Comment
type: QuestionComment
score: 0
has text: what attempts have you made?

http://stackoverflow.com/comment/116210235
type: Comment
type: QuestionComment
has text: For those with the same question, who just want the `Boolean` (`True` or `False`), don't use `.astype(int)`. Just use `df1[col].isin(df2[col])`
comment on: http://stackoverflow.com/q/50449088
score: 3

http://stackoverflow.com/comment/87799120
type: Comment
comment on: http://stackoverflow.com/a/50391388
type: AnswerComment
score: 1
has text: You could make this a bit more efficient if you precalculated which columns to change to 0. `mask = [int(i>=3) for i in SomAprilMay]; Xpos1May = [[mask[i]*v for i, v in enumerate(r)] for r in XposMay]` This uses multiplication by 0 or 1 to set the values to 0 or leave them unchanged. This is still very inefficient compared to `numpy`.

http://stackoverflow.com/comment/88444556
score: 0
type: Comment
type: QuestionComment
has text: @Silvio Did you finally solve this interesting problem, I've opened an issue on mayavi bug tracker but so far the question hasn't been solved. Take a look [here](https://github.com/enthought/mayavi/issues/645). Also, don't you have access to those pdfs? It'd be great to take a look to those
comment on: http://stackoverflow.com/q/50487411

http://stackoverflow.com/comment/87958177
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50470995
has text: I corrected the error and now it is working. It is about 20% faster than HYRY's solution. Nice! I guess rewriting it not using `np.einsum` will make it even faster.
type: Comment

http://stackoverflow.com/q/50473925
tagged with: xgboost
tagged with: hyperparameters
favorite count: 0
score: 3
type: Question
has comment: http://stackoverflow.com/comment/100268401
upvote count: 3
has comment: http://stackoverflow.com/comment/88004176
type: UnansweredQuestion
has title: Retrieve parameters from load model in xgboost
has answer: http://stackoverflow.com/a/54150673
answer count: 1
downvote count: 0
tagged with: python
has body: I have made a classification model, which has been saved using bst.save_model('final_model.model') in another file i load the model and do testing on my testdata using: bst = xgb.Booster() # init model bst.load_model('final_model.model') # load data ypred = bst.predict(dtest) # make prediction Since I use kfold in my training process but need to use the whole test file for testing (so no kfold splitting) it is not possible for me to verify if I still get the exact same results as I should when loading the model in a new file. This made me curious as if there was a way to print my loaded models hyperparameters. After a lot of googling I found a way to do this in R with xgb.parameters(bst) or maybe also xgb.attr(bst) - but I have found no way to do this in Python. Since I do not use R I have not tested the above lines, but from documentation it seems to do what i need: output the hyperparameters in a loaded model. So can this be done in Python with xgboost? EDIT: I can see that if i instead write ypred = bst.predict(dtest, ntree_limit=bst.best_iteration) i get the error 'Booster' object has no attribute 'best_iteration'. So it seems that the loaded model is not remembering all my hyperparameters. If i write bst.attributes() i can get it to output the number of the best iteration and it's eval score - but i don't see how to output the actual hyperparameters used.

http://stackoverflow.com/q/50493662
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50498049
has title: How to retrieve all snapshots related to a AWS EC2 instance using BOTO3 Python?
tagged with: amazon-ec2
type: Question
possible better answer: http://stackoverflow.com/a/50504365
has answer: http://stackoverflow.com/a/50504365
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has body: I am tangled in of the situation: I can retrieve all the snapshots of a volume associated with a EC2 instance but once the EC2 instance gets deleted so does its associated volume. I have been rubbing my head around the Boto3 documentation and struggling. Below is my working example to list the snapshots associated with the Volume. import boto3 ec2 = boto3.resource('ec2') volume_id = "something" list_of_snapshots = [] vol = ec2.Volume(id=volume_id) snapshots = vol.snapshots.all() try: for snapshot in snapshots: if snapshot: list_of_snapshots.append(snapshot.id) return list_of_snapshots[0] except: return None
accepted answer: http://stackoverflow.com/a/50498049

http://stackoverflow.com/q/50535801
answer count: 1
type: Question
tagged with: local
accepted answer: http://stackoverflow.com/a/50535927
has answer: http://stackoverflow.com/a/50535927
has title: call local variable within loop in pandas
has body: So, what I'm trying to do is to get every unique value of the category 'Nombre Capitulo' of my dataframe, for every 'Nombre Partida' ('Nombre Capitulo' is a subcategory of 'Nombre Partida'). My approach was to create local dataframes for every 'Nombre Partida' and then extract unique values of 'Nombre Capitulo' for every one of them. So, my question is twofold: 1. Is there a more Pythonic way to do this? 2. If not, how do I call my recently created local variables? I tried this, but isn't working: Partidas=data1_anio['Nombre Partida'].unique() for p in Partidas: locals()['%s' % p]=data1_anio.loc[data1_anio['Nombre Partida']==p] globals()['cap_%s' % p]= ['%s' % p]['Nombre Capitulo'].unique() Local variables are working, but calling them throws: TypeError: list indices must be integers or slices, not str Any ideas? Thanks in advance, and sorry for the spanish names in the variables, hope it's understandable, Juan
tagged with: python
has comment: http://stackoverflow.com/comment/88088339
type: AnsweredQuestion
score: 0
tagged with: pandas

http://stackoverflow.com/q/50471616
downvote count: 0
score: 6
tagged with: django
tagged with: python
upvote count: 6
type: AnsweredQuestion
answer count: 1
tagged with: seo
favorite count: 0
type: Question
has body: I have a django sitemap and wagtail sitemap for my site. The django sitemap is using https by simply setting the protocol variable in the class, but I can't figure out a way to do this for the wagtail sitemap without overriding many internal methods. Is there a simple way to use https for my wagtail sitemaps?
accepted answer: http://stackoverflow.com/a/50473994
tagged with: wagtail
has title: How to change protocol to https on wagtail sitemaps?
has answer: http://stackoverflow.com/a/50473994

http://stackoverflow.com/comment/87920487
type: Comment
comment on: http://stackoverflow.com/q/50453626
has text: Why are you using `matrix`? You have this problem because you're using `matrix`.
score: 0
type: QuestionComment

http://stackoverflow.com/a/50499626
has comment: http://stackoverflow.com/comment/88011977
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/88012217
answers question: http://stackoverflow.com/q/50499619
upvote count: 4
has comment: http://stackoverflow.com/comment/88012135
has comment: http://stackoverflow.com/comment/88012160
downvote count: 1
has body: sorted(..., key='A23...JQK'.index)

http://stackoverflow.com/a/50441731
accepted answer of: http://stackoverflow.com/q/50441519
answers question: http://stackoverflow.com/q/50441519
type: AcceptedAnswer
has body: You can try something like this: l = [] for i in values: if i in dic.keys(): l.append(f'ROW:{i} {dic[i]}') else: l.append(f'ROW:{i} Empty') return l l will be the list of the output that you desired. remember that the values is you list of elements, so when you say for keys, values in ... these values will be overrides the others. Note that: for these formated staring you should have Python3.6 or higher.
has comment: http://stackoverflow.com/comment/87897987
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87901400

http://stackoverflow.com/comment/88134701
has text: That's a bug - there's nothing wrong with your example except that `qs.order_by()` is ignored because `order_by()` returns a copy of the query instead of modifying the original. Which version of exchangelib is this? Can you capture the XML of the request and response that fails, as described in https://github.com/ecederstrand/exchangelib#troubleshooting, and open an issue at https://github.com/ecederstrand/exchangelib/issues?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50518343

http://stackoverflow.com/a/50398963
accepted answer of: http://stackoverflow.com/q/50396739
has body: One approach would be to convert your Keras model to a TensorFlow model in Python and then export a frozen graph to .pb file. Then load that in C++. I have used this piece of code to export a frozen .pb file from Keras. import tensorflow as tf from keras import backend as K from tensorflow.python.framework import graph_util K.set_learning_phase(0) model = function_that_returns_your_keras_model() sess = K.get_session() output_node_name = "my_output_node" # Name of your output node with sess as sess: init_op = tf.global_variables_initializer() sess.run(init_op) graph_def = sess.graph.as_graph_def() output_graph_def = graph_util.convert_variables_to_constants( sess, sess.graph.as_graph_def(), output_node_name.split(",")) tf.train.write_graph(output_graph_def, logdir="my_dir", name="my_model.pb", as_text=False) You can then follow any tutorial on how to load the .pbfile in C++. For an example this one: https://medium.com/jim-fleming/loading-a-tensorflow-graph-with-the-c-api-4caaff88463f Keras injects the learning_phase variable in the TensorFlow graph and possibly also other Keras-only variables - if I remember correctly, you should make sure to remove these from the graph.
score: 2
answers question: http://stackoverflow.com/q/50396739
type: AcceptedAnswer
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87881289
score: 0
comment on: http://stackoverflow.com/a/50433478
type: Comment
type: AnswerComment
has text: @jjmerelo In Python, the remainder (either with `%` or `divmod()`) always has the same sign as the divisor. Eg `123 % -10` -> -7

http://stackoverflow.com/a/50466589
has body: try below code. not tested but it should work from django.template.loader import render_to_string def render_to_pdf(template_src, context_dict={}): html = render_to_string(template_src, context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return result.getvalue() return None Reference: https://github.com/codingforentrepreneurs/Guides/blob/master/all/Render_to_PDF_in_Django.md
accepted answer of: http://stackoverflow.com/q/50466289
type: Answer
answers question: http://stackoverflow.com/q/50466289
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/88009491
score: 0
type: AnswerComment
has text: @AnjanaShivangi Then you'll need to convert all the sources that you intend to use with 3 to be compatible with 3. There's a tool available via pip called (iirc) py2to3, but it was pretty bad last time I tried to use it. If the entirety of the source is aimed at 2, and conversion isn't feasible, you'll have to run it under a Python 2 interpreter.
type: Comment
comment on: http://stackoverflow.com/a/50498257

http://stackoverflow.com/q/50539070
has answer: http://stackoverflow.com/a/50539153
accepted answer: http://stackoverflow.com/a/50539153
linked to: http://stackoverflow.com/q/17803919
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50539203
linked to: http://stackoverflow.com/q/9110837
tagged with: algorithm
has comment: http://stackoverflow.com/comment/88090025
linked to: http://stackoverflow.com/q/9353802
tagged with: python
linked to: http://stackoverflow.com/q/13808774
upvote count: 4
score: 4
duplicate of: http://stackoverflow.com/q/9110837
linked to: http://stackoverflow.com/q/12063545
has title: Organize list of tuples into distinct categories
type: AnsweredQuestion
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50539203
has body: Suppose you have input of the following format: data = [(1, 5), (7, 2), (3, 4), (4, 8), (6, 3), (5, 2)] I want to organize these numbers into a separate bucket or list. If a number from a tuple is found inside another tuple then it means that those numbers should go into the same bucket; otherwise, into a different bucket. For example, from the above example, the numbers will get distributed into two buckets: bucket_a = {1, 5, 2, 7} because of these tuples: (1, 5) (5, 2) (7, 2) and bucket_b = {3, 4, 6, 8} because of these tuples: (3, 4) (4, 8)
has comment: http://stackoverflow.com/comment/88090324
has answer: http://stackoverflow.com/a/50539189

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/50401604
tags question: http://stackoverflow.com/q/50461813
tags question: http://stackoverflow.com/q/50505169
tags question: http://stackoverflow.com/q/50508358
tags question: http://stackoverflow.com/q/50440947
tags question: http://stackoverflow.com/q/50423279
tags question: http://stackoverflow.com/q/50486567
tags question: http://stackoverflow.com/q/50465122
tags question: http://stackoverflow.com/q/50504523
tags question: http://stackoverflow.com/q/50534813
tags question: http://stackoverflow.com/q/50435737
tags question: http://stackoverflow.com/q/50450953
tags question: http://stackoverflow.com/q/50537982
tags question: http://stackoverflow.com/q/50482770
tags question: http://stackoverflow.com/q/50517121
tags question: http://stackoverflow.com/q/50402970
tags question: http://stackoverflow.com/q/50430887
tags question: http://stackoverflow.com/q/50440568
tags question: http://stackoverflow.com/q/50449774
tags question: http://stackoverflow.com/q/50536822
tags question: http://stackoverflow.com/q/50435926
tags question: http://stackoverflow.com/q/50422789
tags question: http://stackoverflow.com/q/50480530
tags question: http://stackoverflow.com/q/50505628
tags question: http://stackoverflow.com/q/50511551
tags question: http://stackoverflow.com/q/50441703
tags question: http://stackoverflow.com/q/50497871
tags question: http://stackoverflow.com/q/50447559
tags question: http://stackoverflow.com/q/50489982
tags question: http://stackoverflow.com/q/50503319
tags question: http://stackoverflow.com/q/50494073
tags question: http://stackoverflow.com/q/50514919
tags question: http://stackoverflow.com/q/50456133
tags question: http://stackoverflow.com/q/50530834
tags question: http://stackoverflow.com/q/50459154
tags question: http://stackoverflow.com/q/50417461
tags question: http://stackoverflow.com/q/50500210
tags question: http://stackoverflow.com/q/50430168
tags question: http://stackoverflow.com/q/50404490
tags question: http://stackoverflow.com/q/50475303
tags question: http://stackoverflow.com/q/50400301
tags question: http://stackoverflow.com/q/50457404
type: Tag
tags question: http://stackoverflow.com/q/50404408
tags question: http://stackoverflow.com/q/50513128
tags question: http://stackoverflow.com/q/50496358
tag name: html
tags question: http://stackoverflow.com/q/50511655
tags question: http://stackoverflow.com/q/50479820
tags question: http://stackoverflow.com/q/50541429
tags question: http://stackoverflow.com/q/50464361
tags question: http://stackoverflow.com/q/50436791
tags question: http://stackoverflow.com/q/50431978
tags question: http://stackoverflow.com/q/50480318
tags question: http://stackoverflow.com/q/50527882
tags question: http://stackoverflow.com/q/50477634
tags question: http://stackoverflow.com/q/50482810
tags question: http://stackoverflow.com/q/50454248
tags question: http://stackoverflow.com/q/50499911
tags question: http://stackoverflow.com/q/50509905
tags question: http://stackoverflow.com/q/50386860
tags question: http://stackoverflow.com/q/50457043
tags question: http://stackoverflow.com/q/50529820
tags question: http://stackoverflow.com/q/50529727
tags question: http://stackoverflow.com/q/50450129
tags question: http://stackoverflow.com/q/50433720
tags question: http://stackoverflow.com/q/50440066

http://stackoverflow.com/q/50474425
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87962476
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87962777
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50474861
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50474861
has title: Python looping for label variables
has body: I am trying to create a loop that will display each title of product for their individual labels (Tkinter module). With the current loop i can get it to print my 10 "static_webpage_1_titles" in the list, but i am wanting to also increase the variable Label_1 by +1 increment each time. For example, it should do somthing like this: Label_1['text'] = static_webpage_1_titles[0] Label_2['text'] = static_webpage_1_titles[1] Label_3['text'] = static_webpage_1_titles[2] Here is my current code: def Generate_Product_Name_and_Price_1(): if Button_on: Find_static_webpage_1() for i in range(len(static_webpage_1_titles)): Label_1['text'] = static_webpage_1_titles[i] EDIT: product_labels = [Label_1['text'], Label_2['text'], Label_3['text'], Label_4['text'], Label_5['text'], Label_6['text'], Label_7['text'], Label_8['text'], Label_9['text'], Label_10['text']] I have created a list above with each label widget and changed the last line of code in my loop to: def Generate_Product_Name_and_Price_1(): if Button_on: Find_static_webpage_1() for i in range(len(static_webpage_1_titles)): product_labels[i] = static_webpage_1_titles[i] +': $'+ static_webpage_1_price[i] When i run this, i do not receive any IDLE error but my label widgets do not get populated with data.

http://stackoverflow.com/comment/92211156
type: Comment
has text: I use it command line `fab task`, so I don't pass connection object myself.
type: AnswerComment
comment on: http://stackoverflow.com/a/50512658
score: 4

http://stackoverflow.com/comment/87812434
score: 0
comment on: http://stackoverflow.com/a/50398006
type: AnswerComment
has text: yes... it's my first week to use python. thank you very much!
type: Comment

http://stackoverflow.com/comment/87788473
type: QuestionComment
comment on: http://stackoverflow.com/q/50386205
type: Comment
score: 0
has text: Turns out your question is an exact duplicate of [this](https://stackoverflow.com/questions/47225830/axes3d-plot-wireframex-y-z-error). My suggestion does fix your initial issue but then you will get `ValueError: Argument Z must be 2-dimensional.`. None of the answers there are accepted or upvoted though, so it can't be used as a dupe. I suggest you upvote an answer there if it fixes your issue. Also, `ndim` is an attribute, not a method, sorry.

http://stackoverflow.com/a/50416613
score: 3
has comment: http://stackoverflow.com/comment/87849755
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50416251
has body: You can pass the dict you want to update as an additional parameter (see below). This has the advantage that the functions can work on more generic data structures than their own class instance, but the disadvantage that there are non-obvious side effects (the update) when calling the function. This can be partially alleviated by strategic naming. For instance process_msg_a could be update_map_with_msg_a # msg_process.py # def process_msg_a(msg, msg_map): # update msg_map based on msg msg_map[msg['foo']] = msg['bar'] def process_msg_b(msg, msg_map): # update msg_map based on msg_b msg_map[msg['baz']] = msg['qux'] def process_msg(msg_line, msg_type, msg_map): if msg_type == 'A': process_msg_a(msg_line, msg_map) elif msg_type == 'B': process_msg_b(msg_line, msg_map) g_msg_mapping = {} process_msg(msg_line, msg_type, g_msg_mapping)
has comment: http://stackoverflow.com/comment/87849590
type: Answer

http://stackoverflow.com/comment/87909489
has text: If looping through a set of `WebElements` requires you to navigate to a new page within the loop, the loop will not work. Since you are locating using XPath, you could loop through that with XPath indexes instead
comment on: http://stackoverflow.com/q/50440932
score: 0
type: Comment
type: QuestionComment

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

http://stackoverflow.com/q/50527658
has title: Scatter plot of 2 variables with colorbar based on third variable
type: Question
has answer: http://stackoverflow.com/a/50527993
duplicate of: http://stackoverflow.com/q/8202605
has body: I am trying to plot with variable x with respect to another y and add a colormap based on the values of another variable z So the plot should be similar to this My try import numpy as np import pandas as pd import seaborn as sns import random import matplotlib.pyplot as plt import matplotlib.cm as cm x=np.random.randint(0,20,30) y=np.random.randint(-5,5,30) z=np.random.randint(-2,10,30) df=pd.DataFrame(data={'A':x,'B':y,'C':z}) points = plt.scatter(df['A'],df['B'],cmap="jet") m = cm.ScalarMappable(cmap=cm.jet) m.set_array(df['C']) plt.colorbar(points) sns.lmplot('A', 'B', data=df, hue='C', fit_reg=False) TypeError: You must first set_array for mappable I am mixing matplotlib and seaborn as in seaborn I can not use the colormap 'jet' But any alternative aproaches to get the same graph are welcome
tagged with: colorbar
tagged with: seaborn
answer count: 1
type: UnansweredQuestion
score: 4
downvote count: 1
linked to: http://stackoverflow.com/q/8202605
favorite count: 0
tagged with: scatter-plot
upvote count: 5
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/comment/88074009
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50530893
type: Comment
has text: Could you dynamically query for the document you want to change, keep it in a variable and then supply it again?

http://stackoverflow.com/comment/87807001
comment on: http://stackoverflow.com/q/50395265
type: QuestionComment
score: 0
has text: You're right mate, here's the result : { "_id" : ObjectId("5afda3efb2031025afe0d32e"), "k1526346000_500" : { "r4" : { "C" : "1", "V" : "447616", "L" : "1", "D" : "4" }, "r5" : { "C" : "1", "V" : "398949", "L" : "1", "D" : "5" }, "r6" : { "C" : "1", "V" : "9276983", "L" : "1", "D" : "6" }, "r7" : { "C" : "1", "V" : "1544083", "L" : "1", "D" : "7" }, "r0" : { "C" : "1", "V" : "471757766", "L" : "1", "D" : "0" }, "r1" : { "C" : "1", "V" : "3473966", "L" : "1", "D" : "1" }, "r2" : { "C" : "1", "V" : "3396966", "L" : "1", "D" : "2" }} So how can I call this ?
type: Comment

http://stackoverflow.com/a/68807319
upvote count: 3
score: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50420711
has body: This was the simplest method for me for supervised problem with (X, y). def dataset_to_numpy(ds): &quot;&quot;&quot; Convert tensorflow dataset to numpy arrays &quot;&quot;&quot; images = [] labels = [] # Iterate over a dataset for i, (image, label) in enumerate(tfds.as_numpy(ds)): images.append(image) labels.append(label) for i, img in enumerate(images): if i &lt; 3: print(img.shape, labels[i]) return images, labels Usage: ds = tfds.load('mnist', split='train', as_supervised=True)

python-3.x
tags question: http://stackoverflow.com/q/50476103
tags question: http://stackoverflow.com/q/50417376
tags question: http://stackoverflow.com/q/50479425
tags question: http://stackoverflow.com/q/50519741
tags question: http://stackoverflow.com/q/50415666
tags question: http://stackoverflow.com/q/50406571
tags question: http://stackoverflow.com/q/50425008
tags question: http://stackoverflow.com/q/50426870
tags question: http://stackoverflow.com/q/50409408
tags question: http://stackoverflow.com/q/50493892
tags question: http://stackoverflow.com/q/50454098
tags question: http://stackoverflow.com/q/50519627
tags question: http://stackoverflow.com/q/50424963
tags question: http://stackoverflow.com/q/50504590
tags question: http://stackoverflow.com/q/50459602
tags question: http://stackoverflow.com/q/50539314
tags question: http://stackoverflow.com/q/50453416
tags question: http://stackoverflow.com/q/50511905
tags question: http://stackoverflow.com/q/50426842
tags question: http://stackoverflow.com/q/50449797
tags question: http://stackoverflow.com/q/50540370
tags question: http://stackoverflow.com/q/50453299
tags question: http://stackoverflow.com/q/50519459
tags question: http://stackoverflow.com/q/50451593
tags question: http://stackoverflow.com/q/50421457
tags question: http://stackoverflow.com/q/50394820
tags question: http://stackoverflow.com/q/50437484
tags question: http://stackoverflow.com/q/50536277
tags question: http://stackoverflow.com/q/50426654
tags question: http://stackoverflow.com/q/50500512
tags question: http://stackoverflow.com/q/50430377
tags question: http://stackoverflow.com/q/50539858
tags question: http://stackoverflow.com/q/50474361
tags question: http://stackoverflow.com/q/50437268
tags question: http://stackoverflow.com/q/50495099
tags question: http://stackoverflow.com/q/50530349
tags question: http://stackoverflow.com/q/50402895
tags question: http://stackoverflow.com/q/50490567
tags question: http://stackoverflow.com/q/50426090
tags question: http://stackoverflow.com/q/50517267
tags question: http://stackoverflow.com/q/50428894
tags question: http://stackoverflow.com/q/50401436
tags question: http://stackoverflow.com/q/50477575
tags question: http://stackoverflow.com/q/50436833
tags question: http://stackoverflow.com/q/50427896
tags question: http://stackoverflow.com/q/50436562
tags question: http://stackoverflow.com/q/50389707
tags question: http://stackoverflow.com/q/50529508
tags question: http://stackoverflow.com/q/50438501
tags question: http://stackoverflow.com/q/50490437
tags question: http://stackoverflow.com/q/50500264
tags question: http://stackoverflow.com/q/50473505
tags question: http://stackoverflow.com/q/50410666
tags question: http://stackoverflow.com/q/50404469
tags question: http://stackoverflow.com/q/50486382
tags question: http://stackoverflow.com/q/50398444
tags question: http://stackoverflow.com/q/50467781
tags question: http://stackoverflow.com/q/50484813
tags question: http://stackoverflow.com/q/50407417
tags question: http://stackoverflow.com/q/50441839
tags question: http://stackoverflow.com/q/50433604
tags question: http://stackoverflow.com/q/50386716
tags question: http://stackoverflow.com/q/50521394
tags question: http://stackoverflow.com/q/50459648
tags question: http://stackoverflow.com/q/50538651
tags question: http://stackoverflow.com/q/50460905
tags question: http://stackoverflow.com/q/50455880
tags question: http://stackoverflow.com/q/50489604
tags question: http://stackoverflow.com/q/50537218
tags question: http://stackoverflow.com/q/50435988
tags question: http://stackoverflow.com/q/50498851
tags question: http://stackoverflow.com/q/50447107
tags question: http://stackoverflow.com/q/50394183
tags question: http://stackoverflow.com/q/50394097
tags question: http://stackoverflow.com/q/50517253
tags question: http://stackoverflow.com/q/50485560
tags question: http://stackoverflow.com/q/50511457
tags question: http://stackoverflow.com/q/50484686
tags question: http://stackoverflow.com/q/50438194
tags question: http://stackoverflow.com/q/50456945

http://stackoverflow.com/comment/87972701
has text: @AlexSchwab I'm glad my answer helped you! If it answered your original question then don't forget to accept it ;) For the statistics you're interested in summarizing, where exactly are you stuck, and what have you tried? There are numerous answers on SO about computing the mean in `pandas` and `ax.axhline` in `matplotlib`, and the docs for those two libraries are the best and most complete in the whole wide open source biz. If you really are stuck with a unique situation that warrants a new SO question, then please ask it!
comment on: http://stackoverflow.com/a/50471297
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50435896
has body: As a part of a program I want to delete certain values from array. Filtering the values that I want works but I can't put them in the format I wish. I deliberately write a -1 for every value I want removed. Is there a 2'd version on how to use this result[result &gt;= 0]?
answer count: 1
has comment: http://stackoverflow.com/comment/87885924
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: arrays
score: -3
tagged with: python
has title: Python removing specific values in array
has answer: http://stackoverflow.com/a/50436004
upvote count: 0
tagged with: list
downvote count: 3

http://stackoverflow.com/q/50424056
tagged with: python
has body: In Tensorflow, tf.argmax() returns the index of the greatest element in an array. However, for multi-label classification tasks, a function that returns the N greatest elements in an array would be very handy. predicted_array: [0.4, 0.6, 0.7, 0.2, 0.9] tf.something(predicted_array, N = 2): [2,4] To then compare it with the ground truth one hot encoded array one_hot_array: [0, 0, 1, 0, 1] tf.something(one_hot_array, N = 2): [2,4] Is there any function like this? Or something similar to this? Thanks for any help
tagged with: multilabel-classification
has answer: http://stackoverflow.com/a/50424173
score: 2
type: AnsweredQuestion
upvote count: 2
answer count: 1
has title: tf.argmax() for more than one index Tensorflow
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50424173

http://stackoverflow.com/q/50444576
favorite count: 0
type: Question
has body: I have a dataframe like this, a b 0 c1 y 1 c2 n 2 c3 n 3 c4 y 4 c5 y I want to make duplicate of n times for the same dataframe. to do that i used, pd.concat([df]*3).reset_index(drop=True) But now i have a data frame like below, a b c 0 c1 y 2017-10-10 1 c2 n 2017-10-10 2 c3 n 2017-10-10 3 c4 y 2017-10-10 4 c5 y 2017-10-10 In this,I wanna do the same operation but column c should be added by one day. i.e., a b c 0 c1 y 2017-10-10 1 c2 n 2017-10-10 2 c3 n 2017-10-10 3 c4 y 2017-10-10 4 c5 y 2017-10-10 0 c1 y 2017-10-11 1 c2 n 2017-10-11 2 c3 n 2017-10-11 3 c4 y 2017-10-11 4 c5 y 2017-10-11 0 c1 y 2017-10-12 1 c2 n 2017-10-12 2 c3 n 2017-10-12 3 c4 y 2017-10-12 4 c5 y 2017-10-12 0 c1 y 2017-10-13 1 c2 n 2017-10-13 2 c3 n 2017-10-13 3 c4 y 2017-10-13 4 c5 y 2017-10-13 I tried like this, df1=df.copy() df2=df.copy() df3=df.copy() df1['c']=(df['c']+datetime.timedelta(days=1)).copy() df2['c']=(df['c']+datetime.timedelta(days=2)).copy() df3['c']=(df['c']+datetime.timedelta(days=3)).copy() print pd.concat([df,df1,df2,df3]) My code works good, but i'm searching for pythonic efficient way to solve this.
has title: Duplicate of dataframe but increasing date
tagged with: datetime
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50444670
score: 6
upvote count: 6
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50444670
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50476629
has comment: http://stackoverflow.com/comment/87966843
has answer: http://stackoverflow.com/a/50476715
type: Question
linked to: http://stackoverflow.com/q/1436703
tagged with: python
accepted answer: http://stackoverflow.com/a/50476715
has body: I have read and understood the difference between repr and str and noted the difference. repr - unambigous str - readable What happens is both is used? I wrote a simple class and found that repr is called when both are given. class test(): def __repr__(self): return 'repr called' def __str__(self): return 'str called' x = test() print x Now, when I check the implementation of both the classes in Django ValidationError, Im not sure when str will be called as the repr function is already overloaded. https://docs.djangoproject.com/en/2.0/_modules/django/core/exceptions/#ValidationError def __str__(self): # print 'validationerror str' if hasattr(self, 'error_dict'): return repr(dict(self)) return repr(list(self)) def __repr__(self): # print 'validationerror repr' return 'ValidationError(%s)' % self How and when the __str__ function will be called?
duplicate of: http://stackoverflow.com/q/1436703
has title: repr vs str in python classes - both are given
type: AnsweredQuestion
score: 0
tagged with: django
answer count: 1

http://stackoverflow.com/a/50523349
answers question: http://stackoverflow.com/q/50483092
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50483092
has body: This had been perfectly solved here's the code: import pandas as pd writer = pd.ExcelWriter('group.xlsx') for groups in infos['cats']: group=infos[infos['cats']==groups] group.to_excel(writer,encoding='gbk',sheet_name="{0}".format(groups)) writer.save()

http://stackoverflow.com/q/50434826
tagged with: python
has comment: http://stackoverflow.com/comment/87884006
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50435080
has comment: http://stackoverflow.com/comment/89260395
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/50435080
tagged with: 3d
tagged with: opengl
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/16768090
favorite count: 0
tagged with: pyopengl
type: Question
has title: get 3d point in space using 2d point in image in python opengl
has body: Im trying to simulate a depth camera in a room, my camera is able to move and rotate in the world and the room is simulated as a 3d cube around the (0,0,0) At the click of a button I want to sample N random points in the image and get the distance of these points from the camera (distance in the "real world"). So far I've managed to create the scene of the moving camera and the cube (Example) I tried gluUnProject to get the 3d point model_view = np.array(glGetDoublev(GL_MODELVIEW_MATRIX)) proj = np.array(glGetDoublev(GL_PROJECTION_MATRIX)) view = np.array(glGetDoublev(GL_VIEWPORT)) 3d_point = gluUnProject(x,y, 0.0) where x,y are the coordinates of the pixel in the image, but when I check this on pixels that I know their location (the cube corners) I get what feels like random results. I very new to openGL so I might be missing something, math-wise all I want to do is apply the inverse of the projection and view matrix on the pixel coordinates but that doesnt work. I attache the code for the room simulation below. Thanks in advance. import pygame from pygame.locals import * import numpy as np import random from OpenGL.GL import * from OpenGL.GLU import * display = (800, 600) import math def get_cube_information(): vertices = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1, ), (-1, -1, 1), (-1, 1, 1), ) edges = ( (0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7), ) surfaces = ( (0,1,2,3), (3,2,7,6), (6,7,5,4), (4,5,1,0), (1,5,7,2), (4,0,3,6), ) colors = ( (1.000, 0.920, 0.000), (0.000, 0.860, 0.000), (1.000, 0.480, 0.000), (1.000, 1.000, 1.000), (0.900, 0.000, 0.000), (0.000, 0.000, 0.950) ) return vertices, edges, surfaces, colors def Cube(): glBegin(GL_QUADS) (vertices, edges, surfaces, colors) = get_cube_information() for i, surface in enumerate(surfaces): x = 0 color = colors[i] for vertex in surface: x += 1 glColor3fv(color) glVertex3fv(vertices[vertex]) glEnd() glBegin(GL_LINES) for edge in edges: for v…

http://stackoverflow.com/comment/87988835
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50487527
type: Comment
has text: So it comes down to path is incorrect, and you still need to compress it using whitenoise.compress?

http://stackoverflow.com/q/50424969
has comment: http://stackoverflow.com/comment/87864832
has answer: http://stackoverflow.com/a/50425085
type: Question
has body: I need to make two different types of codes to find GCD. I'm not allowed to use def() because I didn't learn it yet. This is my first code. I am not supposed to use the euclid method here. I need to input two numbers together, and set the smaller one to 'bound'. num1, num2 = (input("input two integers to find GCD: ")).split() num1=int(num1); num2=int(num2) if num1 &gt; num2: bound == num2 elif num1 &lt; num2: bound == num1 i=2 while (i &lt;= bound) : if (num1 % i == 0) and (num2 % i == 0): i == GCD i=i+1 print("The GCD for %d, %d is %d."%(num1,num2,GCD)) This is my second code. Here, I need to be using the euclid method. I have tried my best, but I can't catch my errors. num1, num2 = (input("input two integers to find GCD: ")).split() num1=int(num1) num2=int(num2) temp=num1%num2 while (num1 != 0): num1=num2; num2=tmp; tmp=num1%num2 print("The GCD for %d, %d is %d."%(num1, tmp, num2))
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87864730
has comment: http://stackoverflow.com/comment/87864806
score: 0
answer count: 1
has title: Python GCD algorithms without using 'define'

http://stackoverflow.com/q/50413627
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50413697
score: 1
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50413697
upvote count: 1
has answer: http://stackoverflow.com/a/56027635
possible better answer: http://stackoverflow.com/a/56027635
has title: Merging two models in Keras Functional API
tagged with: keras
tagged with: tensorflow
has body: I am messing around with wide and deep models and trying to implement something basic with keras. I am able to produce a simple model and a deep nn using the functional keras. However, I'm having some issues ensembling the two. ############################################################################### ############################################################################### inputs = Input(shape = (X_train.shape[1],)) output = Dense(1, activation='linear')(inputs) wide = Model(inputs, output) wide.compile( optimizer = 'adam', loss = 'mean_squared_error', metrics = ['accuracy'] ) wide.fit(x = X_train, y = Y_train, epochs = 10, verbose = 1) ############################################################################### ############################################################################### inputs = Input(shape = (X_train.shape[1],)) x = Dense(200, kernel_initializer = 'uniform', activation = 'relu')(inputs) x = Dense(100, activation = 'relu')(x) x = Dense(50, activation = 'relu')(x) output = Dense(1, activation='sigmoid')(x) deep = Model(inputs, output) deep.compile( optimizer = 'adam', loss = 'mean_squared_error', metrics = ['accuracy'] ) deep.fit(x = X_train, y = Y_train, epochs = 10, verbose = 1) ############################################################################### ############################################################################### merge = Concatenate([wide, deep]) hidden1 = Dense(10, activation='relu')(merge) output = Dense(1, activation='sigmoid')(hidden1) model = Model(inputs=visible, outputs=output) How can I go about concatenating the two models? I get this error: ValueError: Layer dense_36 was called with an input that isn't a symbolic tensor. Received type: &lt;class 'keras.layers.merge.Concatenate'&gt;. Full input: [&lt;keras.layers.merge.Concatenate object at 0x1a1adda588&gt;]. All inputs to the layer should be tensors.

http://stackoverflow.com/comment/87906537
has text: And how would the return statement look like. return df_ ?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50446334

http://stackoverflow.com/comment/88040816
type: QuestionComment
comment on: http://stackoverflow.com/q/50513688
has text: If you could post a little more of what you've done, that'd help in diagnosing the problem.
score: 0
type: Comment

http://stackoverflow.com/a/50507265
type: Answer
has comment: http://stackoverflow.com/comment/88026640
answers question: http://stackoverflow.com/q/50507235
has body: You can use: In [120]: for item in data.values(): ...: print(item['type']) card wechat Or list comprehension: In [122]: [item['type'] for item in data.values()] Out[122]: ['card', 'wechat']
downvote count: 0
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/88026741

http://stackoverflow.com/q/50388396
upvote count: 5
accepted answer: http://stackoverflow.com/a/51086594
tagged with: python
type: AnsweredQuestion
answer count: 3
has title: error name 'dtype' is not defined
has comment: http://stackoverflow.com/comment/87792329
downvote count: 0
has answer: http://stackoverflow.com/a/71616484
favorite count: 0
has answer: http://stackoverflow.com/a/50388626
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50388626
score: 5
has body: I try to compile this code but I get this errror : NameError: name 'dtype' is not defined Here is the python code : # -*- coding: utf-8 -*- from __future__ import division import pandas as pd import numpy as np import re import missingno as msno from functools import partial import seaborn as sns sns.set(color_codes=True) if dtype(data.OPP_CREATION_DATE)=="datetime64[ns]": print("OPP_CREATION_DATE is of datetime type") else: print("warning: the type of OPP_CREATION_DATE is not datetime, please fix this") Any idea please to help me to resolve this problem? Thank you
has answer: http://stackoverflow.com/a/51086594

http://stackoverflow.com/comment/87955870
type: AnswerComment
has text: Thank you! I use this in python 3.6: return ''.join(['\\x%02x' % b for b in value])
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50471009

http://stackoverflow.com/a/50472175
answers question: http://stackoverflow.com/q/50472011
has body: Since you are not getting what you want with the yaml module immediately, your .conf file is probably using a format different than what the yaml module currently expects. This code is a quick workaround that gives you the dictionary you want: for mainkey in ['production','development']: d = {} for item in config[mainkey].split(): key,value = item.split(':') d[key] = value config[mainkey] = d
score: 2
type: Answer
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/50428790
answers question: http://stackoverflow.com/q/50428119
has comment: http://stackoverflow.com/comment/97391925
type: Answer
has comment: http://stackoverflow.com/comment/131940151
accepted answer of: http://stackoverflow.com/q/50428119
has body: dictionary with EMPLOYEE_ID and MANAGER_ID: dct = dict(zip(df.EMPLOYEE_ID.values, df.MANAGER_ID.values)) function to create hierarchy string def heirarchy(id): boss = str(id) + '/' while dct[id] != 'null': boss += dct[id] + '/' id = int(dct[id]) return boss[:-1] apply df['LEVEL'] = df.EMPLOYEE_ID.apply(heirarchy) # Result EMPLOYEE_ID NAME MANAGER_ID LEVEL 0 101 A 10 101/10/1 1 102 B 11 102/11/1 2 10 C 1 10/1 3 11 D 1 11/1 4 1 E null 1
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87878200
has text: I ran your code and selected "Truncated Normal." I saw four Labels in row 2, the fourth being blank. There were three Entries in row 3, exactly what you would expect after the call to grid_remove(). What is the problem? BTW, grid_remove doesn't delete the object, it just makes it invisible.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50431638

http://stackoverflow.com/comment/88020985
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50491777
type: Comment
has text: Damn that's fast, elegant solution, and I've learnt something new (nesting loops). Thank you very much. Would you mind explaining this line please - `tags[match_elem.group(1)] = match_elem.group(2)`?

http://stackoverflow.com/a/50499451
has comment: http://stackoverflow.com/comment/88030030
has body: Looks like you are missing django-rest-framework requirement. Make sure you have it installed, you can use pip freeze command to check for installed dependencies. I guess you probably have a file named requirementes.txt or something along those lines, try with pip install -r requirements.txt to install all dependencies.
type: Answer
answers question: http://stackoverflow.com/q/50499418
score: 0

http://stackoverflow.com/q/50421555
tagged with: tensorflow
has title: Argmax function of Tensorflow does not print value when evaluated on a constant tensor
type: Question
has answer: http://stackoverflow.com/a/50423704
answer count: 2
tagged with: python
type: UnansweredQuestion
has body: I'm new at Tensorflow. I am having a litte trouble at understanding its constants. I have this simple code mentioned below: import tensorflow as tf vector = tf.constant([[1,2,3,4],[4,5,6,7],[8,9,1,2]],tf.int32,name="vector") with tf.Session() as sess: v = sess.run(vector) argm = tf.argmax(v,1) print(argm) I expect this to return something like [4,7,8], as I understood from the documentation. Instead, I get this: Tensor("ArgMax:0", shape=(3,), dtype=int64). So, i don't know what am I doing wrong.
score: 0
has answer: http://stackoverflow.com/a/50421607

http://stackoverflow.com/comment/87928816
score: 2
comment on: http://stackoverflow.com/q/50457569
has text: It might help people if you broke down the question more. What are you actually trying to do? You pretty much need to explain everything you wrote down more because no one is able to understand your question.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50400522
upvote count: 15
downvote count: 0
type: Answer
score: 15
accepted answer of: http://stackoverflow.com/q/50400485
has body: Group on the last level of your MultiIndex and call DataFrameGroupBy.cumsum: combined_df['cumsum'] = combined_df.groupby(level=-1)['cost'].cumsum()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50400485
has comment: http://stackoverflow.com/comment/87817050
has comment: http://stackoverflow.com/comment/87817016

http://stackoverflow.com/a/52772979
upvote count: 1
score: 1
has body: the mask is not intersect with template image. even though the image is filtered by gausian, the sobel magnitude in mask area is lower than the threshold(default is 55). so it can't be successful. You can lower the threshold or just not give mask.
answers question: http://stackoverflow.com/q/50531699
downvote count: 0
type: Answer

http://stackoverflow.com/a/50461863
type: AcceptedAnswer
downvote count: 0
has body: Use np.searchsorted to get those indices that would split into groups and then split those with np.split - In [41]: np.random.seed(0) In [42]: a = np.sort(np.random.randint(0,100,(10000))) In [43]: bins = [20,40,60,80] In [46]: idx = np.searchsorted(a, bins) In [47]: np.split(a,idx) Out[47]: [array([ 0, 0, 0, ..., 19, 19, 19]), array([20, 20, 20, ..., 39, 39, 39]), array([40, 40, 40, ..., 59, 59, 59]), array([60, 60, 60, ..., 79, 79, 79]), array([80, 80, 80, ..., 99, 99, 99])]
answers question: http://stackoverflow.com/q/50461784
accepted answer of: http://stackoverflow.com/q/50461784
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/q/50479385
has comment: http://stackoverflow.com/comment/89990715
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
tagged with: mysql-python
tagged with: twitter
tagged with: tweepy
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88003245
has title: How to retrieve/find with specific text on tweet from user timeline twitter with python
has body: I'm trying to get specific tweet from user timeline with contain text "#Gempa" using python i am able to get user timeline, but i want to get the timeline with text just contain "#Gempa" or something specific text here is my code #Import the necessary methods from tweepy library import tweepy, codecs import pymysql import time #Variables that contains the user credentials to access Twitter API access_token = "XXX" access_token_secret = "XXX" consumer_key = "XXX" consumer_secret = "XXX" #Authentication auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) #Declare Connection conn = pymysql.connect(host='localhost', port='', user='root', passwd='', db='test', use_unicode=True, charset="utf8mb4") cur = conn.cursor() #Get Current Date Time curdatetime = time.strftime("%Y-%m-%d %H:%M:%S") cur.execute("DELETE FROM tweet order by id desc LIMIT 500") #Get last id from table tweet last_id = 0 cur.execute("SELECT MAX(id) FROM tweet") result = cur.fetchall() for row in result: last_id = row[0] print ("Last ID : " + str(last_id)) #Get Number of Tweet user = api.get_user(108543358) print ("Name:", user.name) print ("Name:", user.screen_name) print ("Number of tweets: " + str(user.statuses_count)) print ("followers_count: " + str(user.followers_count)) print ("Account location: ", user.location) print ("Account created at: ", user.created_at) n = 0 for Tweet in tweepy.Cursor(api.user_timeline, id=108543358, q = "#Gempa", lang = id, result_type = "recent", since_id = last_id).items(3): print ("*****" + str(i) +"*****") print ("ID: " + Tweet.id_str) print ("Text: " + str(Tweet.text.encode("utf-8"))) print ("Retweet Count: " + str(Tweet.retweet_count)) print ("Favorite Count: " + str(Tweet.favorite_count)) print ("Date Time: " + str(Tweet.created_at)) #print (str(Tweet.location)) #how to get geolocation data for mapping ? print ("************") n = n + 1 cur.execute("INSERT INTO tweet (no, id, text, …
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50495837
has comment: http://stackoverflow.com/comment/88013447
accepted answer: http://stackoverflow.com/a/50495837

http://stackoverflow.com/comment/87881605
has text: It still returned exit.
comment on: http://stackoverflow.com/a/50433307
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50470855
has comment: http://stackoverflow.com/comment/87959391
has comment: http://stackoverflow.com/comment/87964331
linked to: http://stackoverflow.com/q/49557809
tagged with: optimization
has answer: http://stackoverflow.com/a/50471305
has title: Optimizing root finding algorithm from scipy
upvote count: 1
score: 1
has body: I use the root function from scipy.optimize with the method "excitingmixing" in my code because other methods, like standard Newton, don't converge to the roots I am looking for. However I would like to optimize my code using numba, which doesn't support the scipy package. I tried to look up the "exciting mixing" algorithm in the documentation to program it myself: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html I didn't find anything useful except the not really helpful statement that the method "uses a tuned diagonal Jacobian approximation". I would be glad if someone could tell me something about the algorithm or has an idea on how to optimize the scipy function in an other way. As requested here is a minimal code example: import numpy as np from scipy import optimize from numba import jit @jit(nopython = True) def func(x): [a, b, c, d] = x da = a*(1-b) db = b*(1-c) dc = c dd = 1 return [da, db, dc, dd] @jit(nopython = True) def getRoot(x0): solution = optimize.root(func, x0, method="excitingmixing") return(solution.x) root = getRoot([0.1,0.1,0.2,0.4]) print(root)
tagged with: scipy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/67455200
answer count: 2
type: UnansweredQuestion
tagged with: numba
downvote count: 0
has comment: http://stackoverflow.com/comment/87958877
tagged with: python

http://stackoverflow.com/comment/88089000
has text: I agree with the overall sentiment here. As long as you're not doing pixel by pixel operations, OpenCV and Numpy should be pretty fast. Also, when it comes to profiling, using `time.time()` you can figure out how many FPS you get. Start from the end of your code and comment out processing operations. For me, running very simple operations, I typically get 20-30 fps on a 640x480 camera running on a snappy workstation. If I'm getting into more heavy stuff like template matching or keypoint/feature matching it drops further to 10-15 fps.
comment on: http://stackoverflow.com/a/50535882
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87957186
score: 0
type: Comment
type: AnswerComment
has text: The code looks nice, but I can't execute it. Replacing `njit` with `jit` I get: `NameError: global name 'y' is not defined`. Using `njit` yields: `TypingError: cannot determine Numba type of <class 'object'>`. The error stems from the `njit` of `simpson_nb()`.
comment on: http://stackoverflow.com/a/50470995

http://stackoverflow.com/comment/87888265
type: QuestionComment
has text: Run `pip install -vvv somepkg`, copy the complete output from the terminal and add it to the question.
comment on: http://stackoverflow.com/q/50436992
score: 1
type: Comment

http://stackoverflow.com/q/50423659
has comment: http://stackoverflow.com/comment/87862129
type: UnansweredQuestion
tagged with: primary-key
has answer: http://stackoverflow.com/a/50424455
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/87862166
has comment: http://stackoverflow.com/comment/87862283
has comment: http://stackoverflow.com/comment/95573772
has comment: http://stackoverflow.com/comment/87863564
tagged with: foreign-keys
has title: how to change django default ForeignKey type from integer to string?
tagged with: python
has body: class NewStock(models.Model): stock_info = models.ForeignKey(Stock) stock_xcode = models.CharField(max_length=10, unique=True, primary_key=True) class Stock(models.Model): stock_name = models.CharField(max_length=200) stock_id = models.CharField(max_length=10, unique=True, primary_key=True) In database,there will be a stock_info_id column and its type is integer. When stock_id starts with 0, such as 000001, It will be stock_info_id=1 and will fail to get stock_info because 1 is not found in column stock_id of Stock table. How can I specify an exact type for a ForeignKey. For this problem, things will be good if stock_info_id is CharField other than Integer. The code before changing looks like this. I just not set stock_id and stock_xcode as primary key. In this situation, stock_info_id should be integer. class NewStock(models.Model): stock_info = models.ForeignKey(Stock) stock_xcode = models.CharField(max_length=10, unique=True) class Stock(models.Model): stock_name = models.CharField(max_length=200) stock_id = models.CharField(max_length=10, unique=True) After I make stock_id as primary key, makemigrations and migrate,the stock_info_id is still integer. The migration file is here. class Migration(migrations.Migration): dependencies = [ ('stockinfo', '0008_auto_20180519_1017'), ] operations = [ migrations.RemoveField( model_name='newstock', name='id', ), migrations.RemoveField( model_name='stock', name='id', ), migrations.AlterField( model_name='newstock', name='stock_xcode', field=models.CharField(max_length=10, primary_key=True, serialize=False, unique=True), ), migrations.AlterField( model_name='stock', name='stock_id', field=models.CharField(max_length=10, primary_key=True, serialize=False, unique=True), ), ] The chosen db is postgresql. The newstock table. name | type | Collation | Nullable | Default ---------------+--------------------------+-----------+----------+--------- stock_xcode | character varying(10) | | not null | stock_info_id | integer | | not null…
has comment: http://stackoverflow.com/comment/87862175
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87862090
has comment: http://stackoverflow.com/comment/87863180

http://stackoverflow.com/q/50479077
has answer: http://stackoverflow.com/a/50479124
type: AnsweredQuestion
tagged with: list
answer count: 2
upvote count: 0
downvote count: 1
has body: For eg. I have the following list: N=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1] I need it to be broken down as follows: N2=[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5], [1]] where the last '1' remains at its original position without being grouped with the other '1's. Thanks for your help
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50479124
has title: Breaking a list into smaller lists of duplicate elements with the original order preserved (Python)
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50479198
possible better answer: http://stackoverflow.com/a/50479198

http://stackoverflow.com/a/50421477
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50420963
has body: Would this work for you? pN ={'dave': 10, 'jacinta': 10, 'james': 8, 'john': 6, 'jack': 3, 'sam': 2} def top_n_scores(n, score_dict): ''' returns the n scores from a name:score dict''' lot = [(k,v) for k, v in pN.items()] #make list of tuple from scores dict nl = [] while len(lot)&gt; 0: nl.append(max(lot, key=lambda x: x[1])) lot.remove(nl[-1]) return nl[0:n] To get the top 4 scores: top_n_scores(4, pN) [('dave', 10), ('jacinta', 10), ('james', 8), ('john', 6)]

http://stackoverflow.com/a/50395478
score: 1
answers question: http://stackoverflow.com/q/50395427
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You can use: df = df1.append(df2.assign(Date=20170120).set_index('Date', append=True).swaplevel(0,1)) print (df) Buying_Date Buying_Price Buying_Qty Code Code.1 Name Date Code 20140117 none 20170101 5 7 NaN 1234.0 a 20170120 none 20180101 6 8 NaN 5678.0 b abcd 20170101 5 7 abcd NaN af efgh 20180101 6 8 efgh NaN bf Detail: print (df2.assign(Date=20170120).set_index('Date', append=True).swaplevel(0,1)) Name Code Buying_Date Buying_Price Buying_Qty Date Code 20170120 abcd af abcd 20170101 5 7 efgh bf efgh 20180101 6 8 Explanation: First assign new column and add to index by set_index swaplevel of levels in MultiIndex Last append to first DataFrame
accepted answer of: http://stackoverflow.com/q/50395427

http://stackoverflow.com/comment/87849054
has text: Thank you fine sir
type: AnswerComment
comment on: http://stackoverflow.com/a/50416735
score: 0
type: Comment

http://stackoverflow.com/a/50480663
type: Answer
answers question: http://stackoverflow.com/q/50480555
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Try this with open('followst.txt') as afile: lines = afile.readlines() follow_dict = {} max_follower = 0 for line in lines: names = line.split() follow_dict[names[0]] = len(names)-1 if max_follower &lt; len(names)-1: max_follower = len(names)-1 for name,num_of_follower in follow_dict.items(): if num_of_follower == max_follower: print(name)
accepted answer of: http://stackoverflow.com/q/50480555

http://stackoverflow.com/comment/87884753
has text: @Upeka Fernando you can use append method to write item in "purchasing.txt", because write can override it. You can change file2=open("purchasing.txt","w") to file2=open("purchasing.txt","a") then i think you resolve the problem.
comment on: http://stackoverflow.com/q/50435295
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50632992
has comment: http://stackoverflow.com/comment/88381094
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50517103
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88469557
score: 1
type: Answer
has body: The trick is to add a new twin axis for each row of tick labels you want. You can then position them properly setting the pad parameter in tick_params. Allow me to make your example a little smaller so it's easier to follow import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mtick fig, ax = plt.subplots(figsize=(12,2)) np.random.seed(42) x0 = np.arange(50) y0 = np.random.rand(50) x1 = np.arange(30) y1 = np.random.rand(30) + 0.7 ax.plot(x0, y0, ls='--', marker='o', ms=6, color='orange') ax.grid(True) ax.tick_params('x', colors='blue') ax.set_xlabel('x1', fontsize=14, color='blue') ax.set_ylabel('y', fontsize=14) tax1 = ax.twiny() tax1.set_xlim(ax.get_xlim()) tax1.tick_params('x', colors='orange', pad=14) tax1.set_xlabel('x2', fontsize=14, color='red', labelpad=6) tax2 = ax.twiny() tax2.set_xlim(ax.get_xlim()) tax2.plot(x1, y1, ls='--', marker='o', ms=6, color='green') tax2.tick_params('x', colors='green') tax2.set_xticks([0, 10, 20, 30]) fig.savefig('img.png', pad_inches=0, bbox_inches='tight') As you pointed out in the comments an issue with this plot is that you get green and orange tick lines and you would like to have them in red just like the x2 label. You can hide the green tick lines setting length=0 in tick_params, draw the orange plot ticks in red first and then set labels color to orange. Here's the modified code import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mtick fig, ax = plt.subplots(figsize=(12,2)) np.random.seed(42) x0 = np.arange(50) y0 = np.random.rand(50) x1 = np.arange(30) y1 = np.random.rand(30) + 0.7 ax.plot(x0, y0, ls='--', marker='o', ms=6, color='orange') ax.grid(True) ax.tick_params('x', colors='blue') ax.set_xlabel('x1', fontsize=14, color='blue') ax.set_ylabel('y', fontsize=14) tax1 = ax.twiny() tax1.set_xlim(ax.get_xlim()) tax1.tick_params('x', colors='red', pad=14) tax1.set_xlabel('x2', fontsize=14, color='red', labelpad=6) [x.set_color("orange") for x in tax1.get_xticklabels()] …
answers question: http://stackoverflow.com/q/50517103

http://stackoverflow.com/q/50391698
downvote count: 0
type: UnansweredQuestion
upvote count: 1
has title: Kivy - ScrollView in Popup within TabbedPanel not scrolling
has body: I made a little interface that's basically a GridLayout within which I put a Button (among other things) that calls a Popup in which there's a ScrollView with other things. The whole code works well but I tried to put the GridLayout in one of the tabs of a TabbedPanel and now the Popup won't scroll. I didn't make any changes in the code whatsoever but changing the class of my Widget to TabbedPanel. What did I do wrong? Relevant .py file: from kivy.config import Config Config.set('graphics', 'resizable', 0) Config.set('graphics', 'position', 'custom') Config.set('graphics', 'left', 100) Config.set('graphics', 'top', 100) Config.write() from kivy.app import App from kivy.clock import Clock from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.properties import ListProperty, ObjectProperty, BooleanProperty, StringProperty from kivy.uix.button import Button from kivy.uix.filechooser import FileChooser from kivy.uix.togglebutton import ToggleButton from kivy.uix.checkbox import CheckBox from kivy.uix.scrollview import ScrollView from kivy.uix.progressbar import ProgressBar from kivy.uix.tabbedpanel import TabbedPanel from kivy.effects.dampedscroll import DampedScrollEffect from kivy.uix.spinner import Spinner from kivy.core.window import Window from kivy.lang.builder import Builder from kivy.uix.popup import Popup class MyWidget(TabbedPanel): def popupSettings(self, *args): list_of_choices = [] list_chosen = [] number_content = len(self.spinner_choices) contentF = ScrollView(do_scroll_x=False, size_hint_y=None, height=400) content = GridLayout(rows=number_content+1, cols=2, size_hint_y=None, height=self.minimum_height, spacing=30) for y in self.spinner_choices: content.add_widget(Label(text=y + " (Current value: {})".format(self.param_values[str(y)]), size_hint_y=None, height=30…
tagged with: interface
score: 1
tagged with: python
tagged with: kivy
favorite count: 0
type: Question
answer count: 0

http://stackoverflow.com/a/50499509
score: 20
answers question: http://stackoverflow.com/q/50498575
has body: It means that particular type was inferred by mypy as a part of performing type variable substitution. For example, blah[0] is actually doing blah.__getitem__(0): it turns out that the __getitem__ method is defined to return some value of type _T, where _T is whatever type is contained within the list*. Mypy understands that blah contains ints, and so inferred that the _T return type is of type int. In contrast, there's no type variable inference going on with just 1 and blah[0] * 2. The former is a literal; the latter is invoking the int.__mul__(...) method, which is typed to return specifically an int. *Well, that's not actually the exact signature, but close enough. For the most part, you can ignore this and just treat it as an implementation detail of mypy. It exists mostly because being able to tell whether or not a type was inferred is occasionally useful to have when you're tinkering with or debugging mypy internals.
has comment: http://stackoverflow.com/comment/130276213
upvote count: 20
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/130280682
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50498575

http://stackoverflow.com/comment/87813024
has text: The fact that you even have a list that looks like `['milk, water, apple, orange']` is usually a sign that you did something wrong to get to this point, and you should adjust that code rather than trying to fix things in post-processing.
score: 2
comment on: http://stackoverflow.com/q/50398603
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50444939
tagged with: spyder
answer count: 1
has comment: http://stackoverflow.com/comment/87903610
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50445024
accepted answer: http://stackoverflow.com/a/50445024
has title: the first line has 5 words , the second line has 4 words and third line has 2 words. So how can i count them using python
has comment: http://stackoverflow.com/comment/87904003
tagged with: python
downvote count: 4
type: AnsweredQuestion
upvote count: 0
has body: example : dam | luru | Goal | Limaste | Querto elh | Dub | Lon row | Mumb lhi | mba I want to count the number of characters in each row. for eg. the first row has 5 characters. please help.
score: -4

http://stackoverflow.com/q/50446393
answer count: 2
has answer: http://stackoverflow.com/a/50446560
has answer: http://stackoverflow.com/a/50446792
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/87906426
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87906482
linked to: http://stackoverflow.com/q/1894269
has title: coverting strings to tuple in python3.5
has body: But now I wish to convert it to the following tuple format: ((1231, 123), (2341, 1210), (342,12), (5462, 565)) I really need to find a way to convert this data to the format directly above. I would greatly appreciate any help! How to covert a string into pairs of tuple? I have already tried this with open("data.txt") as f: list = [line.rstrip('\n') for line in f] mylist = [mylist[x:x+1] for x in range(0, len(mylist), 3)] print(mylist) data = ['I went to work but got delayed at other work and got stuck in a traffic and I went to drink some coffee but got no money and asked for money'] I want my output to be in this format [('i', 'went'),('to', 'work'),('but', 'got').........] I have tried this but not working import itertools import nltk import collections f=open('readme.txt','r') data=f.read() print(data) d1 = data[0].split() output = list(itertools.zip_longest(d1[::2],d1[1::2],fillvalue = None)) print(output) Edited from comment - File content: ['भिन्केन NNP डच NNP प्रकाशन NN समूह NN एल्सेभियर NNP एन.भी. FB को PKO अध्यक्ष NN हुनुहुन्छ VBF । YF कन्सोलिडेटिड NNP गोल्ड NN फिल्ड्स NN पीएलसी NNP का PKO पूर्व JJ सभापति NN ५५ CD वर्षीय JJ रूडोल्फ NNP अग्न्यु NNP लाई PLAI यस DUM ब्रिटिस NNP औद्योगिक JJ समूह NN को PKO सल्लाहकार NN को PKO रूप NN मा POP मनोनयन NN गरिएको VBKO थियो VBX । YF एकताका RBO केन्ट NNP चुरोट NN को PKO फिल्टर NN बनाउन VBI प्रयोग NN भएको VBKO एक CD प्रकार NN को PKO अस्बेस्टोस NNP ']
tagged with: python
possible better answer: http://stackoverflow.com/a/50446560
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50446792
score: 0

json-rpc
tag name: json-rpc
tags question: http://stackoverflow.com/q/50385070
type: Tag

http://stackoverflow.com/comment/87933969
score: 0
has text: Looks fine to me. Returns list with elements:- [('direction', 'north')], assuming that indentations are right.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50460402

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

http://stackoverflow.com/comment/87996729
type: QuestionComment
comment on: http://stackoverflow.com/q/50476905
score: 0
has text: What's wrong with pywinauto? `app.window(handle=hwnd, top_level_only=False).wrapper_object()` In what form do you expect the property data? Which properties do you expect to see?
type: Comment

http://stackoverflow.com/comment/88087167
type: Comment
type: AnswerComment
score: 0
has text: Thanks for getting back. Say in the event say if item `aaa0000` key `index_range` is also `None`, wouldn't your solution removes aaa0000 dictionary too? Can I narrow it down such that it will be checking on a specified key, in this case `location`?
comment on: http://stackoverflow.com/a/50537511

http://stackoverflow.com/q/50450641
type: Question
tagged with: python-3.x
has body: Why in Python (3.6) does chunk = await evt_loop.run_in_executor(io_exec, arc.read, chunk_size) work exactly as expected but read_ftr = evt_loop.run_in_executor(io_exec, arc.read, chunk_size) chunk = await read_ftr throws AssertionError("yield from wasn't used with future",) on the second line, and how do I get it to work? The following is the snippet of code I'm trying to run. Fusing the three read_ftr lines together to get the first single-line implementation works, while the way it is below throws that assertion error at "chunk = await read_ftr". read_ftr: aio.Future = None hash_ftr: aio.Future = None chunk = None with open(arc_path, "rb") as arc: while arc_offs &lt; arc_size: chunk_size = min(arc_size - arc_offs, max_chunk_size) if read_ftr: chunk = await read_ftr read_ftr = evt_loop.run_in_executor(io_exec, arc.read, chunk_size) arc_offs += chunk_size if not chunk: continue if hash_ftr: await hash_ftr hash_ftr = hasher.async_update(chunk) if hash_ftr: await hash_ftr await hasher.async_digest()
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87921913
has comment: http://stackoverflow.com/comment/87915817
has comment: http://stackoverflow.com/comment/87914438
tagged with: python-asyncio
score: 3
has title: Await Doesn't Work with Coroutine Assigned to Variable?
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50451693

http://stackoverflow.com/a/50425139
has comment: http://stackoverflow.com/comment/92698915
has comment: http://stackoverflow.com/comment/88050551
has comment: http://stackoverflow.com/comment/92699359
type: Answer
has comment: http://stackoverflow.com/comment/87937097
has body: You can sort and group by the number of nonzeros in each column. Each group then sort by indices and values and split into blocks of no-change: import numpy as np from scipy import sparse def sparse_unique_columns(M): M = M.tocsc() m, n = M.shape if not M.has_sorted_indices: M.sort_indices() if not M.has_canonical_format: M.sum_duplicates() sizes = np.diff(M.indptr) idx = np.argsort(sizes) Ms = M@sparse.csc_matrix((np.ones((n,)), idx, np.arange(n+1)), (n, n)) ssizes = np.diff(Ms.indptr) ssizes[1:] -= ssizes[:-1] grpidx, = np.where(ssizes) grpidx = np.concatenate([grpidx, [n]]) if ssizes[0] == 0: counts = [np.array([0, grpidx[0]])] else: counts = [np.zeros((1,), int)] ssizes = ssizes[grpidx[:-1]].cumsum() for i, ss in enumerate(ssizes): gil, gir = grpidx[i:i+2] pl, pr = Ms.indptrgil, gir dv = Ms.data[pl:pr].view(f'V{ss*Ms.data.dtype.itemsize}') iv = Ms.indices[pl:pr].view(f'V{ss*Ms.indices.dtype.itemsize}') idxi = np.lexsort((dv, iv)) dv = dv[idxi] iv = iv[idxi] chng, = np.where(np.concatenate( [[True], (dv[1:] != dv[:-1]) | (iv[1:] != iv[:-1]), [True]])) counts.append(np.diff(chng)) idx[gil:gir] = idx[gil:gir][idxi] counts = np.concatenate(counts) nu = counts.size - 1 uniques = M@sparse.csc_matrix((np.ones((nu,)), idx[counts[:-1].cumsum()], np.arange(nu + 1)), (n, nu)) return uniques, idx, counts[1:] a = np.random.uniform(0, 10, (1000, 200)) a[a&gt;1] = 0 a = sparse.csc_matrix(a) b = sparse.csc_matrix((np.ones(1000), np.random.randint(0, 200, (1000,)), np.arange(1001))) c = a@b unq, idx, cnt = sparse_unique_columns(c) unqd, idxd, cntd = np.unique(c.A, axis=1, return_counts=True, return_inverse=True) from timeit import timeit print('sparse:', timeit(lambda: sparse_unique_columns(c), number=1000), 'ms') print('dense: ', timeit(lambda: np.unique(c.A, axis=1, return_counts=True), number=100)*10, 'ms') Sample output: sparse: 2.735588440205902 ms dense: 49.32689592242241 ms
answers question: http://stackoverflow.com/q/50419778
score: 1
has comment: http://stackoverflow.com/comment/88066986
has comment: http://stackoverflow.com/comment/92702023
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88049956
has comment: http://stackoverflow.com/comment/87927561
has comment: http://stackoverflow.com/comment/88046923
has comment: http://stackoverflow.com/comment/88043663

http://stackoverflow.com/a/50478578
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/87999478
has comment: http://stackoverflow.com/comment/87999590
upvote count: 4
has comment: http://stackoverflow.com/comment/87986093
has comment: http://stackoverflow.com/comment/87986289
accepted answer of: http://stackoverflow.com/q/50477443
has comment: http://stackoverflow.com/comment/87986953
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87985462
downvote count: 0
has comment: http://stackoverflow.com/comment/87991304
has comment: http://stackoverflow.com/comment/87986244
has comment: http://stackoverflow.com/comment/87986351
answers question: http://stackoverflow.com/q/50477443
has comment: http://stackoverflow.com/comment/87986421
has body: "Unroll" is just a mechanism to process the LSTMs in a way that makes them faster by occupying more memory. (The details are unknown for me... but it certainly has no influence in steps, shapes, etc.) When you say "2000 points split in 40 time steps", I have absolutely no idea of what is going on. The data must be meaningfully structured and saying "2000" data points is really lacking a lot of information. Data structured for LSTMs is: I have a certain number of individual sequences (data evolving with time) Each sequence has a number of time steps (measures in time) In each step we measured a number of different vars with different meanings (features) Example: 2000 users in a website They used the site for 40 days In each day I measured the number of times they clicked a button I can plot how this data evolves with time daily (each day is a step) So, if you have 2000 sequences (also called "samples" in Keras), each sequence with length of 40 steps, and one single feature per step, this will happen: Dimensions Batch size is defined as 32 by default in the fit method. The model will process batches containing 32 sequences/users until it reaches 2000 sequences/users. input_shape will required to be (40,1) (free batch size to choose in fit) Steps Your LSTMs will try to understand how clicks vary in time, step by step. That's why they're recurrent, they calculate things for a step and feed these things into the next step, until all 40 steps are processed. (You won't see this processing, though, it's internal) With return_sequences=True, you will get the output for all steps. Without it, you will get only the output for the last step. The model The model will process 32 parallel (and independent) sequences/users together in each batch. The first LSTM layer will process the entire sequence in recurrent steps and return a final result. (The sequence is killed, there are no steps left because you didn't use return_sequences=True) Output shape = (batch, 100) You create a new…
has comment: http://stackoverflow.com/comment/88000191
has comment: http://stackoverflow.com/comment/87993007
has comment: http://stackoverflow.com/comment/87999614

http://stackoverflow.com/q/50527345
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50528461
has title: How to find broken links with Selenium python webdriver?
score: 5
type: UnansweredQuestion
upvote count: 5
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/55087722
has comment: http://stackoverflow.com/comment/88066381
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/50533154
answer count: 3
has body: I'm trying to find a broken link in Selenium and Python but getting an error in the code: import requests from selenium import webdriver chrome_driver_path = "D:\\drivers\\chromedriver.exe" driver=webdriver.Chrome(chrome_driver_path) driver.get('https://google.co.in/') links = driver.find_elements_by_css_selector("a") images = driver.find_elements_by_css_selector("img") for link in links: r = requests.head(link.get_attribute('href') print(r.status_code == 200) Unable to find broken links on the page is there is some other solution? Getting: raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='myaccount.google.com', port=443): Max retries exceeded with url: /?utm_source=OGB&amp;utm_medium=app (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:777)'),)) During handling of the above exception, another exception occurred: self._sslobj.do_handshake() ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:777) During handling of the above exception, another exception occurred: Traceback (most recent call last):

http://stackoverflow.com/q/50496938
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88006789
downvote count: 1
has comment: http://stackoverflow.com/comment/88006766
has answer: http://stackoverflow.com/a/50496999
has body: I have written a script that collects data from 2 seperate API's and I am having trouble getting it to all show up on one row, instead it is showing up like this: Device Status Model StatusSub d8d Online 122 Disconnected When I want it to look like this; Device Status Model StatusSub d8d Online 1202 Disconnected Here is my code, the API is password protected so you will not be able to run it directly: while True:#always run if datetime.datetime.now().minute % 15 == 0 or True:#once every 15 minutes name = [('Device'), ('Status'), ('Model'), ('StatusSub')] space = [(''),('')] print (datetime.datetime.now()) today = datetime.date.today().strftime('E.Subdevice.Logs.%m-%d-%Y')#file name if os.path.exists(today + '.csv'):#Create new file if its a new day Append_write = 'ab' else: Append_write = 'wb' with open(today + '.csv',Append_write) as myFile:#open todays csv file, set to write. writer = csv.writer(myFile) writer.writerow(name) writer.writerow(space) #Loop to collect device name and status 500 at a time and print all 2080 in the file specified above. for x in range(5): string1 = "https://api.raincloud.com/rest/device?networkName=Company&amp;take=500&amp;skip="+str(x*500) response = requests.get(string1,headers=headers).json() for y in range (len(response)): myData = [(response[y]['device']),(response[y]['status'])] string2= 'https://api.raincloud.com/rest/device/'+str(myData[0])+'/subdevice' response2 = requests.get(string2,headers=headers).json() for z in range (len(response2)): myData2 = [(response2[z]['model']),(response2[z]['status']),datetime.datetime.now()] writer.writerow(myData) writer.writerow(myData2) Any help is appreciated.
favorite count: 0
type: Question
has title: Skip row when writing to CSV
upvote count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/88085329
score: 0
comment on: http://stackoverflow.com/a/50536608
type: Comment
has text: I knew you would think that when you saw it :-) Hope you have a lot of fun with Python.
type: AnswerComment

http://stackoverflow.com/comment/87850975
has text: Please see how to provide a [mcve]. We are looking for some of your input data as _text_, along with the code you tried and the error you've received, _all_ as text. Not images, or links to images. Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50417688
type: QuestionComment

http://stackoverflow.com/q/50439634
score: 1
accepted answer: http://stackoverflow.com/a/50439734
tagged with: python-2.x
has answer: http://stackoverflow.com/a/50439734
possible better answer: http://stackoverflow.com/a/50439758
favorite count: 0
type: Question
answer count: 2
tagged with: iterator
has title: Yield an item with Python Bottle doesn't work
downvote count: 0
upvote count: 1
tagged with: python
has body: When using: from bottle import route, run, request, view N = 0 def yielditem(): global N for i in range(100): N = i yield i @route('/') @view('index.html') def index(): print yielditem() print N run(host='localhost', port=80, debug=False) the page index.html is successfully displayed, but the yield part is not working: N stays always at 0, for every new request print yielditem() gives &lt;generator object yielditem at 0x0000000002D40EE8&gt; How to make this yield work normally in this Bottle Python context? What I expect is: 0 should be printed at the first request, 1 should be printed at the second request, etc.
tagged with: yield
has answer: http://stackoverflow.com/a/50439758
tagged with: generator
type: AnsweredQuestion

http://stackoverflow.com/comment/87791946
type: QuestionComment
comment on: http://stackoverflow.com/q/50387606
score: 0
has text: @Code-Apprentice Wow, exactly what I am looking for.
type: Comment

http://stackoverflow.com/comment/87993447
comment on: http://stackoverflow.com/q/50490095
type: Comment
type: QuestionComment
score: 0
has text: How are you initializing `curses`? (To be clear, if I just do `import curses; w = curses.initscr()` within a `screen` session, I can still Ctrl+A, D just fine.)

http://stackoverflow.com/comment/87923915
comment on: http://stackoverflow.com/a/50454396
type: Comment
has text: sorry if I'm being a bother, but could you explain how the slices work for the array indices? I'm not familiar with them and looking them up hasn't clarified what you're doing with them here unfortunately
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87868054
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50426629
has text: It just started giving me this warning: `libpng warning: iCCP: known incorrect sRGB profile` This might be the error?

http://stackoverflow.com/a/50538264
type: Answer
has comment: http://stackoverflow.com/comment/88088448
answers question: http://stackoverflow.com/q/50538213
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88088533
has body: Making a change to a module object (such as adding or modifying values in its global namespace) doesn't change its hash value. So while it's not immutable by any normal definition, it's "value" for hashing purposes is its identity, which is immutable. So you can indeed use a module object as a key for a dictionary. You can also use instances of custom classes, like this one: class Example: pass # no __hash__ or __eq__ defined obj = Example() d = {obj: "this works"} print(d) obj.foo = "the attributes of obj don't matter for the hash" d[obj] = "so this overwrites the previous value in the dict" print(d)
has comment: http://stackoverflow.com/comment/88088517
accepted answer of: http://stackoverflow.com/q/50538213

http://stackoverflow.com/comment/112244035
comment on: http://stackoverflow.com/a/53565297
has text: This will load the entire dataset into your driver which may not be desired.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/88065864
has text: Please consider removing the blanket try/except from the code in the answer. It is a Python antipattern which would be a good idea to avoid advertising.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50526198

http://stackoverflow.com/q/50431401
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87877382
score: 1
tagged with: arrays
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87877422
possible better answer: http://stackoverflow.com/a/50446390
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87877634
has comment: http://stackoverflow.com/comment/87877885
tagged with: python
accepted answer: http://stackoverflow.com/a/50431882
has title: The decomposition and collection of back images to pieces 100x100 python
tagged with: image
has body: I have array of image, and I need to decompose it on pieces 100x100 and after manipulations with it collect back in original image. Problem: I can't collect pieces back, I have something like this, but real image is 800x800 My code: get img as array, remove third dimension path_to_image = './la3.jpg' image_array = plt.imread(path_to_image) image_array = image_array[:, :, 0] write in new array pieces 100x100 (work fine): main2_array = np.zeros(10000,) for row in tqdm_notebook(range(0,8)): for col in range(0,8): main2_array = np.vstack((main2_array, image_array[0 + (100*row):100 + (100*row) ,0 + (100*col):100 + (100*col)].flatten())) main2_array = np.delete(main2_array, main2_array[0] , axis=0 ) collect pieces back(It's not working) main_array = np.zeros(100,) for p in tqdm_notebook(range(0,100)): for i in range(0,64): main_array = np.vstack((main_array, main2_array[0 + (10000*i) + (100*p): 100 + (10000*i) + (100*p)])) main_array = np.delete(main_array, main_array[0] , axis=0 ) After collecting pieces I get
has answer: http://stackoverflow.com/a/50431882
has answer: http://stackoverflow.com/a/50446390
tagged with: numpy

http://stackoverflow.com/q/50471730
has comment: http://stackoverflow.com/comment/87957831
has comment: http://stackoverflow.com/comment/87957647
has comment: http://stackoverflow.com/comment/87957824
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87957131
linked to: http://stackoverflow.com/q/14087598
tagged with: python
has title: Can't pip install mysql
has comment: http://stackoverflow.com/comment/87957002
has comment: http://stackoverflow.com/comment/87958001
has comment: http://stackoverflow.com/comment/87957208
has comment: http://stackoverflow.com/comment/87958049
has comment: http://stackoverflow.com/comment/87957807
has comment: http://stackoverflow.com/comment/87957111
has body: I'm trying to connect to a mySQL server through python on a MacBook Pro, and I need to pip install mysql to continue. However when I run that command I get the following error: ModuleNotFoundError: No module named 'ConfigParser' --------------------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/jc/cn0mjt8s13jfb9w3f42qy27c0000gn/T/pip-install-viy629s3/MySQL-python/ Any ideas on how to get pass this would be greatly appreciated.
has comment: http://stackoverflow.com/comment/87957533
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87957246
has comment: http://stackoverflow.com/comment/87957838
downvote count: 0
has comment: http://stackoverflow.com/comment/87957408
tagged with: mysql
has comment: http://stackoverflow.com/comment/87957099
upvote count: 1
has comment: http://stackoverflow.com/comment/87956996
has comment: http://stackoverflow.com/comment/87957851
favorite count: 0
type: Question

http://stackoverflow.com/comment/88003934
comment on: http://stackoverflow.com/a/50495393
type: AnswerComment
type: Comment
score: 0
has text: Already tried that from a response in the comments above. Spits back that __dict__ is not an attribute of the MSG object

http://stackoverflow.com/a/50438931
answers question: http://stackoverflow.com/q/50396786
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50396786
downvote count: 0
type: AcceptedAnswer
has body: Figured it out. I didn't add my redirect uri to the list of authorized ones as the option doesn't appear if you set your app type to "Other". I set it to "Web Application" (even though it isn't) and added my redirect uri and that fixed it.

http://stackoverflow.com/q/50462469
answer count: 1
has comment: http://stackoverflow.com/comment/87938185
upvote count: 1
has comment: http://stackoverflow.com/comment/87938044
linked to: http://stackoverflow.com/q/3471461
accepted answer: http://stackoverflow.com/a/50463740
favorite count: 0
score: -1
type: Question
has answer: http://stackoverflow.com/a/50463740
downvote count: 2
tagged with: python
has title: How do I interrupt a infinite loop without using raw_input or Ctrl-C? Python 2.7
linked to: http://stackoverflow.com/q/510357
type: AnsweredQuestion
has body: I have seen other posts, and searched for a while and read documentation. But I cannot seem to understand the answers. Closest I got was the signal module, but the documentation confused me honestly. I need to break from a loop, without using raw_input, the Ctrl-C is perfect, except I need to change it to activate if the user clicks SPACE or ENTER. from time import sleep try: while True: print "I'm looping!" sleep(1) except KeyboardInterrupt: print "The loop has ended!" This loop would be perfect If i could just change the keys for the KeyboardInterrupt error.
has comment: http://stackoverflow.com/comment/87938048
linked to: http://stackoverflow.com/q/13207678
linked to: http://stackoverflow.com/q/11918999
linked to: http://stackoverflow.com/q/13180941

http://stackoverflow.com/q/50493319
has title: Python destroy only tkinter subclass widget
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88000029
tagged with: tkinter
type: UnansweredQuestion
tagged with: subclass
has comment: http://stackoverflow.com/comment/87999706
tagged with: python
has answer: http://stackoverflow.com/a/50496034
score: 0
has body: I wrote a subclass with tkinter widgets. In a for-loop i place few of them in a Frame. This Frame also contains a Label and a Entry. Now i want to destroy all of my subclass widgets but NOT the Label and the Entry. I tried it like this: for child in self.frame.winfo_children(): if child.winfo_class() == "???": [...] But I wasnt able to figure out what i have to use, so i will use ??? as a placeholder for this. I place them in a rule with this Code: db.execute("SELECT * FROM UsedSystems") rows = db.fetchall() i = 0 for row in rows: image_path = activepath+rows[i][0] name = rows[i][1] performance = rows[i][2] project = rows[i][3] date = rows[i][4] self.e10 = CustomWidget(self.frame, image_path, name, performance, project, date) self.e10.grid(row=1+i,column=0, columnspan=2) i+=1
tagged with: widget
answer count: 1

http://stackoverflow.com/comment/88092912
type: Comment
has text: I think you are using the same dict that contains Signature in your loop, so the first request goes OK, but the subsequent ones fail because the signature is wrong. Try printing `concatenated` on every iteration.
comment on: http://stackoverflow.com/q/50540475
score: 0
type: QuestionComment

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

http://stackoverflow.com/a/59887400
has comment: http://stackoverflow.com/comment/138468744
type: Answer
score: 0
has body: This is a warning that some step of your training process (other than the batch update) is unexpectedly slow. I get the same warning by training the same model in 2 separate instances of jupyter notebook. (But where only training 1 model at a time does not produce the warning.) Regarding your data generator. It could be causing the problem. If your batch size is very small, the batch update step could be much faster than the interim computations. This github issue illustrates examples of heavy cpu load, odd training settings (like extremely small batch size), and other possible triggers for the warning https://github.com/keras-team/keras/issues/5008
answers question: http://stackoverflow.com/q/50469757

http://stackoverflow.com/a/52498270
upvote count: 7
has body: A cleaner and faster way is to load the model directly from S3 through smart_open which is used by gensim.models.KeyedVectors.load() as well as gensim.models.KeyedVectors.load_word2vec_format(). AWS_ACCESS_KEY_ID = 'abc' AWS_SECRET_ACCESS_KEY = 'abc' url = 's3://' + AWS_ACCESS_KEY_ID + ":" + AWS_SECRET_ACCESS_KEY + "@bucket/file.model" wv = gensim.models.KeyedVectors.load(url) See examples on smart_open in the README: https://github.com/RaRe-Technologies/smart_open
downvote count: 0
type: Answer
score: 7
answers question: http://stackoverflow.com/q/50477192

http://stackoverflow.com/comment/87912576
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50449329
has text: Thank you, I don't know how didn't I find this page,, it works great :)
score: 0

http://stackoverflow.com/q/50495998
downvote count: 0
has body: I have a simple need but cannot find its simple solution. I have a matrix to plot, but I wish the row/columns to have given widths. Something looking like a blocked matrix where you tell block sizes. Any workaround with the same visual result is accepted. import matplotlib.pyplot as plt import numpy as np samplemat = np.random.rand(3,3) widths = np.array([.7, .2, .1]) # Display matrix plt.matshow(samplemat) plt.show()
favorite count: 0
type: Question
has title: Python matplotlib: how to let matrixplot have variable column widths
has answer: http://stackoverflow.com/a/50497682
tagged with: matplotlib
tagged with: imshow
tagged with: python
accepted answer: http://stackoverflow.com/a/50497682
score: 2
type: AnsweredQuestion
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/87818343
has text: There are several flavors of the DSVM available. Which one are you using here?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50399751

http://stackoverflow.com/comment/87879778
has text: `input()` always returns str though...
type: AnswerComment
comment on: http://stackoverflow.com/a/50432779
score: 0
type: Comment

http://stackoverflow.com/q/50479491
linked to: http://stackoverflow.com/q/43086715
type: Question
answer count: 0
has title: getting average RGB values of a drawn circle
type: UnansweredQuestion
has body: I have written a code that draws circles over an image using mouse clicks. The radius and centre of the circles drawn are stored in a .txt file. However, I want to add on another component into the text file;- the mean RGB value of the inside of the circles drawn. How do i go about doing that? I've seen another qs where the author recommends using a mask. (RGB average of circles) Is it possible to do so without adding a mask? import cv2 import numpy as np import math drawing = False colours=[(255,0,0),(0,255,0),(0,0,255),(204,0,204),(0,155,255),(0,223,255),(238,220,130), (255,79,79), (161,0,244),(32,178,170),(170,178,32)] def draw_circle(event, x, y, flags, param): global x1, y1, drawing, radius, num, img, img2,z,circleProps if event == cv2.EVENT_LBUTTONDOWN: drawing = True x1, y1 = x, y radius = int(math.hypot(x - x1, y - y1)) cv2.circle(img, (x1,y1), radius, (255, 0, 0), 1) elif event == cv2.EVENT_MOUSEMOVE: if drawing == True: a, b = x, y if a != x &amp; b != y: img = img2.copy() radius = int(math.hypot(a - x1, b - y1)) cv2.circle(img, (x1,y1), radius, (255, 0, 0), 1) elif event == cv2.EVENT_LBUTTONUP: drawing = False num += 1 radius = int(math.hypot(x - x1, y - y1)) z = (z + 1) % (len(colours) - 1) cv2.circle(img, (x1,y1), radius, colours[z], 1) #just need outer circle colour to be different print("rad:",radius) circleProps += "%d "%num + "%d "%x1 + "%d "%y1 + "%d \n"%radius cv2.circle(img, (x1, y1), 1, (0, 255, 0), -1) #draws centre of circle #font = cv2.FONT_HERSHEY_SIMPLEX font = cv2.FONT_HERSHEY_PLAIN cv2.putText(img, str(num), (x1 + radius, y1 + radius), font, 1, (200, 255, 155), 1, cv2.LINE_AA) img2 = img.copy() elif event == cv2.EVENT_RBUTTONUP: pass def handleKeyboard(): if cv2.waitKey(20) == 38: print ('38') if __name__ == "__main__": num = 0 z = 0 windowName = 'Drawing' circleProps ="Num | x1 | y1 | r \n" img = cv2.imread('image.jpg', cv2.IMREAD_COLOR) img2 = img.copy() cv2.namedWindow(windowName) cv2.setMouseCallback(windowName, draw_circle) while (Tr…
has comment: http://stackoverflow.com/comment/87972550
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/87972599
has comment: http://stackoverflow.com/comment/87973430
tagged with: python

http://stackoverflow.com/a/50474111
has body: import csv data = open("path_to_file.txt", 'r') reader = csv.reader(data) allRows = [tuple(row.split('\t')) for row in reader] You were close. And there's almost certainly another way to have csv split on tabs instead of commas if you'd rather go that route. EDIT: as @roganjosh said, you could just do import csv data = open("path_to_file.txt", 'r') reader = csv.reader(data, delimiter='\t')) allRows = [tuple(row) for row in reader]
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50474053
has comment: http://stackoverflow.com/comment/87961814
answers question: http://stackoverflow.com/q/50474053
type: Answer

http://stackoverflow.com/comment/87828136
has text: Welcome to StackOverflow. Your question is very broad. Please try to conentrate on a specific problem you have implementing a solution. Have a look at our guide [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and it will be much more likely that you get a useful answer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50406354

http://stackoverflow.com/q/50432450
tagged with: recursion
has answer: http://stackoverflow.com/a/50432569
score: 0
answer count: 1
has body: I'm trying using pyinstaller pyinstaller --onefile myfile.py to create a standalone python app, but keep getting a recursion limit error: for field, value in iter_fields(node): RecursionError: maximum recursion depth exceeded This is a rather common problem online (a few SO questions, google groups, open github issue), but none of the proposed solutions seem to work. I've tried increasing the recursion limit in the driver.spec file, downgrading to python 3.5... nothing seems to work. Is there a way to get this to work? More broadly, how can I create an executable that is cross-platform?
tagged with: macos
type: Question
has title: recursion error with pyinstaller
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
tagged with: python-3.6

raspberry-pi
tags question: http://stackoverflow.com/q/50473732
tags question: http://stackoverflow.com/q/50486441
tags question: http://stackoverflow.com/q/50464551
tags question: http://stackoverflow.com/q/50407547
type: Tag
tags question: http://stackoverflow.com/q/50496358
tags question: http://stackoverflow.com/q/50452025
tags question: http://stackoverflow.com/q/50501921
tags question: http://stackoverflow.com/q/50463788
tags question: http://stackoverflow.com/q/50428196
tags question: http://stackoverflow.com/q/50453231
tags question: http://stackoverflow.com/q/50471895
tags question: http://stackoverflow.com/q/50442253
tags question: http://stackoverflow.com/q/50449396
tags question: http://stackoverflow.com/q/50533105
tags question: http://stackoverflow.com/q/50447369
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/50494991
tags question: http://stackoverflow.com/q/50540547
tags question: http://stackoverflow.com/q/50495330
tags question: http://stackoverflow.com/q/50465924
tags question: http://stackoverflow.com/q/50497280
tags question: http://stackoverflow.com/q/50388069
tags question: http://stackoverflow.com/q/50403464
tags question: http://stackoverflow.com/q/50524141
tags question: http://stackoverflow.com/q/50524674
tags question: http://stackoverflow.com/q/50519995
tags question: http://stackoverflow.com/q/50461048

http://stackoverflow.com/q/50503356
type: Question
has title: Include CefPython library in setup.py
type: UnansweredQuestion
tagged with: cefpython
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50505320
tagged with: py2app
score: 1
downvote count: 0
answer count: 1
has body: I am working on packaging our Python app and Py2App on Mac is not including CefPython library which forms the basis of our app. From what I can see in the app contents, it includes the entire Python3 library, but not CEFPython. How can I add CefPython in setup.py? Currently, when I am generating the .app file and executing it, I get an error and Mac asks me if I want to open the console. I see nothing in install.log setup.py : """ This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup APP = ['Our_APP.py'] DATA_FILES = [] OPTIONS = {} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) Updated script This is a setup.py script generated by py2applet Usage: python setup.py py2app from setuptools import setup APP = ['20notes.py'] DATA_FILES = [] OPTIONS = {'packages':['cefpython3','objc']} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app','cefpython3'] ) Updated error : Traceback (most recent call last): File "setup.py", line 18, in &lt;module&gt; setup_requires=['py2app','cefpython3'], TypeError: None is not a string I have tried removing the comma, removing cefpython3 option, nothing works. Any idea. THank you.
favorite count: 0

http://stackoverflow.com/a/52242744
downvote count: 0
answers question: http://stackoverflow.com/q/50504053
type: Answer
score: 12
upvote count: 12
has body: axisbg is deprecated in matplotlib 2.0+ Use facecolor instead. https://matplotlib.org/api/api_changes.html

http://stackoverflow.com/comment/88022048
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50504920
type: AnswerComment
has text: This is very interesting on one side... on the other side: it doesn't help. `Py_LIMITED_API` isn't set, but type `Py_Buffer` is still not available...

http://stackoverflow.com/a/50457445
has comment: http://stackoverflow.com/comment/87949184
has body: By default the context_object_name is object_list Either you access your Posts list in template with object_list {% for post in object_list %} {{ post }} &lt;!-- with lowercase --&gt; {% endfor %} Or you change the context_object_name to post_list, so that way you will be able to access the post list with post_list in template class PostListView(ListView): model = Post context_object_name = 'post_list'
type: Answer
has comment: http://stackoverflow.com/comment/87951228
has comment: http://stackoverflow.com/comment/87932344
has comment: http://stackoverflow.com/comment/87929368
score: 1
answers question: http://stackoverflow.com/q/50457404
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87951319

http://stackoverflow.com/a/50510924
has body: Use groupby for looping by groups with ExcelWriter: with pd.ExcelWriter('file.xlsx') as writer: df.groupby('Region').apply(lambda x: x.to_excel(writer, sheet_name=x.name, index=False)) Alternative: with pd.ExcelWriter('file.xlsx') as writer: for i, x in df.groupby('Region'): x.to_excel(writer, sheet_name=i, index=False) If need remove Region column in output: with pd.ExcelWriter('file.xlsx') as writer: for i, x in df.groupby('Region'): x.drop('Region', axis=1).to_excel(writer, sheet_name=i, index=False)
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/88042436
has comment: http://stackoverflow.com/comment/88036012
answers question: http://stackoverflow.com/q/50510865
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87807442
type: Comment
comment on: http://stackoverflow.com/a/50395496
type: AnswerComment
score: 0
has text: You're right, sir ! I have just updated my answer to fix this problem.

http://stackoverflow.com/q/50411516
accepted answer: http://stackoverflow.com/a/50413008
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50413008
has body: I'm trying to teach myself Python and so created a dumb script to check a blogging website to check for new updates and then save metadata associated to the updates. If there are new posts, I open the previous metadata, append the new metadata, and then save. However, I find that quite often (can't figure out when it does and does not work), these updates produce an empty file, and I lose all the metadata. if new_post_count &gt; 0: file_name = 'all_posts' + user previous_posts = pickle.load(open(file_name, 'rb')) current_posts = get_posts(client, user, start_from_posts=0, total_posts=new_post_count) all_posts = previous_posts.extend(current_posts) f = open(file_name, 'wb') pickle.dump(all_posts, f) f.close() Looking at the forums, it might make more sense to use something else to save my data besides pickle (any suggestions?). Even if that's the case, I'd still like to know what I'm doing wrong here so I don't create the same mistake later.
has comment: http://stackoverflow.com/comment/87838454
tagged with: pickle
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: save
has title: Pickle (Python 3.6) Writes Empty File
answer count: 1
has comment: http://stackoverflow.com/comment/87838424

python-2.6
type: Tag
tags question: http://stackoverflow.com/q/50390643
tag name: python-2.6
tags question: http://stackoverflow.com/q/50485225
tags question: http://stackoverflow.com/q/50533225
tags question: http://stackoverflow.com/q/50451087
tags question: http://stackoverflow.com/q/50398492
tags question: http://stackoverflow.com/q/50446707
tags question: http://stackoverflow.com/q/50472727

http://stackoverflow.com/q/50421502
has comment: http://stackoverflow.com/comment/87867612
favorite count: 0
has comment: http://stackoverflow.com/comment/87858166
type: Question
has body: If have a list of different types of strings and from that I want to combine all the alphabetic strings in the list into one single value. For example: ['000000001', 'Aaron', 'Appindangoye', '26', '183', '84.8'] Here, I want to get Aaron Appindangoye together.
upvote count: 1
tagged with: python
score: -3
answer count: 1
accepted answer: http://stackoverflow.com/a/50421728
has comment: http://stackoverflow.com/comment/87858172
has title: Extract alphabetic strings values from a list in Python
has comment: http://stackoverflow.com/comment/87858265
tagged with: list
downvote count: 4
has answer: http://stackoverflow.com/a/50421728
type: AnsweredQuestion

http://stackoverflow.com/a/50430035
has body: Check out Python constructor and default value and "Least Astonishment" and the Mutable Default Argument Your issue is fundamentally similar to the issue described in the above linked issues. Also, when declaring a class, make it a subclass of object: class Vec4(object): class Matrix4(object): Finally, to address your particular issue, remove defaults for the initializer. For example, do something like this: class Matrix4(): def __init__(self, row1=None, row2=None, row3=None, row4=None): if row1 is None: row1 = Vec4() if row2 is None: row2 = Vec4() if row3 is None: row3 = Vec4() if row4 is None: row4 = Vec4() self.m_values = [row1,row2,row3,row4] Same goes for the default of ScaleMatrix argument m_scale: class ScaleMatrix(Matrix4): def __init__(self, m_scale = Vec4(1,1,1), *args, **kwargs):
downvote count: 0
answers question: http://stackoverflow.com/q/50429685
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/50455275
answers question: http://stackoverflow.com/q/50454871
has body: Here's an example of setting a simple FLASK serving REST API for a scikit model. import sys import os import time import traceback from flask import Flask, request, jsonify from sklearn.externals import joblib app = Flask(__name__) model_directory = 'model' model_file_name = '%s/model.pkl' % model_directory # These will be populated at training time clf = None @app.route('/predict', methods=['POST']) def predict(): if clf: try: json_ = request.json # query = get the payload from the json and feed it to your model prediction = list(clf.predict(query)) return jsonify({'prediction': prediction}) except Exception, e: return jsonify({'error': str(e), 'trace': traceback.format_exc()}) else: return 'no model here' if __name__ == '__main__': try: port = int(sys.argv[1]) except Exception, e: port = 80 try: clf = joblib.load(model_file_name) print 'model loaded' app.run(host='0.0.0.0', port=port, debug=True)
downvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50454871
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87990292
type: Comment
comment on: http://stackoverflow.com/q/50488300
score: 1
type: QuestionComment
has text: This is a perfectly fine question, I wonder where the down votes are coming from.

http://stackoverflow.com/a/50403928
has body: Your import parameters in the calls of read_csv() don't fit to your textfile. Your expected output will be in df by calling: df = pd.read_csv('C:/Working/dalal/MTO_11052018.DAT', skiprows=6, header=None) Line2 could be imported like: df_tr = pd.read_csv('C:/Working/dalal/MTO_11052018.DAT', skiprows=1, nrows=1, header=None)
type: Answer
has comment: http://stackoverflow.com/comment/87824149
has comment: http://stackoverflow.com/comment/87824183
answers question: http://stackoverflow.com/q/50403670
has comment: http://stackoverflow.com/comment/87823278
score: 0
has comment: http://stackoverflow.com/comment/87823458

http://stackoverflow.com/q/50539213
linked to: http://stackoverflow.com/q/50568409
tagged with: keras
has body: I'm especially interested in specificity_at_sensitivity. Looking through the Keras docs: from keras import metrics model.compile(loss='mean_squared_error', optimizer='sgd', metrics=[metrics.mae, metrics.categorical_accuracy]) But it looks like the metrics list must have functions of arity 2, accepting (y_true, y_pred) and returning a single tensor value. EDIT: Currently here is how I do things: from sklearn.metrics import confusion_matrix predictions = model.predict(x_test) y_test = np.argmax(y_test, axis=-1) predictions = np.argmax(predictions, axis=-1) c = confusion_matrix(y_test, predictions) print('Confusion matrix:\n', c) print('sensitivity', c[0, 0] / (c[0, 1] + c[0, 0])) print('specificity', c[1, 1] / (c[1, 1] + c[1, 0])) The disadvantage of this approach, is I only get the output I care about when training has finished. Would prefer to get metrics every 10 epochs or so.
tagged with: tensorflow
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50540584
score: 3
has answer: http://stackoverflow.com/a/50540584
tagged with: python
has title: Use tf.metrics in Keras?
tagged with: keras-2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50542015
answer count: 2
tagged with: wrapper
has answer: http://stackoverflow.com/a/50542015
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/87814356
type: AnswerComment
comment on: http://stackoverflow.com/a/50399183
type: Comment
has text: Can you edit your question to include a full "working" example script?
score: 0

http://stackoverflow.com/a/50513483
has comment: http://stackoverflow.com/comment/88074619
score: 0
answers question: http://stackoverflow.com/q/50502581
has body: It sounds like you want the y-coordinate on the PDF where the last line occurs. I don't believe PyPDF2 can do that. If you need x/y-coordinates you could use PyMuPDF. The following code uses PyMuPDF to print the y-coordinate of the last line. import json from tkinter import * import fitz # http://pymupdf.readthedocs.io/en/latest/ from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas root= Tk() root.geometry("100x100") def line_position(): read_pdf = fitz.open("test.pdf") num_page = read_pdf.pageCount print(num_page) page = read_pdf[num_page - 1] # http://pymupdf.readthedocs.io/en/latest/app2/#json data = json.loads(page.getText(output='json')) print(data) highest_y = -1 for block in data['blocks']: if 'lines' in block: for line in block['lines']: for span in line['spans']: if span['text'].strip(): print(span) highest_y = max((highest_y, span['bbox'][3])) print(highest_y) read_pdf.close() Button(root, text="PDF Last Line", command=line_position).pack() root.mainloop()
has comment: http://stackoverflow.com/comment/88058959
type: Answer

http://stackoverflow.com/comment/87951798
type: QuestionComment
has text: @CDNthe2nd Seems you are victim of a brittle absolute _xpath_. Update the question with the relevant _HTML_
score: 0
comment on: http://stackoverflow.com/q/50468629
type: Comment

http://stackoverflow.com/comment/88072771
type: Comment
comment on: http://stackoverflow.com/q/50515323
score: 0
type: QuestionComment
has text: S3 is a object store, not a file system, when a file is not complete transfer, it is not accessible/available. It also take time for S3 to sync the object index. I think the some of the answer explain the situation

http://stackoverflow.com/q/50478204
tagged with: eclipse
type: Question
tagged with: pydev
type: UnansweredQuestion
has title: I have downloaded eclipse and pydev, but I am unsure how to get install django
tagged with: django
tagged with: python
score: 0
answer count: 2
has body: I am attempting to learn how to create a website using python. I have been going off the advice of various websites including stackoverflow. Currently I can run code in eclipse using pydev, but I need to install django. I have no idea how to do this and I don't know who to ask or where to begin. Please help
has answer: http://stackoverflow.com/a/50478284
has answer: http://stackoverflow.com/a/50478352

http://stackoverflow.com/a/50441706
has body: Here's a really basic script to get you started with Flask server: from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/') def hello_world(): print(request.args) return jsonify(["Hello", "world"]) app.run(port=5001) request.args are the arguments to the request as a dictionary. You can do whatever you want with them, then return a JSON as shown. Flask installation instructions are here
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50441592
type: Answer
answers question: http://stackoverflow.com/q/50441592
score: 2

http://stackoverflow.com/q/50397137
has comment: http://stackoverflow.com/comment/87859058
possible better answer: http://stackoverflow.com/a/50397416
has title: Sorting based on frequency and position in python
has answer: http://stackoverflow.com/a/50397576
accepted answer: http://stackoverflow.com/a/50397576
has answer: http://stackoverflow.com/a/50397416
type: AnsweredQuestion
answer count: 3
upvote count: 1
has body: I tried this code for input 3 2 4 6 2 4 3 3 4 5 6 3 2 4 5 5 3 import collections numbers = input().strip().split(" ") counter = collections.Counter(numbers) sorted_list = sorted(counter.most_common(), key=lambda x: -x[1]) ans = [(v * n) for (v, n) in sorted_list] for i in ans: print(" ".join(i),end=" ") When I run this method sometimes I get... 3 3 3 3 3 4 4 4 4 2 2 2 5 5 5 6 6 (This is what I expect - first sort them based on frequency and then according to their order of appearance in the input) sometimes I get... 3 3 3 3 3 4 4 4 4 5 5 5 2 2 2 6 6 Essentially problem arises for same frequency numbers What am I doing wrong?
has comment: http://stackoverflow.com/comment/87810412
has answer: http://stackoverflow.com/a/50431545
score: 1
tagged with: python
favorite count: 0
type: Question
downvote count: 0

http://stackoverflow.com/comment/87945743
score: 0
has text: This below is I think the relevant HTML. One note, I am NOT getting any error if I simply enter a year into the above code instead of a variable attempts I have made. So, the selenium code works perfectly with actual values, just fails as above trying to pass a variable name into the code. [link] #SheetContentPlaceHolder_coaCaseSearch_ddlCaseYear [link]
comment on: http://stackoverflow.com/q/50458613
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88162861
comment on: http://stackoverflow.com/q/50528180
type: Comment
type: QuestionComment
has text: `os.path.join` supports an arbitrary number of arguments.
score: 0

http://stackoverflow.com/q/50498721
type: Question
has body: i am using Pycharm to write python code and all the time have to upload the code via WinSCP to the server. Is there a way to make this process easier?
downvote count: 3
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/50502463
favorite count: 0
tagged with: winscp
tagged with: python-3.x
tagged with: python-2.7
answer count: 2
tagged with: pycharm
has comment: http://stackoverflow.com/comment/88010297
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/77497120
has title: Connecting PyCharm to WinSCP

http://stackoverflow.com/comment/88045753
comment on: http://stackoverflow.com/q/50516002
type: QuestionComment
has text: Thanks! In the meantime, it will help! However, I know I ask a lot, but it there a way to do it in the python script also? Because if I add a path in the python script, I guess that won't be seen in the external tool, but it should from cdll.loadLibrary. Shouldn't it?
type: Comment
score: 0

http://stackoverflow.com/q/50532266
has body: I am trying to replicate the functionality of Statsmodels's weight least squares (WLS) function with Numpy's ordinary least squares (OLS) function (i.e. Numpy refers to OLS as just "least squares"). In other words, I want to compute the WLS in Numpy. I used this Stackoverflow post as reference, but drastically different R² values arise moving from Statsmodel to Numpy. Take the following example code that replicates this: import numpy as np import statsmodels.formula.api as smf import pandas as pd # Test Data patsy_equation = "y ~ C(x) - 1" # Use minus one to get ride of hidden intercept of "+ 1" weight = np.array([0.37, 0.37, 0.53, 0.754]) y = np.array([0.23, 0.55, 0.66, 0.88]) x = np.array([3, 3, 3, 3]) d = {"x": x.tolist(), "y": y.tolist()} data_df = pd.DataFrame(data=d) # Weighted Least Squares from Statsmodel API statsmodel_model = smf.wls(formula=patsy_equation, weights=weight, data=data_df) statsmodel_r2 = statsmodel_model.fit().rsquared # Weighted Least Squares from Numpy API Aw = x.reshape((-1, 1)) * np.sqrt(weight[:, np.newaxis]) # Multiply two column vectors Bw = y * np.sqrt(weight) numpy_model, numpy_resid = np.linalg.lstsq(Aw, Bw, rcond=None)[:2] numpy_r2 = 1 - numpy_resid / (Bw.size * Bw.var()) print("Statsmodels R²: " + str(statsmodel_r2)) print("Numpy R²: " + str(numpy_r2[0])) After running such code, I get the following results: Statsmodels R²: 2.220446049250313e-16 Numpy R²: 0.475486515775414 Clearly something is wrong here! Can anyone point out my flaws here? Am I miss understanding the patsy formula?
has comment: http://stackoverflow.com/comment/107802452
has comment: http://stackoverflow.com/comment/88078275
has comment: http://stackoverflow.com/comment/88080509
answer count: 0
tagged with: patsy
upvote count: 3
tagged with: least-squares
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/107808209
tagged with: statsmodels
score: 3
has comment: http://stackoverflow.com/comment/88080776
has title: Weighted Least Squares in Statsmodels vs. Numpy?
has comment: http://stackoverflow.com/comment/88078475
has comment: http://stackoverflow.com/comment/88080752
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88081341
has comment: http://stackoverflow.com/comment/88080002
linked to: http://stackoverflow.com/q/27128688
tagged with: python
has comment: http://stackoverflow.com/comment/88080741

http://stackoverflow.com/comment/87912145
has text: I think you'll need to step inside your sess.run - you're feeding a whole batch of images to the network and getting accuracy, confusion matrix in return (summing the confusion matrix). Is your batch_size = 1? If not, you need your session to return the predicted labels *in order* (so run it in one thread!), then you can use matplotlib or PIL to turn the RGB(?) data in the batch into .png or .jpg files, naming each file with its predicted label.
type: Comment
comment on: http://stackoverflow.com/q/50449114
type: QuestionComment
score: 0

http://stackoverflow.com/q/50523095
has title: how to add value or text to other level right above element using python
tagged with: python
has answer: http://stackoverflow.com/a/50524384
accepted answer: http://stackoverflow.com/a/50524384
has comment: http://stackoverflow.com/comment/88059390
tagged with: http://stackoverflow.com/tag/xml
has body: I got a question. how do i add or insert attribute value at the end of nodes in other element? Actually, i know how to do it but it's not my problem. I want to add each value of LinkResourceURI to the element Content located above Link element. please see example as following <?xml version="1.0" encoding="UTF-8" standalone="yes"?> BBBBBBBBBB CCCCCCCCCC DDDDDDDDDD and this is what i'm trying to code. import xml.etree.ElementTree as ET tree = ET.parse("c:\\TEST\\XML_data.xml") root = tree.getroot() for Story in root.findall('Story'): for XMLElement in Story.findall('XMLElement'): for ParagraphStyleRange in XMLElement.findall('ParagraphStyleRange'): for XMLElement_1 in ParagraphStyleRange.findall('XMLElement'): for CharacterStyleRange in XMLElement_1.findall('CharacterStyleRange'): for Rectangle in CharacterStyleRange.findall('Rectangle'): for PDF in Rectangle.findall('PDF'): for Link in PDF.findall('Link'): Link_URL = Link.get('LinkResourceURI') Link_count = len(PDF.findall('Link')) print(Link_count) if int(Link_count) >= 1 : for CharacterStyleRange in XMLElement_1.findall('CharacterStyleRange'): for Content in CharacterStyleRange.findall('Content'): Content.text = str(Content.text)+ '-----' + Link_URL + '-----' else : pass tree.write('C:\\test\\datafiles\\Link_test_result.xml') This result is what i need. BBBBBBBBBB C:/test/11l.aiC:/test/222.ai CCCCCCCCCC file:C:/test/333.ai DDDDDDDDDDfile:C:/test/444.ai There is no error, but this isn't what i want. it inserts all values into all Content node. Would you advise for me ?
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88059038
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88059642
has comment: http://stackoverflow.com/comment/88059837

http://stackoverflow.com/q/50540256
tagged with: python
has comment: http://stackoverflow.com/comment/88092216
score: 0
has title: python plotting a histogram from dataframe column
tagged with: pandas
has body: Looking to plot a histogram emanating from a dataframe, I seem to lack in transforming to a right object type that matplotlib can deal with. Here are some failed attempts. How do I fix it up? And more generally, how do you typically salvage something like that? import numpy as np import pandas as pd from matplotlib import pyplot as plt filter(lambda v: v &gt; 0, df['foo_col']).hist(bins=10) ---> 10 filter(lambda v: v > 0, df['foo_col']).hist(bins=100) AttributeError: 'filter' object has no attribute 'hist' hist(filter(lambda v: v &gt; 0, df['foo_col']), bins=100) ---> 10 hist(filter(lambda v: v > 0, df['foo_col']), bins=100) TypeError: 'Series' object is not callable
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50540485
type: UnansweredQuestion
tagged with: matplotlib

http://stackoverflow.com/comment/88071332
type: QuestionComment
comment on: http://stackoverflow.com/q/50529508
type: Comment
score: 0
has text: Firstly, you did provide an example, but you ought to explain a bit further exactly what you intend to accomplish, especially regarding the bit towards the end: "I need to match the result with this list" ... "and drop the element" ... Explaining why you need to do this will clear up the question a lot. Also, how much data are we talking about here? Do you really only need to match those few examples you gave? (Baroness, Lady, etc)

http://stackoverflow.com/comment/88110094
score: 0
type: Comment
has text: If you want to share your solution post it as an answer, do not put answers in questions.
type: QuestionComment
comment on: http://stackoverflow.com/q/50431537

http://stackoverflow.com/q/50403479
has body: I make a simple code: arr = [4, 9, 5, 3, 2, 10] kpmp = [] # Empty list to store the comparison for i in arr: if i&gt;0: x = 0 j = i while j&gt;=0: j-=1 if arr[i] &gt; arr[j]: x+=1 kpmp.append(x) print(kpmp) But, I got this error: Traceback (most recent call last): File "python", line 11, in &lt;module&gt; IndexError: list index out of range Which is this line if arr[i] &gt; arr[j]: The expected output I'd like to print is a list [0, 0, 1, 3, 4, 0] Explanation: arr = [4, 9, 5, 3, 2, 10] 1. 4 has nothing to compare so the result is 0 2. 9 > 4 the result is 0 3. 4 &lt; 5 &lt; 9 the result is 1 4. 3 &lt; 4 &lt; 5 &lt; 9 the result is 3 5. 2 &lt; 3 &lt; 4 &lt; 5 &lt; 9 the result is 4 6. Well, 10 is the greatest in the list so the result is 0 I got stuck here, kinda basic knowledge with Python, though. Thanks for your help!
has answer: http://stackoverflow.com/a/50403659
favorite count: 0
possible better answer: http://stackoverflow.com/a/50403510
has answer: http://stackoverflow.com/a/50403535
accepted answer: http://stackoverflow.com/a/50403579
has answer: http://stackoverflow.com/a/50403510
type: Question
has answer: http://stackoverflow.com/a/50403579
score: 3
has title: Comparing list elements
tagged with: python
tagged with: python-3.x
answer count: 4
type: AnsweredQuestion
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/50392381
tagged with: pymongo
has title: MongoEngine version for MongoDB 3.2.20
tagged with: mongoengine
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87936224
tagged with: python
has body: Our MongoDB version is to be upgraded to 3.2 from 3.0. This matrix shows we need PyMongo version to be 3.2 for working with mongodb 3.2. We will be upgrading PyMongo to 3.2. But not sure which MongoEngine version to move to. MongoEngine site says 3.2+ is not supported yet. Any inputs on which MongoEngine version to move to? Our current versions: MongoDB: 3.0 PyMongo: 2.8.1 MongoEngine: 0.8.7 Versions to upgrade to: MongoDB: 3.2.20 PyMongo: 3.2 MongoEngine: Not sure
has comment: http://stackoverflow.com/comment/87821194
answer count: 0
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/50410637
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50410625
answers question: http://stackoverflow.com/q/50410625
type: Answer
has body: Need convert return output to Series: def myfun(a, b): return pd.Series([a + b, a - b]) df'x', 'y' = df.apply( lambda row: myfun(row.a, row.b), axis=1) print (df) a b x y 0 1 4 5 -3 1 2 5 7 -3 2 3 6 9 -3
score: 2
upvote count: 2

http://stackoverflow.com/q/50421958
downvote count: 1
has comment: http://stackoverflow.com/comment/87858896
has answer: http://stackoverflow.com/a/50422282
has comment: http://stackoverflow.com/comment/88003749
has comment: http://stackoverflow.com/comment/87858969
score: 3
has body: Why do I have to return function in the else case? Can't I just apply the defined function because I have to only return the value of b and store it? def gcd_a(a,b): if a==0: return b else: gcd_a(b%a,a)
has title: returning values of function in python
has answer: http://stackoverflow.com/a/50421982
has comment: http://stackoverflow.com/comment/87858988
has answer: http://stackoverflow.com/a/50422212
answer count: 4
has comment: http://stackoverflow.com/comment/87858909
favorite count: 0
type: Question
upvote count: 4
tagged with: function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50422120
tagged with: python

http://stackoverflow.com/comment/88071542
has text: I'd suggest you to write a minimal (not) working example that people could eventually run, to see where the problem actually is.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50529820
score: 2

http://stackoverflow.com/q/50518388
has answer: http://stackoverflow.com/a/50546516
type: Question
has body: TL;DR: I want to save a foreign key using a CreateView class -- I can get my User groups to save, but not my own model objects. Context: I am writing a Django-App that deals with Groups, Posts, and Users. Post entries contain a foreign key for both Group and User (a post must belong to a group and a user). I want the user to be able to add a post to a group from the group page itself -- i.e. when they access the CreateView form for this new post, there should be no 'Group' field. My Problem: I want to save a new post object with a CreateView class with a behind-the-scenes insertion of the Group (from a slug) and User (from self.request.user). Usually, I use the form_valid() method to do this, and it works just fine for inserting the User object; however, I cannot figure out why my Group object won't save. Some other information: I know that I am able to successfully grab the Group object from the slug in the kwargs. I have assigned this object to the variable self.form_group in the get() method and I have confirmed the 'type' of the object is the correct instance of my Group class. I have tried 'getting' the Group object in the form_valid() method itself: still no luck. I have tried both the commented and uncommented blocks of code in the form_valid() method, respectively. Models: class Post(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'posts') title = models.CharField(max_length = 100,default = '') created_at = models.DateTimeField(auto_now = True) post_text = models.TextField() post_text_html = models.TextField(editable = False) group = models.ForeignKey(Group, on_delete = models.CASCADE, related_name = 'posts', null = True, blank = True) - class Group(models.Model): name = models.CharField(max_length = 255, unique = True) slug = models.SlugField(allow_unicode = True, unique = True) description = models.CharField(max_length = 5000, blank = True, default = '') description_html = models.TextField(editable = False, blank = …
answer count: 2
has answer: http://stackoverflow.com/a/50518583
linked to: http://stackoverflow.com/q/10382838
downvote count: 0
tagged with: database
tagged with: django
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50546516
favorite count: 0
type: AnsweredQuestion
tagged with: django-class-based-views
possible better answer: http://stackoverflow.com/a/50518583
score: 1
has title: Saving a Foreign Key (that isn't a User object) in Django using a CreateView
tagged with: django-models

http://stackoverflow.com/a/50416247
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50415666
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50415666
downvote count: 0
has body: I would use function decorator and logging module. Here is a simple and dirty example : import logging logging.basicConfig(level=logging.INFO) # decorator def logged(func): def wrapper(*args, **kwargs): try: logging.info("started '{0}', parameters : {1} and {2}". format(func.__name__, args, kwargs)) return func(*args, **kwargs) except Exception as e: logging.exception(e) return wrapper @logged def foo(val): print(val/2) if __name__ == "__main__": foo("a") Output : INFO:root:started 'foo', parameters : ('a',) and {} ERROR:root:unsupported operand type(s) for /: 'str' and 'int' Traceback (most recent call last): File "C:/Users/xxxx.py", line 9, in wrapper return func(*args, **kwargs) File "C:/Users/xxxx.py", line 17, in foo print(val/2) TypeError: unsupported operand type(s) for /: 'str' and 'int'

http://stackoverflow.com/a/50440264
has comment: http://stackoverflow.com/comment/87906550
has body: Use a comprehension with pd.value_counts pd.value_counts([ d.year for s, e in zip(df.StartDate, df.EndDate) for d in pd.date_range(s, e, freq='Y') ]).sort_index() 1990 2 1991 2 1992 2 1993 2 1994 2 1995 1 1996 1 1997 1 1999 1 2000 1 2001 1 dtype: int64 Alternate from functools import reduce def r(t): return pd.date_range(t.StartDate, t.EndDate, freq='Y') pd.value_counts(reduce(pd.Index.append, map(r, df.itertuples())).year).sort_index() Setup df = pd.DataFrame(dict( WarName=['fakewar1', 'examplewar', 'feuxwar2'], StartDate=pd.to_datetime(['01-01-1990', '05-01-1990', '05-07-1999']), EndDate=pd.to_datetime(['02-02-1995', '03-07-1998', '06-09-2002']) ), columns=['WarName', 'StartDate', 'EndDate']) df WarName StartDate EndDate 0 fakewar1 1990-01-01 1995-02-02 1 examplewar 1990-05-01 1998-03-07 2 feuxwar2 1999-05-07 2002-06-09
upvote count: 6
has comment: http://stackoverflow.com/comment/87906487
accepted answer of: http://stackoverflow.com/q/50440186
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50440186
has comment: http://stackoverflow.com/comment/87906672
has comment: http://stackoverflow.com/comment/87906457
score: 6
type: Answer

http://stackoverflow.com/comment/88018269
type: AnswerComment
has text: @vinsentparamanantham - Maybe some `)` is missing, edited solution is without `.assign`
comment on: http://stackoverflow.com/a/50491990
type: Comment
score: 0

http://stackoverflow.com/comment/88081648
has text: Oops, I meant: in the Post object that I am trying to create, the User successfully saves to it, but the Group (i.e. the one I have assigned to the variable self.form_group) doesn't.
comment on: http://stackoverflow.com/a/50518583
score: 0
type: AnswerComment
type: Comment

dataframe
tags question: http://stackoverflow.com/q/50475932
tags question: http://stackoverflow.com/q/50447138
tags question: http://stackoverflow.com/q/50467040
tags question: http://stackoverflow.com/q/50435854
tags question: http://stackoverflow.com/q/50437159
tags question: http://stackoverflow.com/q/50499475
tags question: http://stackoverflow.com/q/50452635
tags question: http://stackoverflow.com/q/50401045
tags question: http://stackoverflow.com/q/50400168
tags question: http://stackoverflow.com/q/50490540
tags question: http://stackoverflow.com/q/50470726
tags question: http://stackoverflow.com/q/50415407
tags question: http://stackoverflow.com/q/50462309
tags question: http://stackoverflow.com/q/50386509
tags question: http://stackoverflow.com/q/50395427
tags question: http://stackoverflow.com/q/50481372
tags question: http://stackoverflow.com/q/50521727
tags question: http://stackoverflow.com/q/50516390
tags question: http://stackoverflow.com/q/50457554
tags question: http://stackoverflow.com/q/50476327
tags question: http://stackoverflow.com/q/50399071
tags question: http://stackoverflow.com/q/50494976
tags question: http://stackoverflow.com/q/50456464
tags question: http://stackoverflow.com/q/50485911
tags question: http://stackoverflow.com/q/50492851
tags question: http://stackoverflow.com/q/50421509
tags question: http://stackoverflow.com/q/50494440
tags question: http://stackoverflow.com/q/50461905
tags question: http://stackoverflow.com/q/50511413
tags question: http://stackoverflow.com/q/50417234
tags question: http://stackoverflow.com/q/50517818
tags question: http://stackoverflow.com/q/50514138
tags question: http://stackoverflow.com/q/50393380
tags question: http://stackoverflow.com/q/50471846
tags question: http://stackoverflow.com/q/50412789
tags question: http://stackoverflow.com/q/50537493
tags question: http://stackoverflow.com/q/50491834
tags question: http://stackoverflow.com/q/50507750
tags question: http://stackoverflow.com/q/50485466
tags question: http://stackoverflow.com/q/50441804
tags question: http://stackoverflow.com/q/50503569
tags question: http://stackoverflow.com/q/50531308
tags question: http://stackoverflow.com/q/50534579
tags question: http://stackoverflow.com/q/50508473
tags question: http://stackoverflow.com/q/50455266
tags question: http://stackoverflow.com/q/50533030
tags question: http://stackoverflow.com/q/50494664
tags question: http://stackoverflow.com/q/50437846
tags question: http://stackoverflow.com/q/50418159
tags question: http://stackoverflow.com/q/50449088
tags question: http://stackoverflow.com/q/50468631
tags question: http://stackoverflow.com/q/50386772
tags question: http://stackoverflow.com/q/50455829
tags question: http://stackoverflow.com/q/50537266
tags question: http://stackoverflow.com/q/50533522
tags question: http://stackoverflow.com/q/50471397
tags question: http://stackoverflow.com/q/50530519
tags question: http://stackoverflow.com/q/50531921
tags question: http://stackoverflow.com/q/50532520
tags question: http://stackoverflow.com/q/50429038
tags question: http://stackoverflow.com/q/50531873
tags question: http://stackoverflow.com/q/50504354
tags question: http://stackoverflow.com/q/50523745
tags question: http://stackoverflow.com/q/50525864
tags question: http://stackoverflow.com/q/50391640
tags question: http://stackoverflow.com/q/50511318
tags question: http://stackoverflow.com/q/50415280
tags question: http://stackoverflow.com/q/50389096
tags question: http://stackoverflow.com/q/50476875
tags question: http://stackoverflow.com/q/50476392
tags question: http://stackoverflow.com/q/50521401
tags question: http://stackoverflow.com/q/50464684
tags question: http://stackoverflow.com/q/50529955
tags question: http://stackoverflow.com/q/50413291
tags question: http://stackoverflow.com/q/50417688
tags question: http://stackoverflow.com/q/50425248
tags question: http://stackoverflow.com/q/50449876
tags question: http://stackoverflow.com/q/50393604
tags question: http://stackoverflow.com/q/50430556
tags question: http://stackoverflow.com/q/50499628

http://stackoverflow.com/q/50519202
has comment: http://stackoverflow.com/comment/88050978
has comment: http://stackoverflow.com/comment/88076711
answer count: 2
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/88051025
linked to: http://stackoverflow.com/q/38276007
has comment: http://stackoverflow.com/comment/88050994
accepted answer: http://stackoverflow.com/a/50536600
has title: Compressing multiple nested `for` loops
tagged with: python
has comment: http://stackoverflow.com/comment/88051026
has comment: http://stackoverflow.com/comment/88051501
tagged with: design-patterns
has comment: http://stackoverflow.com/comment/88051140
possible better answer: http://stackoverflow.com/a/50521564
has answer: http://stackoverflow.com/a/50536600
has comment: http://stackoverflow.com/comment/88051435
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50521564
has comment: http://stackoverflow.com/comment/88056895
score: 0
has body: Similar to this and many other questions, I have many nested loops (up to 16) of the same structure. Problem: I have 4-letter alphabet and want to get all possible words of length 16. I need to filter those words. These are DNA sequences (hence 4 letter: ATGC), filtering rules are quite simple: no XXXX substrings (i.e. can't have same letter in a row more than 3 times, ATGCATGGGGCTA is "bad") specific GC content, that is number of Gs + number of Cs should be in specific range (40-50%). ATATATATATATA and GCGCGCGCGCGC are bad words itertools.product will work for that, but data structure here gonna be giant (4^16 = 4*10^9 words) More importantly, if I do use product, then I still have to go through each element to filter it out. Thus I will have 4 billion steps times 2 My current solution is nested for loops alphabet = ['a','t','g','c'] for p1 in alphabet: for p2 in alphabet: for p3 in alphabet: ...skip... for p16 in alphabet: word = p1+p2+p3+...+p16 if word_is_good(word): good_words.append(word) counter+=1 Is there good pattern to program that without 16 nested loops? Is there a way to parallelize it efficiently (on multi-core or multiple EC2 nodes) Also with that pattern i can plug word_is_good? check inside middle of the loops: word that starts badly is bad ...skip... for p3 in alphabet: word_3 = p1+p2+p3 if not word_is_good(word_3): break for p4 in alphabet: ...skip...
tagged with: loops
linked to: http://stackoverflow.com/q/9338052
favorite count: 0
type: Question

http://stackoverflow.com/q/50396560
tagged with: multithreading
tagged with: wait
tagged with: python
has comment: http://stackoverflow.com/comment/87818020
has comment: http://stackoverflow.com/comment/87812719
tagged with: python-2.7
tagged with: pyzmq
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87812381
linked to: http://stackoverflow.com/q/44071684
score: 1
has body: If I start a thread with start_new_thread, and have n independent functions that I want to run concurrently, I would do the following: def foo1(x): print "foo1" time.sleep(5) def foo2(x): print "foo2" time.sleep(1) func_list = [foo1,foo2] for k,j in enumerate(func_list): thread.start_new_thread(func_list[k],(1 ,)) Both functions have the exact same code, but both functions are also independent in that they send messages to independent ZMQ sockets (that in turn wait on a repsonse from an external API before sending back a message for processing within foo). foo1 might take 5 seconds to complete the processing depending on the resopnse time of the API and the size of the payload, hence the problem is that if I try to fire it again in a new thread while it is still processing, the ZMQ socket throws an exception (seen the git already, it's not a bug) So if foo1 is busy, foo2 is available, if foo2 is busy foo(n) might be available (up to foo15) so there are plenty of workers available. But how do I tell which function is busy, and if it's busy wait on it finishing, or if other workers available, use them instead? Remember I can't just spool up 15 threads of the same function because for all intents and purposes, they are independent. Can someone help, this is a very confusing problem I have created for myself. Thanks. EDIT @ martineau - I have list of sockets that I import, I wish I didn't have to do it but the API I use has no limit of http connections (within reason), but a limit on how many requests each one can handle. Hence more connections is the only way to more speed. The folowing is the setup for the job - I process 10 records at a time corresponding to the 10 connections I keep alive with the API. I just went with pooling the threads and will give up the ghost on making another thread run if one is busy (that's a bit too complicated), hence if one thread takes 5 seconds it will delay the next batch of 10. It's a compromise. import socket_handler_a, socket_handl…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87810494
has comment: http://stackoverflow.com/comment/87811680
type: UnansweredQuestion
upvote count: 1
has title: Threading independent functions and waiting on them finishing
linked to: http://stackoverflow.com/q/3033952

http://stackoverflow.com/a/50541664
upvote count: 1
score: 1
type: Answer
has body: Can be achieved by: tf.concat([tf.tile(tf.expand_dims(t,1), [1, tf.shape(t)[0], 1]), tf.tile(tf.expand_dims(t,0), [tf.shape(t)[0], 1, 1])], axis=2) Detailed steps: t = tf.placeholder(tf.int32, shape=[None, 2]) #repeat each row of t d = tf.tile(tf.expand_dims(t,1), [1, tf.shape(t)[0], 1]) #Output: #[[[1 2] [1 2]] # [[3 4] [3 4]]] #repeat the entire input t e = tf.tile(tf.expand_dims(t,0), [tf.shape(t)[0], 1, 1]) #Output: #[[[1 2] [3 4]] # [[1 2] [3 4]]] #concat f = tf.concat([d, e], axis=2) with tf.Session() as sess: print(sess.run(f, {t:np.asarray([[1,2],[3,4]])})) #Output #[[[1 2 1 2] #[1 2 3 4]] #[[3 4 1 2] #[3 4 3 4]]]
downvote count: 0
answers question: http://stackoverflow.com/q/50536721

http://stackoverflow.com/q/50477544
score: 0
has title: Python server can't access files with escaped characters in the URL
has comment: http://stackoverflow.com/comment/87970000
tagged with: python
has comment: http://stackoverflow.com/comment/87969036
has comment: http://stackoverflow.com/comment/87969944
type: Question
has comment: http://stackoverflow.com/comment/87969046
answer count: 0
type: UnansweredQuestion
has body: I have a python server for mp3 streaming. Using Twisted Matrix library. If I try to access the file a.mp3 it works normally. But this file, for example 衝.mp3 doesn't work, it says "File not found". This file name as URL escaped is %E8%A1%9D.mp3 but it can't access it. If I try to access it using unicode instead of the symbol, like this \u885d.mp3 it still says "File not found". Here is the code, notice that I had to put request.path = request.path.replace('%20', ' ') because that's the only way it can access a file that has spaces in the path. That shouldn't be the normal behaviour I believe. class playMP3(Resource): isLeaf = True def render_GET(self, request): this=urlparse.urlparse(request.path)#scheme,netloc,path,query root,ext=os.path.splitext(this.path) filename=os.path.basename(request.path) fileFolder=request.path.replace(filename,"") self.serverRoot=os.getcwd() print (request.path) if ext==".mp3": request.path = request.path.replace('%20', ' ') thisFile=File(self.serverRoot+request.path) return File.render_GET(thisFile,request) resource = playMP3() factory = Site(resource) reactor.listenTCP(8880, factory) reactor.run() I also tried to put request.path = urllib.unquote(request.path) but instead of decoding it to 衝.mp3 it becomes ÞíØ.mp3. Weird.

http://stackoverflow.com/comment/87850324
type: Comment
has text: Heh fair question, but yes. I'm connecting to the database I have defined in `settings.py`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50417251
score: 0

http://stackoverflow.com/comment/88095336
score: 0
type: Comment
type: AnswerComment
has text: How do you want to handle them? For example `28:48.3` doesn't seem like date type data. Do you want to drop them or is there a specific year that these correspond to?
comment on: http://stackoverflow.com/a/50541615

http://stackoverflow.com/a/50395496
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87807442
has comment: http://stackoverflow.com/comment/87808028
answers question: http://stackoverflow.com/q/50395236
has comment: http://stackoverflow.com/comment/87807772
has body: I suggest you the following simple code: def syllables(word): vowels = ['a', 'e', 'i', 'o', 'u', 'y'] N = 0 previousLetterIsAVowel = False # Perform a loop on each letter of the word for i in word.lower(): if i in vowels: # Here it is a vowel # Indicate for the next letter that it is preceded by a vowel # (Don't count it now as a syllab, because it could belong to a group a vowels ending the word) previousLetterIsAVowel = True else: # Here: it is not a vowel if previousLetterIsAVowel: # Here it is preceded by a vowel, so it ends a group a vowels, which is considered as a syllab N += 1 # Indicate for the next letter that it is not preceded by a vowel previousLetterIsAVowel = False return N print(syllables("bureau")) # it prints 1 print(syllables("papier")) # it prints 2 print(syllables("ordinateur")) # it prints 4 print(syllables("India")) # it prints 1 I also provide a one-line style solution using regex, easily readable too if you know a little bit about regex. It simply counts the number of groups of consecutive vowels that are followed by a consonant: import re def syllables(word): return len(re.findall('[aeiouy]+[bcdfghjklmnpqrstvwxz]', word.lower()))
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87806965
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50395236

http://stackoverflow.com/comment/87925454
has text: maybe will help you this https://stackoverflow.com/questions/39190910/nosuchelementexception-unable-to-locate-element?rq=1
type: QuestionComment
comment on: http://stackoverflow.com/q/50455943
type: Comment
score: 0

http://stackoverflow.com/comment/88097040
has text: Hey, thanks a ton for the response. It worked. Adding an update in the question about the same.
score: 0
comment on: http://stackoverflow.com/a/50532439
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87832277
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50408357
has text: `*` means *zero or more*. For *zero up to a maximum of 50* use `{,50}` in place of `*`.
score: 0

http://stackoverflow.com/q/50423272
has comment: http://stackoverflow.com/comment/87861414
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50423736
score: 5
accepted answer: http://stackoverflow.com/a/50423736
has title: Pausing/Resuming script execution?
upvote count: 6
tagged with: python
has body: I'm trying to find a way to pause a script's execution (one that is not timeout) that would allow me to e.g. check variable values at that point, input additional commands from the command line and then resume the execution once I'm ready. In IDL (from which I switched to Python very recently) I was able to do that by including "stop" at the chosen code line and then typing ".cont". Does something similar exist in Python? Many thanks in advance for the help! (This is my first post here, so I hope the above description meets the standards but if not I'd welcome any critical feedback!)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87862710

http://stackoverflow.com/q/50441501
linked to: http://stackoverflow.com/q/328851
score: 0
has body: Suppose the following code: class Person(): def __init__(self,name): self.name = name class Student(Person): pass class Teacher(Person): pass John = Student('John') Tom = Student('Tom') Victor = Teacher('Victor') After the script is run, class Person is aware of its subclasses through In [22]: Person.__subclasses__() Out[22]: [__main__.Student, __main__.Teacher] How to find all instances of class Student like: Student.__instances__() AttributeError: type object 'Student' has no attribute '__instances__'
duplicate of: http://stackoverflow.com/q/328851
has title: Find instances of a particular class
linked to: http://stackoverflow.com/q/12101958
duplicate of: http://stackoverflow.com/q/12101958
type: Question
has comment: http://stackoverflow.com/comment/87897313
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87897482
has comment: http://stackoverflow.com/comment/87897387

http://stackoverflow.com/q/50417795
has comment: http://stackoverflow.com/comment/87851381
has comment: http://stackoverflow.com/comment/87851298
score: 0
has comment: http://stackoverflow.com/comment/87857267
answer count: 0
has comment: http://stackoverflow.com/comment/87851316
type: Question
has body: I want to move the cursor position from current position to given (X,Y), in a given time. I tried this way- import win32api as api import win32gui as gui import time import math def moveMouse(x,y): api.SetCursorPos((x,y)) def move_slowly(x2,y2,total_time): x0, y0 = api.GetCursorPos() draw_steps = int(math.sqrt(math.pow(x0-x2,2) + math.pow(y0-y2,2))) dx = (x2-x0)/draw_steps #how much x to move each step dy = (y2-y0)/draw_steps #how much y to move each step dt = total_time/draw_steps #time between each step for n in range(draw_steps): x = int(x0+dx*n) y = int(y0+dy*n) moveMouse(x,y) time.sleep(dt) But the time is always a bit off. I heard that it could be done using autopy, but no matter how i try- i couldn't download that library. any help?
linked to: http://stackoverflow.com/q/39626215
tagged with: python
has comment: http://stackoverflow.com/comment/87861390
type: UnansweredQuestion
has title: python smoothly move cursor position
tagged with: cursor

http://stackoverflow.com/comment/88009153
has text: @Math There is no event that happens when the values of an EntryBox value is changed. If there was it could be possible to call the method, but it isn't possible as it require's an event.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50497977

http://stackoverflow.com/a/50472019
answers question: http://stackoverflow.com/q/50468807
has body: I got around by creating new FileSystemModel and Root for each tab
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50468807
type: AcceptedAnswer

http://stackoverflow.com/comment/87971268
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50478367
has text: This seems bug in CPython to me. They use PyDict_* API calls to access the dict, rather than the abstract PyMapping_* calls - therefore, they shouldn't allow to set `__dict__` to a subclass in the first place.

http://stackoverflow.com/q/50442336
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87925347
tagged with: python
has comment: http://stackoverflow.com/comment/87928173
linked to: http://stackoverflow.com/q/56626011
linked to: http://stackoverflow.com/q/49959449
has comment: http://stackoverflow.com/comment/88010527
tagged with: python-xarray
score: 0
answer count: 0
tagged with: netcdf
tagged with: gam
has comment: http://stackoverflow.com/comment/103729391
type: Question
tagged with: facebook-prophet
has title: applying a generalized additive model to an xarray
has body: I have a netCDF file which I have read with xarray. The array contains times, latidude, longitude and only one data variable (i.e. index values) # read the netCDF files with xr.open_mfdataset('wet_tropics.nc') as wet: print(wet) Out[]: &lt;xarray.Dataset&gt; Dimensions: (time: 1437, x: 24, y: 20) Coordinates: * y (y) float64 -1.878e+06 -1.878e+06 -1.878e+06 -1.878e+06 ... * x (x) float64 1.468e+06 1.468e+06 1.468e+06 1.468e+06 ... * time (time) object '2013-03-29T00:22:28.500000000' ... Data variables: index_values (time, y, x) float64 dask.array&lt;shape=(1437, 20, 24), chunksize=(1437, 20, 24)&gt; So far, so good. Now I need to apply a generalized additive model to each grid cell in the array. The model I want to use comes from Facebook Prophet (https://facebook.github.io/prophet/) and I have successfully applied it to a pandas array of data before. For example: cns_ap['y'] = cns_ap['av_index'] # Prophet requires specific names 'y' and 'ds' for column names cns_ap['ds'] = cns_ap['Date'] cns_ap['cap'] = 1 m1 = Prophet(weekly_seasonality=False, # disables weekly_seasonality daily_seasonality=False, # disables daily_seasonality growth='logistic', # logistic because indices have a maximum yearly_seasonality=4, # fourier transform. int between 1-10 changepoint_prior_scale=0.5).fit(cns_ap) future1 = m1.make_future_dataframe(periods=60, # 5 year prediction freq='M', # monthly predictions include_history=True) # fits model to all historical data future1['cap'] = 1 # sets cap at maximum index value forecast1 = m1.predict(future1) # m1.plot_components(forecast1, plot_cap=False); # m1.plot(forecast1, plot_cap=False, ylabel='CNS index', xlabel='Year'); The problem is that now I have to 1)iterate through every cell of the netCDF file, 2)get all the values for that cell through time, 3)apply the GAM (using fbprophet), and then export and plot the results. The question: do you have any ideas on how to loop through the raster, get the index_values of each pixel for all times so t…

http://stackoverflow.com/q/50500057
favorite count: 0
has title: How to rearrange rows into columns in Pandas based on row groups
has answer: http://stackoverflow.com/a/50500373
type: Question
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: The problem I am having is if I have the following dataframe that has been sorted by the Customer Number and Date columns, how do get the dates for each customer and corresponding salaries into new columns one by one. df = pd.DataFrame({'Customer Number':[1,1,1,2,2,3,3,3], 'Date': [2013, 2014, 2015, 2016, 2017, 2013, 2014, 2015], 'Salaries': [100, 200, 200, 300, 300, 4000, 5000, 5000]}) produces: Customer Number Date Salaries 0 1 2013 100 1 1 2014 200 2 1 2015 200 3 2 2016 300 4 2 2017 300 5 3 2013 4000 6 3 2014 5000 7 3 2015 5000 For this problem, the output I am trying to obtain is something like the following: Customer Number Date 1 Salary 1 Date 2 Salary 2 Date 3 Salary 3 0 1 2013 100 2014 200 2015 200 1 2 2016 300 2017 300 NaN NaN 2 3 2013 4000 2014 5000 2015 5000 I have tried using pivot tables to arrange this data and numpy for reshaping the table but can't quite manage to get the new columns for dates and salaries in this way. I was hoping there would be a nice and simple solution to this but couldn't manage to find it. I'd really appreciate any help with this problem.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88013197
score: 2
upvote count: 2
tagged with: pivot
linked to: http://stackoverflow.com/q/27842613
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/88052064
type: QuestionComment
comment on: http://stackoverflow.com/q/50519798
score: 1
has text: You could use `del your_deque[index]`.
type: Comment

http://stackoverflow.com/q/50397805
has title: how to select check in and check out using webdriver
has answer: http://stackoverflow.com/a/50404269
tagged with: webdriver
downvote count: 0
upvote count: 1
answer count: 1
tagged with: selenium
has body: I'm trying to scrape the "Booking.com" website but i can't get the price since i can't force the code below to chose a date in the date field , i used the same method that i use to send the town field to send the date field . I managed this code as below : import re import time import csv from datetime import datetime from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup from bs4.element import Tag CITIES=["Bordeaux,france"] driver = webdriver.Chrome() for city in CITIES: driver.get("https://www.booking.com/") driver.find_element_by_css_selector("#ss").send_keys(city) # Enter City Name # Wait until autosuggestion come and click on first suggestion WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.XPATH, '//*[@id="frm"]/div[2]/div/div[1]/ul[1]/li[1]'))) driver.find_element_by_xpath('//*[@id="frm"]/div[2]/div/div[1]/ul[1]/li[1]').click() check_in_time = datetime.fromtimestamp(int(time.time())).strftime("%Y-%m-%d") check_out_time = datetime.fromtimestamp(int(time.time()) + 604800).strftime("%Y-%m-%d") # Waits for Datetime widget and select check In date try: WebDriverWait(driver, 10).until(EC.element_to_be_clickable( (By.XPATH, '//*[@id="frm"]/div[3]/div/div[1]/div[1]/div[2]/div/div[2]/div[1]/div'))) except TimeoutException: driver.find_element_by_xpath('//*[@id="frm"]/div[3]/div/div[1]/div[1]/div[2]').click() WebDriverWait(driver, 10).until(EC.element_to_be_clickable( (By.XPATH, '//*[@id="frm"]/div[3]/div/div[1]/div[1]/div[2]/div/div[2]/div[1]/div'))) table = driver.find_elements_by_xpath('//*[@id="frm"]/div[3]/div/div[1]/div[1]/div[2]/' 'div/div[2]/div[2]/div[3]/div/div/div[1]/table//td') for x in table: if x.get_attribute("data-id") and datetime.fromtimestamp(int(x.get_attribute("data-id")[:-3])).strftime( "%Y-%m-%d") == che…
favorite count: 0
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
score: 1
tagged with: python

http://stackoverflow.com/q/50398398
upvote count: 1
tagged with: python
tagged with: logging
linked to: http://stackoverflow.com/q/13733552
has title: Python logging basicConfig to file and bash
has body: How can I set up the basic logging to write to a logfile and also print output to terminal? I use basicConfig to set up logging for modules and sub modules. Problem: If I use logging.basicConfig(filename=LOGFILE, …) there is no more terminal output from logging module. If I add another FileHandler for the logfile, this is only used by main module and not by sub modules, example: if __name__ == "__main__": logging.basicConfig( level=logging.DEBUG, format="%(name)s (%(lineno)s): %(message)s", filename=LOGFILE ) # add logfile formatter = logging.Formatter("%(name)s (%(lineno)s): %(message)s") logfile = logging.FileHandler(LOGFILE) logfile.setLevel("DEBUG") logfile.setFormatter(formatter) Using Python 2.7 Update Just found https://stackoverflow.com/a/13733863/1907997 but example is not working, no output on terminal or file: if __name__ == "__main__": logFormatter = "%(name)s (%(lineno)s): %(message)s" rootLogger = logging.getLogger() fileHandler = logging.FileHandler(LOGFILE) fileHandler.setFormatter(logFormatter) fileHandler.setLevel("DEBUG") rootLogger.addHandler(fileHandler) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter) consoleHandler.setLevel("DEBUG") rootLogger.addHandler(consoleHandler) Info for newer Python Version: . Since Python 3.3 logging.basicConfig() can take a keyword argument handlers https://stackoverflow.com/a/46098711/1907997
score: 1
has answer: http://stackoverflow.com/a/50398997
linked to: http://stackoverflow.com/q/13479295
favorite count: 0
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87815214
score: 1
type: Comment
has text: Possibly relevant: [blog post](https://markhneedham.com/blog/2015/05/21/python-unicodeencodeerror-ascii-codec-cant-encode-character-uxfc-in-position-11-ordinal-not-in-range128/). The guy even tried to parse names of FC Bayern Munich, so he probably run into exactly the same umlauts (Süle, Götze) (the \0xe4 is the umlaut 'ä').
type: QuestionComment
comment on: http://stackoverflow.com/q/50399673

http://stackoverflow.com/a/50511319
has comment: http://stackoverflow.com/comment/88042746
answers question: http://stackoverflow.com/q/50497442
type: Answer
has body: It should work fine if you follow the official installation instructions: http://snakemake.readthedocs.io/en/stable/getting_started/installation.html#installation-via-conda You need both -c bioconda and -c conda-forge in the installation command, because some dependencies come from conda-forge.
score: 0

http://stackoverflow.com/comment/87910186
has text: I updated my question.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50447107
type: Comment

http://stackoverflow.com/q/50399683
possible better answer: http://stackoverflow.com/a/50401997
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87816532
has answer: http://stackoverflow.com/a/50401997
answer count: 2
tagged with: pandas
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50400967
has title: Using Python to parse header string from a file with a unique header printing technique (.inp extension)
tagged with: header
tagged with: parsing
has answer: http://stackoverflow.com/a/50400967
favorite count: 0
has comment: http://stackoverflow.com/comment/87815663
type: Question
has body: I am looking to use Python to parse a dataframe from a file (for those who might've used, its SWMM model input / inp file). The file header is printed in a rather unique way which has made it very difficult to completely parse it. An example of the dataframe with the troublesome header) I am trying to read from the file is: ;; Param ;;Node Parameter Time Series Type ;;-------------- ---------------- ---------------- -------- 80408 FLOW 80408 FLOW 81009 FLOW 81009 FLOW 82309 FLOW 82309 FLOW The headers are not separated by tabs, or any fixed number of spaces. Also, for some headers when their length is too large, they occupy two vertical lines , while other headers only use one line. The widths are not fixed either, there are more than one such dataframes and they all vary in width. All I was able to do was grab the bottom-most line as header. with open(inp_fname, 'r') as f: for line in f: headers = re.split("\s{2,}", line.replace(';',"").strip())
has comment: http://stackoverflow.com/comment/87817184
tagged with: python
has comment: http://stackoverflow.com/comment/87815281

http://stackoverflow.com/comment/88531333
type: AnswerComment
comment on: http://stackoverflow.com/a/50493602
has text: @Gabriel my original solution is not effective, of course! I want you to find solution. Nobody know. I know. Stunt people sets "-" to me.
type: Comment
score: 0

http://stackoverflow.com/comment/88016087
score: 0
type: Comment
type: AnswerComment
has text: I believe you said "I want to be able to end / join the thread properly, because in the real-life case I'm solving, I want to terminate a network connection nicely." ... You have so many options for terminating your network connection ... making this thread a daemon doesn't prevent you from join it ...
comment on: http://stackoverflow.com/a/50501638

http://stackoverflow.com/q/50504278
has answer: http://stackoverflow.com/a/50504575
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88021170
answer count: 2
has body: This is the text I am referring to: ' High 4:55AM 1.3m Low 11:35AM 0.34m High 5:47PM 1.12m Low 11:40PM 0.47m First Light 5:59AM Sunrise 6:24AM Sunset 5:01PM Last Light 5:27PM ' Using Python and regex, I only want to capture: "High 4:55AM 1.3m Low 11:35AM 0.34" (which is the first part of the text, and ideally I'd like to capture it without the extra spaces). I've tried this regex so far: .{44} It manages to capture the group of text I want, which is the first 44 characters, but it also captures subsequent groups of 44 characters which I don't want.
type: UnansweredQuestion
upvote count: 6
has answer: http://stackoverflow.com/a/50504571
has title: How to only capture first group in regex?
tagged with: python
linked to: http://stackoverflow.com/q/1240504
tagged with: regex
has comment: http://stackoverflow.com/comment/88021045
score: 3
downvote count: 3
duplicate of: http://stackoverflow.com/q/1240504
has comment: http://stackoverflow.com/comment/88020953

http://stackoverflow.com/q/50531652
type: Question
linked to: http://stackoverflow.com/q/19843752
score: 0
has answer: http://stackoverflow.com/a/50646824
accepted answer: http://stackoverflow.com/a/50646824
answer count: 1
tagged with: python
tagged with: optimization
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88076119
has title: multiparametric optimization with scipy and experimental data
has body: I am doing some utility modeling but I got stuck when trying to optimize my objective function and I don't understand the problem. I have a utility function (1) that takes experimental data as arguments as well as two parameters (theta and phi) with which I want to optimize function (1). The function returns the optimal choice given aforementioned data and parameter combinations. The objective function (2) is basically a sum of squared residuals (SSE) which takes function (1) as an input and determines how well the optimal choice from function (1) performs against actual data. This is where things go wrong. I try to optimize function 2 in respects of parameters theta and phi. Here's the code: from scipy.optimize import minimize def costmixed(theta,phi,data): predictions = [] for trialNr,trialDat in data.iterrows(): predictions.append(mixed_model( trialDat['inv'],trialDat['mult'],trialDat['belMult'],theta,phi)) return np.sum(np.square(data['ret'] - np.array(predictions))) #returns sum of squared residuals. #initial guesses x0=[1000,0.5] sol=minimize(costmixed,x0,args=[data],bounds=bnds) And the subsequent errors I receive are: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-46-87cded55e0f8&gt; in &lt;module&gt;() 7 return np.sum(np.square(data['ret'] - np.array(predictions))) #returns sum of squared residuals. 8 ----&gt; 9 sol=minimize(costmixed,x0,args=[data],bounds=bnds) C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options) 448 elif meth == 'l-bfgs-b': 449 return _minimize_lbfgsb(fun, x0, args, jac, bounds, --&gt; 450 callback=callback, **options) 451 elif meth == 'tnc': 452 return _minimize_tnc(fun, x0, args, jac, bounds, callback=callback, C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\lbfgsb.py in _minimize_lbfgsb(fun, x0, args, jac, bounds, disp, ma…
tagged with: scipy

http://stackoverflow.com/q/50524674
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50984021
has answer: http://stackoverflow.com/a/50984021
type: AnsweredQuestion
score: 1
has body: I have a script which should append a row in google spreedsheet every 2 minutes. When i start the script it works well but after a some time I get following error: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } } Python Script import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('auth.json', scope) gc = gspread.authorize(credentials) wks = gc.open('sheet').sheet1 while True: #here is some other code and 2 minutes delay wks.append_row(["test", "test2"]) Auth.json { "type": "x", "project_id": "x", "private_key_id": "x", "private_key": "x", "client_email": "x", "client_id": "x", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "x" }
has title: raspberry pi python gspread OAuth 2 error
has answer: http://stackoverflow.com/a/51053654
tagged with: python
tagged with: gspread
favorite count: 0
type: Question
answer count: 2
tagged with: raspberry-pi
tagged with: oauth
possible better answer: http://stackoverflow.com/a/51053654
tagged with: oauth-2.0

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

http://stackoverflow.com/comment/88007013
type: Comment
has text: is it your problem, that it posts one line per tweet instead of posting many lines in one tweet from file up to a newline? if so, try to concatenate lines like `'\n'.join([line1, line2])` and then post those joined lines at once.
type: QuestionComment
comment on: http://stackoverflow.com/q/50496842
score: 0

http://stackoverflow.com/comment/87907574
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50447007
has text: before applying convexHull you should reduce the lines to their intersections

http://stackoverflow.com/a/51108267
accepted answer of: http://stackoverflow.com/q/50390337
type: Answer
answers question: http://stackoverflow.com/q/50390337
downvote count: 0
type: AcceptedAnswer
has body: its StandardScaler as because your spelling is incorrect so it produces error. if in future when you stuck in any problem then use dir function to see all methods and modules . for eg- print(dir(sklearn))
score: 3
upvote count: 3

http://stackoverflow.com/comment/88077311
has text: I'm really sorry for that. I'm new to StackOverflow and selenium and I think they are two different questions, maybe one for blocked element and another for window's redraw. But they all occur after minimized. I have explained my opinion to admin.Maybe I'm wrong and duplicate, but I don't mean to do so. Thanks for your patience and help anyway, I will check some info about the windows.
comment on: http://stackoverflow.com/a/50494694
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88034197
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50510919
has text: The two answers differ but in a single word. I wonder what's the difference between "can" and "should". <_<
type: Comment

http://stackoverflow.com/q/50466064
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50466210
accepted answer: http://stackoverflow.com/a/50466210
type: Question
has body: I am looking to generate a password in a new window (when a button is pressed) using tkinter with this code: import math, random, os, string, tkinter, tkinter as tk def generate_password(pass_len): symbols = "!$%^&amp;*()-_=+QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm" genpw = ''.join([symbols[math.floor(int(i) / 256 * len(symbols))] for i in os.urandom(pass_len)]) print(genpw) create = tkinter.Button(root, pady=2, height=3, text = "create password", command = generate_password) However, I encounter the following error: TypeError: generate_password() missing 1 required positional argument: 'pass_len' Any help is greatly appreciated.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87981086
score: -2
has comment: http://stackoverflow.com/comment/87945417
tagged with: python
tagged with: tkinter
upvote count: 0
has title: Missing positional argument "pw_len" when generating password in tkinter
downvote count: 2

http://stackoverflow.com/comment/87823718
score: 0
type: Comment
type: QuestionComment
has text: At an (admittedly cursory) glance, your code seems like a solid way to go about it. What problem are you having here?
comment on: http://stackoverflow.com/q/50404156

http://stackoverflow.com/comment/87989001
comment on: http://stackoverflow.com/a/50486615
score: 0
type: AnswerComment
has text: many thanks @Ali Yılmaz , i have another problem, how to avoid for example if we have another list where we have some same key : ['model', 'properties', 'resources', 'properties', 'cpu', 'default'] it's not the exact list and it will overwrite, how to update encapsulate dict in this case ?
type: Comment

http://stackoverflow.com/a/50501529
has comment: http://stackoverflow.com/comment/88051039
has comment: http://stackoverflow.com/comment/88049093
has body: If you want the function to manage this counting feature on its own, you would have to define a class, with your function as a member function with access to a member variable where you can store the counter value. E.g. sth like: class func_with_memory: # define your class i = 1 def write_to_ith_excelrow(self): print('i =', self.i) # replace by meaningful code you want to process self.i += 1 Once defined, you can use this class: In[1]: sms_to_xl = func_with_memory() # instantiate the class In[2]: sms_to_xl.write_to_ith_excelrow() # first call of member function i = 1 In[3]: sms_to_xl.write_to_ith_excelrow() # second call i = 2 In[4]: sms_to_xl.write_to_ith_excelrow() # third call i = 3
answers question: http://stackoverflow.com/q/50501299
has comment: http://stackoverflow.com/comment/88045762
has comment: http://stackoverflow.com/comment/88043950
type: Answer
has comment: http://stackoverflow.com/comment/88048922
has comment: http://stackoverflow.com/comment/88045490
score: 0

http://stackoverflow.com/a/50533071
has comment: http://stackoverflow.com/comment/88082756
has body: I'm gonna do this more of a code review... Your first line for x in range(1,10): shows that you want to create a loop to iterate through a sequence of code 9 times (10 - 1). With programming, counting starts from 0, instead of saying range(1,10), you can say range(0,9) or even range(9). This helps make it more readable (I read 9 faster than computing 10 - 1) Inside this main loop, you've added a lot of for loops... for y in range(1,2):. What this means is that it will iterate through the code indented once, as 2 - 1 is 1. Therefore this for loop is irrelevant and you can just simply use print('1'). If we simplify your code taking into account whats said above, we get: for x in range(9): print("1") print("2 4") print("3 6 9") print("4 8 12 16") print("5 10 15 20 25") print("6 12 18 24 30 36") print("7 14 21 28 35 42 49") print("8 16 24 32 40 48 56 64") print("9 18 27 36 45 54 63 72 81") Isn't that already much nicer and more readable. If you type this into python, it will produce the same result as the code you gave, thats because computationally it is the same, however in your method you have unnecessary steps as mentioned above. Taking this a step further.. Your code prints out this 'pyramid' 9 times. I think you want to print out this pyramid once, so therefore we will have to remove the initial for loop. What you want to for loop is what is printed. Because there is a pattern behind it, a relationship, you can create a for loop to do this for you. This also helps create a more general-case usability. (So instead of doing this until 9, 18, 27, you can do it until n*1, n*2, n*3 [also a checky hint of what you should for loop]). Hope this was helpful, comment if theres anything you dont understand! EDIT: I was just doing some random coding and I found a quite neat way of creating the same result (though it is quite confusing), just wanted to share... for k in [[(j+1)*i for j in range(i)] for i in range(1,11)]: print k
has comment: http://stackoverflow.com/comment/88079789
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50532857

http://stackoverflow.com/q/50488327
has comment: http://stackoverflow.com/comment/87992627
tagged with: python
has comment: http://stackoverflow.com/comment/87995148
tagged with: plot
has comment: http://stackoverflow.com/comment/87990613
score: 0
has comment: http://stackoverflow.com/comment/88020818
has answer: http://stackoverflow.com/a/50504807
has comment: http://stackoverflow.com/comment/87990926
has comment: http://stackoverflow.com/comment/87995248
has comment: http://stackoverflow.com/comment/87990588
has title: Python plt.contour colorbar
has body: I am trying to do a plot of a seismic wave using plt.contour. I have 3 arrays: time (x-axis) frequency (y-axis) amplitude (z-axis) This is my results so far: The problem is that I want to change the scaling of the colorbar: making a gradation and not having this white color when the amplitude is low. But I am not able to do so, even though I spent a lot of time browsing the doc. I read that plt.pcolormesh is not appropriate here (it is just working here because I am in a special case), but this what I want to get regarding to the colours and colorbar: This is the code I wrote: T = len(time[0])*(time[0][1] - time[0][0]) # multiply ampFFT with T to offset Z = abs(ampFFT)*(T) # abbreviation # freq = frequency, ampFFT = Fast Fourier Transform of the amplitude of the wave # freq, amFFT and time have same dimensions: 40 x 1418 (40 steps of time discretization x steps to have the total time. 2D because it is easier to use) maxFreq = abs(freq).max() # maxium frequency for plot boundaries maxAmpFFT = abs(Z).max()/2 # maxium ampFFT for plot boundaries of colorbar divided by 2 to scale better with the colors minAmpFFT = abs(Z).min() plt.figure(1) plt.contour(time, freq, Z, vmin=minAmpFFT, vmax=maxAmpFFT) plt.colorbar() plt.ylim(0,maxFreq) # 0 to remove the negative frequencies useless here plt.title("Amplitude intensity regarding to time and frequency") plt.xlabel('time (in secondes)') plt.ylabel('frequency (in Hz)') plt.show() Thank you for your attention! NB : In case you were wondering about plt.pcolormesh: the plot is completely messed up when I choose to increase the time discretization (here I split the time in 40, but when I split the time in 1000 the plot is not correct, and I want to be able to split the time in smaller pieces). EDIT: When I use plt.contourf instead of plt.contour I got this plot: Which is not really convincing either. I understand why the yellow colour takes so much space (it is because I set a low vmax), but I don't understand why there is still whi…
tagged with: fft
type: Question
tagged with: contour
has comment: http://stackoverflow.com/comment/87990300
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87994713
answer count: 1

http://stackoverflow.com/comment/100431860
has text: I think everything will work perfect but in my case while loading web page in intranet, browser does authentication via active directory and show my name on top right. While doing it via script I get HTML where clearly shown: " 401 - Unauthorized: Access is denied due to invalid credentials. "
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/54690666

http://stackoverflow.com/a/50495021
has body: You are right, that's a focus issue. It's impossible for the user to focus on a Frame, so you either have to do it for them by adding frame.focus() Or you can bind to something that is not going out of focus, like the root window: root.bind("&lt;Left&gt;", LeftTurn)
has comment: http://stackoverflow.com/comment/88005185
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50494824
has comment: http://stackoverflow.com/comment/88003632

http://stackoverflow.com/q/50485560
tagged with: python
has body: I'm currently utilizing selenium in my python script. As per the code below, I'm adding cookies to my driver, however, I have quite a lot of cookies already loaded into a txt file called cookies.txt (see below) which I'd like to also add. I'm looking for a way so that I can create something like: driver.add_cookie(cookies from text file). Any help is appreciated! Current add_cookies code: driver.add_cookie({"name": "__ibxl", "value": "1"}) What cookies.txt looks like: [ { "domain": ".nike.com", "expirationDate": 1552017842, "hostOnly": false, "httpOnly": false, "name": "__ibxl", "path": "/", "sameSite": "no_restriction", "secure": false, "session": false, "storeId": "0", "value": "1", }, { "domain": ".nike.com", "expirationDate": 1558353842, "hostOnly": false, "httpOnly": false, "name": "__ibxu", "path": "/", "sameSite": "no_restriction", "secure": false, "session": false, "storeId": "0", "value": "1", "id": 2 } ]
linked to: http://stackoverflow.com/q/61652777
has answer: http://stackoverflow.com/a/50485724
has comment: http://stackoverflow.com/comment/137055852
type: AnsweredQuestion
tagged with: python-3.x
has title: Python Selenium add_cookie from txt file
score: 0
answer count: 2
tagged with: selenium
has comment: http://stackoverflow.com/comment/87984258
has answer: http://stackoverflow.com/a/50485922
has comment: http://stackoverflow.com/comment/87984399
type: Question
tagged with: scripting
possible better answer: http://stackoverflow.com/a/50485922
accepted answer: http://stackoverflow.com/a/50485724

http://stackoverflow.com/comment/117327016
type: Comment
type: QuestionComment
score: 2
has text: Hello! Where you able to solve this issue?
comment on: http://stackoverflow.com/q/50397058

flask-sqlalchemy
tags question: http://stackoverflow.com/q/50429196
tags question: http://stackoverflow.com/q/50434115
tags question: http://stackoverflow.com/q/50509990
tags question: http://stackoverflow.com/q/50430508
tags question: http://stackoverflow.com/q/50490196
tags question: http://stackoverflow.com/q/50406015
tags question: http://stackoverflow.com/q/50461813
tags question: http://stackoverflow.com/q/50513219
type: Tag
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/50389847
tags question: http://stackoverflow.com/q/50489943
tags question: http://stackoverflow.com/q/50412525
tags question: http://stackoverflow.com/q/50459142
tags question: http://stackoverflow.com/q/50477793

http://stackoverflow.com/comment/88019875
comment on: http://stackoverflow.com/q/50503609
score: 0
type: Comment
type: QuestionComment
has text: It's still incontinuous after I correct the end position: elif event.type == MOUSEMOTION: if (drawing): start_position = event.pos end_position = (event.pos[0] + event.rel[0], event.pos[1] + event.rel[1])

http://stackoverflow.com/q/50386736
score: 0
has body: In django models, I used models.MultipleChoiceField but i want that those variables in the set of choices to be linked to a textinput which will be saved into the django admin. So the user selects the choice then keys in a textbox and saves for that choice is that possible to implement?
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/87797585
has comment: http://stackoverflow.com/comment/87789211
linked to: http://stackoverflow.com/q/24403075
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50387869
has title: Connecting django multiple choice field with textinputs

http://stackoverflow.com/a/50475150
downvote count: 0
type: Answer
has body: In Python the % operator for formatting the older strings is an infix operator, it cannot work across function call syntax. For example, foo = "The string is %s, the number is %d" % ("doo", 5) In your code, your need to include the operator inside the parenthesis. print('The whole set of characters is %d %d %d %d %d %s %s %s' % (a[0],a[1],a[2],a[3][0],a[3][1],a[3][2],a[3][3],a[3][4])) Since your using python 3, and have a large number of fields in your format string, it might be more efficient to use the format() method of strings. This is where you can brace fields as names or indices, such as: &gt;&gt;&gt; "The count is {count}, the list is {lst}".format(count=5, lst=[1, 2]) 'The count is 5, the list is [1, 2]'
has comment: http://stackoverflow.com/comment/87964652
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50475029

http://stackoverflow.com/comment/88076712
score: 0
has text: @JoranBeasley: replacing `\n` by ` ` is not enough to do this; one seems to have to introduce `Paragraph` class, etc. so this question is different in the sense it asks if we have to introduce a layout system like `Paragraph` or if there are other options.
type: QuestionComment
comment on: http://stackoverflow.com/q/50532126
type: Comment

http://stackoverflow.com/a/50433324
answers question: http://stackoverflow.com/q/50431221
type: AcceptedAnswer
upvote count: 1
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50431221
score: 0
has body: Maybe this will help. You can find other splitting methods here: Is there a way to split a string by every nth separator in Python? from itertools import izip text = "I'm working on language model and want to count the number pairs of two consequent words.\ I found an examples of such problem on language model and want to count the number pairs" i = iter(text.split()) rdd = sc.parallelize([" ".join(x) for x in izip(i,i)]) print rdd.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y).collect() [('found an', 1), ('count the', 2), ('want to', 2), ('examples of', 1), ('model and', 2), ('on language', 2), ('number pairs', 2), ("I'm working", 1), ('consequent words.I', 1), ('such problem', 1), ('of two', 1)]

http://stackoverflow.com/q/50526074
tagged with: python
tagged with: unix
score: 0
has body: I have a python script in directory A which is pointed to by a symlink in another directory B. In my python script I have this code: import sys print(sys.path) When I execute the symlink on Unix, the system path contains directory A. When I execute the symlink on Windows, the system path contains the directory B. Why is this the case?
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88125733
has title: Is there a difference in how sys.path is populated when executing symlinks in Windows and Unix systems?
has comment: http://stackoverflow.com/comment/88766030
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/88090196

http://stackoverflow.com/q/50535073
has comment: http://stackoverflow.com/comment/88082213
has comment: http://stackoverflow.com/comment/88082365
has comment: http://stackoverflow.com/comment/88082604
has comment: http://stackoverflow.com/comment/88082171
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/88082149
has comment: http://stackoverflow.com/comment/88082263
has body: I'm trying to cleanup some data The dataframe currently look something like this: id data data2 0 12 NaN 50.0 1 12 a 50.0 2 12 a NaN 3 52 b NaN 4 52 NaN 20.0 5 52 NaN 20.0 I'd like to collapse the rows to remove duplicate entries and keep only what's valid grouping on ID in this specific case, disregarding NaNs and and up with: id data data2 0 12 a 50 1 52 b 20
has title: Pandas - Merge rows in a DataFrame
has comment: http://stackoverflow.com/comment/88082613
has answer: http://stackoverflow.com/a/50535167
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88082275
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50535167
linked to: http://stackoverflow.com/q/20067636
has comment: http://stackoverflow.com/comment/88082627
duplicate of: http://stackoverflow.com/q/20067636

http://stackoverflow.com/comment/87832911
type: Comment
type: QuestionComment
has text: Do you already know what kind of `update` statement you'd like to happen in the database?
comment on: http://stackoverflow.com/q/50408098
score: 0

http://stackoverflow.com/comment/87990521
type: QuestionComment
type: Comment
has text: Try `values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr[%s]/td[%s]" % (row, col)).text`
comment on: http://stackoverflow.com/q/50485017
score: 0

http://stackoverflow.com/comment/87962551
type: QuestionComment
comment on: http://stackoverflow.com/q/50472771
has text: @S.Davis, you are right, thank you for pointing that out. That would be the first of the two values. I will edit my question.
score: 0
type: Comment

http://stackoverflow.com/a/50489737
has body: This will pull out the elements you need, update the attribute values and dump the xml result: import xml.etree.ElementTree as Etree tree = Etree.parse("file.xml") root = tree.getroot() print(root) z = root.findall(".//*[@password]") for elm in z: elm.attrib['password'] = "Password" print(Etree.dump(root)) I could only test on 2.7.12 as it's the only version I have for python2. I would definitely recommend you upgrade if you can, but this should hopefully give you a point in the right direction if you can't.
score: 0
has comment: http://stackoverflow.com/comment/87992475
type: Answer
has comment: http://stackoverflow.com/comment/87992532
answers question: http://stackoverflow.com/q/50489585
has comment: http://stackoverflow.com/comment/87999159

http://stackoverflow.com/a/50404103
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/87823936
score: 0
accepted answer of: http://stackoverflow.com/q/50403338
has body: One way you can go about this is by designing a turtle cursor and stamping it. Cursors are drawn all at once and have more graphics operations at their disposal, like resizing, shear, etc. Here's a simple example using turtle's built in circle shape but you can just as easily design your own and register it as a cursor: RADIUS = 100 CURSOR_SIZE = 20 screen = Screen() screen.colormode(255) turtle = Turtle("circle", visible=False) turtle.speed('fastest') turtle.penup() turtle.pencolor(0, 255, 0) turtle.fillcolor(200, 125, 200) turtle.shapesize(RADIUS / CURSOR_SIZE, outline=5) turtle.stamp() turtle.goto(250, 250) turtle.shapesize(2 * RADIUS / CURSOR_SIZE, outline=10) turtle.stamp() screen.exitonclick()
answers question: http://stackoverflow.com/q/50403338

http://stackoverflow.com/q/50498481
tagged with: tensorflow
favorite count: 0
type: Question
has body: I have good knowledge in the theory of machine learning and neural networks however have a little of it when working with its code. Here i am using tensorflow along with python in order to implement a Multi-layer Perceptron in order to detect fraudulent transaction out from normal ones in a labeled credit card transactions dataset. I started up from a MLP sample built using tensorflow and edited it to fit my data however it seems that it couldn't recognize any fraudulent transaction after a 1000 epoch!!. Now I'm confused, and i couldn't figure out if the problem is in the training or in the output representation (I print out both of the accuracy and the precision at the end where i'm concerned about the precision much more since i have a highly unbalanced dataset where the accuracy will be mostly about 99% in such cases). I highly appreciate any help in the concept or even in the code if there is any problem in it. Below is my code and its corresponding output. import sys import os.path import pandas as pd import numpy as np import tensorflow as tf import sklearn as sk from datetime import datetime from sklearn.model_selection import train_test_split # Choose device from cmd line. Options: gpu or cpu device_name = sys.argv[1] if device_name == 'gpu': device_name = '/gpu:0' else: device_name = '/cpu:0' tf.device(device_name) print('Device used:' + str(device_name)) datasetCSVPath = sys.argv[2] parentPath = os.path.abspath(os.path.join(datasetCSVPath, os.pardir)) print(datasetCSVPath) print(parentPath) print('Reading dataset...') df = pd.read_csv(datasetCSVPath, index_col=False) print('Adding Class inverse column...') clsInv = [ 1 - row.Class for index, row in df.iterrows() ] df = df.assign(classInverse = clsInv) print('') print('Raw Data: \n------------------------------ \n') print(df.head()) print('') print('Whole dataset size: ' + str(len(df))) print('') print('Data Discription\n------------------------------ \n') print(df.describe()) print('') X = pd.DataFrame(df,…
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35155655
has answer: http://stackoverflow.com/a/50498933
tagged with: neural-network
tagged with: python
has answer: http://stackoverflow.com/a/50503836
has title: tensorflow MLP neural network not giving reasonable results
score: 0
answer count: 2
tagged with: backpropagation
tagged with: machine-learning
upvote count: 1
downvote count: 1

web3py
tags question: http://stackoverflow.com/q/50508444
type: Tag
tags question: http://stackoverflow.com/q/50527747
tag name: web3py

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

http://stackoverflow.com/comment/122283638
has text: @GEV How to do that?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/53664884
type: AnswerComment

http://stackoverflow.com/a/50494076
has body: Try using a list-comprehension and set: &gt;&gt;&gt; set([x for x in lst for y in lst if x+y == 90 and x != y]) {40, 50}
type: Answer
answers question: http://stackoverflow.com/q/50493901
score: 0

http://stackoverflow.com/comment/87994029
type: Comment
score: 0
type: AnswerComment
has text: Hello @Alasdair, I want to deploy django-channel on apache2 webserver using supervisord deamon but this package is not supporting from python 2.4, is there any alternatives available ? i also searched for monate but not fit with my configuration
comment on: http://stackoverflow.com/a/50490102

mysql
tags question: http://stackoverflow.com/q/50511640
tags question: http://stackoverflow.com/q/50429609
tags question: http://stackoverflow.com/q/50472092
tags question: http://stackoverflow.com/q/50468159
tags question: http://stackoverflow.com/q/50515397
tags question: http://stackoverflow.com/q/50529703
tags question: http://stackoverflow.com/q/50504502
type: Tag
tags question: http://stackoverflow.com/q/50517319
tags question: http://stackoverflow.com/q/50538774
tags question: http://stackoverflow.com/q/50416391
tags question: http://stackoverflow.com/q/50427076
tag name: mysql
tags question: http://stackoverflow.com/q/50469587
tags question: http://stackoverflow.com/q/50444618
tags question: http://stackoverflow.com/q/50476505
tags question: http://stackoverflow.com/q/50471730
tags question: http://stackoverflow.com/q/50409919
tags question: http://stackoverflow.com/q/50501409
tags question: http://stackoverflow.com/q/50492652
tags question: http://stackoverflow.com/q/50431179
tags question: http://stackoverflow.com/q/50449103
tags question: http://stackoverflow.com/q/50454068
tags question: http://stackoverflow.com/q/50535192
tags question: http://stackoverflow.com/q/50531183
tags question: http://stackoverflow.com/q/50480583
tags question: http://stackoverflow.com/q/50426615
tags question: http://stackoverflow.com/q/50421457
tags question: http://stackoverflow.com/q/50473386
tags question: http://stackoverflow.com/q/50468030
tags question: http://stackoverflow.com/q/50538481
tags question: http://stackoverflow.com/q/50426938
tags question: http://stackoverflow.com/q/50527732
tags question: http://stackoverflow.com/q/50510698
tags question: http://stackoverflow.com/q/50441180
tags question: http://stackoverflow.com/q/50401835
tags question: http://stackoverflow.com/q/50398982
tags question: http://stackoverflow.com/q/50400386
tags question: http://stackoverflow.com/q/50423665
tags question: http://stackoverflow.com/q/50413721
tags question: http://stackoverflow.com/q/50539758
tags question: http://stackoverflow.com/q/50536905
tags question: http://stackoverflow.com/q/50448894
tags question: http://stackoverflow.com/q/50514059

http://stackoverflow.com/comment/87983055
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50484937
score: 2
has text: How did you decide that country code should be US for the second item in the output?

http://stackoverflow.com/comment/87981997
comment on: http://stackoverflow.com/a/50472190
score: 0
has text: `if __name__== '__main__': soup = BeautifulSoup(open("C:/Users/usrname/Desktop/Pneus auto _ Michelin FR.html"), 'lxml') tyre_category = soup.find_all('div', class_='tyre') for category in tyre_category: tyre_name = category.img['alt'] tyre_season = category.find('span', class_='season-icon')['title'] url_for_tyre_details = category.find('a', class_='tyre-detail')['href'] print(tyre_name, tyre_season, url_for_tyre_details, sep=",") print()`#################### please check the formatted code above
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91057562
comment on: http://stackoverflow.com/a/52053099
type: Comment
has text: @GerhardBarnard Thanks for the advice. I added the relevant code snipped
type: AnswerComment
score: 0

http://stackoverflow.com/q/50410625
favorite count: 0
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50410700
tagged with: dataframe
tagged with: python
tagged with: apply
has answer: http://stackoverflow.com/a/50410637
has body: The following Python code works fine import pandas as pd df = pd.DataFrame(data = {'a': [1, 2, 3], 'b': [4, 5, 6]}) def myfun(a, b): return [a + b, a - b] df'x', 'y' = df.apply( lambda row: myfun(row.a, row.b), axis=1) The resulting pandas dataframe looks like: print(df) a b x y 0 1 4 5 -3 1 2 5 7 -3 2 3 6 9 -3 However, if I try to add two more columns, df'xx','yy' = df.apply(lambda row: myfun(row.a, row.b), axis=1) I get the error message, KeyError: "['xx' 'yy'] not in index" How come? And what is the correct way to do this? Many thanks! //A
answer count: 2
tagged with: pandas
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50410700
upvote count: 1
accepted answer: http://stackoverflow.com/a/50410637
has title: add multiple columns to pandas dataframe

http://stackoverflow.com/comment/102531571
comment on: http://stackoverflow.com/q/50534113
type: Comment
has text: Does anybody know how to make things like this happen? I also need to access Debugger2 interface from via pywin32.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87819091
type: AnswerComment
comment on: http://stackoverflow.com/a/50401373
has text: (...and more creative names that defy easy attempts at quoting are possible; consider the directory created by the command `mkdir $'$(rm -rf ~)\'$(rm -rf ~)\''`).
score: 0
type: Comment

http://stackoverflow.com/a/50458785
has body: You can't pass anything else than a string or a buffer of bytes through a socket. To do so you will have to serialize your value into a string or a buffer before passing it through the socket (sender side), and deserialize it later on (receiver side).
answers question: http://stackoverflow.com/q/50458723
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50458723
has comment: http://stackoverflow.com/comment/87931805

http://stackoverflow.com/comment/87800726
type: Comment
type: QuestionComment
has text: Updated, and it's line 24:
comment on: http://stackoverflow.com/q/50392322
score: 0

http://stackoverflow.com/a/50420419
upvote count: 1
score: 1
type: Answer
has body: The references stay around according to the normal python rules. The underlying widget objects are all destroyed when the root window is destroyed.
downvote count: 0
answers question: http://stackoverflow.com/q/50420219

http://stackoverflow.com/comment/87936224
type: QuestionComment
has text: Thanks for the response @OluwafemiSule. Moving from 0.8.7 to 0.15 is a big gap. Which intermediate version of mongoengine would you suggest that supports mongoDB v3.2 just like the latest version does?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50392381

http://stackoverflow.com/a/50433096
answers question: http://stackoverflow.com/q/50432901
has comment: http://stackoverflow.com/comment/87886866
score: 0
has comment: http://stackoverflow.com/comment/87882469
accepted answer of: http://stackoverflow.com/q/50432901
type: AcceptedAnswer
has body: If you really want to convert this code to a while-loop, you could always do something like this: def length_itr_whl(list): total = 0 i = 0 while list[i:i+1]: total = total + 1 i = i + 1 return total print length_itr_whl([1,2,3,4,5]) # prints 5 print length_itr_whl([]) # prints 0 This uses the list-slicing mechanism in Python and it does not require any try-block. When the indices are out of range the result will be [] (an empty list), which evaluates to False in Python. However, why don't you just use the built-in len-function in Python?
type: Answer

http://stackoverflow.com/comment/87880743
type: QuestionComment
comment on: http://stackoverflow.com/q/50432331
score: 0
has text: Possible duplicate of [Getting triplet characters from strings](https://stackoverflow.com/questions/50422077/getting-triplet-characters-from-strings)
type: Comment

http://stackoverflow.com/q/50471895
type: Question
answer count: 2
tagged with: raspberry-pi
score: 5
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50477494
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50477494
has comment: http://stackoverflow.com/comment/87957449
has comment: http://stackoverflow.com/comment/87960381
upvote count: 5
has body: I am trying to log data at with a high sampling rate using a Raspberry Pi 3 B+. In order to achieve a fixed sampling rate, I am delaying the while loop, but I always get a sample rate that is a little less than I specify. For 2500 Hz I get ~2450 Hz For 5000 Hz I get ~4800 Hz For 10000 Hz I get ~9300 Hz Here is the code that I use to delay the while loop: import time count=0 while True: sample_rate=5000 time_start=time.perf_counter() count+=1 while (time.perf_counter()-time_start) &lt; (1/sample_rate): pass if count == sample_rate: print(1/(time.perf_counter()-time_start)) count=0 I have also tried updating to Python 3.7 and used time.perf_counter_ns(), but it does not make a difference.
possible better answer: http://stackoverflow.com/a/50472499
has title: Inaccurate while loop timing in Python
favorite count: 0
has answer: http://stackoverflow.com/a/50472499

http://stackoverflow.com/a/50389013
has comment: http://stackoverflow.com/comment/87793933
has comment: http://stackoverflow.com/comment/87793908
downvote count: 1
has body: You need this: [tuple( i for i in range(1,10))] (i for i in something) notation is called Generator expression in Python and returns a generator object. You are simply, capturing this object in list. See PEP-289, for more knowledge on Generator Expressions Also, I am assuming, you plan to do much more than i for i in range(1,10), as this is completely redundant, you can just as well do [tuple(range(1,10))]
has comment: http://stackoverflow.com/comment/87793785
accepted answer of: http://stackoverflow.com/q/50388974
has comment: http://stackoverflow.com/comment/87793838
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50388974
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87795620
score: 0
has comment: http://stackoverflow.com/comment/87795751

http://stackoverflow.com/a/50441869
has body: I assumes there are just not enough primes in the given range 0 .. 49, so the break condition counter == args[1] never applies and the function returns None. It is better to pass all important parameters into a function and don't use hard coded constants, this make your functions more flexible. For a more efficient algorithm look at: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes def is_prime(a): for y in range(2, a): if a % y == 0: # the modulo operation finds the remainder after division return False return True # pass end condition into function, args[1] is a global variable def prime_func(max_value, max_prime_count=10): # you don't need a counter len(primes) do the same, also counter should start a 1 primes = [3] for x in range(4, max_value): if is_prime(x): primes.append(x) if len(primes) == max_prime_count: break # max prime count reached # calculates composites by set operation composites = set(range(2, max_value)) - set(primes) # also works if max_prime_count is not reached return sorted(composites), primes composites, primes = prime_func(50, 10) print(composites) print(primes) print(len(primes))
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50441421

http://stackoverflow.com/comment/88027505
comment on: http://stackoverflow.com/q/50506076
type: Comment
has text: The question is when do you want to render the plot? In your case (lots of data points) it is better to render the plot with matplotlib, and not store it as a vector graphic to be interpreted and rendered later (by the printer or PDF viewer). So your real question boils down to "How can I make matplotlib render the plot contents, but keep everything else as vector/text?" I would be intrigued to know if this is possible as well.
score: 0
type: QuestionComment

http://stackoverflow.com/q/50414913
favorite count: 0
score: 9
type: Question
upvote count: 9
answer count: 2
has title: Reenable urllib3 warnings
accepted answer: http://stackoverflow.com/a/50415180
tagged with: python
has body: I have a portion of my code where I knowingly make an Insecure Request. So I disable warnings with urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) After that part, how do I reenable/reset urllib3 warnings in my script?
possible better answer: http://stackoverflow.com/a/72049686
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/72049686
tagged with: urllib3
has answer: http://stackoverflow.com/a/50415180

http://stackoverflow.com/comment/87806415
type: QuestionComment
comment on: http://stackoverflow.com/q/50395249
type: Comment
score: 2
has text: You probably have a file in your current directory called "theano.py". Rename it.

http://stackoverflow.com/comment/87948001
type: Comment
type: AnswerComment
score: 0
has text: Great Rakesh ! That's what i want. I think the way i choose is wrong. i should have used string not parse.
comment on: http://stackoverflow.com/a/50466731

http://stackoverflow.com/q/50540807
type: AnsweredQuestion
score: 0
tagged with: exception
has answer: http://stackoverflow.com/a/50579105
tagged with: if-statement
has answer: http://stackoverflow.com/a/50541054
has comment: http://stackoverflow.com/comment/88159112
has title: How to avoid copying code to handle exceptions, undefined variables, & certain comparisons the same way
has body: I have a piece of code that fits each voxel in a data cube with a Gaussian plus a non-zero, sloping linear baseline. Each voxel is a spectrum of line+continuum emission that, depending on the location, can be pretty noisy and is known not to behave well at the edges of either the image or the spectral range. Therefore, sometimes it's necessary to fit the Gaussian and linear components separately in the parts of the spectra where each is most likely to occur, either because the original fit failed, or because the fitting parameters were nonsensical and I can see the line it failed to fit despite the noise. I'd skip straight to the piecewise version if I could, but the discontinuities can be problematic, not to mention it's generally a more costly procedure in terms of time and memory usage. So my situation is this: I want to have my program respond to multiple possible conditions, where some are exceptions (ValueError and RuntimeError) and the others are Boolean or relational conditions, with the same procedure. Can that be done? Right now I have two copies of the same procedure, one in the exception block and the other in the else block with an internal if-statement, and it's annoying the heck out of me. If I can't combine them, is there a way to reroute one or the other statement to the same block of code without defining a new function? Edit: I didn't originally include this because my attempts at reorganization were making a mess of my code at the time I wrote this. Now that I've kind of put it back together a bit (it's still a mess b/c each protocol corresponds to about 6 different cases of 3 different categories that are impossible to test for simultaneously as far as I know), here's the relevant parts of my code: if fitfn not in ['gauss','lorentz']: raise IOError("Fitting function name must be 'lorentz' or 'gauss'") cubedims=np.shape(cube) frames=np.array([(n,w) for n,w in enumerate(wvl) if (lc-0.2&lt;w&lt;lc+0.2)]) #^ 3 sigma is about 27% larger than 2 fwhm i…
tagged with: python
has comment: http://stackoverflow.com/comment/88167273
has comment: http://stackoverflow.com/comment/88093058
answer count: 2
has comment: http://stackoverflow.com/comment/88158960
accepted answer: http://stackoverflow.com/a/50579105
possible better answer: http://stackoverflow.com/a/50541054
linked to: http://stackoverflow.com/q/7969949
type: Question

http://stackoverflow.com/q/50537908
has body: I have installed spyder from source from its main page: Before this, I used brew to install some dependencies and pip3 as well for some anothers. I was able to open spyder from terminal just typing "spyder" but after I quit the terminal an re opened again I am now unable to doing this. The last option is to use Anaconda but, am I going to need to delete all the previos packages I previously have installed? is there any chance I can keep using spyder without installing conda? Thanks in advance
type: UnansweredQuestion
has title: Unable to open Spyder
has comment: http://stackoverflow.com/comment/88087826
tagged with: python
score: 0
tagged with: homebrew
tagged with: spyder
answer count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/50544147
has comment: http://stackoverflow.com/comment/88087931
has comment: http://stackoverflow.com/comment/88098555
type: Question
tagged with: terminal

http://stackoverflow.com/comment/87836376
has text: Another suggestion that I have - which are not directly related to your question though - is to use `f.write()` instead of `print(data, file=f)`. `f.write()` is more explicit and understandable at first than redirecting print to a file-like object.
type: AnswerComment
comment on: http://stackoverflow.com/a/50410571
type: Comment
score: 0

http://stackoverflow.com/comment/87795412
comment on: http://stackoverflow.com/a/50389960
score: 0
type: AnswerComment
has text: Unfortunatey, i've tried and get the same sort of error: No such file or directory: '~/drivers/chromedriver': '~/drivers/chromedriver'
type: Comment

http://stackoverflow.com/q/50389653
tagged with: python
answer count: 3
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50393065
has body: I have a problem here, I can't open ride.py in Python27 Before I try to open that, I have install this : 1. Python27 &emsp;I install this using installer package 2. Robot Framework &emsp; C:\Python27\python -m pip install robotframework 3. Selenium Library &emsp; C:\Python27\python -m pip install robotframework-selenium2library 4. wxPython &emsp; Download from here 5. RIDE &emsp; C:\Python27\python -m pip install robotframework-ride But when I open Ride using this syntax C:\Python27\Scripts\python ride.py It show this : C:\Python27\Scripts&gt;python ride.py Traceback (most recent call last): File "ride.py", line 20, in &lt;module&gt; from robotide import main ImportError: No module named 'robotide' How can I handle that? Thank you
downvote count: 0
has answer: http://stackoverflow.com/a/51059889
upvote count: 1
has answer: http://stackoverflow.com/a/50403727
has title: Can't Open Ride Python27
favorite count: 0
type: Question
tagged with: robotframework

http://stackoverflow.com/a/50396263
has body: I don't think if Regular expression is a proper choice for this problem. Instead you can extract all the 10 words surrounding a dollar sign buy looping over the words and keeping track of five previously traversed words to be returned whenever you find a match. In this case you can use collections.deque() which is a proper data structure with limited number of items to preserve five previous words. Then you can use a collections.Counter() object to return a counter of words within the threshold. from collections import deque from collections import Counter from itertools import chain def my_counter(string): container = deque(maxlen=5) words = iter(string.split()) def next_five(words): for _ in range(5): try: yield next(words) except StopIteration: pass for w in words: if w.startswith('$'): yield Counter(chain(container, next_five(words))) else: container.append(w) Demo: In [8]: s = ' extra1 extra2 I have a sentence with $10.00 within it and this sentence is done.asdf asdf a b c d e $5 k j n m k gg ee' In [9]: In [9]: list(my_counter(s)) Out[9]: [Counter({'I': 1, 'a': 1, 'and': 1, 'have': 1, 'it': 1, 'sentence': 2, 'this': 1, 'with': 1, 'within': 1}), Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'j': 1, 'k': 2, 'm': 1, 'n': 1})]
type: Answer
answers question: http://stackoverflow.com/q/50395461
score: 0

http://stackoverflow.com/a/50451001
answers question: http://stackoverflow.com/q/50439879
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50439879
downvote count: 0
type: AcceptedAnswer
has body: In simple.py, the helper.py was referenced, originally looking like this: import theano.tensor as T import lasagne from lasagne.layers import Layer from helper import ensure_set_name So I added a leading dot infront of helper like this: import theano.tensor as T import lasagne from lasagne.layers import Layer from .helper import ensure_set_name , and the complain is gone.
score: 3
type: Answer

http://stackoverflow.com/comment/87955249
type: Comment
type: QuestionComment
has text: I don't get the logic of your conversion. How are [e, v] and [e, m, s] subdicts of your dict?
comment on: http://stackoverflow.com/q/50470825
score: 0

http://stackoverflow.com/a/50398165
accepted answer of: http://stackoverflow.com/q/50398145
has body: Unix based paths In Unix-based systems, the directories in a path are usually separated with a forward slash (/). So we can simply rewrite it to: # Unix-based operating systems name = "some-name" myDir = os.path.join(BASE_DIR, 'first_scrapy/spiders/tmp/{}'.format(name)) Operating system independent solution If you however wish to write an application that works accross different operating systems, you can use os.path.join. For example: # works on "all" operating systems (well, those suported by the os module) name = "some-name" myDir = os.path.join(BASE_DIR, 'first_scrapy', 'spiders', 'tmp', name) Providing functionality accross the different operating systems is actually one of the main tasks the os module aims to handle.
type: Answer
has comment: http://stackoverflow.com/comment/87814182
has comment: http://stackoverflow.com/comment/87814343
has comment: http://stackoverflow.com/comment/87814304
has comment: http://stackoverflow.com/comment/87814143
has comment: http://stackoverflow.com/comment/87814196
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87814282
has comment: http://stackoverflow.com/comment/87814376
answers question: http://stackoverflow.com/q/50398145

http://stackoverflow.com/q/50455516
has comment: http://stackoverflow.com/comment/87924597
tagged with: progress-bar
tagged with: parallel-processing
linked to: http://stackoverflow.com/q/26520781
has answer: http://stackoverflow.com/a/66931989
tagged with: python
tagged with: multiprocess
upvote count: 11
has comment: http://stackoverflow.com/comment/87924525
favorite count: 0
score: 11
type: Question
has body: I added a progress bar to my 2.7 python code using tqdm but it has slowed down my code significantly. Without the progress bar for one example it takes 12 seconds while with the progress bar it takes 57 seconds. The code without the progress bar looks like this: p = mp.Pool() combs = various combinations result = p.map(self.parallelize, combs) p.close() p.join() The code with the progress bar is as follows: from tqdm import tqdm p = mp.Pool() combs = various combinations result = list(tqdm(p.imap(self.parallelize, combs), total = 5000)) p.close() p.join() Is there a better way that wouldn't slow down my code as much?
has comment: http://stackoverflow.com/comment/102193327
has title: progress bar slows down code by factor of 5 using tqdm and multiprocess
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: tqdm

http://stackoverflow.com/comment/87809686
comment on: http://stackoverflow.com/q/50396802
score: 0
type: Comment
type: QuestionComment
has text: @user2357112 I am using scons here, and I don't think I can change the default of the arg that is part of that module.

http://stackoverflow.com/q/50424196
has body: I am reading a tweeter feed in json format to read the number of users. Some lines in the input file might not be tweets, but messages that the Twitter server sent to the developer (such as limit notices). I need to ignore these messages. These messages would not contain the created_at field and can be filtered out accordingly. I have written the following piece of code, to extract the valid tweets, and then extract the user.id and the text. def safe_parse(raw_json): try: json_object = json.loads(raw_json) if 'created_at' in json_object: return json_object else: return except ValueError as error: return def get_usr_txt (line): tmp = safe_parse(line) if(tmp != None): return ((tmp.get('user').get('id_str'),tmp.get('text'))) else: return My challenge is that I get one extra user called "None" Here is a sample output (it is a large file) ('49838600', 'This is the temperament you look for in a guy who would have access to our nuclear arsenal. ), None, ('2678507624', 'RT @GrlSmile: @Ricky_Vaughn99 Yep, which is why in 1992 I switched from Democrat to Republican to vote Pat Buchanan, who warned of all of t…'), I am struggling to find out, what I am doing wrong. There is no None in the tweeter file, hence I am assuming that I am reading the {"limit":{"track":1,"timestamp_ms":"1456249416070"}} but the code above should not include it, unless I am missing something. Any pointers? and thanks for the your help and your time.
tagged with: python
has title: Parsing tweets in json format to find tweeter users
tagged with: twitter
accepted answer: http://stackoverflow.com/a/50424448
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50424448
tagged with: apache-spark
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/33383275
tagged with: pyspark
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/88049874
has text: I'm up for anything that works. Do you have an example based on the html structure? Thanks!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50517271

database
tags question: http://stackoverflow.com/q/50409097
tags question: http://stackoverflow.com/q/50537452
tags question: http://stackoverflow.com/q/50444618
tags question: http://stackoverflow.com/q/50535956
tags question: http://stackoverflow.com/q/50529909
tags question: http://stackoverflow.com/q/50506046
tags question: http://stackoverflow.com/q/50449103
tags question: http://stackoverflow.com/q/50480583
tags question: http://stackoverflow.com/q/50406015
tags question: http://stackoverflow.com/q/50426615
tags question: http://stackoverflow.com/q/50529703
tags question: http://stackoverflow.com/q/50497250
type: Tag
tags question: http://stackoverflow.com/q/50409212
tags question: http://stackoverflow.com/q/50522442
tags question: http://stackoverflow.com/q/50518388
tags question: http://stackoverflow.com/q/50454420
tags question: http://stackoverflow.com/q/50445870
tags question: http://stackoverflow.com/q/50503858
tags question: http://stackoverflow.com/q/50461448
tags question: http://stackoverflow.com/q/50407780
tags question: http://stackoverflow.com/q/50477948
tags question: http://stackoverflow.com/q/50529984
tag name: database

http://stackoverflow.com/q/50484946
has answer: http://stackoverflow.com/a/50485299
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87983228
has body: I am new to R and I need code for the following requirement: There are src and trg records like 1 matched with 2, 2-3,3-4. Now when I ask the system to provide link between 1 and 4 it should give me o/p as 1-2-3-4. When I ask the system to give link between 2 and 4 it should give 2-3-4 as o/p. Please help me with your valuable suggestions.
has title: how to get the links between two nodes using R or python
score: 0
answer count: 1
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/50485299
type: Question
tagged with: http://stackoverflow.com/tag/r

http://stackoverflow.com/a/50473569
type: Answer
has comment: http://stackoverflow.com/comment/87972896
answers question: http://stackoverflow.com/q/50473386
has body: Python is quite flexible for processing data, you may also convert your csv data to json using Pandas in python import pandas as pd df = pd.read_csv('filename.csv') df.to_json('jsonfilename.json') You can also store csv files in mysql by exporting them using python , please read http://www.vallinme.com/v1/?p=95 Petl is another library for such purpose.
score: 0

http://stackoverflow.com/a/50396971
has body: You should not use tbody tag in your XPath as it's actually not present in page source, but added by browser while page rendering. Just skip it: .../table[2]/tbody/tr[1]... -> .../table[2]//tr[1]...
type: Answer
has comment: http://stackoverflow.com/comment/87810206
answers question: http://stackoverflow.com/q/50396564
accepted answer of: http://stackoverflow.com/q/50396564
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2

http://stackoverflow.com/a/50468516
downvote count: 0
has comment: http://stackoverflow.com/comment/87950424
has comment: http://stackoverflow.com/comment/87950365
has body: Pandas has isnull, notnull, isna, and notna These functions work for arrays or scalars. Setup a = np.array([[1, np.nan], [None, '2']]) Pandas functions pd.isna(a) # same as # pd.isnull(a) array([[False, True], [ True, False]]) pd.notnull(a) # same as # pd.notna(a) array([[ True, False], [False, True]]) DataFrame (or Series) methods b = pd.DataFrame(a) b.isnull() # same as # b.isna() 0 1 0 False True 1 True False b.notna() # same as # b.notnull() 0 1 0 True False 1 False True
has comment: http://stackoverflow.com/comment/87950338
type: Answer
upvote count: 11
score: 11
has comment: http://stackoverflow.com/comment/87950627
answers question: http://stackoverflow.com/q/50468494

http://stackoverflow.com/q/50535941
type: Question
type: AnsweredQuestion
has title: Issue with python subprocess.check_output vs os.system
has body: So I'm trying to use the 'newer' subprocess to execute a fortran program in the bash shell... Not sure what I am doing wrong, but if I do result = os.system('./get_cpus -inp ./output_00076 -xc {:.4e} -yc {:.4e} -zc {:.4e} -rad {:.4e}'.format(loc[0],loc[1],loc[2],rad) ) I get the fortran program's output (from get_cpus) in result. Thinks seem to work fine... But if I do: result = subprocess.check_output(['./get_cpus', '-inp ./output_00076', '-xc {:.4e}'.format(loc[0]), '-yc {:.4e}'.format(loc[1]), '-zc {:.4e}'.format(loc[2]), '-rad {:.4e}'.format(rad)]) I get an error: ./get_cpus -inp ./output_00076 -xc 3.1670e-01 -yc 9.6000e-02 -zc 2.4170e-01 -rad 2.0360e-03 forrtl: severe (59): list-directed I/O syntax error, unit -5, file Internal List-Directed Read Image PC Routine Line Source get_cpus 0000000000409CD8 Unknown Unknown Unknown get_cpus 000000000042AF2D Unknown Unknown Unknown get_cpus 0000000000429696 Unknown Unknown Unknown get_cpus 00000000004065E7 get_cpus_IP_read_ 280 get_cpus.f90 get_cpus 00000000004029B1 MAIN__ 46 get_cpus.f90 get_cpus 000000000040297E Unknown Unknown Unknown libc-2.22.so 00007FFFECE456D5 __libc_start_main Unknown Unknown get_cpus 00000000004028A9 Unknown Unknown Unknown Traceback (most recent call last): File "findCPUs.py", line 45, in &lt;module&gt; '-rad {:.4e}'.format(rad)]) File "/nasa/pkgsrc/2014Q4/lib/python2.7/subprocess.py", line 573, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['./get_cpus', '-inp ./output_00076', '-xc 3.1670e-01', '-yc 9.6000e-02', '-zc 2.4170e-01', '-rad 2.0360e-03']' returned non-zero exit status 59 Where the 'CalledProcessError: Command' looks fine to me ... I've tried this with 'shell=True' and then I get the program to run, but the inputs are all missing because the fortran code returns the 'usage' statement (describing that I need input arguments). ???? e.g. - result = subprocess.check_output(['./get_cpus', '-inp ./output_00076', '-xc {:.4e}'.…
tagged with: python
has comment: http://stackoverflow.com/comment/88084172
score: 2
accepted answer: http://stackoverflow.com/a/50536004
tagged with: subprocess
upvote count: 2
has answer: http://stackoverflow.com/a/50536004
answer count: 1
has comment: http://stackoverflow.com/comment/88083975
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50429809
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50427694
score: 2
answers question: http://stackoverflow.com/q/50427694
type: AcceptedAnswer
downvote count: 0
has body: With the exception of mutable matrices, SymPy objects are immutable. Their methods do not modify them; a new object is returned instead. This object needs to be assigned to something (or printed, or returned): q2 = q1.subs(...) print(q1.subs(...)) return q1.subs(...) all make sense; the lonely q1.subs(...) is useless. This is covered in the "Gotchas and Pitfalls" article under Immutability of Expressions; I recommend reading the rest of that page too.

http://stackoverflow.com/comment/87933623
type: QuestionComment
has text: The list is irrelevant to the problem... `type(l.getLayerFilters()[0])` is a filter object
score: 0
comment on: http://stackoverflow.com/q/50460233
type: Comment

http://stackoverflow.com/a/50434104
has body: You're trying to find the maximum by length: item = max(names, key=len) print(len(item)) You could also be a bit more direct: print(max(len(x) for x in names)) ...though you won't know what the item is if you decide to go this way.
upvote count: 9
type: Answer
score: 9
answers question: http://stackoverflow.com/q/50434088
downvote count: 0

http://stackoverflow.com/q/50456945
has comment: http://stackoverflow.com/comment/87927519
has comment: http://stackoverflow.com/comment/87927494
downvote count: 0
has comment: http://stackoverflow.com/comment/87976515
has comment: http://stackoverflow.com/comment/87927926
tagged with: pandas
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87975240
favorite count: 0
type: Question
has body: Update 5/22/18: Answer by @aorr below original question. I am trying to collect each ID and the data for that ID for thousands of inputs. I am trying to collect each row of individual ID's, sort the dates, then plot each ID + plus data and export the chart for each ID. Edited Sample data: Col names: Id Date O G Company Date2 aab72ffd-4d0b-4c62-b6fe-4c55b98be9a0 3/1/1999 180.66 673 A 1/1/1996 aab72ffd-4d0b-4c62-b6fe-4c55b98be9a0 3/1/1995 173.9 651 A 1/1/1996 a15961bc-0263-4c66-a825-1deb69bda8be 12/1/2010 55.14 542 C 1/1/2011 a15961bc-0263-4c66-a825-1deb69bda8be 5/1/2012 49.24 577 C 1/1/2011 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 12/1/2000 48.14 290 D 3/1/2002 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 3/1/2003 69.03 282.5 D 3/1/2002 Desired output arrays/charts, but sorted by date. 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 7/1/2005 28.24 327 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 10/1/1998 45.11 335 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 7/1/2001 28.22 348 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 7/1/1997 44.53 350.5 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 8/1/2001 28.4 333.5 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 10/1/2005 41.72 314 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 12/1/2001 29.53 313.5 10a1d17b-1f5c-4a4d-8186-e4dbf62e3bf2 8/1/2002 43.24 319 The code I have typed so far successfully creates an indexed array of the the different data types. Now, I am just trying to iterate over all rows and organize the data so that it prints out/writes individual arrays/charts based on ID's. Here is what I have so far: import pandas as pd import matplotlib.pyplot as plt import numpy as np #import data mydataset = pd.read_csv('input_test.csv', dtype=None) x = mydataset.iloc[:,:].values y = mydataset.iloc[:,:].values #Id b = np.array((x[:,0]), dtype=str) #Date c = np.array((x[:,1]), dtype=str) # O Var d = np.array((x[:,2]), dtype=int) # G var e = np.array((x[:,3]), dtype=int) #Stack f = np.vstack((b,c,d,e)) #Transpose array g = f.T #Plot data plt.figure() plt.plot(x[:,2], y[:,3], label ='Rate over time') p…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87927792
has comment: http://stackoverflow.com/comment/87975380
score: 1
has title: Iterating rows and collecting values for output. Numpy and Python 3.6
has comment: http://stackoverflow.com/comment/87927514
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87971791
has comment: http://stackoverflow.com/comment/87927464
tagged with: python
has comment: http://stackoverflow.com/comment/87927894
has answer: http://stackoverflow.com/a/50471297
accepted answer: http://stackoverflow.com/a/50471297
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87979102

http://stackoverflow.com/q/50456856
has comment: http://stackoverflow.com/comment/87927206
accepted answer: http://stackoverflow.com/a/50456921
type: Question
linked to: http://stackoverflow.com/q/7167008
tagged with: seek
answer count: 2
possible better answer: http://stackoverflow.com/a/50456953
has body: I have a CSV file of dates and a float (day,month,year,float). here is sample, 1,1,2000,4076.79 2,1,2000,1216.82 3,1,2000,1299.68 4,1,2000,637.36 5,1,2000,3877.91 6,1,2000,3308.99 7,1,2000,2925.93 8,1,2000,1559.09 9,1,2000,3190.81 10,1,2000,3008.66 11,1,2000,2026.35 12,1,2000,3279.61 13,1,2000,3601.6 14,1,2000,2021.1 15,1,2000,2103.62 16,1,2000,609.64 17,1,2000,633.16 18,1,2000,1195.34 I want to read the first line then the last one: handle = open(getInputFileName(), "r") getInputFileName() obv. is a function that return file name. then, print "numberlines", numberLines #DEBUG# &gt;&gt;&gt; 3660 numberLines is the number of lines in file. then, handle.seek(0) lineData = handle.readline().split(",") print lineData #DEBUG# &gt;&gt;&gt; ['1','1','2000','4076.79\n'] until here everything works just fine. but then, handle.seek(numberLines-1) lineData = handle.readline().split(",") print lineData #DEBUG# &gt;&gt;&gt;['7', '7', '2000', '2347.51\n'] but in fact the last line in file is 31,12,2009,3823.02 why isnt seek going all the way down? i tried deleting the line that it gets stuck at but then the program crashed ValueError: could not convert string to float: (I then use lineData as float): newestDate.insert(1,float(lineData[1])) I checked the file if there was a problem with lines but the format never changes. how come does my code work for the first line but not the last?
has answer: http://stackoverflow.com/a/50456953
has answer: http://stackoverflow.com/a/50456921
tagged with: python
has title: seek() not working properly, although file opened in "r" mode
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: file-io
linked to: http://stackoverflow.com/q/25962114
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/50518351
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50518293
type: Answer
has body: I'd suggest making a dictionary then using the built in json module to convert it to a JSON string, because I find that cleaner to read. import json mydict = { "test": "hello world.", "server": machine, "ip": ip, "reason": "data" } json.dumps(mydict) See Robᵩ's answer for how to do it without the json module

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

http://stackoverflow.com/comment/87909425
type: AnswerComment
has text: check the code now, i have edited it. i explicitly converted it into string
comment on: http://stackoverflow.com/a/50447595
score: 0
type: Comment

http://stackoverflow.com/comment/87856753
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50416841
type: Comment
has text: @tdelaney `json.loads` code is my code . The data is taken using jquery ajax method from the json file with `dataType : 'jsonp' ` and `jsonpCallback : 'data'` .

http://stackoverflow.com/a/50450588
has comment: http://stackoverflow.com/comment/87916999
has comment: http://stackoverflow.com/comment/87916149
has comment: http://stackoverflow.com/comment/87916936
has comment: http://stackoverflow.com/comment/87916038
has comment: http://stackoverflow.com/comment/118425885
has comment: http://stackoverflow.com/comment/87916972
downvote count: 0
has comment: http://stackoverflow.com/comment/87916948
accepted answer of: http://stackoverflow.com/q/50450129
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87916538
has comment: http://stackoverflow.com/comment/87917209
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50450129
has comment: http://stackoverflow.com/comment/87915721
has comment: http://stackoverflow.com/comment/87919752
has comment: http://stackoverflow.com/comment/87919633
has comment: http://stackoverflow.com/comment/87915994
type: Answer
has body: If you want to search the source code for the occurrence of a certain substring, there is no need to use BeautifulSoup. It will only let you parse the actual page contents, and not including the source code. Replace count_words() with the following code. def count_words(url, the_word): r = requests.get(url).text return r.count(the_word) Output (do NOT include this in the final code): &gt;&gt;&gt; count_words('https://google.com', 'Google') 8 You just need to get the web page source code as a string using requests, and count the occurrences of a substring using .count(). Also, make sure that you add a scheme (e.g. http, https) in your URL. Otherwise, BeautifulSoup will "freak" out.

http://stackoverflow.com/comment/87912709
type: AnswerComment
score: 0
has text: What files do I add and which one do I add to? User DSN, System DSN or File DSN?
comment on: http://stackoverflow.com/a/50449499
type: Comment

http://stackoverflow.com/comment/116176463
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/64806395
has text: Might be renamed. Can't test right now, but does `chrome://settings/clearBrowserData` work? Otherwise just go to 'chrome://settings` and click on the respective section. Check the URL and change `cleardriverData` to the new section name.
type: Comment

http://stackoverflow.com/comment/88085902
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50536885
has text: Give your Playing_Cards class `__str__` and `__unicode__` methods.

http://stackoverflow.com/q/50417047
tagged with: switch-statement
downvote count: 1
has body: I am trying to write a switch case using a dictionary, and calling functions from them all. But the {key,value} pairs are all being printed: def addWord(): print "Add word" def searchWord(): print "Search word" def displayAll(): print "display all" #Executing the choice def switch_choice(choice): switcher = { 1:addWord(), 2:searchWord(), 3:displayAll() }.get(choice,"Invalid input") #MAIN print "Enter your choice" print "1.Add new word" print "2.Search for a word" print "3.Display all words" choice=input() switch_choice(choice) Output - Enter your choice 1.Add new word 2.Search for a word 3.Display all words 1 Add word Search word display all Can anyone please let me know the reason.
has title: All keys are getting selected in dictionary python
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/9168340
duplicate of: http://stackoverflow.com/q/9168340
has comment: http://stackoverflow.com/comment/87849777
has comment: http://stackoverflow.com/comment/87850513
tagged with: python
tagged with: dictionary
score: -1
has comment: http://stackoverflow.com/comment/87849826
has answer: http://stackoverflow.com/a/50417066
has comment: http://stackoverflow.com/comment/87850833
accepted answer: http://stackoverflow.com/a/50417066
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87849859
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/88076021
type: Comment
type: QuestionComment
has text: I used the set argument because it was what worked for the previous list. I'm a very new, very poorly skilled coder. I see now why set doesnt work. What I'm trying to do is reduce the length of the list by removing 30% of its elements from it.
score: 0
comment on: http://stackoverflow.com/q/50531729

http://stackoverflow.com/comment/87808494
type: Comment
comment on: http://stackoverflow.com/a/50395189
type: AnswerComment
score: 0
has text: This is what I was looking for. Now I have to find a way to get the data in the right order and combine the data with the data from the other rows with the classes even smallrow and odd smallrow.

http://stackoverflow.com/q/50482720
possible better answer: http://stackoverflow.com/a/50485368
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87978814
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/87982727
has comment: http://stackoverflow.com/comment/87985065
score: 1
tagged with: dataframe
linked to: http://stackoverflow.com/q/33168970
has comment: http://stackoverflow.com/comment/87982896
has body: I have 2 dataframes named - brand_name and poi_name. Dataframe 1(brand_name):- +-------------+ |brand_stop[0]| +-------------+ |TOASTMASTERS | |USBORNE | |ARBONNE | |USBORNE | |ARBONNE | |ACADEMY | |ARBONNE | |USBORNE | |USBORNE | |PILLAR | +-------------+ Dataframe 2:-(poi_name) +---------------------------------------+ |Name | +---------------------------------------+ |TOASTMASTERS DISTRICT 48 | |USBORNE BOOKS AND MORE | |ARBONNE | |USBORNE BOOKS AT HOME | |ARBONNE | |ACADEMY, LTD. | |ARBONNE | |USBORNE BOOKS AT HOME | |USBORNE BOOKS &amp; MORE | |PILLAR TO POST HOME INSPECTION SERVICES| +---------------------------------------+ I want to check whether the strings in brand_stop column of dataframe 1 are present in Name column of dataframe 2. The matching should be done row wise and then if there is a successful match, that particular record should be stored in a new column. I have tried filtering the dataframe using Join:- from pyspark.sql.functions import udf, col from pyspark.sql.types import BooleanType contains = udf(lambda s, q: q in s, BooleanType()) like_with_python_udf = (poi_names.join(brand_names1) .where(contains(col("Name"), col("brand_stop[0]"))) .select(col("Name"))) like_with_python_udf.show() But this shows an error "AnalysisException: u'Detected cartesian product for INNER join between logical plans" I am new to PySpark. Please help me with this. Thank you
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87979281
has comment: http://stackoverflow.com/comment/87980457
answer count: 2
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/87981157
has answer: http://stackoverflow.com/a/50485368
has comment: http://stackoverflow.com/comment/87982362
upvote count: 2
accepted answer: http://stackoverflow.com/a/50486770
has comment: http://stackoverflow.com/comment/87985161
has comment: http://stackoverflow.com/comment/87979573
duplicate of: http://stackoverflow.com/q/33168970
tagged with: pyspark
has answer: http://stackoverflow.com/a/50486770
has title: Compare String Values in 2 Spark Dataframes
has comment: http://stackoverflow.com/comment/87979519
tagged with: python
has comment: http://stackoverflow.com/comment/87980217
has comment: http://stackoverflow.com/comment/87983911
has comment: http://stackoverflow.com/comment/87982864

http://stackoverflow.com/q/50444096
tagged with: python
has title: Is there any potential vuln when use as object after with statement?
has answer: http://stackoverflow.com/a/50444486
has comment: http://stackoverflow.com/comment/87902082
upvote count: 2
tagged with: python-3.x
answer count: 1
tagged with: with-statement
accepted answer: http://stackoverflow.com/a/50444486
favorite count: 0
has body: I'm using python3.6 in virtualenv. And I wonder if I use with object from outside with statement. This is example code for the question. with tempfile.NamedTemporaryFile(delete=False) as tf: tf.write(audio_stream) # outside of with print(tf.name) # is it dangerous? I want to do only write in with statement, and do other stuff outside of with. (Such as tf.name). Is there a potential threat to access the tf object from outside with? (Unintentional garbage collection, etc.) If that's not recommended, I wonder the exact reason as well. thanks
type: Question
type: AnsweredQuestion
score: 1
downvote count: 1

http://stackoverflow.com/comment/87798026
score: 0
type: Comment
type: QuestionComment
has text: I guess your `print` statements are after the progress bar display code ?
comment on: http://stackoverflow.com/q/50390838

http://stackoverflow.com/a/50413486
upvote count: 1
answers question: http://stackoverflow.com/q/50413377
has comment: http://stackoverflow.com/comment/87842784
has body: Instead of a for loop then break, use manual iteration on the file with next Just skip as many lines as you wish using next on the csv reader, then use next one last time and pick the column you want: with open(filename) as f: reader = csv.reader(f, delimiter=';') # skip 2 rows for _ in range(2): next(reader) useful_data = next(reader)[2]
type: Answer
has comment: http://stackoverflow.com/comment/87842987
has comment: http://stackoverflow.com/comment/87842888
score: 1
has comment: http://stackoverflow.com/comment/87842929
downvote count: 0

http://stackoverflow.com/comment/88093943
score: 0
has text: @iobs, consider accepting the answer. Happy coding :)
type: AnswerComment
comment on: http://stackoverflow.com/a/50541313
type: Comment

http://stackoverflow.com/a/50410394
score: 0
answers question: http://stackoverflow.com/q/50410174
has comment: http://stackoverflow.com/comment/87836184
type: Answer
has comment: http://stackoverflow.com/comment/87836244
has comment: http://stackoverflow.com/comment/87836317
has comment: http://stackoverflow.com/comment/87836139
has body: The problem is not the list but rather the nested tuple. You have something like data = [(('f00', 1, 'bla'), (...))] So you cannot do data[1]. Instead of .append(), use data = cursor.fetchall() and do not initialize it (data = []), there is no need for that.

http://stackoverflow.com/comment/87917753
type: QuestionComment
has text: What do files have anything to do with your question?
comment on: http://stackoverflow.com/q/50451593
score: 0
type: Comment

http://stackoverflow.com/comment/88064445
score: 0
comment on: http://stackoverflow.com/q/50525301
has text: Hmm, the introduction in the django-polymorphic docs says it supports proxy models, but then doesn't mention them anywhere else. It might be worth a try though.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50529827
type: Answer
has body: You need to include the parameter "a" in the decorator @app.route: @app.route('/&lt;int:a&gt;') def hello(a): return a + 2
score: 0
answers question: http://stackoverflow.com/q/50529779

http://stackoverflow.com/a/50519447
answers question: http://stackoverflow.com/q/50518671
upvote count: 0
score: -2
downvote count: 2
type: Answer
has body: This is possible using vectorised logic via 3rd party library numpy. The idea is to use broadcasting to take the difference between the array and its transposed representation. Then take the maximum of the lower triangle from the resulting array. import numpy as np A = np.array([7, 5, 3, 4, 6, 4, 7]) B = A - A[:, None] res = np.max(B[np.tril_indices(B.shape[0])]) print(res) 4

http://stackoverflow.com/q/50427972
tagged with: selenium-chromedriver
type: Question
has answer: http://stackoverflow.com/a/50428007
has comment: http://stackoverflow.com/comment/87870627
type: UnansweredQuestion
tagged with: python
answer count: 1
tagged with: selenium-webdriver
has title: Cant figure out how to fix this. Python Selenium Chromedriver Error
score: 0
has body: from selenium import webdriver from selenium.webdriver.common.keys import Keys import os Game_Pin = input('Enter your PIN: ') NickNAME = input('Enter your nickname: ') def Enter_Press(): browser.find_element_by_name("Enter").click() def Kahoot_Spammer(Game_Pin, NickNAME): chromedriver = os.chdir(r'C:\WebDriver\bin\chromedriver_win32.exe') browser = webdriver.Chrome(chromedriver) browser.get('https://kahoot.it/') game_pin = browser.find_element_by_id("Game PIN") Name = browser.find_element_by_id("Nickname") game_pin.send_keys(Game_Pin) Enter_Press() Name.send_keys(NickNAME) Enter_Press() Kahoot_Spammer(Game_Pin, NickNAME) I am brand new to Python programming and programming in general. Anyway I have been looking for a clear answer as to why this isn't working for quite a while now. I pretty sure I have the file in the PATH but it still cant find it for some reason. Here is the error I keep getting. Any thoughts Traceback (most recent call last): File "C:\Users\ovvip\AppData\Local\Programs\Python\Python36-32\KahootSpammer.py", line 28, in &lt;module&gt; Kahoot_Spammer(Game_Pin, NickNAME) File "C:\Users\ovvip\AppData\Local\Programs\Python\Python36-32\KahootSpammer.py", line 13, in Kahoot_Spammer chromedriver = os.chdir(r'C:\WebDriver\bin\chromedriver_win32.exe') FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\WebDriver\\bin\\chromedriver_win32.exe'
tagged with: selenium

http://stackoverflow.com/comment/87867898
type: QuestionComment
comment on: http://stackoverflow.com/q/50426629
has text: Btw, it'd be nice if you format the code in your post nicely. I'm sometimes confused with the code because of the improper indentations.
score: 0
type: Comment

http://stackoverflow.com/comment/88090035
has text: Yup! I think the classic approach would be to add a bit of randomization in (probability of picking not the next least constrained option) and run it a few times, then take the best result. Running this multiple times should still be much faster than a brute force.
type: Comment
comment on: http://stackoverflow.com/a/50524529
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87993057
type: Comment
score: 0
has text: `import operator, functools` then `common_keys = functools.reduce(operator.and_, (d.keys() for d in data))` would produce a set of all common keys in a sequence of dictionaries.
comment on: http://stackoverflow.com/q/50489970
type: QuestionComment

http://stackoverflow.com/comment/87872214
has text: @OldBunny2800 Which error? Try brew doctor and after that brew upgrade python3
comment on: http://stackoverflow.com/a/50428732
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50403947
has comment: http://stackoverflow.com/comment/87824034
type: UnansweredQuestion
tagged with: python
tagged with: valueerror
score: 0
tagged with: random
has title: ValueError: negative dimensions are not allowed while generating samples from multivariate normal distribution
answer count: 0
has comment: http://stackoverflow.com/comment/87824089
has comment: http://stackoverflow.com/comment/87824433
has comment: http://stackoverflow.com/comment/87824927
has body: I want to generate samples from multivariate normal distribution in numpy. Here is my code: import numpy as np import random from random import uniform import math from sklearn.datasets import make_spd_matrix k = 5 # how many classes N = 20 # how many samples x_min = -20 x_max = 20 y_min = -20 y_max = 20 def main(): w = np.random.random(k) # generate k random numbers w /= w.sum() # divide by their sum # now these sum to 1 #print(w) # actual weight vector number_of_divisions_x = number_of_divisions_y = math.ceil(math.sqrt(k)) x_div = (x_max - x_min)/number_of_divisions_x y_div = (y_max - y_min)/number_of_divisions_y # divide a grid # x = x_min to x_max # y = y_min to y_max # now form the grid and put the means points = [] # the list of actual means # now generate means for i in range(number_of_divisions_x): for j in range(number_of_divisions_y): if len(points) == k: # after generating k points, break the loop break point = [x_min + i * x_div, y_min + j * y_div] # array (not tuple) is needed for the function points.append(point) if len(points) == k: # after generating k points, break the loop break samples = [] # list containing all the samples actual_sample = [None] * k # how many samples in each class actually. Stored for later weight correction covs = [] # actual covariances for i in range(k): number_of_samples = math.ceil(N * w[i]) # number of samples from class i, generate at least one sample actual_sample[i] = number_of_samples # for later weight correction if i == k-1: number_of_samples = N - sum(actual_sample[:k-1]) # for the last class, take all the remaining samples actual_sample[i] = number_of_samples mean = points[i] # generate covariance matrix cov = make_spd_matrix(2) # Generate a random symmetric, positive-definite matrix, whose size is 2x2 covs.append(cov) file = open("class " + str(i+1) + ".txt", "w") # class 1, 2, 3 etc file.write(str(mean) + "\n\n") file.write(str(cov)) file.close() # save the actual mean and covariance to file s = np.random.multiva…
type: Question
tagged with: numpy

http://stackoverflow.com/q/50403670
upvote count: 1
score: 1
has title: Adding column in pandas python
has answer: http://stackoverflow.com/a/50403928
possible better answer: http://stackoverflow.com/a/50403928
has body: After adding column in dataframe, am not getting proper output file. Here is my input file Security Wise Delivery Position - Compulsory Rolling Settlement 10,MTO,01022018,592287763,0001583 Trade Date &lt;01-FEB-2018&gt;,Settlement Type &lt;N&gt;,Settlement No &lt;2018023&gt;,Settlement Date &lt;05-FEB-2018&gt; Record Type,Sr No,Name of Security,Quantity Traded,Deliverable Quantity(gross across client level),% of Deliverable Quantity to Traded Quantity 20,1,20MICRONS,EQ,53466,27284,51.03 20,2,3IINFOTECH,EQ,7116046,3351489,47.10 20,3,3MINDIA,EQ,2613,1826,69.88 20,4,5PAISA,EQ,8463,5230,61.80 20,5,63MOONS,EQ,324922,131478,40.46 Expecting output 20,1,20MICRONS,EQ,53466,27284,51.03,01022018 20,2,3IINFOTECH,EQ,7116046,3351489,47.10,01022018 20,3,3MINDIA,EQ,2613,1826,69.88,01022018 20,4,5PAISA,EQ,8463,5230,61.80,01022018 20,5,63MOONS,EQ,324922,131478,40.46,01022018 My code import pandas as pd df = pd.read_csv('C:/Working/dalal/MTO_11052018.DAT', sep='\t',skiprows=1) df=df.iloc[1] l1=list(str(df).split(",")) l2=l1[2] df2=pd.read_csv('C:/Working/dalal/MTO_11052018.DAT',sep='\t',skiprows=3) df2['Trans_dt']=df2.apply(lambda row:[l2],axis=1) df2.to_csv('C:/Working/dalal/deldata/MTO_11052018.OUT',sep=',') am not getting expected out. Please help on this
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87823194
answer count: 2
has comment: http://stackoverflow.com/comment/87823000
has answer: http://stackoverflow.com/a/50404609
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50404609

http://stackoverflow.com/q/50434888
has body: I have a for loop from which i am generating a list of dict like below isv = [] for obj in hearts: rawvalue = obj.raw - readvalue if rawvalue &lt; 0: rawvalue = rawvalue + 440 else: rawvalue obj = str(obj) obj = ((obj.strip('&lt;').split(" ")[0])) isv.append({'Plo':obj,'Ots': viewdata(rawvalue)[0][3],'Gts':viewdata(rawvalue)[0][0],'Mts': viewdata(rawvalue)[0][1],'Frts': viewdata(rawvalue)[0][2],'Fin':rawvalue}) i am creating a dataframe from this list of dict as below pdadata = pd.DataFrame(isv) For some reason, the DF columns are not in order as mentioned in the isv.append as Plo,Ots,Gts,Mts,Frts,Fin What should be done to make this work Sample Data: Plo Ots Gts Mts Frts Fin 1 Parcel Red Blue Yellow 678.547 2 Gift Green purple Black 876.214 3 Order Green purple Black 877.217 4 Base Green purple Black 922.145 5 Flat Green purple Black 964.2 6 Deal Green purple Black 400 7 Mission Green purple Black 450.124 8 Base Green purple Black 520.2145 9 Flat Green purple Black 570.145 10 Deal Green purple Black 600.178
type: AnsweredQuestion
tagged with: pandas
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87883963
accepted answer: http://stackoverflow.com/a/50435030
has title: List of dict to dataframe not coming in order
has answer: http://stackoverflow.com/a/50435030
upvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87883842

http://stackoverflow.com/comment/87923400
type: QuestionComment
comment on: http://stackoverflow.com/q/50454861
score: 0
type: Comment
has text: I'm not clear on what this is supposed to do but perhaps you want to look into sessions.

http://stackoverflow.com/a/50539609
accepted answer of: http://stackoverflow.com/q/50539540
has body: You can use quiz_question__quiz lookup to filter by quize. Use following query to query by quiz and learner: quiz = all_quizes[0] learner= User.objects.get(id=1) LearnerQuestionAnswer.objects.filter(quiz_question__quiz=quiz, learner=learner) Check this part of the doc about filter by related model's fields.
answers question: http://stackoverflow.com/q/50539540
type: AcceptedAnswer
type: Answer
score: 0

http://stackoverflow.com/comment/88000191
type: AnswerComment
has text: I tried to explain my question here with a new post: https://stackoverflow.com/questions/50493609/lstm-prediction-neural-network-too-good-expected-error
score: 0
comment on: http://stackoverflow.com/a/50478578
type: Comment

http://stackoverflow.com/q/50405012
tagged with: jupyter-notebook
type: Question
score: 0
has title: jupyter notebook command can not run correctly
type: UnansweredQuestion
answer count: 1
has body: After i install anaconda3 and open Jupyter, it open by IE, i copy the url "http://localhost:8889/tree" and paste to Chrome, then it show this page page picture link I follow instruction enter jupyter notebook list but it response this error File "", line 1 jupyter notebook list ^ SyntaxError: invalid syntax why this error happen?
linked to: http://stackoverflow.com/q/41159797
tagged with: python
has answer: http://stackoverflow.com/a/50405156

http://stackoverflow.com/a/50476907
has comment: http://stackoverflow.com/comment/87967787
has comment: http://stackoverflow.com/comment/87967653
downvote count: 1
has body: I ended up doing this for each of the colors. blue_data = data[data.color =='blue']
answers question: http://stackoverflow.com/q/50476392
has comment: http://stackoverflow.com/comment/87967414
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/a/50557877
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Be warned that many have tried to reproduce the reported 'Paragraph Vector' results using concatenated PV-DBOW and PV-DM+dm_concat vectors without success. (For example, Mikolov himself reports being unable to reproduce the exact numbers that he says co-author Le contributed to the paper.) The ConcatenatedDoc2Vec class is just a thin wrapper to join two models you've already trained separately, for the purposes of vector-lookup-by-tag (__getitem__() indexed access) and combined inference. (It's a mere 10 lines of code.) To make this post-training join sensible, those two models should have been trained with the exact same documents/tags in the exact same order. So if you need a list of tags, ask either model separately. If you need some other combination of the two models – such as a single large array including all concatenated vectors – you'd have to construct that yourself, perhaps using numpy's hstack method. You can see my notebook trying to reproduce some of the paper's results inside the gensim docs/notebooks directory, or view online at: https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/doc2vec-IMDB.ipynb
answers question: http://stackoverflow.com/q/50535278

http://stackoverflow.com/q/50415402
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87846671
score: 1
has title: pandas calculates column value means on groups and means across whole dataframe
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50415533
has comment: http://stackoverflow.com/comment/87846942
type: Question
has body: I have a df, df['period'] = (df['date1'] - df['date2']) / np.timedelta64(1, 'D') code y_m date1 date2 period 1000 201701 2017-12-10 2017-12-09 1 1000 201701 2017-12-14 2017-12-12 2 1000 201702 2017-12-15 2017-12-13 2 1000 201702 2017-12-17 2017-12-15 2 2000 201701 2017-12-19 2017-12-18 1 2000 201701 2017-12-12 2017-12-10 2 2000 201702 2017-12-11 2017-12-10 1 2000 201702 2017-12-13 2017-12-12 1 2000 201702 2017-12-11 2017-12-10 1 then groupby code and y_m to calculate the average of date1-date2, df_avg_period = df.groupby(['code', 'y_m'])['period'].mean().reset_index(name='avg_period') code y_m avg_period 1000 201701 1.5 1000 201702 2 2000 201701 1.5 2000 201702 1 but I like to convert df_avg_period into a matrix that transposes column code to rows and y_m to columns, like 0 1 2 3 0 -1 0 201701 201702 1 0 1.44 1.44 1.4 2 1000 1.75 1.5 2 3 2000 1.20 1.5 1 -1 represents a dummy value that indicates either a value doesn't exist for a specific code/y_m cell or to maintain matrix shape; 0 represents 'all' values, that averages the code or y_m or code and y_m, e.g. cell (1,1) averages the period values for all rows in df; (1,2) averages the period for 201701 across all rows that have this value for y_m in df. apparently pivot_table cannot give correct results using mean. so I am wondering how to achieve that correctly?
has answer: http://stackoverflow.com/a/50415533
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/127437025
has text: Great answer! With a good deal of modification I used it in my application, it was a good starting point. if someone else uses it in the future, I give a little warning: The update of the graph is tangled with the update of the sliders, u should decouple them in case your use case doesn't use sliders.
comment on: http://stackoverflow.com/a/50477532
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88083635
type: QuestionComment
has text: @MForMarlon I added some code to my view that may be relevant. It would be cool if you could check out my question again.
comment on: http://stackoverflow.com/q/50533727
score: 0
type: Comment

http://stackoverflow.com/comment/88012093
type: QuestionComment
comment on: http://stackoverflow.com/q/50455772
has text: @rioualen `expand` does allow line splitting
score: 0
type: Comment

http://stackoverflow.com/q/50395008
has comment: http://stackoverflow.com/comment/87807095
has title: Python multiprocessing multiple processes per thread
has body: I'm currently using python's multiprocessing module with a pool to run a function millions of times, simultaneously. While multiprocessing works well, the function is so lightweight that barely 30% of each core is used and threads are maxed out only during the Locking(). Looking at my script's profile, indeed locking is the most expensive. Given each function run is very short, the trade off between locking each time I'm mapping to the function and running the function is not worth it (in fact I'm getting better performance by running it serially; 15 mins parallelized vs. 4.5 mins serial). The function writes to independent files so calls are completely independent. Is it possible to 'mimic' running/calling the same parallelized python script multiple times (with different inputs) to make more use of the CPU? Current Code: pool = Pool(cpu_count(), initializer=tqdm.tqdm.set_lock, initargs=(Lock(),)) for _ in tqdm.tqdm(pool.imap_unordered(parallel_process, pubfiles, chunksize=70), total=nfiles, desc='Parsing files'): pass EDIT: To ensure it has nothing to do with tqdm's locking, modifying the code to the following achieves the same issue: pool = Pool(cpu_count()) for i in pool.imap_unordered(parallel_process, files, chunksize=70): print(i) I've profiled my code for a while and most expensive processes seem to be related to locking (?)/multiprocessing in general. The actual function is very close to the bottom of the processing time.
has comment: http://stackoverflow.com/comment/87807161
tagged with: threadpool
linked to: http://stackoverflow.com/q/3822512
tagged with: python
has comment: http://stackoverflow.com/comment/87807142
tagged with: parallel-processing
has answer: http://stackoverflow.com/a/50552290
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87806592
has comment: http://stackoverflow.com/comment/87807929
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50552290
has comment: http://stackoverflow.com/comment/87807219
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/87806280

http://stackoverflow.com/q/50456464
score: -1
has body: I have two dataframes df1 and df2. In both the two columns _a and _b. In df1, both columns are filled. import numpy as np import pandas as pd df1 = pd.DataFrame({'_a':[1,1,1,2,2,3,3],'_b':[3,4,5,3,3,3,9]}) df1 _a _b 0 1 4 1 3 9 2 4 3 3 2 5 In df2 only column _a is filled in another order. I need fill column _b in analogy with df1. In the end, it should look like this: _a _b 0 4 3 1 3 9 2 1 4 3 2 5 Thank you in advance.
favorite count: 0
type: Question
has title: How combine 2 arrays of pandas, by common column
has answer: http://stackoverflow.com/a/50456569
upvote count: 0
accepted answer: http://stackoverflow.com/a/50456569
answer count: 1
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
tagged with: group-by
downvote count: 1
has comment: http://stackoverflow.com/comment/87926401
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/50475453
has title: xarray - cannot serialize coordinates
type: AnsweredQuestion
answer count: 2
score: 2
upvote count: 2
tagged with: netcdf
downvote count: 0
has body: I'm trying to use xarray to append and write a netCDF file. Some info on the original file is below. Dimensions: (Time: 744, south_north: 289, west_east: 339) Coordinates: XLAT (Time, south_north, west_east) float32 ... XLONG (Time, south_north, west_east) float32 ... Dimensions without coordinates: Time, south_north, west_east Data variables: Times (Time) |S19 ... RAINNC (Time, south_north, west_east) float32 ... I_RAINNC (Time, south_north, west_east) int32 ... SNOWNC (Time, south_north, west_east) float32 ... GRAUPELNC (Time, south_north, west_east) float32 ... HAILNC (Time, south_north, west_east) float32 ... Here's some information on the appended file (two variables added). Dimensions: (Time: 744, south_north: 289, west_east: 339) Coordinates: XLAT (Time, south_north, west_east) float32 ... XLONG (Time, south_north, west_east) float32 ... Dimensions without coordinates: Time, south_north, west_east Data variables: Times (Time) |S19 ... RAINNC (Time, south_north, west_east) float32 0.0 0.0 0.0 0.0 0.0 I_RAINNC (Time, south_north, west_east) int32 0 0 0 0 0 0 0 0 0 0 0 0 SNOWNC (Time, south_north, west_east) float32 ... GRAUPELNC (Time, south_north, west_east) float32 ... HAILNC (Time, south_north, west_east) float32 ... PRCP (Time, south_north, west_east) float32 0.0 0.0 0.0 0.0 0.0 CUMPRCP (Time, south_north, west_east) float32 0.0 0.0 0.0 0.0 0.0 I'm attempting to write a new file with xarray.to_netcdf(), but am receiving this error: ValueError: cannot serialize coordinates because variable RAINNC already has an attribute 'coordinates' Any ideas on how to resolve this error? EDIT: Data was generated through Weather and Research Forecasting Model (WRF). Data loaded via open_dataset() with decode_cf at default. Attributes for RAINNC are the same for both files and listed below. OrderedDict([('FieldType', 104), ('MemoryOrder', 'XY '), ('description', 'ACCUMULATED TOTAL GRID SCALE PRECIPITATION'), ('units', 'mm'), ('stagger', ''), ('coordinates', 'XLONG XLAT XTIM…
possible better answer: http://stackoverflow.com/a/55840014
accepted answer: http://stackoverflow.com/a/50475925
has answer: http://stackoverflow.com/a/55840014
has answer: http://stackoverflow.com/a/50475925
favorite count: 0
type: Question
tagged with: python-xarray
tagged with: python

http://stackoverflow.com/a/50532302
downvote count: 0
has body: Unfortunately you can't do that. From the server side filtering perspective, only thing you could do is filter blobs by prefix i.e. filter blobs where name starts with a particular value (e.g reports/). All other kind of filtering needs to be done on the client side itself.
has comment: http://stackoverflow.com/comment/128941885
has comment: http://stackoverflow.com/comment/88078306
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50532205
upvote count: 2
answers question: http://stackoverflow.com/q/50532205
type: AcceptedAnswer

http://stackoverflow.com/comment/87896381
type: QuestionComment
comment on: http://stackoverflow.com/q/50440947
score: 0
has text: @JerryHu There :)
type: Comment

http://stackoverflow.com/comment/88153294
comment on: http://stackoverflow.com/a/50536103
has text: Removed my comments, it was growing too big. I created another answer that should explain the differences and hopefully not generate too many new questions ;)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/74146835
type: Answer
has body: I just got pytail working and as far as I can tell there is no option to follow a file as it grows so it's basically pointless in most use cases. Just prints the last X lines. To answer your question, not very.
score: 1
answers question: http://stackoverflow.com/q/50487511
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87940833
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50463669
has text: Is adding the brackets to the list element an option ? Is the `(New)` element always the last in the list ?

http://stackoverflow.com/comment/88894121
has text: @Fulco No worries about the bounty - jpp directly answers the question in the heading. I just feel that the MultiIndex is unnecessary for this task - partly, the reason is my unfamiliarity with complex MultiIndex tricks.
type: Comment
comment on: http://stackoverflow.com/a/50871876
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88090915
has text: Did you also upgrade `pip3` via the system package manager?
comment on: http://stackoverflow.com/q/50539516
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88110417
type: Comment
type: QuestionComment
has text: saddly, i got error. Traceback (most recent call last): File "C:/Users/Samsung/AppData/Local/Programs/Python/Python36-32/asd.py", line 8, in <module> f=(2*pi*(standard_deviation)**2)**(-1/2)*exp((-((x-mean)**2)/(2* (standard_deviation)**2))) File "C:\Users\Samsung\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sympy\core\expr.py", line 239, in __float__ raise TypeError("can't convert expression to float") TypeError: can't convert expression to float
comment on: http://stackoverflow.com/q/50501155
score: 0

http://stackoverflow.com/a/50428968
upvote count: 2
answers question: http://stackoverflow.com/q/50428894
has body: Out of the 3 paths in search(), only 1 returns something: def search(v, searchterm, vid, path=(),): if isinstance(v, dict): # Path 1 for k, v2 in v.items(): p2 = path + ('{}'.format(k),) search(v2, searchterm, vid, p2) # Nothing returned here else: if searchterm in v: # Path 2 a = {} a[0] = path a[1] = v[vid] print(a) return(a) else: # Path 3 # Nothing returned here Path 1 calls Path 2 which explains why there is something printed but not returned to main().
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/87885006
type: QuestionComment
has text: @YvesDaoust how can I define the number of clusters according to number of "hole's area" ?
score: 0
comment on: http://stackoverflow.com/q/50391853
type: Comment

http://stackoverflow.com/q/50531101
has title: Methods to extract email signature
upvote count: 0
downvote count: 4
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/50588600
answer count: 1
has comment: http://stackoverflow.com/comment/88074231
has comment: http://stackoverflow.com/comment/88074184
tagged with: python
has body: I would like to extract email signatures from a single-column Pandas data frame where each row contains a discrete email message as a string. Some emails are HTML encoded and some are not. They can be of any email provider (e.g.: Gmail, Microsoft, Yahoo, etc.). I know that Gmail signatures are contained in a div where class="email_signature" which simplifies parsing those. My dilemma is: what is the best way to extract non-gmail email signatures? Is there a regex that captures the content of an email? How can I apply this regex over the Pandas data frame in Python? I'd provide an example but the data is private and frankly I don't think it's necessary for this question.
tagged with: pandas
tagged with: email
tagged with: dataframe
tagged with: parsing
favorite count: 0
type: Question

http://stackoverflow.com/comment/87852885
score: 0
type: Comment
has text: @Coolio2654. I myself did not learn from books, so I can't really recommend any. If I were to make a recommendation it would be to get a solid foundation in algorithms, complexity theory, etc. --- if you haven't already got it. Another thing that helps me is knowing at least one low-level language like `C` because even when using the conviences of a high-level language like `Python` having an idea of how they are likely to be implemented is very helpful when optimizing. I wish I had more concrete advice. Anyway, this is how I got there. Sound fundamentals and practice, practice, practice.
type: AnswerComment
comment on: http://stackoverflow.com/a/50403102

http://stackoverflow.com/q/50498755
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50498807
tagged with: tensorflow
favorite count: 0
type: Question
has body: I'm having the following error with this code: File "C:/Users/lourd/Desktop/Arquivos/PROGRAMAÇÂO/treino/IA", line 56, in module error, _ =sess.run([cost,optimizer],feed_dict={inputs: inp,targets:out}) File "C:\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 900, in run run_metadata_ptr) File "C:\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1111, in _run str(subfeed_t.get_shape()))) ValueError: Cannot feed value of shape (4, 1) for Tensor 'input:0', which has shape '(?, 2)' My code: import tensorflow as tf # Espaços reservados inputs = tf.placeholder('float', [None, 2], name='input') targets = tf.placeholder('float', name='Target') # Variaveis weight1 = tf.Variable(tf.random_normal(shape= [2, 3], stddev=0.02, name='Weight1')) biases1 = tf.Variable(tf.random_normal(shape= [3], stddev=0.02), name='Biases1') # Multiplicador hlayer = tf.matmul(inputs, weight1) hlayer += biases1 # Função de ativação hlayer = tf.sigmoid(hlayer, name='hAtivador') # Camada oculta crie camadas de saida e conclua a rede weight2 = tf.Variable(tf.random_normal(shape=[3, 1], stddev=0.02), name='Weight2') biases2 = tf.Variable(tf.random_normal(shape=[1], stddev=0.02), name='Biases2') # Camada de saida output = tf.matmul(hlayer, weight2) output += biases2 output = tf.sigmoid(output, name='outActivation') # Optimização para treinar cost = tf.squared_difference(targets, output) cost = tf.reduce_mean(cost) optimizer = tf.train.AdamOptimizer().minimize(cost) # sessao TensotFlow import numpy as np inp = [[0.1], [0.2], [1.0],[1.1]] out = [[0], [1], [1], [0]] inp = np.array(inp) out = np.array(out) # Começar a sessão epochs = 4000 with tf.Session() as sess: tf.global_variables_initializer().run() for i in range(epochs): error, _ =sess.run([cost,optimizer],feed_dict={inputs: inp,targets:out}) print(i,error) # Teste with tf.Session() as sess: tf.global_variables_initializer().run() for i in range(epochs): error, _ = sess.run([cost, optimizer], fee…
tagged with: python
has title: Tensorflow error ''Cannot feed value of shape (4, 1) for Tensor 'input:0', which has shape '(?, 2)'''
tagged with: deep-learning

http://stackoverflow.com/comment/87923565
has text: Try this, without the index_col parameter. `pd.read_csv('Desktop/test.pln',sep='\t',header=[0,1])`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50454630
score: 0

http://stackoverflow.com/comment/87932400
type: QuestionComment
has text: @pstatix you don't need to convert to `int` and then to `str`. `input()` is already a string. Just `len(input())` will do. To handle negatives, use `len(str(abs(int(input()))))`.
score: 0
comment on: http://stackoverflow.com/q/50459313
type: Comment

http://stackoverflow.com/comment/88081461
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50532934
has text: Code 1 you are mentioned in question regards to connection, not to publishing ("4.3 Payload The PUBACK Packet has no payload."). It is not possible to publish when client is not connected. The other possibility is that you are exceeding keep alive time
type: Comment

http://stackoverflow.com/a/50412447
has comment: http://stackoverflow.com/comment/87899075
type: Answer
accepted answer of: http://stackoverflow.com/q/50404408
has comment: http://stackoverflow.com/comment/87897661
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: I have two areas where your error is coming from 1) Form name is deprecated since HTML 4 and is no longer submitted therefore if request.form['btn'] == "project": will not be understood by flask The way to go around that is to give your submit button a name like this Fetch Details and in your flask view, check for the form like this if 'project' in request.form: 2) The second error is on this line line two here should be name= "subsystem_value", not id="subsystem_value" otherwise this line in flask will not be understood subsystem = request.form['subsystem_value'] So I have this simplified code that is no longer giving me an error and returning the values the way I think you want them in flask @app.route('/ip',methods = ['POST', 'GET']) #Used @pp.route to match my testing app def ip(): if request.method == 'POST': if 'project' in request.form: project = request.form['project_name'] return str(project) else: subsystem = request.form['subsystem_value'] return str(subsystem) else: return render_template('test.html') in the template Select Project : Ki S L Fetch Details t1 t2 t3 Hope that helps you out
answers question: http://stackoverflow.com/q/50404408

http://stackoverflow.com/a/59514584
downvote count: 0
upvote count: 10
score: 10
type: Answer
answers question: http://stackoverflow.com/q/50434026
has body: Very well pointed by @jrtapsell To Add further information: There is a regular expression defined for each type when it comes to naming convention. You may note the length of a name can vary from 2 to 30 characters along with its regex. +-------------------+---------------+-------------------------------------------+ | Type | Option | Default regular expression | +-------------------+---------------+-------------------------------------------+ | Argument | argument-rgx | [a-z_][a-z0-9_]{2,30}$ | | Attribute | attr-rgx | [a-z_][a-z0-9_]{2,30}$ | | Class | class-rgx | [A-Z_][a-zA-Z0-9]+$ | | Constant | const-rgx | (([A-Z_][A-Z0-9_]*)|(__.*__))$ | | Function | function-rgx | [a-z_][a-z0-9_]{2,30}$ | | Method | method-rgx | [a-z_][a-z0-9_]{2,30}$ | | Module | module-rgx | (([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ | | Variable | variable-rgx | [a-z_][a-z0-9_]{2,30}$ | | Variable, inline1 | inlinevar-rgx | [A-Za-z_][A-Za-z0-9_]*$ | +-------------------+---------------+-------------------------------------------+
has comment: http://stackoverflow.com/comment/135305846
has comment: http://stackoverflow.com/comment/136254711

http://stackoverflow.com/q/50441031
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50441053
type: AnsweredQuestion
has body: I just started learning Python. I following the textbook and created the a function as below: def Hello(name): print('Hello'+ name) Hello('Anne') It should give me following answer: Hello Anne but nothing shown up, then I ran the code, it gives me: Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; ======== RESTART: C:/Users/lampard1990/Desktop/Python/helloFunc 2.py ======== &gt;&gt;&gt; anyone knows why what happened? thanks
downvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/50441704
accepted answer: http://stackoverflow.com/a/50441704
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/50441053
has title: Self-Defined Python function didn't work
score: -3
has comment: http://stackoverflow.com/comment/87896436

http://stackoverflow.com/comment/87888264
has text: @AlexHall how can I remove the list for the ngrams methodand maintain the grouping? Any idea in mind or suggestion will much appreciated.
type: QuestionComment
comment on: http://stackoverflow.com/q/50436311
type: Comment
score: 0

http://stackoverflow.com/q/50493027
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50493074
accepted answer: http://stackoverflow.com/a/50493066
tagged with: pandas
has answer: http://stackoverflow.com/a/50493066
downvote count: 2
upvote count: 7
has answer: http://stackoverflow.com/a/50493065
has answer: http://stackoverflow.com/a/50493112
favorite count: 0
type: Question
score: 5
answer count: 5
possible better answer: http://stackoverflow.com/a/50493065
has comment: http://stackoverflow.com/comment/87999309
tagged with: python
has title: Changing positive(+) and negative(-) signs to integers in python
has answer: http://stackoverflow.com/a/50493565
has body: I have a dataframe with the following column: A + + - + - How do I convert this column into integer values. So that I could multiply it to other numerical values? Therefore, all '+' would be replaced by 1 and '-' by -1.

http://stackoverflow.com/q/50474488
has body: What I am trying to do is convert my date to datetime64[D]. At source - Some of the dates are object type and some of the dates are datetime64[ns]. I am not asking how to do the conversion - I know it. But something's happening while I create a new column, and following code seems to have no impact and datetime64[ns] doesnt change. df2['date'].values.astype('datetime64[D]') This is the sample dataframe: d = {'date' :['2015-10-05 15:08:43', '2015-10-05 19:17:12', '2015-10-06 15:51:22', '2015-10-06 19:39:18', '2015-10-06 19:58:06', '2015-12-18 11:09:01'], 'name': ['john', 'tom', 'phill', 'nero', 'bob', 'rob']} df2 = pd.DataFrame(data = d) date in df2 is object type. When we do the following df2['date'] = pd.to_datetime(df2['date']) date becomes dtype: datetime64[ns]. Now following code works and produces datetime64[D] output df2['date'].values.astype('datetime64[D]') But when I create a new column, it goes back to df2['date'] = df2['date'].values.astype('datetime64[D]') See the output here - Name: date, dtype: datetime64[ns] So, my question is that why is it not working when I am creating a new column ? Note: I know that last line produces warning. So I also tried below method but its not producing datetime64[D] newcol = df2['date'].values.astype('datetime64[D]') df2.assign(date = newcol)
has comment: http://stackoverflow.com/comment/87962691
has comment: http://stackoverflow.com/comment/87963652
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87962789
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/67738133
has comment: http://stackoverflow.com/comment/87962787
score: 3
has comment: http://stackoverflow.com/comment/87962636
linked to: http://stackoverflow.com/q/31917964
tagged with: pandas
has comment: http://stackoverflow.com/comment/87963122
has title: Date conversion doesn't work when creating new column
tagged with: datetime
has comment: http://stackoverflow.com/comment/87963050
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87962746
favorite count: 0
has comment: http://stackoverflow.com/comment/87962960
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87963891

http://stackoverflow.com/comment/87919603
type: Comment
type: QuestionComment
has text: @RohitGirdhar It was always returning the value, but if you don't handle it in any way it'd just be lost on the void. The output won't get written on a file by itself.
comment on: http://stackoverflow.com/q/50452934
score: 1

http://stackoverflow.com/comment/88091398
type: Comment
type: QuestionComment
score: 0
has text: I see your edit, and it is annoying because that is important information you should've added into your question _before_ I answered it.
comment on: http://stackoverflow.com/q/50539880

http://stackoverflow.com/q/50519700
has body: I want to give access to a user to the Jenkins job. To simulate his perms, I removed myself from admin group and called http://&lt;jenkins-url&gt;:8080/crumbIssuer/api/json using requests library in python. I get error 403 - Missing Overall/Read permissions. However, if I type the same url in jenkins where I am logged in using github, I get the crumb properly. Here is my requests call: req = requests.get('http://jenkins-url:8080/crumbIssuer/api/json', auth=('username', 'api-token')) What am I doing wrong? How do I get crumb through a python script.
answer count: 0
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88289998
tagged with: oauth
type: Question
tagged with: jenkins
has comment: http://stackoverflow.com/comment/88459252
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88398658
has title: Request Jenkins Crumb with Github Auth - Missing Overall/Read permissions

http://stackoverflow.com/comment/88041011
score: 0
has text: Just got this:tar: Damaged tar archive tar: Retrying... tar: Damaged tar archive tar: Retrying...
comment on: http://stackoverflow.com/q/50513091
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50400485
score: 7
tagged with: python
accepted answer: http://stackoverflow.com/a/50400522
type: Question
has answer: http://stackoverflow.com/a/50400522
has title: cumsum() on multi-index pandas dataframe
answer count: 2
has body: I have a multi-index dataframe that shows the sum of transactions on a monthly frequency. I am trying to get a cumsum() on yearly basis that respects my 'mapid' and 'service' multi-index. However I don't know how to derive that data combined_df = combined_df.groupby([pd.Grouper(freq='M'), 'provider', 'mapid', 'service']).sum() cost datetime provider mapid service 2017-08-31 Amazon 10147.0 Monitor 0.41 Storage 90.51 Virtual Machine 11646.32 2017-09-30 Amazon 10147.0 Monitor 0.89 Storage 226.06 Virtual Machine 32624.91 2017-10-31 Amazon 10147.0 Monitor 0.17 Storage 261.72 Virtual Machine 36934.93 2017-11-30 Amazon 10147.0 Monitor 0.35 Storage 269.06 Virtual Machine 30790.70 I would like to derive the follow results
downvote count: 0
upvote count: 7
possible better answer: http://stackoverflow.com/a/77864990
favorite count: 0
has answer: http://stackoverflow.com/a/77864990
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas

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

http://stackoverflow.com/q/50455845
tagged with: python
has answer: http://stackoverflow.com/a/50456257
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50456168
answer count: 3
tagged with: function
has answer: http://stackoverflow.com/a/50456168
has comment: http://stackoverflow.com/comment/87925380
has title: Changing arguments in Function after Importing
has answer: http://stackoverflow.com/a/50456322
type: Question
has comment: http://stackoverflow.com/comment/87925557
has body: I have a script which has a function that is used in various classes and other functions throughout the script. For example: from scipy.stats import beta import matplotlib.pyplot as plt def function(i): x = beta.pdf(i,a=10,b=2, scale = 100, loc = -50) return x def plotme(): graphme = [] for i in range(500): graphme.append(function(i)) plt.plot(graphme) def average(): averageme = [] for i in range(500): averageme.append(function(i)) average = sum(averageme)/float(len(averageme)) return print(average) Now if I wanted to import the module and call plotme() or average() it would use the values that are in the function(i). But is there a way for me to change the values of a, b, scale, and loc in function(i) when importing it? I know I could change each function to allow for it to change but I am hoping I could just adjust the initial function. Ideally, I would like to be able to do something like this: import mymodule mymodule.function(i, a = 500, b = 200, scale = 50, loc = 0) mymodule.plotme() And the plotme() would be based on the new values not what is coded in the script.
possible better answer: http://stackoverflow.com/a/50456257

http://stackoverflow.com/q/50469243
has body: I have 2 data sets with different variables. But both includes a variable, say NUM, that helps to identify the occurrence of an event. With the NUM, I was able to identify the event, by labelling it. How can one run RF to effectively include considerations of the 2 datasets? I am not able to append them (column wise) as the number of records for each NUM differs.
type: Question
has title: How to use classifier random forest in Python for 2 different data sets?
answer count: 2
has answer: http://stackoverflow.com/a/50487464
type: UnansweredQuestion
tagged with: random-forest
has comment: http://stackoverflow.com/comment/87956254
has comment: http://stackoverflow.com/comment/87951891
has comment: http://stackoverflow.com/comment/87953181
upvote count: 1
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/87951970
has comment: http://stackoverflow.com/comment/87955086
has answer: http://stackoverflow.com/a/50471284
tagged with: python
favorite count: 0

http://stackoverflow.com/q/50403717
tagged with: dictionary
has answer: http://stackoverflow.com/a/50403842
possible better answer: http://stackoverflow.com/a/50403842
has comment: http://stackoverflow.com/comment/87822953
score: 0
answer count: 2
upvote count: 1
has body: I have a json file, now I want to modify(change the key) of that json file. I am able to read through every item in that file but don't know how to write it in the new dictionary with modification using Python Currently the json file is like this : [ {"detail": ["Jishnu Prasad Rijal ", " Biratnagar , Morang,", "M", "BBS, India", "1"]}, {"detail": ["Lakshmishwar Prasad ", " Kharihani , Dhanusa,", "M", "BBS, India", "2"]}, ] But I want this in this format : [{ "name":"Jishnu Prasad Rijal","roll_no":1,"gender":"Male", "address":"Biratnagar,Morang","degree":"BBS, India" }, { "name":"Lakshmishwar Prasad ","roll_no":2,"gender":"Male", "address":"Kharihani , Dhanusa","degree":"BBS, India" }] Help would be really appreciated. Thank You
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87822984
has title: Load a json file, iterate through it and write every element in a new file
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87822932
has answer: http://stackoverflow.com/a/50403820
accepted answer: http://stackoverflow.com/a/50403820
tagged with: python

http://stackoverflow.com/comment/88030141
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50508838
score: 0
has text: I wonder why you need a UDF here at all? Your code should work fine in order to change the dtypes of your columns.

http://stackoverflow.com/a/50498262
has body: What you're looking for isn't possible using any built-in regexp functions that I know of. re.findall() only returns non-overlapping matches. After it matches dc, it looks for another match starting after that. Since the rest of the string is just c, and that doesn't match, it's done, so it just returns ["dc"]. When you use a quantifier like *, you have a choice of making it greedy, or non-greedy -- either it finds the longest or shortest match of the regexp. To do what you want, you need a way of telling it to look for successively longer matches until it can't find anything. There's no simple way to do this. You can use a quantifier with a specific count, but you'd have to loop it in your code: d.{0}c d.{1}c d.{2}c d.{3}c ... If you have a regexp with multiple quantified sub-patterns, you'd have to try all combinations of lengths.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50498073

http://stackoverflow.com/comment/87941571
score: 0
comment on: http://stackoverflow.com/q/50463421
type: Comment
type: QuestionComment
has text: That's debatable. Some say yes, others say no. Personally, I don't have a strong opinion on the topic.

http://stackoverflow.com/a/50479955
has comment: http://stackoverflow.com/comment/87985482
upvote count: 11
has comment: http://stackoverflow.com/comment/87973935
type: AcceptedAnswer
has body: If your code is primarily limited by IO and the files are on multiple disks, you might be able to speed it up using threads: import concurrent.futures import pickle def read_one(fname): with open(fname, 'rb') as f: return pickle.load(f) def read_parallel(file_names): with concurrent.futures.ThreadPoolExecutor() as executor: futures = [executor.submit(read_one, f) for f in file_names] return [fut.result() for fut in futures] The GIL will not force IO operations to run serialized because Python consistently releases it when doing IO. Several remarks on alternatives: multiprocessing is unlikely to help because, while it guarantees to do its work in multiple processes (and therefore free of the GIL), it also requires the content to be transferred between the subprocess and the main process, which takes additional time. asyncio will not help you at all because it doesn't natively support asynchronous file system access (and neither do the popular OS'es). While it can emulate it with threads, the effect is the same as the code above, only with much more ceremony. Neither option will speed up loading the six files by a factor of six. Consider that at least some of the time is spent creating the dictionaries, which will be serialized by the GIL. If you want to really speed up startup, a better approach is not to create the whole dictionary upfront and switch to an in-file database, possibly using the dictionary to cache access to its content.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50479487
has comment: http://stackoverflow.com/comment/87974565
has comment: http://stackoverflow.com/comment/87996339
answers question: http://stackoverflow.com/q/50479487
type: Answer
score: 11

http://stackoverflow.com/q/50413336
tagged with: python
has body: I have a program where each task is a call to a C++ external program through subprocess.Popen. The tasks are arranged in a graph and everything is executed through the dask get command. I have a single node version of this program that works just fine with dask.threaded and I am trying to extend this version to a distributed setting. My goal is to run it on a Slurm cluster but I have trouble deploying the workers. When I run the following: screen -d -m dask-scheduler --scheduler-file scheduler.json screen -d -m srun dask-worker --scheduler-file scheduler.json python3 myscript.py only a single core gets used on every node (out of twenty cores per node). I did suspect some issues with the GIL but the script works just fine with dask.threaded so I am not quite sure what is going on and some help would be appreciated.
has answer: http://stackoverflow.com/a/50413832
accepted answer: http://stackoverflow.com/a/50413832
type: Question
upvote count: 2
tagged with: dask
tagged with: slurm
downvote count: 0
answer count: 1
tagged with: dask-distributed
has title: Dask.distributed only uses one core per node
favorite count: 0
linked to: http://stackoverflow.com/q/56313707
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/99250169

http://stackoverflow.com/comment/87955863
has text: @TAH Oh nice. I'll expand and add that as an answer
score: 1
comment on: http://stackoverflow.com/q/50470933
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88126527
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50523549
type: Comment
has text: thank you. but by using "prevnext" it will create an endless clicking, because at the last page, there is a "Prev" button which is also located using "prevnext". this was my previous issue.

http://stackoverflow.com/comment/88008432
has text: I think function attributes are cute, but they aren't popular. Partly, that's for the reason given by zvone, and partly it's because they're obscure, so many people don't even realise that they're possible (apart from `.__doc__` and `.__name__`). I sometimes use them for state that doesn't affect the return value, eg tracking how many times the function gets called. I once thought they'd be ok for a memoizing cache, but they're slow (lookup time for the global function name, then lookup of the attribute).
score: 0
comment on: http://stackoverflow.com/q/50496545
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50469878
has answer: http://stackoverflow.com/a/50503983
has title: Restore Tensorflow Model Failed in Google Colab
has comment: http://stackoverflow.com/comment/88005901
has comment: http://stackoverflow.com/comment/87971647
type: UnansweredQuestion
has body: Restoring tensorflow model using saver.restore(sess,model_dir) is failing in Google Colaboratory. Restore Code tf.reset_default_graph() sq_net = classifierNet(input_shape,out_classes,lr_rate,is_train) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) train_vars = tf.trainable_variables() if model_dir is not None: if os.path.exists("{}.index".format(model_dir)): saver = tf.train.Saver() saver.restore(sess, model_dir) print("Model at %s restored" % model_dir) else: print("Model path does not exist, skipping...") else: print("Model path is None - Nothing to restore") The above code produces the following error: INFO:tensorflow:Restoring parameters from dri//colab//mod// --------------------------------------------------------------------------- NotFoundError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 1360 def _register_dead_handle(self, handle): -&gt; 1361 # Register a dead handle in the session. Delete the dead tensors when 1362 # the number of dead tensors exceeds certain threshold. /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata) 1339 # Nothing to do if we're using the new session interface -&gt; 1340 # TODO(skyewm): remove this function altogether eventually 1341 if self._created_with_new_api: return /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg) NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for dri//colab//mod//model.ckpt [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]] During …
downvote count: 0
answer count: 1
upvote count: 1
tagged with: google-colaboratory
has comment: http://stackoverflow.com/comment/88020083
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87977208
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/49675374

http://stackoverflow.com/q/50401562
has title: How to ask the user for a specific path to be used with open()?
upvote count: 3
has answer: http://stackoverflow.com/a/50401606
tagged with: path
downvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/64158945
answer count: 4
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50401658
type: UnansweredQuestion
has body: I'm trying to build a file transfer system with python3 sockets. I have the connection and sending down but my issue right now is that the file being sent has to be in the same directory as the program, and when you receive the file, it just puts the file into the same directory as the program. How can I get a user to input the location of the file to be sent and select the location of the file to be sent to?
has comment: http://stackoverflow.com/comment/87818969
tagged with: file
has answer: http://stackoverflow.com/a/50401663
score: 0

http://stackoverflow.com/comment/87909028
has text: Hi, I have one more question, just in case you know. If my model has a manytomany relationship (for example x and y are located on an object Location), can I use F() to access them? For example something like F("location.x")? (I tried this and it doesn't work)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50427417

http://stackoverflow.com/a/50467699
score: 1
type: Answer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87949542
answers question: http://stackoverflow.com/q/50465865
has body: If you want to use re this should do it: import re output = '''interface xe-1/2/0.0; interface ge-1/2/1.0; interface lo0.0 {''' print(re.findall('xe-\d/\d/\d', output)) #['xe-1/2/0'] To get to desired output, you can use: for found in re.findall('xe-\d/\d/\d', output): print('show interface {} extensive'.format(found))
has comment: http://stackoverflow.com/comment/87949491
has comment: http://stackoverflow.com/comment/87949113

http://stackoverflow.com/comment/87890204
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50437906
has text: There is the `str.rjust` method, but I guess you aren't allowed to use that for this exercise. Although you could use it during development to test that your code does the same thing as that method.

http://stackoverflow.com/comment/87973705
type: QuestionComment
type: Comment
has text: @ThuYeinTun Yes, while you can do that, it is nearly always a bad idea to do so.
comment on: http://stackoverflow.com/q/50480175
score: 0

http://stackoverflow.com/q/50531353
type: UnansweredQuestion
tagged with: flask-security
tagged with: flask
has body: So I am trying to configure flask security to send a confirmation email when I register but it doesn't seem to work. I want to use the credentials I generated from Google Cloud instead of setting up mail settings (MAIL_SERVER, MAIL_PASSWORD, etc). Here is my code: class BaseConfig: SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_RECORD_QUERIES = False SQLALCHEMY_EXPIRE_ON_COMMIT = False MARSHMALLOW_STRICT = True MARSHMALLOW_DATEFORMAT = 'rfc' SECRET_KEY = 'secret_key' SECURITY_LOGIN_SALT = 'test' SECURITY_PASSWORD_HASH = 'pbkdf2_sha512' SECURITY_TRACKABLE = True SECURITY_PASSWORD_SALT = 'something' WTF_CSRF_ENABLED = False SECURITY_REGISTERABLE = True SECURITY_CONFIRMABLE = True SECURITY_RECOVERABLE = True SECURITY_TOKEN_AUTHENTICATION_HEADER = 'Authorization' MAX_AGE = 86400 GOOGLE_APPLICATION_CREDENTIALS = '.\google_credentials_etc.json' But everytime I register I get this exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/usr/local/lib/python3.6/site-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/usr/local/lib/python3.6/site-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/usr/local/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.6/site-packages/flask/app.py…
tagged with: flask-mail
score: 0
tagged with: python
has title: Not able to use Google Cloud Authentication instead of mail settings
has comment: http://stackoverflow.com/comment/88075070
type: Question
answer count: 0
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/88074620

http://stackoverflow.com/comment/87951780
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50469113
type: AnswerComment
has text: But variables named `i` and `j` are likely to be declared integers anyway in any programming language.

http://stackoverflow.com/a/50390017
answers question: http://stackoverflow.com/q/50389746
downvote count: 1
has comment: http://stackoverflow.com/comment/87795912
type: Answer
score: -1
upvote count: 0
has body: I have test the same code on my mac. It works just fine. 0.25 for multi process and 0.45 for single process. Just change [N/process_num for x in range(process_num)] to [int(N/process_num for x in range(process_num)]

http://stackoverflow.com/q/50528067
tagged with: widget
has answer: http://stackoverflow.com/a/50528565
answer count: 1
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88068087
has comment: http://stackoverflow.com/comment/88068296
has comment: http://stackoverflow.com/comment/88067922
has comment: http://stackoverflow.com/comment/88068251
tagged with: python
has title: Bind mousewheel to two canvas but only one works
has body: I try to bind the mousewheel to a scroll canvas in two frames. But I can not get it right! Only in one frame the mousewheel is bound correctly. Where did I make the mistake? Is it not common to give every, let me call is CustomWidget and own binding to the MouseWheel? Do I have to unbind it in any way? If yes how can I unbind it from my "MyFirstGUI" Class ? I have some troubles to find the right "self". The binding in general is working for one class. If I scroll my mousewheel while SystemsGUI is shown in my window MainGUI gets scrolled. Here is an extraction of my code: from tkinter import * import tkinter.ttk as ttk class MyFirstGUI(object): def __init__(self, master): self.master = master self.gui_control = ttk.Notebook(master) self.main_gui = ttk.Frame(self.gui_control, borderwidth=0) self.systems_gui = ttk.Frame(self.gui_control, borderwidth=0) self.gui_control.add(self.main_gui, text='Main') self.gui_control.add(self.systems_gui, text='Systems') self.gui_control.grid(column=1,row=1, columnspan=9, rowspan=50,sticky=N+E+S+W) self.test_1 = Main.MainFrame(self.main_gui) self.test_1.grid(row=0, column=0, sticky="NESW") self.test_2 = Systems.SystemFrame(self.systems_gui) self.test_2.grid(row=0, column=0, sticky="NESW") #[...] master.mainloop() MainGUI: class MainFrame(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.main_canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0) self.main_canvas.grid(row=0,column=0, sticky="NESW") self.vsb = tk.Scrollbar(self, orient="vertical", command=self.main_canvas.yview) self.vsb.grid(row=0,column=1, sticky="NS") self.main_canvas.bind_all("&lt;MouseWheel&gt;", self._on_mousewheel) def _on_mousewheel(self, event): self.main_canvas.yview_scroll(int(-1*(event.delta/120)), "units") #[...] Systems GUI (basically the same): class SystemFrame(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.rowconfigure(0, weight=…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88068256
score: 0
tagged with: class
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88068146
accepted answer: http://stackoverflow.com/a/50528565

http://stackoverflow.com/q/50499429
has comment: http://stackoverflow.com/comment/88011664
has comment: http://stackoverflow.com/comment/88011651
has title: Self extract or something?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88011676
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88011706
has comment: http://stackoverflow.com/comment/88011695
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88011632
has comment: http://stackoverflow.com/comment/88011683
has comment: http://stackoverflow.com/comment/88108966
upvote count: 1
score: 1
has body: I'm trying to sell a very important file, because of that, I planned to create a "confirm and extract" python script, so that my python script will only extract the file only once and only when my client has paid. Now my problem is, can I do this? read my important file encode it with base64 compress and encrypt it (to make my script small size as possible) and then when extracting: decrypt, decompress and decode it' base64 and write the date to a file Is there any option better than this? I just don't want to download anything, so that the only way they'll be getting my file is through the (compiled to executable) python script

http://stackoverflow.com/q/50408842
has comment: http://stackoverflow.com/comment/87833387
has comment: http://stackoverflow.com/comment/87833359
score: 0
answer count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87907011
type: Question
has title: Python Memory Error while loading data into list
has body: I'm working with JSON Files, and trying to split consolidated JSON File to individual Files. But when the source file size is 503308 kb, my python code is giving error.I have tried with Pycharm and Cmd Prompt but its not working for me. Following is the Error-- line 67, in _buffer_decode codecs.utf_8_decode(input[3:], errors, final) MemoryError I have been looking for solutions, but nothing worked for me. Any help on this will be appreciated. Thanks a lot in advance :) import json import glob s_path = "D:\\User\\Desktop\\users\\SourceFolder\\" extension = "*.json" for file in glob.iglob(s_path+extension): with open(file, encoding="utf-8-sig") as json_data: d_list = json.load(json_data) item_count = len(d_list) target_path = 'D:\\Desktop\\users\\DumpingFolder\\' print(item_count) for item in d_list: file_name = "Raw_Response_" + str(item['id']) + ".json" print(file_name) with open(target_path+file_name, 'w+') as file_obj: json.dump(item, file_obj, indent=2, sort_keys=False)
type: UnansweredQuestion
tagged with: python
tagged with: memory

http://stackoverflow.com/q/50428095
type: Question
tagged with: frequency
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87871230
has answer: http://stackoverflow.com/a/50428244
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/87871206
has answer: http://stackoverflow.com/a/50428350
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50428223
score: 1
downvote count: 0
has title: Get frequency of letters in a sentence
upvote count: 1
favorite count: 0
has body: I am trying to make a code where I can input a random sentence, and count the frequency of the times a letter returns in this string: def getfreq(lines): """ calculate a list with letter frequencies lines - list of lines (character strings) both lower and upper case characters are counted. """ totals = 26*[0] chars = [] for line in lines: for ch in line: chars.append(totals) return totals # convert totals to frequency freqlst = [] grandtotal = sum(totals) for total in totals: freq = totals.count(chars) freqlst.append(freq) return freqlst So far I have achieved to append each letter of the input in the list (chars). But now I need a way to count the amount of times a character returns in that list, and express this in a frequency.

http://stackoverflow.com/comment/87940509
comment on: http://stackoverflow.com/q/50463669
score: 0
type: Comment
type: QuestionComment
has text: Updated my question

http://stackoverflow.com/a/50538176
has comment: http://stackoverflow.com/comment/88095878
has comment: http://stackoverflow.com/comment/88092887
has body: Consider below approach and example: df = pd.DataFrame({ 'col': ['a', 'b', 'c', 'd', 'e'] }) list_ = ['d', 'b', 'a'] print(df) Output: col 0 a 1 b 2 c 3 d 4 e Then in order to sort the df with the list and its ordering: df.reindex(df.assign(dummy=df['col'])['dummy'].apply(lambda x: list_.index(x) if x in list_ else -1).sort_values().index) Output: col 2 c 4 e 3 d 1 b 0 a
score: 0
answers question: http://stackoverflow.com/q/50537595
type: Answer

http://stackoverflow.com/q/50415578
has answer: http://stackoverflow.com/a/50416749
type: Question
type: UnansweredQuestion
tagged with: python
has title: Multicolor scatter plot legend in Python
tagged with: scatter-plot
upvote count: 2
tagged with: legend-properties
score: 2
has body: I have some basic car engine size, horsepower and body type data (sample shown below) body-style engine-size horsepower 0 convertible 130 111.0 2 hatchback 152 154.0 3 sedan 109 102.0 7 wagon 136 110.0 69 hardtop 183 123.0 Out of which I made a scatter plot with horsepower on x axis, engine size on y axis and using body-style as a color scheme to differentiate body classes and. I also used "compression ratio" of each car from a seperate dataframe to dictate the point point size This worked out well except I cant display color legends for my plot. Help needed as i'm a beginner. Here's my code: dict = {'convertible':'red' , 'hatchback':'blue' , 'sedan':'purple' , 'wagon':'yellow' , 'hardtop':'green'} wtf["colour column"] = wtf["body-style"].map(dict) wtf["comp_ratio_size"] = df['compression-ratio'].apply ( lambda x : x*x) fig = plt.figure(figsize=(8,8),dpi=75) ax = fig.gca() plt.scatter(wtf['engine-size'],wtf['horsepower'],c=wtf["colour column"],s=wtf['comp_ratio_size'],alpha=0.4) ax.set_xlabel('horsepower') ax.set_ylabel("engine-size") ax.legend()
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87847086
tagged with: matplotlib
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/87957072
comment on: http://stackoverflow.com/a/50471009
score: 0
has text: @JianDai: note that I still don't think you are using the redis pipe feature correctly.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50479517
tagged with: python
tagged with: telnet
score: 0
has title: Telnet using python example not working
type: Question
has answer: http://stackoverflow.com/a/50479741
type: UnansweredQuestion
has body: I have tried the below code as mentioned in python.org. As per the code, it asks for the remote account and password but nothing happens beyond that. The script waits for a couple of minutes and then just exits. import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() Am I missing something here? Thank you!!!
answer count: 1
has comment: http://stackoverflow.com/comment/87972606

http://stackoverflow.com/comment/87959419
type: QuestionComment
comment on: http://stackoverflow.com/q/50472831
score: 1
type: Comment
has text: Learning to code is a great start. Now you have some code you have written that isn't working right. That is, it compiles but does not run as expected, or issues errors. Even better! This is your opportunity to learn what is arguably the _most important skill a coder will ever learn_: debugging. Folks here will want to see what you have done to dig into the guesses you have shared with us. See here: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/

http://stackoverflow.com/q/50496439
score: 1
upvote count: 1
has body: I'm using Selenium. I want to save all the links (that are partial links ("https://instagram.com/p/")) in an array from a html page. My code looks like this: src = browser.page_source #here I get the html page tag = src.findall("https://instagram.com/p/") tag = [] print(tag) I want to do something just like this but don't know how.
favorite count: 0
has answer: http://stackoverflow.com/a/50496498
type: Question
has title: Find all links in a html file and store it in an array
type: UnansweredQuestion
tagged with: python
answer count: 1
tagged with: selenium
downvote count: 0

http://stackoverflow.com/a/54356494
score: 16
downvote count: 1
has comment: http://stackoverflow.com/comment/116936388
upvote count: 17
answers question: http://stackoverflow.com/q/50397250
has body: Here is my solution: def is_outlier(s): lower_limit = s.mean() - (s.std() * 3) upper_limit = s.mean() + (s.std() * 3) return ~s.between(lower_limit, upper_limit) df = df[~df.groupby('Group')['count'].apply(is_outlier)] You can write your own is_outlier function
has comment: http://stackoverflow.com/comment/112035912
has comment: http://stackoverflow.com/comment/124480565
type: Answer
has comment: http://stackoverflow.com/comment/124480358
has comment: http://stackoverflow.com/comment/137872829

http://stackoverflow.com/a/50830694
type: AcceptedAnswer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50486598
has body: Unfortunately I think you have hit a long-standing bug in ipython where it can't debug the call stack up through generators. See https://github.com/ipython/ipython/issues/6251 for details. I suspect that this is a result of their logic to hide the last frame (which would be inside ipython), but have no hard evidence for that. Until they fix it, you can work around the problem by using import pdb; pdb.pm() instead of the magic.
type: Answer
answers question: http://stackoverflow.com/q/50486598
score: 5
downvote count: 0

http://stackoverflow.com/a/50533758
has body: If your're ok with having a new dataframe, simply concatenate the columns: df1 = df[['1928','1928.1']] df2 = df[['1929','1929.1']] df2.columns = ['1928','1928.1'] df3 = df[['1930','1930.1']] df3.columns = ['1928','1928.1'] df = pd.concat([df1,df2,df3]) I think thats the most readable, and easiest way. You can overwrite your original dataframe and discard the others.
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50533522

http://stackoverflow.com/q/50427865
score: -1
has comment: http://stackoverflow.com/comment/87889741
has comment: http://stackoverflow.com/comment/87870480
has comment: http://stackoverflow.com/comment/87890416
has title: Write Output CSV has wrong/weird format
possible better answer: http://stackoverflow.com/a/50440941
has comment: http://stackoverflow.com/comment/87894136
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87872011
answer count: 2
has comment: http://stackoverflow.com/comment/87870498
has comment: http://stackoverflow.com/comment/87870381
downvote count: 2
tagged with: web-scraping
has body: I'm doing Web Scraping - I have a list that contains around 140 page titles but after writing it to CSV, the format of titles become very weird. In Python using Spyder, I can see proper results but only after writing it, in CSV it becomes weird. This is my write code. Am I doing anything wrong here? o_file = open('headlines.csv','w') with o_file: writer = csv.writer(o_file, delimiter=' ', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') writer.writerows(h_list) Output is coming like this in CSV (space after every alphabet and quotes after every word): H e r e ' s " " W h y " " T h e r e " " W a s " " a n " " E m p t y " " S e a t " " N e x t " " t o " " P r i n c e " " W i l l i a m " " a t " " t h e " " R o y a l " " W e d d i n g Also, in CSV at some rows there is data in Second column as well. While the work I'm doing has a list with 140 page titles which I can see in Spyder then how and why it is giving some page titles in second column as well? Any thoughts?
upvote count: 1
accepted answer: http://stackoverflow.com/a/50452905
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87889699
has answer: http://stackoverflow.com/a/50440941
has answer: http://stackoverflow.com/a/50452905
has comment: http://stackoverflow.com/comment/87889831
tagged with: python

http://stackoverflow.com/comment/87791193
score: 1
type: QuestionComment
has text: 'rollback doesn't work' isn't a very specific error. It's especially tricky to help because you're using such an old version of Django. Django 1.4 is years out of date, and the transaction APIs were overhauled in Django 1.5.
comment on: http://stackoverflow.com/q/50387068
type: Comment

http://stackoverflow.com/a/50494640
upvote count: 2
has body: Give this code a try: from skimage import io, color import os import imghdr source = r'C:\Users\Images\RGB' destination = r'C:\Users\Images\Greyscale' image_files = [os.path.join(root, filename) for root, dirs, files in os.walk(source) for filename in files if imghdr.what(os.path.join(root, filename))] for fn in image_files: rgb = io.imread(fn) grey = color.rgb2gray(rgb) head, tail = os.path.split(fn) io.imsave(os.path.join(destination, tail), grey) Notice that image_files is a list containing the full path name of all the image files found in source and its subdirectories (recursively). The complete list of image types being detected can be found at the documentation of the imghdr module.
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50476084

http://stackoverflow.com/q/50425973
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87866749
has comment: http://stackoverflow.com/comment/87866697
has body: I have a daily sales dataset of 4 items which is sold across 4 different franchises. I have to build a model to predict the weekly sales of all those 4 items for all the franchises. I am planning to use one base model for prediction reg = linear_model.Ridge(alpha=1) My question is how can I code to apply that model across all the 4 products and franchises. I will appreciate your time and effort to help me. Thank you My table is like below DepotName Product Date SalesUnits A A1 2015-01-23 2.0 A A2 2015-01-23 225.0 A A3 2015-01-23 120.0 A A4 2015-01-23 72.0 B A1 2015-01-23 90.0 B A2 2015-01-23 2.0 B A3 2015-01-23 1.0 B A4 2015-01-23 2.0 C A1 2015-01-23 1.0 C A2 2015-01-23 1.0 C A3 2015-01-23 4.0 C A4 2015-01-23 8040.0 D A1 2015-01-23 1590.0 D A2 2015-01-23 1.0 D A3 2015-01-23 1590.0 D A4 2015-01-23 1.0 A A1 2015-01-24 2.0 A A2 2015-01-24 225.0 A A3 2015-01-24 120.0 A A4 2015-01-24 72.0 B A1 2015-01-24 90.0 B A2 2015-01-24 2.0 B A3 2015-01-24 1.0 B A4 2015-01-24 2.0 C A1 2015-01-24 1.0 C A2 2015-01-24 1.0 C A3 2015-01-24 4.0 C A4 2015-01-24 8040.0 D A1 2015-01-24 1590.0 D A2 2015-01-24 1.0 D A3 2015-01-24 1590.0 D A4 2015-01-24 1.0
has comment: http://stackoverflow.com/comment/87866976
type: UnansweredQuestion
tagged with: linearmodels
tagged with: python
score: -1
has title: How to apply one model for different categories of interest in python?
has comment: http://stackoverflow.com/comment/87867207
tagged with: pandas
has answer: http://stackoverflow.com/a/50428302
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87867184
has comment: http://stackoverflow.com/comment/87867272
downvote count: 1

http://stackoverflow.com/a/50409830
answers question: http://stackoverflow.com/q/50408978
score: 0
has body: I recreated your project. The only thing you missed providing was your view. So I suppose that is where your problem is. Here is my view: def demoview(request): objs = BrandReport.objects.all() c = { "brand_reports": objs, } return render(request, "blog/demoview.html", c) And here is my template: {% for brand_report in brand_reports %} REPORT for Brand: {{ brand_report.brand.name }} {% for link in brand_report.links.all %} link: {{link.url}} {% endfor %} {% endfor %} And my result is exactly how you have desired. Please check your view.
type: Answer

http://stackoverflow.com/comment/87858478
has text: and if it is there, what do you want to do?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50421649
type: QuestionComment

http://stackoverflow.com/q/50434462
tagged with: tornado
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50435132
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: inheritance
has title: Python tornado use inheritance with parameters
score: 2
tagged with: python-2.7
answer count: 1
has body: I have a base handler class like this: class BaseHandler(RequestHandler): def get(self, id=None, *args, **kwargs): module = self.request.uri.split('/')[1].split('?')[0] this get method handler consists of 100 lines of code, As you can see module is acquired from url. in some cases I just need to change module and I don't want to completely rewrite get method. Is there any way to Inherit this method and change module?

http://stackoverflow.com/comment/88093861
comment on: http://stackoverflow.com/q/50541286
type: Comment
type: QuestionComment
has text: `for i in xrange(startFrame, endFrame + 1):` ??
score: 0

for-loop
tags question: http://stackoverflow.com/q/50448598
tags question: http://stackoverflow.com/q/50448351
tags question: http://stackoverflow.com/q/50458339
tags question: http://stackoverflow.com/q/50432300
tags question: http://stackoverflow.com/q/50529504
tags question: http://stackoverflow.com/q/50452324
tags question: http://stackoverflow.com/q/50393604
tags question: http://stackoverflow.com/q/50423965
tags question: http://stackoverflow.com/q/50517004
tags question: http://stackoverflow.com/q/50387793
tags question: http://stackoverflow.com/q/50479577
tags question: http://stackoverflow.com/q/50390409
tags question: http://stackoverflow.com/q/50485174
type: Tag
tags question: http://stackoverflow.com/q/50483587
tags question: http://stackoverflow.com/q/50406336
tags question: http://stackoverflow.com/q/50485911
tags question: http://stackoverflow.com/q/50533239
tags question: http://stackoverflow.com/q/50416452
tags question: http://stackoverflow.com/q/50413341
tags question: http://stackoverflow.com/q/50520133
tags question: http://stackoverflow.com/q/50520959
tags question: http://stackoverflow.com/q/50398933
tags question: http://stackoverflow.com/q/50530519
tags question: http://stackoverflow.com/q/50404487
tags question: http://stackoverflow.com/q/50514405
tags question: http://stackoverflow.com/q/50434132
tags question: http://stackoverflow.com/q/50417851
tag name: for-loop
tags question: http://stackoverflow.com/q/50448922
tags question: http://stackoverflow.com/q/50398535
tags question: http://stackoverflow.com/q/50508072
tags question: http://stackoverflow.com/q/50464273
tags question: http://stackoverflow.com/q/50457730
tags question: http://stackoverflow.com/q/50495057

http://stackoverflow.com/q/50530861
downvote count: 1
has title: large text editing, paste replace
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50531953
has body: I have a large text file with over ~200 million lines. It is split into blocks of approximately 50000 lines. What I need to do is replace lines 10-100 from all the blocks with lines 10-100 from the first block. Any ideas how to go about this? Thanks in advance
tagged with: python
score: -1
tagged with: editing
tagged with: text
upvote count: 0

http://stackoverflow.com/q/50395789
favorite count: 0
type: Question
has body: I am having trouble organizing my code in a well-principled object-oriented way. In summary: I would like to have two separate classes each implement their own functionality (e.g. simulating and plotting, respectively) but somehow combine them (in an extensible manner!) to have a single instance implement both of their functionalities. Example: suppose I have a class that generates data class DataSimulator(): def __init__(self, N): self.N = N self.result = None def simulate(self): self.result = range(self.N) #imagine lots of simulation code here I would also like to plot my data. I could simply add a plot() method to the DataSimulator but I think the DataPlotter should be its own separate class since its functionality is completely different from that of DataSimulator. A. One option I came up with was a separate class that stores a DataSimulator instance, then plots it as necessary class DataPlotter(): def __init__(self, data_simulator_instance): self.d = data_simulator_instance def plot(self): plt.plot(self.d.result) #e.g. using matplotlib dataSim = DataSimulator(5) dataPlt = DataPlotter(dataSim) dataSim.simulate() dataPlt.plot() However, in order to use this paradigm; I need to always be keeping track of two separate tightly coupled objects. This seems like bad practice. I will never have one without the other, so I'd like to combine their functionality into one. B. I considered having the DataPlotter inherit from DataSimulator like this: class DataPlotter(DataSimulator): def plot(self): plt.plot(self.result) dataPlt = DataPlotter(5) dataPlt.simulate() dataPlt.plot() This is nice because I now have only one instance that does everything I need, but this still seems wrong because: It's confusing for the DataPlotter instance to be performing the simulation routine If I write a DataSimulatorVersion2, I can't re-use my DataPlotter. C. Similarly I also considered the DataSimulator to inherit from DataPlotter class DataPlotter(): def plot(self): plt.plot(self.result) cl…
type: UnansweredQuestion
tagged with: python
tagged with: class
has title: Best-practice way to make two coupled classes interact
answer count: 2
tagged with: oop
downvote count: 0
tagged with: project-organization
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50395950
has answer: http://stackoverflow.com/a/50396037
has comment: http://stackoverflow.com/comment/87923909

http://stackoverflow.com/q/50418429
tagged with: python-2.7
type: Question
has body: I have a dataset in raw text file(its a log file),I am preparing python list using this text file reading line by line,with that list i will create a dataframe using pyspark .if you see the dataset ,some value are missing in respective column,i want to fill it with "NA".This is sample of Dataset,missing value can be in any column,column are separated by white space ============================================== empcode Emnname Date DESC 12d sf 2018-02-06 dghsjf asf2 asdfw2 2018-02-16 fsfsfg dsf21 sdf2 2016-02-06 sdgfsgf sdgg dsds dkfd-sffddfdf aaaa dfd gfg dfsdffd aaaa df dfdf efef 4fr freff ---------------------------------------------- MyCode: path="something/demo.txt" EndStr="----------------------------------------------" FilterStr="==============================================" findStr="empcode Emnname" def PrepareList(findStr): with open(path) as f: out=[] for line in f: if line.rstrip()==Findstr: #print(line) tmp=[] tmp.append(re.sub("\s+",",",line.strip())) #print(tmp) for line in f: if line.rstrip()==EndStr: out.append(tmp) break tmp.append(re.sub("\s+",",",line.strip())) return (tmp) f.close() LstEmp=[] LstEmp=prepareDataset("empcode Emnname Dept DESC") print(LstEmp) My output is: ['empcode,Emnname,Date,DESC', '12d,sf,2018-02-06,dghsjf', 'asf2,asdfw2,2018-02-16,fsfsfg', 'dsf21,sdf2,2016-02-06,sdgfsgf', 'sdgg,dsds,dkfd-sffddfdf,aaaa', 'dfd,gfg,dfsdffd,aaaa', 'df,dfdf,efef', '4fr,freff'] Expected output: ['empcode,Emnname,Date,DESC', '12d,sf,2018-02-06,dghsjf', 'asf2,asdfw2,2018-02-16,fsfsfg', 'dsf21,sdf2,2016-02-06,sdgfsgf', 'sdgg,dsds,dkfd-sffddfdf,aaaa', 'dfd,gfg,dfsdffd,aaaa', 'df,NA,dfdf,efef', '4fr,NA,NA,freff']
has comment: http://stackoverflow.com/comment/87852810
linked to: http://stackoverflow.com/q/41944689
has title: How to fill with NA in missing place of a text file using python list
has comment: http://stackoverflow.com/comment/87852461
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50422459
score: 0
accepted answer: http://stackoverflow.com/a/50431722
answer count: 2
tagged with: pyspark
has answer: http://stackoverflow.com/a/50422459
tagged with: python
has answer: http://stackoverflow.com/a/50431722

http://stackoverflow.com/q/50457448
linked to: http://stackoverflow.com/q/45061088
answer count: 2
accepted answer: http://stackoverflow.com/a/50457496
type: Question
has body: Lets say I have the following dataframe: ID | has_id_dummy ----------------------- 340 NaN NaN NaN NaN NaN 200 NaN And I want to turn it into this DataFrame: ID | has_id_dummy ----------------------- 340 1 NaN 0 NaN 0 200 1 To do this I came up with the following function: def dummypopulator(x): if x != np.nan: return 1 return 0 which I call with the following line df['has_id_dummy'] = df['ID'].apply(dummypopulator) But the value is then set to 1 for all rows, even the rows that dont have an ID and should be 0. ID | has_id_dummy ----------------------- 340 1 NaN 1 NaN 1 200 1 I tried calling the function with a seperate lambda as I saw in an example: df['has_id_dummy'] = df['ID'].apply(lambda x: dummypopulator(x)) Yet the result is the same. I feel like I am missing a very obvious error, but for the life of me cant figure out why it wont work. Does anyone know what I am doing wrong?
possible better answer: http://stackoverflow.com/a/50457465
tagged with: pandas
has title: Pandas: .apply function gives entire column single value
has answer: http://stackoverflow.com/a/50457465
duplicate of: http://stackoverflow.com/q/45061088
tagged with: python
has comment: http://stackoverflow.com/comment/87928574
has answer: http://stackoverflow.com/a/50457496
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87856472
type: AnswerComment
comment on: http://stackoverflow.com/a/50420213
score: 0
has text: Thanks, but that's not efficient, as it requires the entire file to be read. My file won't fit in RAM; my file is 100GB to 1000GB in size. I don't have a machine with 2-5 TB of RAM.
type: Comment

mpc
tag name: mpc
type: Tag
tags question: http://stackoverflow.com/q/50437334

http://stackoverflow.com/q/50473951
has body: I'd like to give documentation for each member of a python enum in a way that IPython can find it. What I have right now is something like: class Color(Enum): """ RED: The color red GREEN: The color green BLUE: The color blue. These docstrings are more useful in the real example """ RED = 1 GREEN = 2 BLUE = 3 This isn't great, as it duplicates the member names, and makes it harder to ask for the documentation for just one member. I can get what I'm after with class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 Color.RED.__doc__ = "The color red" Color.GREEN.__doc__ = "The color green" Color.BLUE.__doc__ = "The color blue. These docstrings are more useful in the real example" But this still suffers from repetition of the names. Is there an easier way of doing this?
possible better answer: http://stackoverflow.com/a/50475245
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
has title: How can I attach documentation to members of a python enum?
duplicate of: http://stackoverflow.com/q/19330460
has answer: http://stackoverflow.com/a/50475245
upvote count: 16
accepted answer: http://stackoverflow.com/a/50473952
favorite count: 0
score: 16
has answer: http://stackoverflow.com/a/50473952
tagged with: enums
type: Question

http://stackoverflow.com/comment/87962059
type: Comment
has text: Missing a closing bracket at `self.BookSum[self.ByNum.get[int(bnum)]`. Let this be a lesson to not do too much in a single line of code.
type: QuestionComment
comment on: http://stackoverflow.com/q/50474250
score: 2

http://stackoverflow.com/q/50514138
has answer: http://stackoverflow.com/a/50514229
tagged with: plot
favorite count: 0
type: Question
has title: Resample Dataframe Monthly and store the count for each month in new Dataframe with columns as Date and Count
has answer: http://stackoverflow.com/a/50514310
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: date
has body: I want to sample my Dataframe with the date as an index to monthly data and count the instances for each month and then store it in a new dataframe. Data: Date Title 2001-05-22 A 2001-05-28 B 2001-06-13 C 2001-06-14 D 2001-06-15 E 2001-07-15 F 2001-07-13 G 2001-07-16 H 2001-07-17 I . . . . . . 2001-12-01 Y 2001-12-31 Z So I want the ouput should be like: New Dataframe with columns Date Count 2001-05-31 2 2001-06-30 3 2001-07-31 4 2001-08-30 1 . . . . And after that, plot the data as any graph(bar or which ever looks good for such data) with date as x-axis. Note: The data is for a long-range period(2001-2017) so x-axis shouldn't get overlap.
answer count: 2
score: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/87880915
type: QuestionComment
comment on: http://stackoverflow.com/q/50432745
has text: I think this [answer](https://stackoverflow.com/a/45666029/6220679) will help you. I could just copy and paste it here, and that means I should vote to close this question, since it's a duplicate, unless you want to do someting different.
score: 0
type: Comment

http://stackoverflow.com/q/50536885
has title: Questions regarding this implement of a playing card game
answer count: 0
linked to: http://stackoverflow.com/q/4932438
upvote count: 1
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/1535327
has comment: http://stackoverflow.com/comment/88193698
has comment: http://stackoverflow.com/comment/88086501
has comment: http://stackoverflow.com/comment/88085902
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88085908
has comment: http://stackoverflow.com/comment/88089234
tagged with: python
tagged with: playing-cards
has comment: http://stackoverflow.com/comment/88085917
type: Question
has body: from enum import Enum from enum import IntEnum class Suits(Enum): DIAMONDS="diamonds" HEARTS="hearts" SPADES="spades" CLUBS="clubs" class Values(IntEnum): TWO=2 THREE=3 FOUR=4 FIVE=5 SIX=6 SEVEN=7 EIGHT=8 NINE=9 TEN=10 JACK=11 QUEEN=12 KING=13 ACE=14 deck_of_cards=[] class Playing_Cards(): def __init__(self, card_value, card_suit): self.card_value=card_value self.card_suit=card_suit deck_of_cards=[] for suit in Suits: for value in Values: deck_of_cards.append(Playing_Cards(value,suit)) print(deck_of_cards) I want to print deck_of_cards and it's showing a list of objects. Could you please explain why? [&lt;__main__.Playing_Cards object at 0x102268128&gt;, &lt;__main__.Playing_Cards object at 0x102268198&gt;, &lt;__main__.Playing_Cards object at 0x1022681d0&gt;, &lt;__main__.Playing_" Questions: Did I add cards(value, suit) to the list properly? How can I print what is in the list deck_of_cards?
score: 0
linked to: http://stackoverflow.com/q/1535327

http://stackoverflow.com/comment/88038693
comment on: http://stackoverflow.com/q/50512524
type: QuestionComment
has text: @cdarke will it be similar with the approach that I use right now? By counting the start and end using `time.time()` and subtracting the delay by that?
type: Comment
score: 0

http://stackoverflow.com/comment/118495267
has text: What's meaning of `NOQA`?
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50439398

http://stackoverflow.com/comment/88001922
type: AnswerComment
has text: Thanks for fixing that, it's one of my pet peeves :) Again, I think most people would understand "call-by-reference" to mean "passing a reference to the object", but I like to keep terminology straight, and I believe that drift in this regards just makes everything more confusing
score: 2
comment on: http://stackoverflow.com/a/50494501
type: Comment

http://stackoverflow.com/q/50394097
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50394366
answer count: 2
has body: I have a dataframe df as below: date1 item_id 2000-01-01 00:00:00 0 2000-01-01 10:01:00 1 2000-01-01 00:02:00 2 2000-01-01 00:03:00 3 2000-01-01 00:04:00 4 2000-01-01 00:05:00 5 2000-01-01 00:06:00 6 2000-01-01 12:07:00 7 2000-01-02 00:08:00 8 2000-01-02 00:00:00 0 2000-01-02 00:01:00 1 2000-01-02 03:02:00 2 2000-01-02 00:03:00 3 2000-01-02 00:04:00 4 2000-01-02 00:05:00 5 2000-01-02 04:06:00 6 2000-01-02 00:07:00 7 2000-01-02 00:08:00 8 I need the data for single day i.e. 1st Jan 2000. Below query gives me the correct result. But is there a way it can be done just by passing "2000-01-01"? result= df[(df['date1'] &gt; '2000-01-01 00:00') &amp; (df['date1'] &lt; '2000-01-01 23:59')]
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50394127
favorite count: 0
has answer: http://stackoverflow.com/a/50394127
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: datetime
tagged with: python
has title: Getting data for given day from pandas Dataframe
possible better answer: http://stackoverflow.com/a/50394366

http://stackoverflow.com/comment/87991027
comment on: http://stackoverflow.com/a/50488693
has text: `numpy`. It is stated somewhere in the documentation. But by just looking at my example it should be self-explanatory why this is true.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88024378
score: 0
type: QuestionComment
has text: have you tried calling it with `index=True` or do you specifically want to avoid making the DF's index the DB index as well
comment on: http://stackoverflow.com/q/50503934
type: Comment

http://stackoverflow.com/comment/137872829
has text: This does not work with the recent pandas version. It returns `IndexingError: Unalignable boolean Series provided as indexer` error
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/54356494

http://stackoverflow.com/comment/87892074
type: QuestionComment
has text: @georgewg i think django wont process the request, if Access control header is not defined, correct me if i am wrong
score: 0
comment on: http://stackoverflow.com/q/50438567
type: Comment

pandas-apply
tags question: http://stackoverflow.com/q/50458605
tag name: pandas-apply
tags question: http://stackoverflow.com/q/50533570
type: Tag

http://stackoverflow.com/a/50403842
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50403717
upvote count: 2
downvote count: 0
has body: Simply using zip keys = ['name', 'address', 'gender', 'degree', 'role_no'] x = [dict(zip(keys, i['detail'])) for i in x] [{'name': 'Jishnu Prasad Rijal ', 'address': ' Biratnagar , Morang,', 'gender': 'M', 'degree': 'BBS, India', 'role_no': '1'}, {'name': 'Lakshmishwar Prasad ', 'address': ' Kharihani , Dhanusa,', 'gender': 'M', 'degree': 'BBS, India', 'role_no': '2'}]

http://stackoverflow.com/q/50487703
has comment: http://stackoverflow.com/comment/87988152
has comment: http://stackoverflow.com/comment/87988188
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87988112
has body: I'm writing a program for multiplying rabbits every month, I know there's already questions about it but I can't find something that makes sense to me, I'm new to python so I can't do a lot of advanced stuff. This is my code so far. Every month, a pair of rabbits has 4 bunnies, so after one month there are 6 rabbits, after two months there's 18, and after three months there's 54. months=input("Enter number of months:") total=0 while months&gt;0: total=months*4+2 total=total+((total/2)*4) print (total)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87988131
has title: Multiplying Rabbits python
has comment: http://stackoverflow.com/comment/87988237
has comment: http://stackoverflow.com/comment/87988371
has answer: http://stackoverflow.com/a/50488106
tagged with: python
has answer: http://stackoverflow.com/a/50488077
has comment: http://stackoverflow.com/comment/87988304
upvote count: 2
score: 2
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50502793
type: Question
accepted answer: http://stackoverflow.com/a/50509717
score: 0
has title: Pyside QTablewidget qcheckbox click event
has body: I have added qcheckbox in first cell of qtablewidget now what I want is how to access checkbox and how to get its click event.Basically what I want is on checkbox check row should be selected and on unchecked row should be dis-selected. Here is code: def add_items(self): rows = 5 cols = 5 self.tableWidget.setRowCount(5) self.tableWidget.setColumnCount(5) for r in range(0, rows): for c in range(1, cols): self.qwidget = QtGui.QWidget() self.checkbox = QtGui.QCheckBox() self.checkbox.setCheckState(QtCore.Qt.Checked) qhboxlayout = QtGui.QHBoxLayout(self.qwidget) qhboxlayout.addWidget(self.checkbox) qhboxlayout.setAlignment(QtCore.Qt.AlignCenter) qhboxlayout.setContentsMargins(0, 0, 0, 0) self.tableWidget.setCellWidget(r, 0, self.qwidget) item = QTableWidgetItem('note'+str(r)) self.tableWidget.setItem(r, c, item) print 'done'
tagged with: pyqt
answer count: 1
tagged with: qcheckbox
has answer: http://stackoverflow.com/a/50509717
type: AnsweredQuestion
tagged with: qtablewidget
tagged with: pyside
tagged with: python

http://stackoverflow.com/q/50513186
accepted answer: http://stackoverflow.com/a/50513249
type: Question
tagged with: text
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50513263
possible better answer: http://stackoverflow.com/a/50513263
has answer: http://stackoverflow.com/a/50513512
has answer: http://stackoverflow.com/a/50513277
downvote count: 1
has answer: http://stackoverflow.com/a/50513249
favorite count: 0
type: AnsweredQuestion
answer count: 5
has body: I have a long string, and would like to replace occurrences of this kind: 'eggs (spam): tomatoes' with ones of this kind: 'eggs : spam tomatoes' That is to say, if there is a pattern of the kind 'left bracket, text, right bracket, double-colon, space', then I would like it to be replaced with 'double-colon, space, text'. I have tried writing the following: import re re.sub('\(.+\): ', '', 'eggs (spam): tomatoes') but (unsurprisingly) it removes the bracketed text completely, and I don't know how to retain the text which was previously bracketed in the 'replace' part of the function.
has title: Remove brackets around text and add colon at the end
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50513306

http://stackoverflow.com/comment/88084366
comment on: http://stackoverflow.com/q/50535964
has text: What URL are you attempting to reach on the remote server, and where is the 404 message appearing? What corresponding messages appear in the remote server's error and/or log files?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87914425
type: AnswerComment
comment on: http://stackoverflow.com/a/50450119
score: 0
type: Comment
has text: "Concurrently" may not mean what you think it means. Python threads do run [concurrently](https://en.wikipedia.org/wiki/Concurrent_computing), but the GIL prevents them from running in _[parallel](https://en.wikipedia.org/wiki/Parallel_computing)_.

http://stackoverflow.com/comment/87842850
score: 0
has text: is maybe the "#/" at the end of the URL the problem? Do i need the "s" after %? But i've tryed with and without...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50412172

http://stackoverflow.com/comment/104655114
type: Comment
has text: I have tried the same, I dont know why my code throws the error at y_train = le.fit_transform(datacan['Gene_Symbol'][:-1]) KeyError: 'Gene_Symbol'
comment on: http://stackoverflow.com/a/50458228
type: AnswerComment
score: 0

http://stackoverflow.com/a/50522719
type: Answer
has comment: http://stackoverflow.com/comment/88071044
has comment: http://stackoverflow.com/comment/88115343
has comment: http://stackoverflow.com/comment/88066345
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50521738
has body: Spark will process each partition depending on the total amount of cores available to the job you're running. Let's say your spark job has 100 executors, each one with 3 cores. This means that you'll be able to process 100 x 3 = 300 partitions concurrently, assuming spark.task.cpus is set to 1. spark.task.cpus is the number of cores to allocate for each task and --executor-cores specify Number of cores per executor. worker node with 2 executors, process 2 x 3 = 6 partitions. And default spark.default.parallelism = 12. So 6x12 = 72. The two configuration properties in Spark to tune the number of partitions at runtime are as follows: Increase the default parallelism by --conf spark.default.parallelism=36 --conf spark.default.parallelism=36 set spark.task.cpus=2 and --executor-cores 4 (in spark submit command). So each node will process only (4/2 =) 2 partitions. In this case 36 nodes will be used in processing data in parallel.
score: 1

http://stackoverflow.com/q/50480348
has comment: http://stackoverflow.com/comment/88149580
score: 2
has body: I have a project where I have to use robotframework to make a series of tests. In my Python 2.7 environment I have installed robotframework 3.0.4. At this point I want to use the framework in my python code (is a Django project) like this: from robot import run as run_test run_test('&lt;path of my html test file&gt;.html') test start and create a log and report files but in the log.html there aren't INFO and WARN messages. Now, if i open IDLE and make the same things: &gt;&gt;&gt;from robot import run as run_test &gt;&gt;&gt;run_test('&lt;same path above&gt;.html') test run and in the log.html file I have my FAIL, INFO, and WARN messages logged correctly! How is possible that from my python code for the same test robotframework don't log INFO and WARN and from IDLE it do?
answer count: 0
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: robotframework
has title: Python and robotframework not INFO or WARN in log
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/87978701
score: 0
has text: Can you [edit] the question to show a small example of `pg5200.txt` that recreates your problem?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50481291

http://stackoverflow.com/q/50496325
tagged with: string
upvote count: 10
has comment: http://stackoverflow.com/comment/88005516
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23564955
has comment: http://stackoverflow.com/comment/88006343
type: UnansweredQuestion
has title: Why does augmented assignment behave differently when adding a string to a list
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/88005869
tagged with: augmented-assignment
has answer: http://stackoverflow.com/a/50497033
has comment: http://stackoverflow.com/comment/88005660
duplicate of: http://stackoverflow.com/q/9766387
duplicate of: http://stackoverflow.com/q/2347265
tagged with: list
has answer: http://stackoverflow.com/a/50496451
downvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/88005688
has answer: http://stackoverflow.com/a/50496529
has body: I am in a very interesting situation and I am so surprised. actually I thought both i += 1 and i = i + 1 are same. but it'is not same in here; a = [1,2] a += "ali" and output is [1,2,"a","l","i"] but if I write like that; a = [1,2] a = a + "ali" it doesn't work. I am really confused about this. are they different?
duplicate of: http://stackoverflow.com/q/8322792
has comment: http://stackoverflow.com/comment/88007078

http://stackoverflow.com/q/50416841
accepted answer: http://stackoverflow.com/a/50421764
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87849429
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has comment: http://stackoverflow.com/comment/87856753
has body: My online json file is like data( [ { "CCODE": "15ET", "CNAME": "JOE", "CAGE": 32 },{ "CCODE": "15ET", "CNAME": "JOE", "CAGE": 32 },{ "CCODE": "15ET", "CNAME": "JOE", "CAGE": 32 } ] ) I am trying to scrap it using scrapy , but the code json.loads(response.body_as_unicode()) is giving JSONDecodeError: Expecting value as the json format is incorrect . Is there any workarounds for this problem .
tagged with: scrapy
has comment: http://stackoverflow.com/comment/87849362
has comment: http://stackoverflow.com/comment/87858672
type: Question
has comment: http://stackoverflow.com/comment/87849933
has answer: http://stackoverflow.com/a/50421764
has title: Scraping non formatted json
tagged with: python

http://stackoverflow.com/a/50430028
has comment: http://stackoverflow.com/comment/87875044
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50429685
type: AcceptedAnswer
downvote count: 0
has body: Python evaluates the default parameters when a function is defined. When you define: class Matrix4(): def __init__(self, row1 = Vec4() ... you create a Vec4 instance, and this instance will now be used as default value each time this __init__ method gets called. The first time you create a Matrix4 instance, __init__ will execute, and this instance gets refered to by the name row1 Then you have: self.m_values = [row1,row2,row3,row4] So this instance is now refered to by self.m_values[0]. Later, in ScaleMatrix.update, you update this Vec4 instance: for i in range(3): self.m_values[i].values[i] = self.getScale().values[i] The next time you will call Matrix4.__init__ without parameters, the default value will be used, and this is the Vec4 that you just updated. You have a similar behaviour when you use an empty list as default parameter, see “Least Astonishment” and the Mutable Default Argument . The usual way to avoid this problem is to avoid using mutable objects as default parameters. You could do: class Matrix4(): def __init__(self, row1 = None, row2 = None, row3 = None, row4 = None): if row1 is None: row1 = Vec4() if row2 is None: row2 = Vec4() if row3 is None: row3 = Vec4() if row4 is None: row4 = Vec4() self.m_values = [row1,row2,row3,row4] self.trans_values = [Vec4(),Vec4(),Vec4(),Vec4()] self.set_transp_matrix() which gives as output: 3 0 0 0 0 4 0 0 0 0 5 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 6 9 12 20 24 28 32 45 50 55 60 13 14 15 16
accepted answer of: http://stackoverflow.com/q/50429685
type: Answer

http://stackoverflow.com/q/50408590
downvote count: 0
score: 1
upvote count: 1
has title: Manage RabbitMQ auto-delete queues in different threads. Python
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: pika
has body: I would like to know if this is the correct way to manage auto_delete queues in different threads (is mainly for testing issues where I don't want the RabbitMQ queues stay when connection closes) import pika from threading import Thread class ConsumerThread(Thread): def __init__(self, callback, queue): Thread.__init__(self) self.setDaemon(True) self.callback = callback self.queue = queue def run(self): # stablish connection connection = pika.BlockingConnection(pika.ConnectionParameters(CONNECTION['address'], CONNECTION['port'], CONNECTION['vhost'], CONNECTION['credentials'])) channel = connection.channel() # create the auto-delete queue channel.queue_declare(queue=self.queue, auto_delete=True) # start consuming channel.basic_qos(prefetch_count=1) channel.basic_consume(self.callback, queue=self.queue) channel.start_consuming() class Factory: def __init__(self): self.queue_init = "init.queue" self.queue_start = "start.queue" threads = [ConsumerThread(self.init_callback, self.queue_init), ConsumerThread(self.start_callback, self.queue_start)] for t in threads: t.start() def init_callback(self, ch, method, properties, body): # doing something def start_callback(self, ch, method, properties, body): # doing something
type: Question
has answer: http://stackoverflow.com/a/50413495
tagged with: python
type: UnansweredQuestion
tagged with: rabbitmq
tagged with: multithreading

http://stackoverflow.com/comment/87867283
comment on: http://stackoverflow.com/a/50426334
has text: Is this faster than `flt(parts[1:])`? I guess not.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50435561
upvote count: 0
downvote count: 2
type: UnansweredQuestion
score: -2
answer count: 1
has title: Variable with two user inputs
favorite count: 0
tagged with: python
has body: rentalPeriod = input("Number of Weeks Rented:\n") I need some help with using one variable and two user inputs and then to print out the rentalPeriod using the two variables with a logical operator using or. With the second string "Number of Days Rented:\n as the second input
has answer: http://stackoverflow.com/a/50435583
type: Question

http://stackoverflow.com/q/50440848
has title: Check if bullet point is in list
possible better answer: http://stackoverflow.com/a/50440866
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50440990
has answer: http://stackoverflow.com/a/50440866
upvote count: 2
has answer: http://stackoverflow.com/a/50440990
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87896081
score: 2
has comment: http://stackoverflow.com/comment/87896087
has body: So I am trying to check and see if a bullet point is part of an item in a list by iterating through it with a for loop. I know that, at least in Regex a bullet point is defined as \u2022. But don't know how to use this. What I currently have but obviously doesn't work is something like this. list = ['changing. • 5.0 oz.', 'hello', 'dfd','df', 'changing. • 5.0 oz.'] for items in list: if "\u2022" in items: print('yay') Thanks in Advance!
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/87983573
type: QuestionComment
comment on: http://stackoverflow.com/q/50484406
score: 1
has text: You should look at weasyprint. PyPDF2 is more suited for reading and merging pdf files.
type: Comment

http://stackoverflow.com/comment/124205939
comment on: http://stackoverflow.com/a/50388018
score: 1
type: Comment
has text: @strike_noir: what I figured out is, when you trying to use values in form or tree, then you are possibly "breaking" odoo logic. If you want to render just some values, you need to create a new widget (template) and add this by calling an action for it.
type: AnswerComment

http://stackoverflow.com/q/50431320
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Getting data from one column based on the value of other column
has comment: http://stackoverflow.com/comment/87877510
tagged with: pandas
has comment: http://stackoverflow.com/comment/87877472
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50440589
has body: I am having trouble coming up with an algorithm for the following problem: I have two data frames, df1 and df2 (the following are just an example): import pandas as pd df1 = pd.DataFrame({'Col1': [1, 7, 10, 50, 73, 80 ], 'Col2': [1,2,3,4,5,6]}) df2 = pd.DataFrame({'Col1': [0, 4, 10, 80], 'Col3': [7,6,8,9]}) As you can see, they both have the Col1, but the values aren't always coincident, but they are in ascending order. I want to create a function that will create a new column on df1, let's call it Col4. The values on this column have to come from df2 following these rules: 1) If df1 and df2 have the same value in Col1, the value in Col4 should be the corresponding value in Col3. 2)If they do not share the same value in Col1, Col4 should be the average between values in Col3 that correspond to the values immediately before and after it. For example: As df2 does not have a value in Col1 for 1, the first entry in Col4 should be the average between 7 and 6 (1 is between 0 and 4). I don't know if I made myself very clear, but the final result for Col4 should be: (7+6)/2, (6+8)/2, 8, (8+9)/2, (8+9)/2, 9 It would be nice to have a function because I will have to make this operation on many different data frames. I know it is a weird problem, but thanks for the help!
has comment: http://stackoverflow.com/comment/87877069
upvote count: 2
has comment: http://stackoverflow.com/comment/87877539
tagged with: function
type: UnansweredQuestion

http://stackoverflow.com/comment/87921429
has text: @Hitesh glad to help.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50454010
type: AnswerComment

http://stackoverflow.com/q/50391357
type: Question
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/87805583
type: UnansweredQuestion
downvote count: 0
has body: From Google Cloud Documentation we have Cloud Machine Learning Engine online prediction is a service optimized to run your data through hosted models with as little latency as possible. You send small batches of data to the service and it returns your predictions in the response. You can learn more general information about online prediction with the other prediction concepts. Blockquote https://cloud.google.com/ml-engine/docs/tensorflow/online-predict And my experience with it is sub-par I must say. Don't get me wrong, I love ML Engine and I do a whole lot of training there, but in my experience, the inference time is ridiculous. I've made a small semantic segmentation network on images of size 256x256. I'm using Estimators and I convert the model to a SavedModel format, then make predictions using this code predictor_fn = tf.contrib.predictor.from_saved_model( export_dir=saved_model_dir, signature_def_key="prediction" ) On my computer, this gave me inference time around 0.9 seconds. I tried the same code on a Datalab instance, with machine-type of n1-highmem-2 which gave me inference time of around 2.3 seconds. Now, if I serve my saved model on ML-Engine instead gcloud ml-engine models create SEM --regions europe-west1 gcloud ml-engine versions create SEM --model V0 --origin "MY_BUCKET_PATH" --runtime-version=1.6 And the serving input function is so: def parse_incoming_tensors(incoming): img = vgg16_normalize(tf.reshape(incoming, [-1, 256, 256, 3])) return img def serving_input_fn_web(): """Input function to use when serving the model on ML Engine.""" inputs = tf.placeholder(tf.string, shape=(None, )) feature_input = batch_base64_to_tensor(inputs) feature_input = {'img': parse_incoming_tensors(feature_input)} return tf.estimator.export.ServingInputReceiver(feature_input, inputs) Then, I make predictions using this class: class MakeQuery(): def __init__(self, project, model, version=None, client_secret=None): # Set the environment variable secret_path = os.path.abs…
tagged with: tensorflow
favorite count: 0
has title: ML Engine - Slow Inference Time
tagged with: google-cloud-ml
tagged with: python
has comment: http://stackoverflow.com/comment/87825525

http://stackoverflow.com/comment/87807142
has text: Which lock are you referring to? Is it in the multiprocessing queue? Do you use a `Manager` (which can be expensive)?
type: QuestionComment
comment on: http://stackoverflow.com/q/50395008
type: Comment
score: 0

http://stackoverflow.com/a/50430579
has comment: http://stackoverflow.com/comment/87897549
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87897499
type: AcceptedAnswer
has body: During the process of destroy() in pack() it appears that Frames are appended to root, and in grid() it appears they are inserted. Not exactly. In both cases they are added to the frame according to their options. In the case of pack, the default placement option (eg: side) is to place the widget at the top of the available space in the parent/master. In the case of grid the default is to use the first unoccupied row after all other widgets in the same parent/master. If not specified, the column number will be zero. Best practices dictate that you should always specify at least the side option with pack, and the row and column option with grid so that there is never any confusion about where the widget is intended to be placed. I have also run into the problem of the entries being of type(') instead of tkinter.Entry That question doesn't make any sense. The objects created by Entry will always be of type &lt;class 'tkinter.Entry'&gt;, and the method get will always work when used on an object of that type.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50429744
type: Answer
answers question: http://stackoverflow.com/q/50429744

http://stackoverflow.com/comment/87860192
score: 1
comment on: http://stackoverflow.com/a/50422501
has text: @Mulliganaceous i add this :)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50487345
has body: I am trying to write a program which can automatically fill in and submit a form in a web in particular time slot. But i have no idea how and where to start. i searched this in google, but only resulting very general answer like using JavaScript, python. Can anyone tell me which languages should i learn first?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50487539
type: UnansweredQuestion
has title: Write a auto-fill and submit web form program
has answer: http://stackoverflow.com/a/50487585
tagged with: javascript
tagged with: php
has comment: http://stackoverflow.com/comment/87987525
score: 0
has comment: http://stackoverflow.com/comment/87987716
answer count: 3
upvote count: 3
downvote count: 3
tagged with: autofill
tagged with: python
tagged with: forms
has answer: http://stackoverflow.com/a/54690666

http://stackoverflow.com/comment/87859155
type: QuestionComment
score: 0
has text: https://github.com/advancedCV/vehicle_numberplate_logger This is what i am trying to achive
comment on: http://stackoverflow.com/q/50421935
type: Comment

http://stackoverflow.com/q/50405987
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/50410954
has comment: http://stackoverflow.com/comment/87829979
downvote count: 0
possible better answer: http://stackoverflow.com/a/56590468
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/56590468
type: AnsweredQuestion
score: 2
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/87831004
has body: I am using the tf.estimator API to train models. As I understand, the model_fn defines the computation graph, which returns a different tf.estimator.EstimatorSpec according to the mode. In mode==tf.estimator.ModeKeys.TRAIN, one can specify a train_op to be called at each training iteration, which in turns changes trainable instances of tf.Variable, to optimise a certain loss. Let's call the train_op optimizer, and the variables A and B. In order to speed up prediction and evaluation, I would like to have an auxiliary non-trainable tf.Variable Tensor C, exclusively dependent on the already trained variables. The values of this tensor would thus be exportable. This Tensor does not affect training loss. Let's assume we want: C = tf.Variable(tf.matmul(A,B)) update_op = tf.assign(C, tf.matmul(A,B)) What I tried: Passing tf.group(optimizer, update_op) as train_op in the EstimatorSpec works good but slows down training a lot, since the train_op now updates C at each iteration. Because C is only needed at eval/predict time, one call of update_op at the end of training is enough. Is it possible to assign a Variable at the end of training a tf.estimator.Estimator?
has answer: http://stackoverflow.com/a/50410954
tagged with: tensorflow
favorite count: 0
has title: In `tf.estimator`, how to `tf.assign` a variable at end of training (not at every iteration)?
type: Question

http://stackoverflow.com/comment/87817496
type: Comment
has text: @RominaAlarcon Keep it respectful.
type: QuestionComment
comment on: http://stackoverflow.com/q/50400715
score: 0

http://stackoverflow.com/comment/87863760
has text: Thanks! `df.dtypes.to_frame('dtypes').reset_index()` was what I was looking for : a way to make that "intangible" info "tangible"! And json is precisely how I intend to store it. Also, thanks for showing a way which doesn't involve the actual data.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50423394

http://stackoverflow.com/q/50475966
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87965747
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87965812
has comment: http://stackoverflow.com/comment/87965770
has comment: http://stackoverflow.com/comment/87967493
has body: This is a testing question, not an implementation question. I have a program which produces a JSON, I want to be able to compare outputs consistently, so I'm converting all of my dicts to OrderedDicts. I've searched through, and I'm pretty confident that I got them all, but good programming still requires testing. I'm not sure how to actually test that my dictionaries are coming out in the same order because I told them to, vs they just happened to come out in the same order... Is there a way to force Python to randomize its non-Ordered dicts? ETA: I'm using python 2.7. I've still got 18 months to convert this thing... it's on the list..
type: Question
has comment: http://stackoverflow.com/comment/87965852
tagged with: testing
has comment: http://stackoverflow.com/comment/87965729
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87965830
has title: How should I test that dictionaries will always be in the same order?
tagged with: python
tagged with: dictionary
tagged with: ordereddict
has answer: http://stackoverflow.com/a/50476093
has comment: http://stackoverflow.com/comment/87965580
favorite count: 0
has comment: http://stackoverflow.com/comment/87965818

http://stackoverflow.com/q/50412812
tagged with: opencv
has body: I am trying to recognize numbers written in a cartoonish font, so the traditional tools (e.g. pytesser) did not really work. However, I was able to get quite accurate single digit recognition with cv2.matchTemplate and a library of the 10 digits. I am basically treating each digit as a symbol and simply trying to find the best match. import cv2 import numpy as np def match_char(im1, im2): result = cv2.matchTemplate(im1,im2,cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) return max_va def process_image(im, i): try: gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) a, t = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY_INV) return t except: print("Error while processing the image") pass def process_lib(im, i): try: gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) a, t = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY) return t except: print("Error while processing the image") pass def process_num(): test = cv2.imread('test.png') test = process_image(test, 11) test = cv2.resize(test, (0,0), fx=2.2, fy=2.2) #best scores = [] for i in range(10): img = cv2.imread('char-{}.png'.format(i)) img = process_lib(img, i) scores.append(match_char(img, test)) win = scores.index(max(scores)) print("The best match is {} with {}".format(win, scores[win])) The problem is that I was not able to extend this to multiple digits numbers. Even when generating two digits numbers and trying to match them, the program always identifies a single digit as the best match. If I restrain the search to two digits numbers, it sometimes gets one digit correct, but never both. Of course, this is not the most elegant solution, but it seemed the simplest and even that doesn't work.
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50434788
favorite count: 0
has title: OpenCV - Recognize a serie of symbols
type: Question
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50473162
downvote count: 0
answers question: http://stackoverflow.com/q/50472447
type: Answer
has body: A simpler way is using expand=True argument. # sample data df = pd.DataFrame({'c1':['a','b','c'], 'c2':['a b c d','e f g h','i j k l']}) # transform into multiple columns df = pd.concat([df['c1'],df['c2'].str.split(' ', expand=True)], axis=1) print(df) c1 0 1 2 3 0 a a b c d 1 b e f g h 2 c i j k l
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50472447
type: AcceptedAnswer

http://stackoverflow.com/q/50493838
has comment: http://stackoverflow.com/comment/88001102
has comment: http://stackoverflow.com/comment/88000761
has answer: http://stackoverflow.com/a/50569360
tagged with: performance
accepted answer: http://stackoverflow.com/a/50569360
tagged with: python-3.7
tagged with: python
tagged with: dictionary
has body: Now that the insertion order of Python dictionaries is guaranteed starting in Python 3.7 (and in CPython 3.6), what is the best/fastest way to sort a dictionary - both by value and by key? The most obvious way to do it is probably this: by_key = {k: dct[k] for k in sorted(dct.keys())} by_value = {k: dct[k] for k in sorted(dct.keys(), key=dct.__getitem__)} Are there alternative, faster ways to do this? (Note that the answer prior to 3.7 was, basically, You can't; use a collections.OrderedDict instead).
favorite count: 0
type: Question
has title: Fastest way to sort a python 3.7+ dictionary
linked to: http://stackoverflow.com/q/39980323
has comment: http://stackoverflow.com/comment/88001005
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88001046
has comment: http://stackoverflow.com/comment/88000911
upvote count: 31
score: 31
type: AnsweredQuestion

http://stackoverflow.com/comment/88029201
type: QuestionComment
has text: `tkinter` doesn't work well with `sleep`. Search and use the method `after`.
comment on: http://stackoverflow.com/q/50508640
score: 1
type: Comment

http://stackoverflow.com/q/50408895
has title: Pandas Rearranging Multiindex Series
linked to: http://stackoverflow.com/q/19798229
has body: On pandas version 0.19.2, I have the below dataframe with multiindex: import pandas as pd import numpy as np arrays = [[2001, 2001, 2002, 2002, 2002, 2003, 2004, 2004], ['A', 'B', 'A', 'C', 'D', 'B', 'C', 'D']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) s = pd.Series(np.random.randn(8), index=index, name='signal') Which looks like follows: first second 2001 A -2.48 B 0.95 2002 A 0.55 C 0.65 D -1.32 2003 B -0.25 2004 C 0.86 D -0.31 I want to get a summary contingency dataframe where columns are unique "second" and indices are the "first" index, like below: A B C D 2001 -2.48 0.95 NaN NaN 2002 0.55 NaN 0.65 2003 NaN -0.25 NaN NaN 2004 NaN NaN 0.86 -0.31 Any idea how this can be done? I played around with groupby() as below but could not get anywhere s.groupby(level=1).apply(lambda x: "to do") Linked question: Python Pandas - how to do group by on a multiindex how-to-do-group-by-on-a-multiindex
accepted answer: http://stackoverflow.com/a/50408913
tagged with: python
type: AnsweredQuestion
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50408913
downvote count: 0
answer count: 1
upvote count: 1
tagged with: multi-index
favorite count: 0
type: Question

http://stackoverflow.com/a/50433646
has comment: http://stackoverflow.com/comment/87884946
type: Answer
upvote count: 1
has body: There is no way to do this directly. The only way I can think of is to put all of the text from the 'td' tags into a data structure such as a list or dictionary and test it there.
score: 0
answers question: http://stackoverflow.com/q/50432978
downvote count: 1
has comment: http://stackoverflow.com/comment/87884862

http://stackoverflow.com/q/50439564
upvote count: 1
tagged with: python
tagged with: python-3.6
has body: Setting the count, the first list starts at zero and increments by 20 until count is exhausted. Using the same count, the second list starts at 1 repeats 1 for the first five indexes and then increments by 1 at 100. Repeats this cycle until list is exhausted. aaa should increment by 20 starting at 0 bbb should increment by 1 for every 5th index starting at 1 Results: aaa00_bbb1 aaa20_bbb1 aaa40_bbb1 aaa60_bbb1 aaa80_bbb1 aaa100_bbb2 aaa120_bbb2 aaa140_bbb2 aaa160_bbb2 aaa180_bbb2 aaa200_bbb3 aaa220_bbb3 aaa240_bbb3 aaa260_bbb3 aaa280_bbb3 aaa300_bbb4 aaa320_bbb4 ... Tried something like this but I don't know how to get list bbb working. def my_func_a(cnt): mylist = [] for i in range(0, cnt, 20): value = 'aaa' + str(i) mylist.append(value) return mylist aaa = my_func_a(500) # print(aaa) def my_func_b(cnt): mylist = [] for i in range(0, cnt, 20): value = '_bbb' + str(i) mylist.append(value) return mylist bbb = my_func_b(500) # print(bbb) combined = list(map(''.join, zip(map(str, aaa), bbb))) print(combined) Output: ['aaa0_bbb0', 'aaa20_bbb20', 'aaa40_bbb40', 'aaa60_bbb60', 'aaa80_bbb80', 'aaa100_bbb100', 'aaa120_bbb120', 'aaa140_bbb140', 'aaa160_bbb160', 'aaa180_bbb180', 'aaa200_bbb200', 'aaa220_bbb220', 'aaa240_bbb240', 'aaa260_bbb260', 'aaa280_bbb280', 'aaa300_bbb300', 'aaa320_bbb320', 'aaa340_bbb340', 'aaa360_bbb360', 'aaa380_bbb380', 'aaa400_bbb400', 'aaa420_bbb420', 'aaa440_bbb440', 'aaa460_bbb460', 'aaa480_bbb480'] Tried some things with itertools and got closer but still bbb I can't get working. from itertools import chain, repeat, cycle def myfunc(cnt): mylist = [] for i in range(0, cnt+20, 20): value = 'aaa' + str(i) + '_' mylist.append(value) return mylist inventory_list = myfunc(500) # print(inventory_list) inventory = list(zip(inventory_list, chain(repeat(1,5), cycle(range(2, 3))))) print(inventory) Output: [('aaa0_', 1), ('aaa20_', 1), ('aaa40_', 1), ('aaa60_', 1), ('aaa80_', 1), ('aaa100_', 2), ('aaa120_', 2), ('aaa140_', 2), ('aaa160_', 2), ('aaa180_', …
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50439649
has answer: http://stackoverflow.com/a/50439660
has title: Combine two lists created from range with different steps and repeat values for certain number of indexes
has answer: http://stackoverflow.com/a/50439645
has answer: http://stackoverflow.com/a/50439654
has answer: http://stackoverflow.com/a/50439608
favorite count: 0
type: Question
answer count: 5
possible better answer: http://stackoverflow.com/a/50439645
downvote count: 0
accepted answer: http://stackoverflow.com/a/50439608

http://stackoverflow.com/q/50499617
type: UnansweredQuestion
answer count: 1
type: Question
has title: python fabric output hangs
has answer: http://stackoverflow.com/a/50502349
tagged with: fabric
tagged with: python
has body: I am trying a very basic fabric code like this: from fabric.api import run, task @task def test(): run("find /tmp -type f") The output however gets stuck like this forever: [root@e059fb ]# fab test -i tej.pem -H tej@10.90.242.76 [tej@10.90.242.76] Executing task 'test' [tej@10.90.242.76] run: find /tmp -type f [tej@10.90.242.76] out: /tmp/qwer.pid [tej@10.90.242.76] out: /tmp/install.pid [tej@10.90.242.76] out: /tmp/xxxx [tej@10.90.242.76] out: /tmp/pki_data1381109216648547511.tmp [tej@10.90.242.76] out: /tmp/component_event.xlf5716431074152235003.jar [tej@10.90.242.76] out: /tmp/MIME3880781677960930334.tmp [tej@10.90.242.76] out: /tmp/component_event.xlf2448949157221874062.jar [tej@10.90.242.76] out: /tmp/pki_data4307187884067858048.tmp [tej@10.90.242.76] out: /tmp/MIME492598143052197490.tmp [tej@10.90.242.76] out: /tmp/component_event.xlf6922738826235471484.jar [tej@10.90.242.76] out: /tmp/xxxxx [tej@10.90.242.76] out: /tmp/component_event.xlf5514972543465832532.jar [tej@10.90.242.76] out: /tmp/MIME7456325891227527672.tmp [tej@10.90.242.76] out: /tmp/component_event.xlf7878309880872461565.jar [tej@10.90.242.76] out: What could be the issue ?
score: 0

http://stackoverflow.com/q/50520683
score: 0
tagged with: python
tagged with: dictionary
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88057000
has body: d1 = [{'del':True, 'Name':'tbl_n','node':'3'},{'del':True, 'Name':'src_n','node':'5'}] d2 = [{'items':'23', 'column_name':'tbl_n','created':'3.34','count':0,'valid':'yes'}, {'items':'43', 'column_name':'src_n','created':'3.34','count':40,'valid':'yes'}, {'items':'22', 'column_name':'mod_n','created':'3.34','count':13,'valid':'no'} I would like to merge d1 to d2 with respect to 'Name' key in d1 and 'column_name' in d2 below is one of the tried step from collections import Counter summed = sum((Counter({elem['column_name']: elem['val_count']}) for elem in my_dict1 + my_dict2), Counter()) print(summed) the expected output im looking for is d3 = [{'items':23, 'Name': 'tbl_n','node':3,'created':3.34,'count':0,'valid':'yes'},{'del':True,'items':43,'Name':'src_n','node':5.'created':3.34,'count':40,'valid':'yes'},{'items':22,'column_name:'mod_n','created':3.34,'count':14,'valid':'no'}
has comment: http://stackoverflow.com/comment/88053675
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88057043
has comment: http://stackoverflow.com/comment/88057112
answer count: 1
has answer: http://stackoverflow.com/a/50523089
has title: Have two non identical list of dictionaries and need to merge them with a non unique key
has comment: http://stackoverflow.com/comment/88057281

http://stackoverflow.com/q/50455784
has comment: http://stackoverflow.com/comment/87925143
linked to: http://stackoverflow.com/q/35745050
score: -4
downvote count: 5
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50455913
accepted answer: http://stackoverflow.com/a/50455913
tagged with: python-3.6
has body: In the follow f-string, print("It's fleece was white as {}.".format('snow')) Is 'snow' a variable? I am confused with what exactly it would be judged as.
favorite count: 0
has comment: http://stackoverflow.com/comment/87925157
type: AnsweredQuestion
has title: Python and F-Strings explanation
answer count: 1
has comment: http://stackoverflow.com/comment/87925305
type: Question

http://stackoverflow.com/a/57206456
downvote count: 0
answers question: http://stackoverflow.com/q/50435630
type: Answer
has body: For empirical data with duplicates (or other form of redundancy), the use of smoothing (instead of forcing the interpolation through all points) is appropriate. Without smoothing, what is worse than duplicates is "incompatible near duplicates" (close in the X,Y plane but markedly different in Z). The "almost singular" point would spoil the result in the vicinity. Rbf has a smooth keyword parameter, float: Values greater than zero increase the smoothness of the approximation. 0 is for interpolation (default), the function will always go through the nodal points in this case. I designed an example with near-singular points. Try it with different values for the smooth parameter. import numpy as np from scipy.interpolate import Rbf import matplotlib.pyplot as plt np.random.seed(99) x, y = np.random.rand(2, 100) x[0] = 0. for i in range(1,len(x)): # Generate clumpy distribution. x[i] = x[i-1] + np.exp(-6.*x[i]) y += 2.*np.sin(x) fig, ax = plt.subplots(figsize=(15,4)) ax.plot(x ,y ,'ko') xi = np.linspace(x[0], x[-1], 1000) for smooth in [.01, 1, 100]: rbfi = Rbf(x, y, smooth=smooth) yi = rbfi(xi) ax.plot(xi,yi,'k-') fig.show()
score: 2
upvote count: 2

http://stackoverflow.com/q/50521774
has body: I am using ZSH. I was having trouble running the Anaconda package manager commands in my terminal. I found that I could add the bin to my PATH using this code: export PATH="$HOME/anaconda3/bin:$PATH" That worked. All of the Anaconda and associated commands work and it left me with this PATH: /Users/USER/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin But the PATH variable would reset each time I closed the terminal window. After some research, I figured out how modify my .zshrc to make it permanent. I simply pasted this into my .zshrc: export PATH=/Users/USER/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin All the commands work and are permanent, but aren't I setting myself up for failure down the road? Everything in the PATH, minus the "/Users/USER/anaconda3/bin" were set automatically. What happens when I update Python, for example? How can I include the "USER/anaconda3/bin" portion of my PATH in my .zshrc without being so explicit?
tagged with: python
type: Question
type: UnansweredQuestion
has title: How can I make my PATH more succinct in ZSH?
answer count: 1
has comment: http://stackoverflow.com/comment/88055759
score: 0
tagged with: zsh
tagged with: anaconda
has answer: http://stackoverflow.com/a/50521817

http://stackoverflow.com/comment/87828809
score: 0
type: Comment
type: QuestionComment
has text: Using a windows machine
comment on: http://stackoverflow.com/q/50406354

http://stackoverflow.com/a/50497139
downvote count: 0
answers question: http://stackoverflow.com/q/50485506
has comment: http://stackoverflow.com/comment/88024595
type: Answer
has comment: http://stackoverflow.com/comment/88024558
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88033542
accepted answer of: http://stackoverflow.com/q/50485506
type: AcceptedAnswer
has body: The input: Plotting the synthetic data with two classes. Output from the code above: All outputs are classified as a single class and because of class imbalance, accuracy is high 70%. Issues with the code Even though there are two layers defined, no activation function defined between the two. So tf.softmax( ((x*w1)+b1) * w2 + b2) squashes down to a single layer. There is just a single hyperplane trying to separate this input and the hyperplane lies outside the input space, thats why you get all inputs classified as a single class. Bug: Softmax is applied twice: on the logits as well as during entropy_loss. The entire input is given as a single batch, instead of mini-batches. Inputs need to be normalized. Fixing the above issues and the output becomes: The above output makes sense, as the model has two hidden layers and so we have two hyperplanes trying to separate the data. The final layer then combines these two hyperplanes in such a way to minimize error. Increasing the hidden layer from 2 to 3: With 3 hidden layers, we get 3 hyperplanes and we can see the final layer adjusts these hyperplanes to separate the data well. Code: # Normalize data data = (data - np.mean(data)) /np.sqrt(np.var(data)) n_hidden = 3 batch_size = 128 # Feed batch data def get_batch(inputX, inputY, batch_size): duration = len(inputX) for i in range(0,duration//batch_size): idx = i*batch_size yield inputX[idx:idx+batch_size], inputY[idx:idx+batch_size] # Create the graph tf.reset_default_graph() graph=tf.Graph() with graph.as_default(): X = tf.placeholder(tf.float32, [None, 2] ) layer1 = tf.layers.dense(X, n_hidden, activation=tf.nn.sigmoid) layer2 = tf.layers.dense(layer1, 2) Y = tf.nn.softmax(layer2) y_true = tf.placeholder(tf.int32, [None] ) loss = tf.losses.sparse_softmax_cross_entropy(logits=layer2, labels=y_true) optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(loss) accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(Y, 1),tf.argmax(tf.one_hot(y_true,2), 1)), tf.float32)) …

http://stackoverflow.com/comment/88101553
has text: Sorry, have corrected the url, I've posted it after hours of tries very and my consciousness was in more near to bed than my body... But I still gave the same problem.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50540158
type: Comment

http://stackoverflow.com/comment/87886430
type: Comment
has text: Thanks.I implemented the solution, but i am still unable to understand all the nodes at left
comment on: http://stackoverflow.com/a/50435893
score: 0
type: AnswerComment

http://stackoverflow.com/a/50468702
has comment: http://stackoverflow.com/comment/87950760
has comment: http://stackoverflow.com/comment/87951290
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87951110
score: 1
has comment: http://stackoverflow.com/comment/87951046
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50468597
has body: Each call to menu() produces a new, separate local scope, with the variables in that scope independent from other calls to menu(). Changes in one call do not affect the local values in other calls, even recursive ones. So when you call menu(), the new function call starts at the top, and the line a, b = 1, 1 is executed and new, local variables a and b are created, both set to 1. Don't use recursion. Use a while loop, and break or return to exit the loop when you are done: def menu(): # set the initial values for a and b before starting the loop a, b = 1, 1 while True: ch = int(input('Choice:')) if ch == 1: a = 11 elif ch == 2: b = 22 print(a+b) else: print('End') # exit the function, and thus also exit the loop return Demo: &gt;&gt;&gt; menu() Choice:1 Choice:2 33 Choice:2 33 Choice:4 End Recursion is never a good idea for menus anyway; function calls cause the current function state to be pushed on top of a stack, to be retrieved later when the function call returns. That stack has a limited amount of space; too many in-progress function calls and you'll get a runtime error. And you'd be surprised how often users will push a computer menu to those limits. You could of course pass along the current values of a and b to another function by passing them along as function parameters, and you could return new state back to the caller with return. But it's so much easier to use an endless loop, and that way you don't have to think about having to pass along your program state each time you want to ask the user for the next input. Note: Do not use is to test for value equality, use ==. is tests for identity, if both expressions reference the same object, not just if two objects have the same value. ch is 1 and ch is 2 only happens to work in CPython because you hit upon an implementation detail of the interpreter.
upvote count: 1
has comment: http://stackoverflow.com/comment/87950837
has comment: http://stackoverflow.com/comment/87950669
accepted answer of: http://stackoverflow.com/q/50468597

http://stackoverflow.com/comment/87850841
type: QuestionComment
comment on: http://stackoverflow.com/q/50417434
score: 0
has text: @PaulaThomas just `python` works. But it uses system 2.7 version. i need python 3.5.0
type: Comment

http://stackoverflow.com/comment/88808634
type: AnswerComment
has text: Thank you for the great answer, it has helped me a lot! I have an additional question though: suppose that the loss for the output 'height' is a custom one, which needs the y_pred predictions from the 'speed' output. Is this possible? I could only imagine to concatenate the outputs into a single output again, and then the losses history for the single losses would be lost.
comment on: http://stackoverflow.com/a/50534785
type: Comment
score: 0

http://stackoverflow.com/a/50480749
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50480726
has body: You can use: In [10]: n = 5 In [11]: [[i+((9-j)*j)//2 for j in range(0, i)] for i in range(1, n+1)] Out[11]: [[1], [2, 6], [3, 7, 10], [4, 8, 11, 13], [5, 9, 12, 14, 15]]
score: 1
downvote count: 0

http://stackoverflow.com/comment/87873349
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50428661
score: 0
has text: Did you run `pip install asyncio`? That would shadow the standard library with the version intended for Python 3.3.

http://stackoverflow.com/comment/87958899
comment on: http://stackoverflow.com/q/50470726
has text: Yes. Exactly, you are iterating over the whole dataset every time right here: `sortedData['visitorId'] == visitor`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50504770
type: AnsweredQuestion
score: 3
has body: After using keras by implementing some examples and looking for tutorials I am kind of confused which cross entropy function I should use in my project. In my case I want to predict multiple labels such as (positive, negative and neutral) for online comments with a LSTM model. The labels have been converted to one-hot vectors with the to_categorical method in keras, which is also documented in keras: (...) when using the categorical_crossentropy loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros expect for a 1 at the index corresponding to the class of the sample). The one-hot array looks as follow: array([[1., 0., 0.], [1., 0., 0.], [0., 0., 1.], Because there a multiple labels I would prefer to use categorical_crossentropy. I also implemented a model with this criteria but the accuracy of this model was only above 20%. Using binary_crossentropy with a sigmoid function my accuracy have been reached to 80%. I am really confused, because some guys argued with the following statements: the accuracy computed with the Keras method "evaluate" is just plain wrong when using binary_crossentropy with more than 2 labels whereas other have already implemented high performanced model with binary crossentropy and multiple labels, which is kind of the same workflow. We want probability of each class. So we are using sigmoid on final layer, which gives output in range 0 to 1. If our aim was to find the class, then we will have used softmax So I just want to know if there are any problems if I would to choose the binary_crossentropy like in the following link to predict the outcome class.
tagged with: python
accepted answer: http://stackoverflow.com/a/50505609
has comment: http://stackoverflow.com/comment/88022803
type: Question
has title: keras categorical and binary crossentropy
upvote count: 3
answer count: 1
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50505609
tagged with: keras
linked to: http://stackoverflow.com/q/42081257
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/50393654
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87804849
tagged with: tkinter
has title: Tkinter trying to destroy a Label defined inside a function after the function has finished
has comment: http://stackoverflow.com/comment/87803099
has body: from tkinter import * def spaces(int1,int2): if int1 == 1: return(int2*"\n") else: return(int2*" ") def submitButton(): subButton_text = subButton.get() try: informationText.destroy() except UnboundLocalError: print("an error has occured.") print("Attempting to run with the error.") pass informationText = Label(window, text=subButton_text, bg = "grey", fg = "white", font = "none 12 bold") informationText.grid(row=4,column=0,sticky=W) #informationText.destroy() #return informationText def exit_Button(): window.destroy() window = Tk() window.title("Learning tkinter") window.configure(background="grey") subButton = StringVar() #pic1 = PhotoImage(file="test.png") #Label(window, image=pic1, bg = "grey").grid(row = 0, column = 0, sticky=W) Label(window, text="Please enter a value", bg = "grey", fg = "white", font = "none 12 bold").grid(row=0,column=0,sticky=W) Entry(window, width=50, bg="white",textvariable=subButton).grid(row=1,column=0,stick=W) subButton.set("default value") Button(window, text="Submit", width=10, command = submitButton).grid(row=2,column=0, sticky=W) Label (window, text="\nInformation:", bg="grey", fg="white", font="none 12 bold").grid(row=3,column=0, sticky=W) Button (window, text="Save\nand exit", width=8, command=exit_Button).grid(row=0,column=2,sticky=NW) Label(window, text=spaces(1,10), bg = "grey", fg = "white", font = "none 12 bold").grid(row=100,column=0,sticky=W) Label(window, text=spaces(2,20), bg = "grey", fg = "white", font = "none 12 bold").grid(row=0,column=1,sticky=W) window.mainloop() This is my code for a simple tkinter program. When the "submitButton" it creates create a Label called "informationText". But when the button is clicked again with new text I want it to destroy the old text, but it doesn't work. If I destroy the text immediately after creating it (commented out) it works. Is it because I declared it in a function? If so how can I destroy it after the function has finished? (first ask, tips appreciated for better questions …
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50394729

http://stackoverflow.com/a/50520829
has body: You can from math import inf and use inf rather than some ad-hoc number. Ints compare against floats just fine in Python.
answers question: http://stackoverflow.com/q/50520802
type: Answer
has comment: http://stackoverflow.com/comment/88053902
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/87907722
score: 0
type: Comment
has text: Heyy thanks for the suggestion. but how would i change the $PATH or create an alias
type: AnswerComment
comment on: http://stackoverflow.com/a/50446813

http://stackoverflow.com/comment/87959413
has text: I actually tried something like this and the problem here is i cannot specify all the keys each time to get sorted and i also want the sorted order in a dictionary with the key retained.
type: AnswerComment
comment on: http://stackoverflow.com/a/50472777
score: 0
type: Comment

http://stackoverflow.com/a/50442260
answers question: http://stackoverflow.com/q/50442155
score: 3
accepted answer of: http://stackoverflow.com/q/50442155
upvote count: 3
type: AcceptedAnswer
has body: Python doesn't allow duplicate keys in dictionaries. In something similar to your example: &gt;&gt;&gt; d={100:1, 90:2, 90:3, 80:3, 70:4} &gt;&gt;&gt; d[90] 3 If it allowed duplicate keys, theres no way for it to know whether to return 2 or 3 for 90. You could use collections.Counter, if you want to keep track of the count of tuples: from collections import Counter listy = [[(100, 1), (90, 2), (90, 2), (80, 3), (70, 4)], [(100, 1), (90, 2), (90, 2), (80, 3), (80, 3)]] count = [Counter(x) for x in listy] print(count) Which gives the output: [Counter({(90, 2): 2, (100, 1): 1, (80, 3): 1, (70, 4): 1}), Counter({(90, 2): 2, (80, 3): 2, (100, 1): 1})] Or, if all you want to do is relate the keys to values, you can use a defaultdict: from collections import defaultdict listy = [ [(100, 1), (90, 2), (90, 2), (80, 3), (70, 4)], [(100, 1), (90, 2), (90, 2), (80, 3), (80, 3)], ] update_lists = [] for l in listy: # if a key is not found, automatically create a list u = defaultdict(list) for (k, v) in l: u[k].append(v) update_lists.append(u) print(update_lists) Which gives the following output: [defaultdict(&lt;class 'list'&gt;, {100: [1], 90: [2, 2], 80: [3], 70: [4]}), defaultdict(&lt;class 'list'&gt;, {100: [1], 90: [2, 2], 80: [3, 3]})]
downvote count: 0
type: Answer

http://stackoverflow.com/a/50420589
type: Answer
has comment: http://stackoverflow.com/comment/87856622
has comment: http://stackoverflow.com/comment/87856604
answers question: http://stackoverflow.com/q/50420451
has comment: http://stackoverflow.com/comment/87856631
has body: According to the documentation: In case the JSON decoding fails, r.json() raises an exception. For example, if the response gets a 204 (No Content), or if the response contains invalid JSON, attempting r.json() raises ValueError: No JSON object could be decoded. Although it's not throwing the same error message, the cause appears to be the same: you're probably not getting JSON as an answer, which would explain why it JSONDecode throws an exception. You should be able to confirm this by printing req_obj.text instead of using req_obj.json(). As for how to fix it, I suspect that there must be something different between the request you're making using the browser and the one you're making using Python (such as different parameters). I suggest you read this to further investigate the source of the problem.
has comment: http://stackoverflow.com/comment/87856692
score: 0
has comment: http://stackoverflow.com/comment/87856654
has comment: http://stackoverflow.com/comment/87857012

http://stackoverflow.com/comment/87842725
type: Comment
comment on: http://stackoverflow.com/a/50413421
type: AnswerComment
has text: this is great. thank you :)
score: 0

http://stackoverflow.com/q/50398622
has body: I'm trying to use pyautogui's screenshot functions with Python 3.6.5 on OSX 10.11. &gt;&gt;&gt; import pyautogui &gt;&gt;&gt; image = pyautogui.screenshot() I get: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyscreeze/__init__.py", line 331, in _screenshot_osx im = Image.open(tmpFilename) NameError: name 'Image' is not defined My understanding is that pyscreeze is failing to get the name Image from Pillow for some reason. I tried to update the pyautogui (it was up to date), then reinstall the pyautogui, which carries all its dependencies including pyscreeze and Pillow along with it. I found this question with the same issue, but the fix that worked there (reinstalling) isn't working for me.
type: UnansweredQuestion
has title: Pyautogui screenshot - NameError: name 'Image' is not defined
has answer: http://stackoverflow.com/a/63982077
score: 13
tagged with: python
has answer: http://stackoverflow.com/a/67875978
upvote count: 13
linked to: http://stackoverflow.com/q/48208631
answer count: 2
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/87821213
downvote count: 0
tagged with: pyautogui
tagged with: osx-elcapitan
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87948280
has text: What improvement are you looking for? A more readable code?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50467436
score: 0

http://stackoverflow.com/a/55140106
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50434746
type: Answer
upvote count: 1
has body: Given that you have a list of labels like [0, 1, 2] and 10 classes, you need to def int64_feature(value): if type(value) != list: value = [value] return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) Then you pass label to tf.Example as one of the features 'label': int64_feature(label) After that, when you parse your dataset during training, you decole label like this: tf.reduce_max(tf.one_hot(labels, num_classes, dtype=tf.int32), axis=0) Which gives [1 1 1 0 0 0 0 0 0 0]

http://stackoverflow.com/comment/88021656
score: 1
has text: Literally like that? No. Perhaps you want a decorator?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50504808

http://stackoverflow.com/comment/87975102
score: 0
type: Comment
has text: Ok, it was just a guess as your path says python37. Does the mysqlclient package show up in the list of packages in File -> Settings -> Project Interpreter (assuming you are using PyCharm as IDE)?
type: QuestionComment
comment on: http://stackoverflow.com/q/50480583

http://stackoverflow.com/q/50528742
has comment: http://stackoverflow.com/comment/88069122
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88069080
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/88069266
answer count: 0
has comment: http://stackoverflow.com/comment/88069743
tagged with: python
type: UnansweredQuestion
has title: Python 2 to 3 conversion: 'TypeError: missing required positional argument:'
tagged with: python-2to3
type: Question
score: 0
has body: I'm new to Python (and to stackoverflow) and my first task is to convert an energy flow simulation program from Python 2.7 to Python 3.6 and get it running on 3.6. I already used the 2to3 converter and solved some other errors but now I'm hitting a wall with this error, not knowing if it's an error of the existing program or if I use the wrong syntax etc. The code apparently worked in Python 2. If I additionaly put in house_atrs in the function it will start the function but throws a long list of other errors. So I hope for your help and would like to understand the reason of this error in 3.6 compared to 2.7. Error: Traceback (most recent call last): File "D:\Users\hs\workspace\selfsuffbat\vpp_interface_refpool_noPCR_161026.py", line 85, in &lt;module&gt; analyze(sim_atrs, output_folder, output_subfolder, economic=True, binary=True) TypeError: analyze() missing 1 required positional argument: 'output_subfolder' Code of vpp_interface_refpool_noPCR161026.py: from pool_builder import pool_df from main import simulate from main import analyze if __name__ == '__main__': output_folder = 'output/data/' output_subfolder = 'refpool_noPCR' [...] simulate(house_atrs, sim_atrs, sim_args, output_folder, output_subfolder) analyze(sim_atrs, output_folder, output_subfolder, economic=True, binary=True) Code of the function analyze() in main.py: def analyze(sim_atrs, house_atrs, output_folder, output_subfolder, economic=True, economic_standalone=False, binary=False): print('started analyzing') analysis(folder=output_folder, subfolder=output_subfolder, fileindata=None, firstloop=True, binary=binary, usegreengrey=sim_atrs['use_greengrey'], usedegradation=sim_atrs['use_degradation'], uselocalbalance=sim_atrs['use_localbalance'], providePCR=sim_atrs['provide_pcr'], usethermal=sim_atrs['use_thermal_load']) if economic: assert economic_standalone is False, 'Set "economic" to False and "economic_standalone" to True for standalone calculations' economic_calc(output_folder, output_subfolder,…
favorite count: 0

http://stackoverflow.com/q/50399522
has body: I have a website based off Mezzanine of which Bleach is installed as a dependency. Bleach 2.0 is incompatible with my version of Mezzanine. I tried specifying Bleach's version as ==1.5 in my requirements.txt file but every pip install still upgrades the version. I'm thinking another dependency keeps forcing the upgrade. Is there a way to tell pip to lockdown a package's version, or barring that a way to see a dependency tree? Worst case the OS's python is forcing Bleach 2.0.
type: UnansweredQuestion
downvote count: 0
tagged with: pip
upvote count: 1
tagged with: python
tagged with: bleach
favorite count: 0
has comment: http://stackoverflow.com/comment/87814930
has comment: http://stackoverflow.com/comment/87815359
score: 1
tagged with: mezzanine
tagged with: macos
has title: Prevent pip from upgrading a dependency
type: Question
answer count: 0

http://stackoverflow.com/q/50415281
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50423244
has title: Kivy: Scatter inside scatter
favorite count: 0
has body: Question: How do I put one Scatter inside another Scatter? I have some troubles with kivy's coordinates. In principal I would like to have a Scatter in a Scatter. They should be drageable (moving first scatter moves everything, moving 2nd scatter moves the 2nd scatter inside the first scatter). Concrete setup I would like to have a base map (scatter 1) that is scaleable and moveable. When we transform this map, everything drawn "on top" of this map should be transformed as well (s.t. it keeps its position on the map). Then I would like to draw a grid on top of the map which is moveable by its own (scatter 2). Then I add some point onto scatter 2. The relative positions must be preserved on rescaling the window. Expected behavior When I grab scatter 2, it can be moved around and the points (3.) stay relative to scatter 2. When I grab scatter 1, it should move everything s.t. scatter 2 and the points stay where they are on the map (scatter 1). Basic example code from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder kv = """ &lt;MyRoot&gt;: orientation: 'vertical' ActionBar: ActionView: ActionPrevious: title: '' with_previous: True ActionOverflow: ActionButton: text: 'Preferences' on_press: app.open_settings() Scatter: canvas: Color: rgb: .2, .2, .3 Rectangle: pos: self.pos size: self.size Scatter: canvas: Color: rgb: .8, .2, .3 Rectangle: pos: self.pos size: self.size Widget: pos: 200, 200 canvas: Color: rgb: .1, .7, .3 Ellipse: pos: 30,50 size: 10, 10 """ Builder.load_string(kv) class MyApp(App): def build(self): return MyRoot() class MyRoot(BoxLayout): pass if __name__ == '__main__': MyApp().run() Also here is an image of what's happening. I would like to have the green point fixed on the red scatter and the red scatter sitting inside the violet one: Approach I guess I have to transform the coordinates in each step and overwrite the functions on_touch_..., maybe using self.parent.to_parent(*touch.pos) but unfortunately I don…
type: Question
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/50423244
type: AnsweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50451782
answers question: http://stackoverflow.com/q/50451593
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: I'm not sure if you have to use numpy at all. With bare python: just rebuild your list using a list comprehension, iterating on the "order" list (minus 1 because python lists start at 0): lst = [ 2, 3, 4, 5, 1] order = [ 5, 3, 2, 1, 4 ] result = [lst[i-1] for i in order] print(result) result: [1, 4, 3, 2, 5]

http://stackoverflow.com/comment/88059452
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50491932
has text: @Udi I have checked all of them the problem fixed with a trick, I generated a new geometry from geom_t.wkb and tried to save it and it worked fine. I have no idea why this happened?

http://stackoverflow.com/q/50401721
tagged with: selenium
has body: I am practicing with Selenium (in Python) and am trying to find something to assertEquals to. I open GoogleMaps, type in a destination and I want to make sure the address listed is correct. When I click on the address and "inspect element" this is all I see: 123 Broadway Ave When I type this however: address = self.search_field = self.driver.find_element_by_class_name('widget-pane-link') self.assertEqual(address,'123 Broadway Ave') It throws an error: Message: no such element: Unable to locate element: {"method":"class name","selector":"widget-pane-link"} I am not sure what else I can assert on given those "inspect" results in Chrome. Any ideas how to go about this? Thanks
has comment: http://stackoverflow.com/comment/87819383
type: Question
score: 0
tagged with: python
tagged with: webdriver
has comment: http://stackoverflow.com/comment/87819305
has title: Selenium - assert on GoogleMaps address
tagged with: assert
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50456840
answer count: 1
upvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has title: Typo in the example "custom layer in Tensorflow using Keras"
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50456881
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50456881
has body: I think there is a typo in the Tensorflow example for building a custom layer using Keras. The tutorial is on using Eager mode. The only missing part is super(MySimpleLayer, self).__init__() in the init method: class MySimpleLayer(tf.keras.layers.Layer): def __init__(self, output_units): **super(MySimpleLayer, self).__init__()** self.output_units = output_units def build(self, input): # The build method gets called the first time your layer is used. # Creating variables on build() allows you to make their shape depend # on the input shape and hence remove the need for the user to specify # full shapes. It is possible to create variables during __init__() if # you already know their full shapes. self.kernel = self.add_variable( "kernel", [input.shape[-1], self.output_units]) ...
downvote count: 0

http://stackoverflow.com/comment/87938093
type: QuestionComment
has text: No code in your question and no error, what could we do with that?
score: 0
comment on: http://stackoverflow.com/q/50462487
type: Comment

http://stackoverflow.com/comment/87889167
type: Comment
comment on: http://stackoverflow.com/q/50437640
type: QuestionComment
score: 1
has text: You need to call the function. At the end of the file, put `main()` without any indentation.

http://stackoverflow.com/q/50421196
type: Question
upvote count: 8
has comment: http://stackoverflow.com/comment/87858160
downvote count: 0
tagged with: python
tagged with: apply
has body: What is a more elegant way of implementing below? I want to apply a function: my_function to a dataframe where each row of the dataframe contains the parameters of the function. Then I want to write the output of the function back to the dataframe row. results = pd.DataFrame() for row in input_panel.iterrows(): (index, row_contents) = row row_contents['target'] = my_function(*list(row_contents)) results = pd.concat([results, row_contents])
type: AnsweredQuestion
has title: apply a function to each row of the dataframe
linked to: http://stackoverflow.com/q/36489576
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50421203
accepted answer: http://stackoverflow.com/a/50421203
has comment: http://stackoverflow.com/comment/87857614
score: 8
favorite count: 0

http://stackoverflow.com/comment/111396693
type: AnswerComment
comment on: http://stackoverflow.com/a/52555629
score: 0
type: Comment
has text: If you ask: "Where is file.zip?" you could find it at the bottom on the left pane of the Colab Notebook. Then you could download it by right-clicking on it.

http://stackoverflow.com/q/50454492
answer count: 2
has answer: http://stackoverflow.com/a/68247606
score: 5
has title: Django referral system with pinax-referrals?
has comment: http://stackoverflow.com/comment/104981655
downvote count: 0
tagged with: django
tagged with: referrals
accepted answer: http://stackoverflow.com/a/59396707
favorite count: 0
has comment: http://stackoverflow.com/comment/87929472
has answer: http://stackoverflow.com/a/59396707
type: AnsweredQuestion
upvote count: 5
has body: I am trying to create referral system in my Django project. I found very interesting app (pinax-referrals) for this task and want to test it. From documentation its not clear how correctly to use it and there is no example. As I understand we need make next steps: 1) Create Profile models with such code: from django.contrib.auth.models import User from django.dispatch import receiver from account.signals import user_signed_up # django-user-account app from pinax.referrals.models import Referral class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) referral = models.OneToOneField(Referral, null=True, on_delete=models.CASCADE) @receiver(user_signed_up) def handle_user_signed_up(sender, user, form, **kwargs): Referral.create(redirect_to=user.profile.get_absolute_url()) 2) Сreate custom signup view: from account.views import SignupView from pinax.referrals.models import Referral class RegistrationView(SignupView): def after_signup(self, form): super(RegistrationView, self).after_signup(form) Referral.record_response(self.request, "USER_SIGNUP") How correct are my steps? Could you give a simple example?
tagged with: python
has comment: http://stackoverflow.com/comment/87932714
has comment: http://stackoverflow.com/comment/104981977
possible better answer: http://stackoverflow.com/a/68247606
type: Question
tagged with: pinax

http://stackoverflow.com/comment/87971155
comment on: http://stackoverflow.com/q/50478033
type: QuestionComment
score: 0
has text: Either the IP address you have was being used for something else in the past or someone is scanning the server for vulnerabilities. Either set up a firewall or try getting a new droplet with a new IP address.
type: Comment

http://stackoverflow.com/comment/88051320
has text: It isn't entirely clear what you're doing with the data. If they are matrix operations then changing the algorithm could improve your time substantially.
comment on: http://stackoverflow.com/q/50519298
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/87971465
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50477815
has text: @PaulCornelius I updated the question =)
type: Comment

http://stackoverflow.com/comment/87817956
score: 0
type: Comment
type: AnswerComment
has text: I think you mean "The teacher intended to have you count the number of times a certain sum appeared." Also, you can replace four lines of your code with just `dosdados[dado1 + dado2] = dosdados.get(dado1 + dado2,0)+1`. Or initialize `dosdados` as `{total:0 for total in range(2,13)}` and then do `dosdados[dado1 + dado2] += 1`. This will result in any total that isn't rolled have a value of 0, rather than be missing from the dictionary entirely.
comment on: http://stackoverflow.com/a/50400788

http://stackoverflow.com/q/50389430
score: 0
has body: I am using python 2.7.9 to create excel sheet using tab delimited text files; however I am getting problem while running this python script #!/usr/bin/env python # encoding=utf8 import xlwt import os import sys reload(sys) sys.setdefaultencoding('utf8') wb = xlwt.Workbook() path = "/home/Final_analysis/" #print(os.listdir()) lis = os.listdir(path) sheetnumber = 1 for x in lis: if os.path.isfile(x)==True: extension = os.path.splitext(x) print(extension[1]) if extension[1] == '.txt': #print("Yes") ws = wb.add_sheet(extension[0]) row = 0 column = 0 a = open(x) while True: a1 = a.readline() if len(a1)==0: break data = a1.split("\t") for z in data: ws.write(row,column,z) column += 1 column = 0 row += 1 sheetnumber+=1 else: pass wb.save("Ronic.xls") I am getting following error Traceback (most recent call last): File "home/Final_analysis/combine_excel_v2.py", line 39, in <module> wb.save("Ronic.xls") File "/usr/local/lib/python2.7/site-packages/xlwt/Workbook.py", line 710, in save doc.save(filename_or_stream, self.get_biff_data()) File "/usr/local/lib/python2.7/site-packages/xlwt/Workbook.py", line 674, in get_biff_data shared_str_table = self.__sst_rec() File "/usr/local/lib/python2.7/site-packages/xlwt/Workbook.py", line 636, in __sst_rec return self.__sst.get_biff_record() File "/usr/local/lib/python2.7/site-packages/xlwt/BIFFRecords.py", line 77, in get_biff_record self._add_to_sst(s) File "/usr/local/lib/python2.7/site-packages/xlwt/BIFFRecords.py", line 92, in _add_to_sst u_str = upack2(s, self.encoding) File "/usr/local/lib/python2.7/site-packages/xlwt/UnicodeUtils.py", line 50, in upack2 us = unicode(s, encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 83: ordinal not in range(128) I have used answer given in thread How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte" But it didn't work. problem is at wb.save() command
answer count: 1
has title: Python Unicode decode error- Not able to run script even after suggested correction
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50389671
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50389671
linked to: http://stackoverflow.com/q/21129020
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/87891251
score: 1
comment on: http://stackoverflow.com/q/50438606
has text: You do (well, *should*) however have to use a `unicode` literal.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50527993
has body: How about this (use c=df.C in the scatter command): points = plt.scatter(df.A, df.B, c=df.C,cmap="jet", lw=0) plt.colorbar(points)
downvote count: 0
upvote count: 10
score: 10
type: Answer
answers question: http://stackoverflow.com/q/50527658

http://stackoverflow.com/q/50457126
has comment: http://stackoverflow.com/comment/87927945
tagged with: numpy
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50457503
has answer: http://stackoverflow.com/a/50457458
has comment: http://stackoverflow.com/comment/87927994
type: Question
has comment: http://stackoverflow.com/comment/87928592
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87928007
has title: How to apply a function all numpy array elements
tagged with: python
has comment: http://stackoverflow.com/comment/87928050
has body: I have a 1D numpy array of integers. When my python script starts executing, the numpy array consists of all zeroes. I want to apply the following function to every element in the array: a [i] = i * 2.0 In that function, i is the array index and a[i] is the element at that index. How can I do this in a vectorized fashion (as fast as possible without writing an explicit loop in python)? I know how to do the multiplication. The problem is that I don't know how to get at the array index in a vectorized fashion. Edit: I am getting the pointer to the array buffer from a C DLL. Then I am using np.ctypeslib.as_array to construct a numpy array from the memory buffer pointer returned from the C DLL. I need to update the contents of the memory buffer pointer returned by the C DLL and I thought that I could accomplish that very quickly using numpy.
has comment: http://stackoverflow.com/comment/87928289

http://stackoverflow.com/comment/88127092
type: AnswerComment
score: 0
has text: @Lee. Please select the answer if it fulfills your needs
comment on: http://stackoverflow.com/a/50524477
type: Comment

http://stackoverflow.com/comment/87990434
score: 0
has text: well, this gets quite far from the original question and it worth an investigation by its own. I suggest that you raise a new question on how you can parse a rule of that form into a `dict` of type `{'in': [in_list], 'out': [out_list]}`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50389624

http://stackoverflow.com/comment/87813919
has text: Hi RafaelC, thanks for getting back to me, i have striptime conversion which convert unicode to datatime format and compare, i have updated the code.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50398933
type: QuestionComment

http://stackoverflow.com/a/50419774
has body: I ended up converting the list into a dataframe, comparing the two dataframes by merging them on a column, and then creating a dataframe out of the missing values so, for example example_list = [{'email':'myemail@email.com'},{'email':'another@email.com'}] df_two = pd.DataFrame(item for item in example_list) common = df_one.merge(df_two, on=['Email']) df_diff = df_one[(~df_one.Email.isin(common.Email))]
type: Answer
answers question: http://stackoverflow.com/q/50416419
score: 0

session
tags question: http://stackoverflow.com/q/50445889
tags question: http://stackoverflow.com/q/50385495
tags question: http://stackoverflow.com/q/50533727
tag name: session
type: Tag

http://stackoverflow.com/comment/87793481
score: 0
has text: try to change input shape to `model.add(Conv2D(32, (3,3), input_shape=(None, 9000,7), activation='relu'))`, where None is for batch size.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50388684

http://stackoverflow.com/q/50478846
has answer: http://stackoverflow.com/a/50485601
tagged with: python
type: Question
has body: I want to make a program that can define a variable using radiobuttons but I don't really know how the values of them works.. I have something like this import tkinter as tk from tkinter import * root=Tk() root.geometry("1366x768+0+0") var_gender=IntVar() selectGender1= Radiobutton(root,text="Male",variable= var_gender,value=1) selectGender2= Radiobutton(root, text="Female",variable= var_gender,value=2) seleccionGenero.place(x=500,y=350) seleccionGenero2.place(x=700,y=350) if var_gender=="1": genderUser="Male" else: genderUser="Female" but it doesn't save any value on genderUser, so I think this isn't the way the value on radiobuttons works...
tagged with: tkinter
tagged with: radio-button
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87977499
downvote count: 2
answer count: 1
has title: how to use radiobuttons on tkinter
linked to: http://stackoverflow.com/q/43218625
has comment: http://stackoverflow.com/comment/87971673
favorite count: 0
score: -2

http://stackoverflow.com/q/50535498
type: Question
has body: I have a program with mainly OpenCV and NumPy, with some SciPy as well. The system needs to be a real-time system with a frame rate close to 30 fps but right now only about 10 fps. Will using Cython help speed this up? I ask because OpenCV is already written in C++ and should already be quite optimized, and NumPy, as far as I understand, is also quite optimized. So will the use of Cython help improve the processing time of my program?
has comment: http://stackoverflow.com/comment/88083839
tagged with: opencv
score: 10
upvote count: 11
tagged with: python
has answer: http://stackoverflow.com/a/61811370
has comment: http://stackoverflow.com/comment/88085477
has comment: http://stackoverflow.com/comment/88083815
has comment: http://stackoverflow.com/comment/88312152
tagged with: numpy
has answer: http://stackoverflow.com/a/50535882
answer count: 3
has comment: http://stackoverflow.com/comment/88321183
has comment: http://stackoverflow.com/comment/88084083
linked to: http://stackoverflow.com/q/5105482
type: UnansweredQuestion
downvote count: 1
has title: Cython + OpenCV and NumPy
tagged with: cython
has answer: http://stackoverflow.com/a/59591407
has comment: http://stackoverflow.com/comment/88084044
favorite count: 0

http://stackoverflow.com/a/50466985
has comment: http://stackoverflow.com/comment/87947129
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50464474
has body: You might try to use open with the encoding= named parameter, so that Python knows which encoding to read. Without knowing this (looks like a Windows-CP1252 file according to the hex code, but I might be wrong) you're basically out of luck. On *nix oder MacOS you can use the file command that tries to make an educated guess of the encoding. Second, you should probably not try to read everything in a list with readlines(). For really large files this is a memory hog. Better stream-read thru the file by iterating as shown below. MAXLINES = 100000 csvfile = open('./world_formatted.tsv', mode='r', encoding='utf-8') # or 'Latin-1' or 'CP-1252' filename = 0 for rownum, line in enumerate(csvfile): if rownum % MAXLINES == 0: filename += 1 outfile = open(str(filename) + '.tsv', mode='w', encoding='utf-8') outfile.write(line) outfile.close() csvfile.close() I'm sure you close the files after running, just added it to be sure. :-) If you are on a *nix'ish operating system (or MacOS) you might want to check out the split command that does exactly this (and more): How to split a large text file into smaller files with equal number of lines?
type: Answer

http://stackoverflow.com/comment/88065629
type: Comment
comment on: http://stackoverflow.com/a/50526974
type: AnswerComment
has text: Oh ok! I get it now! 32 gets skipped because it gets left shifted to the third spot when 91 is removed and we've already iterated over the 3rd spot. Thanks for explaining it so well.
score: 0

http://stackoverflow.com/comment/87872791
comment on: http://stackoverflow.com/a/50419352
has text: I'm going through this practice set of problems to learn Python, so yes it is likely that my code and my intentions do not line up exactly. Thank you for taking the time to respond.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50536946
answers question: http://stackoverflow.com/q/50536875
has body: . . . I don't know what f(a, b) is and how to use it. f(a, b) is simply a function call. All the code you provided does is define a function that returns a function. The function returned from the first function, itself returns a function. I assume the way it would be used is perhaps something like: &gt;&gt;&gt; cons(1, 2)(lambda x, y: x + y) 3 &gt;&gt;&gt; The above code would be equivalent to: &gt;&gt;&gt; pair_func = cons(1, 2) # return the `pair` function defined in `cons` &gt;&gt;&gt; f = lambda x, y: x + y &gt;&gt;&gt; pair_func(f) # apply the `f` function to the arguments passed into `cons`. 3 &gt;&gt;&gt; It might also help to note that the pair function defined in this case, is what's know as a closure. Essentially, a closure is a function which has access to local variables from an enclosing function's scope, after the function has finished execution. In your specific case, cons is the enclosing function, pair is the closure, and a and b are the variables the closure is accessing.
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/50415308
possible better answer: http://stackoverflow.com/a/50415380
tagged with: windows
has body: For accessability reasons I wonder it is possible, in python, to export a list to .txt such that line breaks can be read by notepad? Below is an example code that is read correctly in notepad++ but not in notepad. In notepad++ each entry of the list is on a separate line, in notepad all entries are on the same line. string =['str1 123','str2 234','str3 345'] outF = open("outp.txt", "w") for item in string: outF.write("%s\n" % item) outF.close()
tagged with: python
has answer: http://stackoverflow.com/a/50415380
score: 2
type: AnsweredQuestion
has title: Is it possible to export a list to .txt such that line breakes can be read by notepad?
answer count: 2
has comment: http://stackoverflow.com/comment/87846327
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87846456
accepted answer: http://stackoverflow.com/a/50415366
has answer: http://stackoverflow.com/a/50415366

http://stackoverflow.com/q/50438903
tagged with: web-crawler
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87891867
has body: I'm new to Python and Scrapy. I'm trying to create a spider to scrape: https://www.festicket.com/festivals/ I've managed to get the spider working, the problem is that some URLs are like so: https://www.festicket.com/festivals/electric-daisy-carnival-edc-las-vegas/2018/ and some URLS have: /shop/#ticket appended to them which is stoping the spider from crawling the listing page. My question is, is there some way that if the spider finds a URL with /shop/#ticket it simple deletes the /shop/#ticket but keeps the rest of the URL??? My code so far is below: import scrapy class AuthorsSpider(scrapy.Spider): name = "festicket" start_urls = ['https://www.festicket.com/festivals/'] npages = 20 # This mimics getting the pages using the next button. for i in range(2, npages + 2): start_urls.append("https://www.festicket.com/festivals/?page=" + str(i) + "") #Scrape and follow listings def parse(self, response): urls = response.xpath( "//h3[@class='festival-title heading-3ry notranslate']//@href").extract() for url in urls: url = response.urljoin(url) yield scrapy.Request(url=url, callback=self.parse_details) def parse_details(self, response): yield { 'title': response.xpath("//h1[@class='sc-jzJRlG gbLQoU']/text()").extract_first(), 'festival_url': response.xpath("//meta[@property='og:url']/@content").extract_first(), 'location': response.xpath("//ul[contains(@class,'styles__StyledList')][1]/li[contains(@class,'styles__DotSeparatorSpan-h0jg7b')][1]/descendant::text()").extract_first(), 'address': response.xpath("//div[@class='sc-gzVnrw bpJeJY'][2]/section[@class='sc-gZMcBi gDrvBk']/div/p[@class='sc-chPdSV hifsJb']/descendant::text()").extract_first(), 'date': response.xpath("//ul[contains(@class,'styles__StyledList')][1]/li[contains(@class,'styles__DotSeparatorSpan-h0jg7b')][2]/descendant::text()").extract_first(), 'genre1': response.xpath("//ul[contains(@class,'styles__StyledList')][2]/li[contains(@class,'styles__DotSeparatorSpan-h0jg7b')][1]/descendant::text()").extract_first…
has answer: http://stackoverflow.com/a/50440850
has title: Scrapy _ How to append / delete text to listing URL
answer count: 1
tagged with: web
tagged with: web-scraping
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/50440850
tagged with: python

http://stackoverflow.com/a/50534785
has comment: http://stackoverflow.com/comment/88814419
answers question: http://stackoverflow.com/q/50525747
has comment: http://stackoverflow.com/comment/89679902
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50525747
has body: A possible solution is to use a separate output layer for each target, and assign a name for each of them (i.e., Dense(1, name='...')). In your case it would be the same as training with a Dense(n) output layer, since the total loss is just the sum of the individual losses. For example, input_layer = Input(shape=(1000,)) x = Dense(100)(input_layer) # name each output layer target_names = ('speed', 'height') outputs = [Dense(1, name=name)(x) for name in target_names] model = Model(inputs=input_layer, outputs=outputs) model.compile(loss='mean_absolute_error', optimizer='sgd', metrics=['mean_squared_error']) Now when you fit the model, you should be able to see the losses (and metrics) for each target separately. X = np.random.rand(10000, 1000) y = [np.random.rand(10000) for _ in range(len(outputs))] history = model.fit(X, y, epochs=3) Epoch 1/1 10000/10000 [==============================] - 1s 127us/step - loss: 0.9714 - speed_loss: 0.4768 - height_loss: 0.4945 - speed_mean_squared_error: 0.5253 - height_mean_squared_error: 0.5939 Epoch 2/3 10000/10000 [==============================] - 1s 101us/step - loss: 0.5109 - speed_loss: 0.2569 - height_loss: 0.2540 - speed_mean_squared_error: 0.0911 - height_mean_squared_error: 0.0895 Epoch 3/3 10000/10000 [==============================] - 1s 107us/step - loss: 0.5040 - speed_loss: 0.2529 - height_loss: 0.2511 - speed_mean_squared_error: 0.0873 - height_mean_squared_error: 0.0862 The losses saved to the returned history object will also be named. print(history.history) {'height_loss': [0.49454938204288484, 0.2539591451406479, 0.25108356306552887], 'height_mean_squared_error': [0.5939331066846848, 0.08951960142850876, 0.08619525188207626], 'loss': [0.9713814586639404, 0.5108571118354798, 0.5040025643348693], 'speed_loss': [0.47683207807540895, 0.25689796624183653, 0.25291900217533114], 'speed_mean_squared_error': [0.5252606071352959, 0.09107607080936432, 0.0872862442612648]} EDIT: If the loss of output height depends on the v…
has comment: http://stackoverflow.com/comment/104065625
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88808634
score: 4
has comment: http://stackoverflow.com/comment/89620705
type: Answer

http://stackoverflow.com/q/50406664
score: -2
has comment: http://stackoverflow.com/comment/87840754
answer count: 1
has comment: http://stackoverflow.com/comment/87830121
has comment: http://stackoverflow.com/comment/87840916
has body: The problem is: randomly generate n positive integers that sum up to a fixed value sum and follow a normal distribution. How can I achieve this in Python?
favorite count: 0
downvote count: 3
tagged with: algorithm
has answer: http://stackoverflow.com/a/50428388
tagged with: math
tagged with: python
has title: How to generate a random normal distribution of a fixed number of positive integers that sum up to a fixed value
has comment: http://stackoverflow.com/comment/87830196
type: Question
tagged with: numpy
tagged with: random
upvote count: 1
has comment: http://stackoverflow.com/comment/87828673
type: UnansweredQuestion

http://stackoverflow.com/comment/87915355
type: Comment
comment on: http://stackoverflow.com/q/50451087
score: 0
has text: Cannot reproduce your problem on my computer. Everything's fine.
type: QuestionComment

http://stackoverflow.com/comment/87853308
type: Comment
has text: @psyche I edited my post so you can see the whole thing I've done
type: QuestionComment
comment on: http://stackoverflow.com/q/50418725
score: 0

http://stackoverflow.com/a/50388018
upvote count: 3
has comment: http://stackoverflow.com/comment/124183465
has body: Text in odoo view Python code: notes = fields.Text(string='Notes') XML view: the_name_of_the_view a.beautiful.model notes ===> Text here
has comment: http://stackoverflow.com/comment/89138309
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/124205939
answers question: http://stackoverflow.com/q/50387358
has comment: http://stackoverflow.com/comment/124191374
has comment: http://stackoverflow.com/comment/124269204
score: 3

http://stackoverflow.com/q/50403483
possible better answer: http://stackoverflow.com/a/50403537
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87822585
has body: I took some text from a website by beautifulsoup, at the beginning it looks like this: 9-Day Weather Forecast General Situation: An anticyclone aloft over the northern part of the South China Sea will bring mainly fine and hot weather to the south China coast in the next few days. Under the influence of a trough of low pressure, there will be showers over southern China midweek next week. Date/Month 18/5 (Friday) Wind: South force 3. Weather: Fine and hot. Temp Range: 27 - 32 C R.H. Range: 65 - 85 Per Cent Date/Month 19/5(Saturday) Wind: South force 3. Weather: Fine and hot. Temp Range: 27 - 32 C R.H. Range: 65 - 85 Per Cent I want to separate each part between "Date/Month" and "Per Cent" which spanned across several lines. I got a NavigableString by looking up a large string within a html tag. I tried but I could not search a NavigableString by re, so I turned the string into unicode string by: daily_forecast_text = str(daily_forecast_text.encode('utf-8')) It returned as below: b'\r\n9-Day Weather Forecast\n\nGeneral Situation:\nAn anticyclone aloft over the northern part of the South\nChina Sea will bring mainly fine and very hot weather to the\nsouth China coast in the next few days. Under the influence\nof a trough of low pressure, there will be showers over\nsouthern China midweek next week.\n\nDate/Month 18/5 (Friday)\nWind: South force 2 to 3.\nWeather: Fine. Very hot during the day.\nTemp Range: 27 - 33 C\nR.H. Range: 60 - 85 Per Cent\n\nDate/Month 19/5(Saturday)\nWind: South force 2 to 3.\nWeather: Fine. Very hot during the day.\nTemp Range: 27 - 33 C\nR.H. Range: 60 - 85 Per Cent\n\nDate/Month 20/5(Sunday)\nWind: South force 2 to 3.\nWeather: Fine. Very hot during the day.\nTemp Range: 28 - 33 C\nR.H. Range: 65 - 85 Per Cent\n\nDate/Month 21/5(Monday)\nWind: Southwest force 3.\nWeather: Fine. Very hot during the day.\nTemp Range: 28 - 33 C\nR.H. Range: 65 - 85 Per Cent\n\nDate/Month 22/5(Tuesday)\nWind: Southwest force 2 to 3.\nWeather: Mainly fine and ver…
has comment: http://stackoverflow.com/comment/87822610
has comment: http://stackoverflow.com/comment/87822720
has comment: http://stackoverflow.com/comment/87822727
has answer: http://stackoverflow.com/a/50403865
accepted answer: http://stackoverflow.com/a/50403865
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87822644
has title: How to match start and end of line across multiple lines
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35329098
answer count: 2
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87822691
has answer: http://stackoverflow.com/a/50403537

http://stackoverflow.com/comment/87948649
has text: I just update how read the input data
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50467121

http://stackoverflow.com/comment/87980784
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50480388
has text: did you use virtualenv or pyenv?
type: Comment

http://stackoverflow.com/comment/87985485
type: QuestionComment
comment on: http://stackoverflow.com/q/50486328
score: 0
type: Comment
has text: And does this work `ind = where(loss==min(loss))`?

http://stackoverflow.com/comment/87841022
comment on: http://stackoverflow.com/a/50412172
type: Comment
has text: More loops? What for? With my code you should be able to iterate through all the numbers... Check what is the output of `print(numbers)`. Is it a list of all your numbers?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88022005
comment on: http://stackoverflow.com/q/50504567
score: 0
type: Comment
type: QuestionComment
has text: Please add the error message to the question instead of the image.

http://stackoverflow.com/a/50524363
downvote count: 0
has comment: http://stackoverflow.com/comment/88060734
has comment: http://stackoverflow.com/comment/88060775
answers question: http://stackoverflow.com/q/50524328
has comment: http://stackoverflow.com/comment/88060735
type: Answer
has body: Use slicing to extract n elements of the list &gt;&gt;&gt; print(sorted_dict[:n])
score: 2
upvote count: 2

http://stackoverflow.com/a/50387783
accepted answer of: http://stackoverflow.com/q/50387142
type: Answer
answers question: http://stackoverflow.com/q/50387142
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: By default QListWidget will order the elements with respect to the text, if you want to be ordered with respect to the numeric value that is associated with the text you must create a custom QListWidgetItem and overwrite the method __lt__: import sys from PyQt4.QtGui import QApplication, QListWidget, QListWidgetItem from PyQt4.QtCore import Qt class ListWidgetItem(QListWidgetItem): def __lt__(self, other): try: return float(self.text()) &lt; float(other.text()) except Exception: return QListWidgetItem.__lt__(self, other) if __name__ == '__main__': app = QApplication(sys.argv) w = QListWidget() for i in [1, 10, 100, 11, 110, 111, 12]: w.addItem(ListWidgetItem(str(i))) w.sortItems() w.show() sys.exit(app.exec_())

http://stackoverflow.com/q/50415280
has comment: http://stackoverflow.com/comment/87846422
favorite count: 0
has body: Let's say I have the following bit of code: import pandas as pd import numpy as np A = ['red', 'blue'] B = range(2) C = np.random.random((4,2,2)) import pandas as pd df = pd.DataFrame({'Color':np.repeat(A,2),'Trial':np.tile(B,2),'V0':C[:,0,0],'V1':C[:,0,1], 'V2':C[:,1,0], 'V3':C[:,1,1]}) df Which outputs the following dataframe &gt; Color Trial V0 V1 V2 V3 &gt; 0 red 0 0.726781 0.549726 0.053999 0.469885 &gt; 1 red 1 0.609131 0.012120 0.587780 0.344290 &gt; 2 blue 0 0.285235 0.491907 0.907871 0.549792 &gt; 3 blue 1 0.646334 0.164288 0.029917 0.181290 I would like to avoid having to type out each entry of the numpy array if the size of the array grows so I came up with the following solution for larger arrays A = ['red', 'blue'] B = range(2) C = np.random.random((4,2,2)) import pandas as pd df = pd.DataFrame({'Color':np.repeat(A,2),'Trial':np.tile(B,2)}) _df = pd.DataFrame(C.reshape(4,4)).add_prefix('V') df = pd.concat([df,_df],axis=1) df Which has the same output. My question is if there is a better way of doing this that doesn't involve creating a dataframe for each array I want to include and then concatenating them?
type: Question
has answer: http://stackoverflow.com/a/50415345
answer count: 2
accepted answer: http://stackoverflow.com/a/50415324
has answer: http://stackoverflow.com/a/50415324
tagged with: arrays
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50415345
type: AnsweredQuestion
score: 3
has title: Initialise DataFrame from numpy array with supplementary columns
tagged with: pandas
upvote count: 3
tagged with: dataframe

http://stackoverflow.com/comment/87878868
has text: Please do not save characters - had you used longer variable names you wouldn't have tripped yourself.
type: Comment
comment on: http://stackoverflow.com/q/50432300
type: QuestionComment
score: 2

twisted
tags question: http://stackoverflow.com/q/50475611
tags question: http://stackoverflow.com/q/50472613
type: Tag
tag name: twisted
tags question: http://stackoverflow.com/q/50429891

http://stackoverflow.com/a/52595074
upvote count: 1
type: Answer
has body: I also do uploads of up to 40GB. Since I do multi-part uploads, I check if the file I am writing to is closed. An S3 file(object) is only closed when all operations are finished. Another way is to use asynchronous task queue like Celery. You will get notifications when a task is done. I now use Golang but both those methods have worked very well for me.
answers question: http://stackoverflow.com/q/50515323
downvote count: 0
score: 1

http://stackoverflow.com/q/50446707
tagged with: python-2.6
score: 0
has title: Remove Python from server
linked to: http://stackoverflow.com/q/45542690
answer count: 1
has comment: http://stackoverflow.com/comment/87906890
type: Question
tagged with: server
has answer: http://stackoverflow.com/a/50446813
type: UnansweredQuestion
has body: Want to delete python from my server, Using Centos 7. i have python 2.6.6 and python 3.6 in my server and i think thats the reason i am getting an error. so want to remove python 2.6. i am getting these version error so want to try removing python 2.6.6 and then running my code File "chatbot.py", line 7, in &lt;module&gt; import sqlite3 File "/home/pythondemo/.local/lib/python3.6/sqlite3/__init__.py", line 23, in &lt;module&gt; from sqlite3.dbapi2 import * File "/home/pythondemo/.local/lib/python3.6/sqlite3/dbapi2.py", line 50, in &lt;module&gt; version_info = tuple([int(x) for x in version.split(".")]) NameError: name 'version' is not defined
tagged with: python
tagged with: python-3.6

http://stackoverflow.com/a/50467345
accepted answer of: http://stackoverflow.com/q/50467297
upvote count: 3
downvote count: 0
has body: Use nested list comprehension: df = pd.DataFrame([[y[1] for y in x] for x in example]) print (df) 0 1 0 b d 1 b1 d2 df = pd.DataFrame([[y[1] for y in x] for x in example], columns=['col1','col2']) print (df) col1 col2 0 b d 1 b1 d2
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50467297
score: 3

http://stackoverflow.com/comment/87874424
comment on: http://stackoverflow.com/a/50429811
has text: It was returning Bolean value , which is not what I want .
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50425704
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50426030
has title: how to get value in input balise
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50426030
has body: good evening, I would like to get the number 6355 in the balise below: &lt;div class="submitContainer txtC"&gt;&lt;input class="btnRed bold" type="submit" value="Rechercher (6 355 annonces)"/&gt;&lt;/div&gt; This is the code that I use and I need help for the variable pagination: from fake_useragent import UserAgent from bs4 import BeautifulSoup import requests URL_accueil = "https://www.lacentrale.fr/listing?mileageMax=150000&amp;priceMax=17000&amp;priceMin=5000&amp;yearMin=2012&amp;age=1" page_accueil = requests.get(URL_accueil, headers={'User-Agent': str(UserAgent().chrome)}) soup = BeautifulSoup(page_accueil.text, "lxml").find('div', {"class": "submitContainer txtC"}) print(soup) print("\n\n") try: pagination = soup.find('input', {"type": "submit"}).text() except Exception: pagination = "missing" print(pagination)
answer count: 1
tagged with: web-scraping
type: Question

http://stackoverflow.com/comment/87978660
score: 0
type: AnswerComment
has text: Yes, you are right. I managed to make a request twice and that wiped pattern out. Thank you!
type: Comment
comment on: http://stackoverflow.com/a/50474279

http://stackoverflow.com/q/50403664
tagged with: python
has body: I have a pd dataframe: A B 1 2 2 3 3 2 I want: totalA = 1+2+3=6 and totalB = 2+3+2=7 I tried df.sum()
upvote count: 2
type: AnsweredQuestion
tagged with: pandas
has title: Add the total of a column in pandas dataframe
score: 1
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/38470550
has answer: http://stackoverflow.com/a/50403843
favorite count: 0
accepted answer: http://stackoverflow.com/a/50403843
type: Question
duplicate of: http://stackoverflow.com/q/38470550

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/50504112
tags question: http://stackoverflow.com/q/50416336

http://stackoverflow.com/comment/88094164
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50541457
has text: Where do you get the 403 error? From the proxy or from yelp? Is there an error message body with the 403 response? 403 is a typical response when you are trying to access a resource that requires authentication, but you are not logged in. Retrying is not a proper response to a 403, what you need to do is to authenticate and get a proper login token for the resource you are trying to access.

http://stackoverflow.com/comment/88037722
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50512524
has text: Did you tried to give your process real time priority? Accuracy is a problem of non-deterministic systems, but linux can be really close to most needs. How much delay you're willing to tolerate? ms, us, ns? Time constrained solutions are always hard to delivery and very fragile, any changes on code, kernel, or runtime in general will impact such solutions.
score: 0

http://stackoverflow.com/q/50447893
score: 2
answer count: 1
downvote count: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/87919712
favorite count: 0
type: Question
tagged with: opencv
has body: Here is my code: def load_cascades(): cascades = [] for root, dirs, files in os.walk(rooted('data/logos')): for fname in files: if fname == 'cascade.xml': path = os.path.join(root, fname) cascade = cv2.CascadeClassifier(path) cascades.append(cascade) return cascades cascades = load_cascades() def get_heuristics(pair): url = pair[0] image = pair[1] matches_any_logos = False for cascade in cascades: frame = cv2.imread(image, 0) logos = cascade.detectMultiScale( image=frame, minNeighbors=5, minSize=(25, 25), ) if len(logos) &gt; 0: matches_any_logos = True return { 'matches_any_logos': matches_any_logos, 'matches_corresponding_urls': matches_corresponding_urls, } class LogoDetectionVectorizer(DictVectorizer): def fit(self, x, y=None): x = [get_heuristics(v) for v in x] return super(LogoDetectionVectorizer, self).fit(x) def fit_transform(self, x, y=None): x = [get_heuristics(v) for v in x] return super(LogoDetectionVectorizer, self).fit_transform(x) def transform(self, x, y=None): x = [get_heuristics(v) for v in x] return super(LogoDetectionVectorizer, self).transform(x) This is a module in a machine learning algorithm of model training, I have a set of trained models related to logos which I have trained, however when I try and train the model on a large dataset I get this error: cv2.error: /io/opencv/modules/core/src/matrix.cpp:436: error: (-215) u != 0 And opencv reports that it is out of memory. I do not understand why? I am simply creating all cascades once and then using them multiple times, I saw somewhere that I need to call cascade.deallocate() after each iteration and then recreate the cascades however python claims that cascade.desallocate() does not exist as well as the obvious performance hit of having to recreate the cascades each time. Can someone help? Thanks
tagged with: out-of-memory
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50464654
tagged with: cascade-classifier
upvote count: 2
has title: OpenCV CascadeClassifier Python out of memory

http://stackoverflow.com/a/50433489
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I think it's hard to say which one is correct, since the whisker positions simply depend on a definition. In the current matplotlib version the definition of the whisker position is that it shows at the highest datum within the range determined by the whis parameter. Here you use whis=[5.0,95.0] and the 95-percentile would be ~36. The highest datum below or equal 36 is 25.33; hence the whisker is shown at that value. I do not know the definition used in the initial version of the boxplot in matplotlib 1.4, but I could imagine it to be the lowest value outside the percentile range given to whis; hence it would be shown at 49.33.
answers question: http://stackoverflow.com/q/50427368
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87914943
accepted answer of: http://stackoverflow.com/q/50427368

http://stackoverflow.com/q/50477026
has answer: http://stackoverflow.com/a/50477200
favorite count: 0
score: 1
tagged with: python
tagged with: elementtree
has body: The tree I'm adding nodes to uses a namespace: xmlns:ns0="http://someplace.net/xml/" Before inserting the child, you must reach the parent node first, and in my case findall() gives me the parent node that looks like this: &lt;ns0:parent xmlns:ns0="http://someplace.net/xml/" someattrib="some value"&gt; I tried to construct a child node like this: node = ET.Element('mytag') or node = ET.Element('ns0:mytag') or node = ET.Element('ns0:mytag') node.set('xmlns:ns0', "http://someplace.net/xml/") Then parent.extend(node) But the node was nowhere to be found in the resulting tree. None of the three methods worked. What am I missing here?
tagged with: http://stackoverflow.com/tag/xml
type: Question
has title: With python ElementTree, how to add a node to a tree having namespace?
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/87796341
comment on: http://stackoverflow.com/q/50390255
score: 0
type: QuestionComment
has text: I was to quick to judge. But I cannot reproduce your error. Could you post a [mcve]?
type: Comment

http://stackoverflow.com/comment/88101318
comment on: http://stackoverflow.com/a/50538015
type: AnswerComment
has text: this is exactly what I was looking for. but with this solution, can I still have methods in bar that are not in foo?
score: 0
type: Comment

http://stackoverflow.com/comment/87954145
score: 0
has text: You're welcome! I updated the code again. I also added all the table parameters and the website type.
type: Comment
comment on: http://stackoverflow.com/a/50440704
type: AnswerComment

http://stackoverflow.com/a/50392170
answers question: http://stackoverflow.com/q/50391766
type: Answer
score: 0
has body: It can depends on your environement. Test: conda search python to see the available versions for your environement. Have you tried: conda create -n py364 python=3.6.4 anaconda ?

http://stackoverflow.com/q/50414179
has answer: http://stackoverflow.com/a/50421045
tagged with: snapshot
tagged with: python
type: AnsweredQuestion
score: 0
has body: [Very new to AWS] Hi, I am trying to move my EBS volume snapshot copies across regions. I have been trying to use Boto3 to move the snapshots. My objective is to move the latest snapshot from us-east-2 region to us-east-1 region automatically on a daily basis. I have used aws configure command in terminal to setup my security credentials and set region to us-east-2. I am using pandas to acquire the most recent snapshot-id using this code: import boto3 import pandas as pd from pandas.io.json.normalize import nested_to_record import boto.ec2 client = boto3.client('ec2') aws_api_response = client.describe_snapshots(OwnerIds=['self']) flat = nested_to_record(aws_api_response) df = pd.DataFrame.from_dict(flat) df= df['Snapshots'].apply(pd.Series) insert_snap = df.loc[df['StartTime'] == max(df['StartTime']),'SnapshotId'] insert_snap = insert_snap.reset_index(drop=True) insert_snap returns a snapshot id something like snap-1234ABCD I am try to use this code to move the snap shot from us-east-2 to us-east-1: client.copy_snapshot(SourceSnapshotId='%s' %insert_snap[0], SourceRegion='us-east-2', DestinationRegion='us-east-1', Description='This is my copied snapshot.') The snapshot is copying in the same region using the above line. I have also tried switching regions through aws configure command in terminal, with the same issue occurring where snapshot is being copied in the same region. There is a bug in Boto3 that is skipping the destination parameter in the copy_snapshot() code. Information found here: https://github.com/boto/boto3/issues/886 I have tried inserting this code with into the lambda manager but keep getting error "errorMessage": "Unable to import module 'lambda_function'": region = 'us-east-2' ec = boto3.client('ec2',region_name=region) def lambda_handler(event, context): response=ec.copy_snapshot(SourceSnapshotId='snap-xxx', SourceRegion=region, DestinationRegion='us-east-1', Description='copied from Ohio') print (response) I am out of options, what I can do …
tagged with: amazon-ebs
tagged with: amazon-ec2
answer count: 1
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/50421045
type: Question
has title: Boto3 not copying snapshot to other regions, other options?

http://stackoverflow.com/a/50456049
has body: try the following idx = result['Contas Resultado'] == 0 result.loc[idx, 'Contas Resultado'] = 'Faturamento'
type: Answer
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50455974
score: 2
answers question: http://stackoverflow.com/q/50455974
downvote count: 0

http://stackoverflow.com/comment/88010834
has text: Yes, x is global -- please see the updated example. And yes, the race condition between setting x and testing its value was my point of concern. This solution looks pretty robust. Assuming x is a string (immutable in Python IIRC) would we still be in "mostly/always? harmless" territory with the original code?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50498653
score: 0

http://stackoverflow.com/q/50402400
answer count: 2
has comment: http://stackoverflow.com/comment/87820555
possible better answer: http://stackoverflow.com/a/50404773
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50404773
downvote count: 1
type: AnsweredQuestion
tagged with: performance
tagged with: pandas
tagged with: sum
upvote count: 5
accepted answer: http://stackoverflow.com/a/50402463
has title: sum every element of first array with all the elements of second array
has body: I have two arrays: array1 = [1,2,3] array2 = [10,20,30] I want the next sum: array3 = [10+1,10+2,10+3,20+1,20+2,20+3,30+1,30+2,30+3] How can I do that? (I know that it can be done with two for loops but I want something more efficient if possible) Note: those two arrays are contained in a dataframe (pandas)
has answer: http://stackoverflow.com/a/50402463
favorite count: 0
type: Question

pycharm
tags question: http://stackoverflow.com/q/50423903
tags question: http://stackoverflow.com/q/50497451
tags question: http://stackoverflow.com/q/50500362
tags question: http://stackoverflow.com/q/50528919
tags question: http://stackoverflow.com/q/50459260
tags question: http://stackoverflow.com/q/50461995
tags question: http://stackoverflow.com/q/50392215
tags question: http://stackoverflow.com/q/50533848
tags question: http://stackoverflow.com/q/50498721
tags question: http://stackoverflow.com/q/50516650
tags question: http://stackoverflow.com/q/50440391
tag name: pycharm
tags question: http://stackoverflow.com/q/50493158
tags question: http://stackoverflow.com/q/50426987
tags question: http://stackoverflow.com/q/50400963
type: Tag
tags question: http://stackoverflow.com/q/50493837
tags question: http://stackoverflow.com/q/50387354
tags question: http://stackoverflow.com/q/50443513
tags question: http://stackoverflow.com/q/50450552
tags question: http://stackoverflow.com/q/50386050
tags question: http://stackoverflow.com/q/50473417
tags question: http://stackoverflow.com/q/50385348
tags question: http://stackoverflow.com/q/50464360
tags question: http://stackoverflow.com/q/50497956
tags question: http://stackoverflow.com/q/50534928
tags question: http://stackoverflow.com/q/50387950
tags question: http://stackoverflow.com/q/50488707
tags question: http://stackoverflow.com/q/50493601
tags question: http://stackoverflow.com/q/50432712
tags question: http://stackoverflow.com/q/50474051
tags question: http://stackoverflow.com/q/50492727
tags question: http://stackoverflow.com/q/50531898

constraints
type: Tag
tags question: http://stackoverflow.com/q/50437334
tags question: http://stackoverflow.com/q/50541591
tags question: http://stackoverflow.com/q/50513505
tags question: http://stackoverflow.com/q/50410037
tag name: constraints

http://stackoverflow.com/a/50543106
score: 1
type: Answer
has body: Do loss and val_loss imply the overall loss and overall validation loss of the model respectively? Yes, they are the training and validation overall losses. The individual losses for each output are weighted according to the coefficients specified in loss_weights. Is it possible to have the accuracy of the model printed as well? You can have the accuracy for each output individually, but I believe Keras doesn't support "overall" metrics. This would require more information on how the individual outputs' metrics should be aggregated.
downvote count: 0
answers question: http://stackoverflow.com/q/50541409
upvote count: 1

http://stackoverflow.com/q/50531632
tagged with: uwsgi
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: flask
favorite count: 0
score: 3
upvote count: 3
has body: I have an app writen by python with Flask, and deploy it use uwsgi +ngix, here is my config of uwsgi: [uwsgi] master=true socket = :8223 chdir= /SWS/swdzweb wsgi-file = manage.py callable = app processes = 4 threads = 2 My app will response a request which want to start or stop a daemon process writen by pytho too. as below in the request function do os.system("python /SWS/webservice.py %s" % cmd) where cmd is start|stop. in my daemon process, it is single process and single thread, and i capture SIGTEM then exit,like this signal(SIGTERM, lambda signo,handler:sys.exit(0)) But. when I start this daemon process by uwsgi in my request function, i can't stop it, for example kill -15 pid or python /SWS/web service.py stop just like the SIGTERM signal does not send to my daemon process. however, when i config uwsgi with 4 processes and 1 thread, this works fine. config like this [uwsgi] master=true socket = :8223 chdir= /SWS/swdzweb wsgi-file = manage.py callable = app processes = 4 threads = 1 I can not figure out the reason, so I have to ask for help. Thanks!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
downvote count: 0
tagged with: python-daemon
tagged with: python
has title: uwsgi+flask to start|stop a python daemon process

http://stackoverflow.com/comment/89570933
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50548698
type: Comment
has text: If you have many `on_message` events across multiple cogs, then all of those `on_message` events will be triggered. That means that potentially many `process_commands` are being called for a single message.

http://stackoverflow.com/q/50518607
score: 4
favorite count: 0
type: AnsweredQuestion
tagged with: conditional-statements
tagged with: if-statement
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/50518641
has body: I'm an R programmer trying to get into Python. In R, when I want to mutate a column conditionally, I use: col = dplyr::mutate(col, ifelse(condition, if_true(x), if_false(x)) In Python, how does one mutate a column value conditionally? Here's my minimally reproducible example: def act(cntnt): def do_thing(cntnt): return(cntnt + "has it") def do_other_thing(cntnt): return(cntnt + "nope") has_abc = cntnt.str.contains.contains("abc") if has_abc == T: cntnt[has_abc].apply(do_thing) else: cntnt[has_abc].apply(do_other_thing)
has answer: http://stackoverflow.com/a/50518641
type: Question
upvote count: 4
has title: Mutate column conditionally
answer count: 2
accepted answer: http://stackoverflow.com/a/50519161
has answer: http://stackoverflow.com/a/50519161
downvote count: 0
has comment: http://stackoverflow.com/comment/88050231
linked to: http://stackoverflow.com/q/34835951

http://stackoverflow.com/a/50476869
has body: You already call the 3 other functions inside holiday_cost. You don't need to call them multiple times. Also ive made a few other helpful changes such as while city &gt; 3: instead of while city != 4: in plane_cost() and I added a return ticket line at the end of plane_cost() Also the line: elif city == '4': print 'You have selected an invalid option' was unnecessary as city == '4' falls into the else condition. Here is the final code: def hotel_cost(nights): return nights * 875 def plane_cost(city): ticket = 0 while city &gt; 3: if city == '1': ticket = 750 break elif city == '2': ticket = 850 break elif city == '3': ticket = 600 break else: print 'You have selected an invalid option' return ticket def car_rental(days): return days * 275 def holiday_cost(nights, city, days): nights = hotel_cost(nights) city = plane_cost(city) days = car_rental(days) return nights + city + days nights = int(raw_input('How many nights will you be staying? ')) city = raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? ') days = int(raw_input('How many days will you need a car for?: ')) total = holiday_cost(nights, city, days) print total
score: 0
accepted answer of: http://stackoverflow.com/q/50476638
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87969122
has comment: http://stackoverflow.com/comment/87968741
type: Answer
answers question: http://stackoverflow.com/q/50476638

http://stackoverflow.com/q/50478832
has comment: http://stackoverflow.com/comment/87971472
type: AnsweredQuestion
downvote count: 3
has body: In Python turtle, when drawing objects on the screen, if there was a way to have a circle's radius connected to the window width or height, so that it can be resized by altering the window size?
upvote count: 1
has title: Tie circle radius to window size in Python Turtle
tagged with: python-turtle
has answer: http://stackoverflow.com/a/50479181
has answer: http://stackoverflow.com/a/50479835
possible better answer: http://stackoverflow.com/a/50479835
tagged with: drawing
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: turtle-graphics
accepted answer: http://stackoverflow.com/a/50479181
score: -2
tagged with: python

http://stackoverflow.com/a/50428596
has comment: http://stackoverflow.com/comment/87914066
type: Answer
has comment: http://stackoverflow.com/comment/87873428
answers question: http://stackoverflow.com/q/50427969
score: 0
has body: As far as I can see, that is not possible if you are limited to having just one file. Check out this answer which explains the different file access methods: Confused by python file mode “w+”. If you are allowed to use two files, well then it's plain sailing but I don't see how you can write to an existing file without it being append; i.e. at the end of the file.

http://stackoverflow.com/comment/87993364
score: 0
comment on: http://stackoverflow.com/q/50490095
type: Comment
has text: `curses` and the script itself run fine. The problem is, pressing `ctrl+a+d` doesn't do anything anymore after I switched to `curses` from `sys.stdout.write()` So I can't exit it at all without stopping the script from running.
type: QuestionComment

http://stackoverflow.com/q/50529448
has answer: http://stackoverflow.com/a/50530603
type: UnansweredQuestion
tagged with: opengl
score: 7
has answer: http://stackoverflow.com/a/76952043
tagged with: python
has title: Pyqtgraph & Changing color base on height for surfaceplot
answer count: 2
upvote count: 7
downvote count: 0
has body: I am looking for a way to make my surface plot item to change color base on height. Below is my current method: def __init__(self, s): self.traces = dict() self.app = QtGui.QApplication(sys.argv) self.w = gl.GLViewWidget() self.w.opts['distance'] = 2000 self.w.setWindowTitle('pyqtgraph example: GLLinePlotItem') self.w.setGeometry(0, 0, 600, 600) self.w.show() self.socket = s self.timer = QtCore.QTimer() self.timer.setInterval(1) # in milliseconds self.timer.start() self.timer.timeout.connect(self.onNewData) # create the background grids #gx is the y grid #gz is the x gid gx = gl.GLGridItem() gx.rotate(90, 0, 1, 0) gx.translate(0, 0, 0) self.w.addItem(gx) gz = gl.GLGridItem() gz.translate(200, 0, -500) self.w.addItem(gz) gx.scale(100, 10, 100) gz.scale(20, 10, 100) self.y = np.linspace(0, 100, 10) self.x = np.linspace(60,400, 708) temp_z = np.zeros((10,708)) self.surf = gl.GLSurfacePlotItem(x=self.y, y=self.x, z=temp_z, shader='heightColor', computeNormals=False, smooth=False) self.surf.scale(3,1,1) self.surf.shader()['colorMap'] = np.array([0.7, 2, 0.5, 0.2, 0.7, 0.7, 0.2, 0, 2]) self.w.addItem(self.surf) But the method is not working out quiet well. As Z values get very high, the surface become completely white. Btw, I have no idea of what I am doing with colormap, i just took it off the example.
tagged with: pyqtgraph
favorite count: 0
type: Question

http://stackoverflow.com/q/50489585
has answer: http://stackoverflow.com/a/50489737
downvote count: 0
has body: I want to find all password attribute while xml parsing and replace that with string "password". To find the password attribute I tried findall(), but it return "None". Python version: python2.6 Sample code : from xml.etree.ElementTree import ElementTree tree = ElementTree() a= tree.parse("/home/xxxx/securityfile_test.xml") z = tree.findall(".//password") print z Can any one please help Sample xml <?xml version="1.0" encoding="UTF-8"?> <rMember ref="A"/> <gMember ref="A"/> <rMember ref="O"/> <gMember ref="A"/>
has answer: http://stackoverflow.com/a/50489784
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: xpath
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 2
upvote count: 2
has title: ElementTree.findall returns none

http://stackoverflow.com/q/50420721
score: 0
has title: How to change the time format of timedelta
duplicate of: http://stackoverflow.com/q/26456825
has answer: http://stackoverflow.com/a/50420933
upvote count: 1
type: UnansweredQuestion
downvote count: 1
favorite count: 0
answer count: 3
tagged with: pandas
has body: Hi I hv a timedelta in the following format 0days 01:25:53.0000000 I want to change this time delta to equivalent minutes(I.e. 85.88) Thanks
has answer: http://stackoverflow.com/a/50420789
tagged with: python
has answer: http://stackoverflow.com/a/50420742
linked to: http://stackoverflow.com/q/26456825
type: Question

http://stackoverflow.com/a/52124239
downvote count: 0
answers question: http://stackoverflow.com/q/50415356
upvote count: 1
score: 1
type: Answer
has body: I think you are missing the combining part. The 'abc' must be combined before the sorting can be done, otherwise you are not really sorting the right list: l = [('abc', 10), ('def', 15), ('ghi', 10), ('abc', 12), ('xyz', 100)] diction = {} for (i, j) in l: if i in diction: diction[i] = diction[i] + j else: diction[i] = j sorted_list = list(diction.items()) sorted_list = sorted(sorted_list, key=lambda x: x[1], reverse=True) print(sorted_list[:10])

http://stackoverflow.com/a/51706087
answers question: http://stackoverflow.com/q/50463238
upvote count: 14
downvote count: 0
has comment: http://stackoverflow.com/comment/94341914
score: 14
has body: You can compile your code in -w mode or --windowed, but then you have to assign stdin and stderr as well. So change: s = subprocess.Popen([EXE,files,'command'],shell=True, stdout=subprocess.PIPE) to: s = subprocess.Popen([EXE,files,'command'],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
type: Answer
has comment: http://stackoverflow.com/comment/119409566

http://stackoverflow.com/a/50517673
type: Answer
score: 0
has body: This is because the slicing syntax can handle the case where the length of the list is less than the slice length. For example: my_list = [1] print(my_list[:3]) #[1] However, indexing is not as forgiving: print(my_list[1]) IndexErrorTraceback (most recent call last) &lt;ipython-input-2-f6bea31a1a9e&gt; in &lt;module&gt;() ----&gt; 1 print(my_list[1]) IndexError: list index out of range Somewhere in your rdd, you have a row where the length of the keys is less than 2. You may want to first filter: r_parsed = r_parsed.filter(lambda x: len(x.keys()) &gt; 1).map(lambda x: x.keys()[1]) Or build the logic into your map function: r_parsed = r_parsed.map(lambda x: x.keys()[1] if len(x.keys()) &gt; 1 else None)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50517559
answers question: http://stackoverflow.com/q/50517559

http://stackoverflow.com/comment/87860003
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [Python function not accessing class variable](https://stackoverflow.com/questions/16680221/python-function-not-accessing-class-variable)
comment on: http://stackoverflow.com/q/50422593

http://stackoverflow.com/comment/87978541
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50477475
has text: Yup, something's going wrong with decoding: the UTF-8 representation of "é", which is the bytes sequence `C3 A9`, is being interpreted as Latin-1, which results in "Ã©". This is shown clearly in the JSON output, which should be "\u00e9". I suspect it's habanero's fault, and filing an issue on their GitHub repo was the right thing to do.
score: 0

http://stackoverflow.com/q/50399550
has title: Retrieving column names from ref cursor with cx_Oracle
has comment: http://stackoverflow.com/comment/87816438
has comment: http://stackoverflow.com/comment/87817276
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/50413182
accepted answer: http://stackoverflow.com/a/50413182
has body: In using cx_Oracle to invoke a simple stored procedure, I can easily get data back from the procedure as so: db = db_class() #Sets up stuff, etc. conn = db.connect() #Returns a connection to the database cursor = conn.cursor() l_results = cursor.var(cx_Oracle.CURSOR) res = cursor.callproc("PROG.DATA.GET_EVENTS", [1,2,l_results]) #params = siteID, userID, ref cursor res[2] ends up being some sort of enumerable I can easily iterate through like so: data = [row for row in res[2]] I end up with a list of lists/tuples which gives me the values, but I also need the column names. I've tried the following: cols = cursor.description if cursor.description is not None else [] #Returns None cols = res[2].description if res[2].description is not None else [] #Returns an error. Same if l_results is used instead How do I get the column names from l_results? I've determined that l_results is a Variable object and not a cursor, so it won't work. Same with res[2]. But I just can't get the columns from curs. curs.description after this appears to be a None value, when it should be a list of 7-item tuples What in the world am I missing? EDIT 1: I've tried changing it from callproc to the following. Same issue. res = cursor.execute("BEGIN PROG.DATA.GET_EVENTS(:1,:2,:3); END;", {"1": 1,"2": 2,"3":, l_results}) cols = cursor.description #Returns None, again. The call does return data, so I'm not sure why description isn't being set.
upvote count: 5
score: 5
downvote count: 0
tagged with: cx-oracle
answer count: 1
favorite count: 0
type: AnsweredQuestion

cloudera-cdh
tag name: cloudera-cdh
type: Tag
tags question: http://stackoverflow.com/q/50531584

http://stackoverflow.com/comment/87801666
score: 1
comment on: http://stackoverflow.com/q/50392823
has text: may be share your environment details, running on windows or ubuntu? interactive shell or script? jupyter-notebook or some other IDE?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87936485
has text: All these i have installed and getting successfully installed , but while running the program getting the same error as i have posted above pip install "dask[complete]";pip install dask;pip install "dask[dataframe]"
comment on: http://stackoverflow.com/q/50461126
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50484211
type: Answer
has body: pip install tldextract In Python interpreter: import tldextract tldextract.extract('www.ghi').domain Works fine for all of the three examples. I am using Python 2.7.12.
answers question: http://stackoverflow.com/q/50482402
has comment: http://stackoverflow.com/comment/110435049
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/50510620
upvote count: 1
has comment: http://stackoverflow.com/comment/88039427
has body: A functional solution is possible using set.difference: res = set(map(tuple, a)).difference(set(map(tuple, b))) [(1, 2, 3, 4, 5, 6)] Explanation Since list is not a hashable type, we convert sublists to type tuple, which are immutable and hashable, e.g. set(map(tuple, a)). Then use set.difference to take the difference between the 2 resulting sets.
has comment: http://stackoverflow.com/comment/88040591
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50510255
has comment: http://stackoverflow.com/comment/88039335

http://stackoverflow.com/a/50431324
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87877519
type: Answer
has comment: http://stackoverflow.com/comment/87877202
has body: That "only difference" is a huge difference. The WAV format, by default, stores samples as signed little-endian 16-bit integers. So, when you write an array of int16 values as raw data, you get a playable WAV file (on a little-endian system, at least). But when you write an array of int32 values, you get nonsense—each number turns into 2 samples, one of which is the high word of your data, the next of which is the low word. So, you've got your original audio samples at half speed, and interleaves with what's effectively random noise. Or, alternatively, you can use a non-default WAV format. You didn't show enough of your code to show how you're handling this, but you can write WAV files in a variety of different formats, from 8-bit unsigned int to 32-bit float, and 32-bit signed ints are a valid format. WAV files can even handle compression (including MP3). But less-common formats may not actually play with every tool; a lot of programs assume a WAV is 16-bit integers, and won't know what to do with anything else. So, you're probably better off writing 16-bit integers. Or, maybe you're already doing that—writing 32-bit int values with the right header—and maybe your player is handling them properly. But you're writing 32-bit int values between -32768 and 32767. Which means you're only using 1/65536th of the dynamic range, so everything will be incredibly quiet. If you want to write 32-bit int values, you want to normalize them to the 32-bit int range, not the 16-bit int range. The simplest solution to all of these problems is: convert the values back to int16 before writing them: y3 = y2.astype(np.int16)
score: 2
answers question: http://stackoverflow.com/q/50431296
downvote count: 0
has comment: http://stackoverflow.com/comment/87877253
accepted answer of: http://stackoverflow.com/q/50431296

http://stackoverflow.com/comment/87804671
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50393604
has text: sorry chrisz , I have only given the few SKUs , there are lot more but I couldn't display all. In reality each day have mutliple SKUs

http://stackoverflow.com/comment/87964825
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50456662
has text: Please, try the updated code. Also, feel free to mark it as accepted if it helps you to solve the issue.

http://stackoverflow.com/q/50540215
upvote count: 1
has comment: http://stackoverflow.com/comment/88092783
has comment: http://stackoverflow.com/comment/88098655
has comment: http://stackoverflow.com/comment/88091925
downvote count: 1
answer count: 1
has body: import csv with open('loan.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter='', quotechar='|') for row in spamreader: print ','.join(row) On running this i get the followinh error : File "loan.py", line 5 print ','.join(row) ^ SyntaxError: invalid syntax
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88091934
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88092025
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88098567
has title: opening csv files - SyntaxError: invalid syntax
has answer: http://stackoverflow.com/a/50540249

http://stackoverflow.com/q/50493036
linked to: http://stackoverflow.com/q/15042129
has title: Changing the position of an axis on a Axes3D
has body: I am using mplot3d from the mpl_toolkits library. When displaying the 3D surface on the figure I'm realized the axis were not positioned as I wished they would. Let me show, I have added to the following screenshot the position of each axis: Is there a way to change the position of the axes in order to get this result: Here's the working code: import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D ax = Axes3D(plt.figure()) def f(x,y) : return -x**2 - y**2 X = np.arange(-1, 1, 0.02) Y = np.arange(-1, 1, 0.02) X, Y = np.meshgrid(X, Y) Z = f(X, Y) ax.plot_surface(X, Y, Z, alpha=0.5) # Hide axes ticks ax.set_xticks([-1,1]) ax.set_yticks([-1,1]) ax.set_zticks([-2,0]) ax.set_yticklabels([-1,1],rotation=-15, va='center', ha='right') plt.show() I have tried using xaxis.set_ticks_position('left') statement, but it doesn't work.
tagged with: surface
favorite count: 0
tagged with: matplotlib-3d
has answer: http://stackoverflow.com/a/53010872
type: Question
answer count: 2
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/77202868
type: UnansweredQuestion
upvote count: 6
score: 6
tagged with: mplot3d

http://stackoverflow.com/q/50438308
score: 0
has body: I try to predict hits in a sequence of numbers, but it is important to me not to predict hits that already exist. For example, I have a sequence of numbers from 1 to 100000. And for some of these numbers I have hit, now I would like to predict even more hits. Which method is suitable for this?
has comment: http://stackoverflow.com/comment/87894348
answer count: 1
has answer: http://stackoverflow.com/a/50439137
accepted answer: http://stackoverflow.com/a/50439137
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87892263
type: Question
tagged with: prediction
has comment: http://stackoverflow.com/comment/87891223
tagged with: python
tagged with: keras
has title: Keras: prediction of matches in a series of numbers
tagged with: data-science
type: AnsweredQuestion

http://stackoverflow.com/comment/88026227
has text: Always fun to see a link to your own repo. But yeah: `axisbg` is deprecated in favour of `facecolor`.
score: 4
comment on: http://stackoverflow.com/q/50504053
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50517155
has comment: http://stackoverflow.com/comment/88046921
has comment: http://stackoverflow.com/comment/88048892
score: 0
has body: Use this: https://www.w3schools.com/tags/tag_progress.asp Ex:
answers question: http://stackoverflow.com/q/50517121
downvote count: 1
has comment: http://stackoverflow.com/comment/88046869
type: Answer
upvote count: 1

pip
tags question: http://stackoverflow.com/q/50477348
tags question: http://stackoverflow.com/q/50416753
tags question: http://stackoverflow.com/q/50507194
tags question: http://stackoverflow.com/q/50487626
tags question: http://stackoverflow.com/q/50392646
tags question: http://stackoverflow.com/q/50537908
tags question: http://stackoverflow.com/q/50535418
tags question: http://stackoverflow.com/q/50432786
tags question: http://stackoverflow.com/q/50402058
tags question: http://stackoverflow.com/q/50498672
tags question: http://stackoverflow.com/q/50539695
tags question: http://stackoverflow.com/q/50518518
tags question: http://stackoverflow.com/q/50496637
tags question: http://stackoverflow.com/q/50405946
tags question: http://stackoverflow.com/q/50474051
tags question: http://stackoverflow.com/q/50498476
tags question: http://stackoverflow.com/q/50468202
tags question: http://stackoverflow.com/q/50468951
tags question: http://stackoverflow.com/q/50501141
tags question: http://stackoverflow.com/q/50535136
tags question: http://stackoverflow.com/q/50417434
tags question: http://stackoverflow.com/q/50474137
tags question: http://stackoverflow.com/q/50436992
tags question: http://stackoverflow.com/q/50429056
type: Tag
tags question: http://stackoverflow.com/q/50506088
tags question: http://stackoverflow.com/q/50456843
tags question: http://stackoverflow.com/q/50511109
tags question: http://stackoverflow.com/q/50470672
tags question: http://stackoverflow.com/q/50452344
tags question: http://stackoverflow.com/q/50437329
tags question: http://stackoverflow.com/q/50390674
tags question: http://stackoverflow.com/q/50437251
tags question: http://stackoverflow.com/q/50466609
tags question: http://stackoverflow.com/q/50488869
tags question: http://stackoverflow.com/q/50457863
tags question: http://stackoverflow.com/q/50420167
tags question: http://stackoverflow.com/q/50535911
tags question: http://stackoverflow.com/q/50428342
tags question: http://stackoverflow.com/q/50427087
tags question: http://stackoverflow.com/q/50517289
tags question: http://stackoverflow.com/q/50507228
tags question: http://stackoverflow.com/q/50471802
tags question: http://stackoverflow.com/q/50460965
tags question: http://stackoverflow.com/q/50399522
tags question: http://stackoverflow.com/q/50475580
tags question: http://stackoverflow.com/q/50510218
tag name: pip
tags question: http://stackoverflow.com/q/50408796
tags question: http://stackoverflow.com/q/50490990
tags question: http://stackoverflow.com/q/50403963
tags question: http://stackoverflow.com/q/50480903
tags question: http://stackoverflow.com/q/50475606
tags question: http://stackoverflow.com/q/50521033
tags question: http://stackoverflow.com/q/50400571
tags question: http://stackoverflow.com/q/50392373
tags question: http://stackoverflow.com/q/50405072
tags question: http://stackoverflow.com/q/50457676
tags question: http://stackoverflow.com/q/50462578
tags question: http://stackoverflow.com/q/50421295
tags question: http://stackoverflow.com/q/50404212
tags question: http://stackoverflow.com/q/50419764
tags question: http://stackoverflow.com/q/50408941
tags question: http://stackoverflow.com/q/50471010
tags question: http://stackoverflow.com/q/50401827
tags question: http://stackoverflow.com/q/50421287
tags question: http://stackoverflow.com/q/50431292
tags question: http://stackoverflow.com/q/50436171

http://stackoverflow.com/comment/87844676
type: QuestionComment
comment on: http://stackoverflow.com/q/50414210
score: 0
type: Comment
has text: Can you just compare `chunk1 == chunk2` directly? If there is a difference, do you care _where_ it is?

http://stackoverflow.com/comment/87869274
comment on: http://stackoverflow.com/q/50427058
score: 0
type: Comment
type: QuestionComment
has text: EPI has its own forum, authors respond there: http://talk.elementsofprogramminginterviews.com/

http://stackoverflow.com/a/50472733
score: 0
has comment: http://stackoverflow.com/comment/87982878
answers question: http://stackoverflow.com/q/50470991
has comment: http://stackoverflow.com/comment/87976122
has body: Here's my solution (using defaultdict): movie_sub_themes = { 'Epic': ['Ben Hur', 'Gone With the Wind', 'Lawrence of Arabia'], 'Spy': ['James Bond', 'Salt', 'Mission: Impossible'], 'Superhero': ['The Dark Knight Trilogy', 'Hancock, Superman'], 'Gangster': ['Gangs of New York', 'City of God', 'Reservoir Dogs'], 'Fairy Tale': ['Maleficent', 'Into the Woods', 'Jack the Giant Killer'], 'Romantic':['Casablanca', 'The English Patient', 'A Walk to Remember'], 'Epic Fantasy': ['Lord of the Rings', 'Chronicles of Narnia', 'Beowulf']} movie_themes = { 'Action': ['Epic', 'Spy', 'Superhero'], 'Crime' : ['Gangster'], 'Fantasy' : ['Fairy Tale', 'Epic Fantasy'], 'Romance' : ['Romantic']} from collections import defaultdict newdict = defaultdict(list) for theme, sub_themes_list in movie_themes.items(): for sub_theme in sub_themes_list: newdict[theme] += movie_sub_themes.get(sub_theme, []) dict(newdict) &gt;&gt; {'Action': ['Ben Hur', 'Gone With the Wind', 'Lawrence of Arabia', 'James Bond', 'Salt', 'Mission: Impossible', 'The Dark Knight Trilogy', 'Hancock, Superman'], 'Crime': ['Gangs of New York', 'City of God', 'Reservoir Dogs'], 'Fantasy': ['Maleficent', 'Into the Woods', 'Jack the Giant Killer', 'Lord of the Rings', 'Chronicles of Narnia', 'Beowulf'], 'Romance': ['Casablanca', 'The English Patient', 'A Walk to Remember']} timings: 4.84 µs vs 14.6 µs
type: Answer
has comment: http://stackoverflow.com/comment/87986016
has comment: http://stackoverflow.com/comment/87983118

http://stackoverflow.com/a/50539546
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50539516
has body: Use python -m pip instead of just pip3 to be sure you install packages for that python. Make sure your python launches the new version, or use whatever command does that plus the -m pip.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50409078
upvote count: 4
tagged with: jupyter-notebook
type: AnsweredQuestion
downvote count: 0
tagged with: pytest
answer count: 1
tagged with: jupyter
favorite count: 0
has answer: http://stackoverflow.com/a/50409536
type: Question
accepted answer: http://stackoverflow.com/a/50409536
has title: Running Jupyter notebook test in pytest. OSError
has body: I have a python test, which should run Jupyter notebook file and check it for errors. When I run it, it returns an error: OSError: [Errno 8] Exec format error: './file.ipynb' Does anyone know how to fix this? What I've found in similar questions doesn't seem to be my case. My code is below: import os import subprocess import tempfile import nbformat def _notebook_run(path): """Execute a notebook via nbconvert and collect output. :returns (parsed nb object, execution errors) """ dirname, __ = os.path.split(path) os.chdir(dirname) with tempfile.NamedTemporaryFile(suffix=".ipynb") as fout: args = [path, fout.name, "nbconvert", "--to", "notebook", "--execute", "--ExecutePreprocessor.timeout=60", "--output"] subprocess.check_call(args) fout.seek(0) nb = nbformat.read(fout, nbformat.current_nbformat) errors = [output for cell in nb.cells if "outputs" in cell for output in cell["outputs"]\ if output.output_type == "error"] return nb, errors def test_ipynb(): nb, errors = _notebook_run('./file.ipynb') assert errors == []
tagged with: python
score: 4

http://stackoverflow.com/a/53320214
type: Answer
score: 2
has body: Just use the following commands after installing the module twine with Python 3 twine upload dist/* username: Enter your https://pypi.org username Password: Enter your https://pypi.org password Note: before uploading the package, you must verify your email ID from your pypi account.
downvote count: 0
answers question: http://stackoverflow.com/q/50436171
upvote count: 2

http://stackoverflow.com/a/50421899
answers question: http://stackoverflow.com/q/50421723
type: AcceptedAnswer
type: Answer
has body: You can try below line of code :- item.get_attribute('innerHTML')
score: 0
accepted answer of: http://stackoverflow.com/q/50421723

http://stackoverflow.com/comment/88043417
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50511424
type: AnswerComment
has text: This worked for me. It installs the package directly in the `target` directory. Just to note that it does not build the 'lib', 'bin', etc., just the module directory and the `*.dist-info` directory. To use it, in my python I used: `export PYTHONPATH=/path/to/target:$PYTHONPATH`

http://stackoverflow.com/q/50472696
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50473161
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50473161
has title: Pandas read excel sheet with multiple header when first column is empty
has body: I have an excel sheet like this: I want to read it with pandas read_excel and I tried this: df = pd.read_excel("test.xlsx", header=[0,1]) but it throws me this error: ParserError: Passed header=[0,1] are too many rows for this multi_index of columns Any suggestions?
favorite count: 0
has comment: http://stackoverflow.com/comment/87959273
type: Question
has comment: http://stackoverflow.com/comment/87959972
has answer: http://stackoverflow.com/a/50473042
answer count: 2
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/50473042
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/q/50429720
downvote count: 3
has title: Subtract 1 from all values in dictionary
tagged with: python
tagged with: dictionary
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87874123
accepted answer: http://stackoverflow.com/a/50429733
has answer: http://stackoverflow.com/a/50429733
has comment: http://stackoverflow.com/comment/87874092
answer count: 1
upvote count: 6
type: Question
has body: I have a dictionary like the following: dict = {'hi':1, 'hi2':2, 'lskdjf':3} It continues like this for over a million values. I want to convert this into a dictionary with a value starting at 0 For example, this is the desired output: dict = {'hi':0, 'hi2':1, 'lskdjf':2} How can this be done efficiently?
has comment: http://stackoverflow.com/comment/87887299
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/50523745
has answer: http://stackoverflow.com/a/50524067
downvote count: 0
has comment: http://stackoverflow.com/comment/88059742
upvote count: 1
score: 1
has title: insert an indexed new row based on condition
favorite count: 0
accepted answer: http://stackoverflow.com/a/50523924
type: Question
has answer: http://stackoverflow.com/a/50523924
answer count: 2
tagged with: dataframe
tagged with: python
has body: I have a pandas df with named index and two columns as shown in the picture. df = pd.DataFrame(columns=['system_call','frequency','file_frequency']) df.set_index('system_call', inplace=True) I want to add a new row if a if-else condition is met. I tried df.loc[-1]=[words[0],words[1],1] but I think it might be for non-named indexes. expected output- system_call frequency file_frequency madvise 300 3 write 277 2 read 23 5 ioctl 45 4 getuid 78 2 epoll_pwait 12 1 futex 13 6 as can be seen the last row is added now
has comment: http://stackoverflow.com/comment/88059703
possible better answer: http://stackoverflow.com/a/50524067
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/a/50482370
has body: You are using pytest-ordering plugin (https://pytest-ordering.readthedocs.io/en/develop/). You're setting the order in which tests should be executed. It makes pytest execute tests from highest order (1) to lowest. Tests with the same order can be found in both classes, which is why pytest is jumping between classses.
has comment: http://stackoverflow.com/comment/87978563
has comment: http://stackoverflow.com/comment/88129307
type: Answer
has comment: http://stackoverflow.com/comment/87978960
score: 0
answers question: http://stackoverflow.com/q/50465491

http://stackoverflow.com/comment/87994713
score: 0
has text: Thank you for your answer. I did not wrote it here, but before plotting, I built a loop to check that for every iteration, for every i, (time[i][j+1] - time[i][j]) is always the same size, and len(time[i]) is the same size as len(freq) and len(ampFFT). Unfortunately, I have to use something like `plt.contourf` because I in my internship, this is how seismogram are made. I'm back, talked with my teacher. He used gnuplot to check that my data were correct (he gave me data he already worked on). The data I have are correct, so it is definitely how I plot my data that cause the problem.
type: Comment
comment on: http://stackoverflow.com/q/50488327
type: QuestionComment

http://stackoverflow.com/comment/88068778
type: AnswerComment
comment on: http://stackoverflow.com/a/50528541
has text: that was fast well done.
type: Comment
score: 0

http://stackoverflow.com/q/50533812
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/2682745
has answer: http://stackoverflow.com/a/50534521
downvote count: 3
tagged with: configuration-files
has title: what is the best way to define constant variables python 3
has body: I am writing a program in python which contains many constant variables. I would like to create a file that will hold all these variables like the .h file in C that contains many #define. I tried to use configparser however I didn't find it easy and fun to use. Do you know a better way?
has answer: http://stackoverflow.com/a/65706030
has comment: http://stackoverflow.com/comment/88080069
type: Question
has answer: http://stackoverflow.com/a/50534023
upvote count: 38
has answer: http://stackoverflow.com/a/54249676
score: 35
tagged with: python
type: UnansweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/57181433
answer count: 6
tagged with: constants
has answer: http://stackoverflow.com/a/50534870

http://stackoverflow.com/a/50534262
answers question: http://stackoverflow.com/q/50531131
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/88082353
downvote count: 0
has comment: http://stackoverflow.com/comment/88082314
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88085487
has body: Here's a way... The class variable Test._fields_ defines the attributes and their C types. The class attributes generated by assigning the fields contain information about the offset for that attribute, for example: &gt;&gt;&gt; Test.a &lt;Field type=c_long, ofs=0, size=4&gt; &gt;&gt;&gt; Test.b &lt;Field type=c_double, ofs=8, size=8&gt; &gt;&gt;&gt; Test.c &lt;Field type=c_char_Array_10, ofs=16, size=10&gt; For each type, the from_buffer() method builds a C type using the same data buffer as an existing type. An instance of the structure implements the buffer API required to access its data, so if you know the offset of a structure element's data, you can generate a ctypes type that references the same data, and create a pointer to it. from ctypes import * class Test(Structure): _fields_ = [('a',c_int), ('b',c_double), ('c',c_char * 10)] x = Test(1,2.5,b'abc') for field,ftype in Test._fields_: # Look up each attribute in the class, and get its offset. ofs = getattr(Test,field).offset # Create a pointer to the same field type using the same data. p = pointer(ftype.from_buffer(x,ofs)) print(p,p.contents) Output: &lt;__main__.LP_c_long object at 0x000001932DE0EEC8&gt; c_long(1) &lt;__main__.LP_c_double object at 0x000001932DE0ECC8&gt; c_double(2.5) &lt;__main__.LP_c_char_Array_10 object at 0x000001932DE0EDC8&gt; &lt;__main__.c_char_Array_10 object at 0x000001932DE0ECC8&gt;
has comment: http://stackoverflow.com/comment/88260502
accepted answer of: http://stackoverflow.com/q/50531131
has comment: http://stackoverflow.com/comment/88082383
upvote count: 6

http://stackoverflow.com/comment/87889423
has text: @wwii I'm sure we can do a lot more, but I just want to update the minimum so OP can build from that. As for using super().__del__ it's because I forsee that one might want del to delete the last added item.
comment on: http://stackoverflow.com/a/50437500
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50457730
accepted answer: http://stackoverflow.com/a/50458414
tagged with: loops
has body: This is my first question, so please be nice. I am leaning Python through an online course. I completed this assignment using Trinket, and it worked there. I submitted the code via the online grading system, and it passed there too. So, I already have been given 'credit' for this assignment. When I try it in Idle or PyCharm, the code does not work. It seems to be skipping over the for loop completely. I have looked at other answers on this type of question, but I cannot figure out how to apply them to my situation. Please help me understand why my for loop seems to be getting skipped. fname = input("Enter file name: ") fh = open(fname + ".txt") x = fh.read() count = 0 for line in fh: line = line.rstrip() word = line.split() if len(word) == 0: continue if word[0] != "From": continue else: print(word[1]) count += 1 print("There were", count, "lines in the file with From as the first word") In the .txt file being used, there are 27 email addresses that print out one by one, then the final line gives the total count. Like I said, it works in Trinket and the online code grader, but not in PyCharm or Idle. Thanks in advance.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87929011
answer count: 2
tagged with: for-loop
has title: Python For loop seems to be getting skipped over
tagged with: python
tagged with: skip
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50458354
possible better answer: http://stackoverflow.com/a/50458354
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50458414

http://stackoverflow.com/q/50431537
accepted answer: http://stackoverflow.com/a/50435133
has comment: http://stackoverflow.com/comment/87877663
has comment: http://stackoverflow.com/comment/87878341
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87878380
score: 2
has body: I have this test above. My problem is the after training my machine learning models the result is a little different each time. So, I would like to assert TRUE when are similar in my Flask-api. The ChangeToSurvive is a float, so sometimes is 29.2 and after training again change to 30.5 or other number. def test_by_name(self): post_data = { 'name': 'Andre' } resp = self.app.post('/survivals', data=json.dumps(post_data), content_type='application/json') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') content = json.loads(resp.get_data(as_text=True)) size = len(content['Passengers']) self.assertEqual(size, 2) self.maxDiff = None expected = { "Passengers": [ { "SibSp": 1, "Sex": "0", "PassengerId": 925, "Survived": 1, "Parch": 2, "Age": 1, "Name": "Johnston, Mrs. Andrew G (Elizabeth Lily\" Watson)\"", "ChangeToSurvive": 74.7, "Embarked": "0" }, { "SibSp": 0, "Sex": "1", "PassengerId": 1096, "Survived": 0, "Parch": 0, "Age": 1, "Name": "Andrew, Mr. Frank Thomas", "ChangeToSurvive": 29.2, "Embarked": "0" } ] } self.assertEqual(content, expected) # each train in a model the ChangeToSurvive can a little diferrent
tagged with: python-unittest
answer count: 1
tagged with: unit-testing
has title: Can I compare 2 floats in unittest for similarity but not equality?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87878334
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87927536
tagged with: python
has comment: http://stackoverflow.com/comment/88110094
has answer: http://stackoverflow.com/a/50435133

http://stackoverflow.com/comment/87924551
score: 0
type: Comment
type: AnswerComment
has text: I am trying to run your code but I am getting errors-FileNotFoundError: File b'00002d74a9faa53f5199c910b652ef09d3a7f6bd42b693755a233635c3ffb0f4.apk.sys_names.txt' does not exist
comment on: http://stackoverflow.com/a/50455321

http://stackoverflow.com/comment/87975427
type: AnswerComment
has text: In a symbolic solution I kind of like this pattern, but in a numeric solution I think it is problematic to rely on a interpolated time series - rounding errors all I see.
type: Comment
comment on: http://stackoverflow.com/a/50472227
score: 0

django-sites
type: Tag
tag name: django-sites
tags question: http://stackoverflow.com/q/50493467

http://stackoverflow.com/a/50535927
score: 0
type: Answer
has body: If I understand correctly, I believe you can leverage groupby here. It's hard to test without seeing example data, but I think this should do it: data1_anio.groupby('Nombre Partida')['Nombre Capitulo'].unique() Example: data1_anio = pd.DataFrame({'Nombre Partida':['a', 'a', 'a', 'b', 'b', 'b'], 'Nombre Capitulo':['random1', 'random1', 'random2', 'random3', 'random4', 'random4']}) &gt;&gt;&gt; data1_anio Nombre Partida Nombre Capitulo 0 a random1 1 a random1 2 a random2 3 b random3 4 b random4 5 b random4 Running the groupby returns a Series of all unique values of Nombre Capitulo for each Nombre Partida: &gt;&gt;&gt; data1_anio.groupby('Nombre Partida')['Nombre Capitulo'].unique() Nombre Partida a [random1, random2] b [random3, random4]
accepted answer of: http://stackoverflow.com/q/50535801
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88084089
answers question: http://stackoverflow.com/q/50535801

http://stackoverflow.com/q/50454789
score: 0
answer count: 1
has body: I'm trying to download .pdfs using links from a xlsx file with urlretrieve(), one column has the links and the other has the names that the downloaded file should have. The issue is that my code seems to just overwrite the same file over and over again as it downloads each item of the list. from urllib.request import urlretrieve from urllib.error import URLError, HTTPError import os import xlrd workbook = xlrd.open_workbook('file.xlsx',on_demand=True) sheet = workbook.sheet_by_name('Sheet1') listofvalues = sheet.col_values(21, 1) listofnames = sheet.col_values(2, 1) for name in listofnames: for value in listofvalues: try: results = 'C:\\results' full_file_name = os.path.join(results, str(name + ".pdf")) urlretrieve(value, full_file_name) print(str(value) + ' DOWNLOADED') except (HTTPError, ValueError, URLError) as e: print("------------------------------------") print(e) print(value) print("-----------------------------------") continue I think it has something to do with nested loops, but I can't find a solution.
has title: Python 3 downloading pdfs with urlretrive () and nested loops
has comment: http://stackoverflow.com/comment/87923210
type: Question
has comment: http://stackoverflow.com/comment/87922994
type: UnansweredQuestion
tagged with: nested-loops
tagged with: python
has answer: http://stackoverflow.com/a/50454889
tagged with: urlretrieve
linked to: http://stackoverflow.com/q/1663807
tagged with: xlrd

http://stackoverflow.com/comment/88053098
type: QuestionComment
score: 0
has text: @eyllanesc I update a example code for it. However, the cursor only allow move in graph2, but I want to move and get data in both graph1 and graph2.
comment on: http://stackoverflow.com/q/50512391
type: Comment

http://stackoverflow.com/comment/88035783
score: 0
type: Comment
has text: `all_names = [man.name for man in men] + [woman.name for woman in women]` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/50511707

scikit-image
tags question: http://stackoverflow.com/q/50485458
tags question: http://stackoverflow.com/q/50491707
tags question: http://stackoverflow.com/q/50529731
tags question: http://stackoverflow.com/q/50430493
tags question: http://stackoverflow.com/q/50476084
tags question: http://stackoverflow.com/q/50446418
tags question: http://stackoverflow.com/q/50445459
type: Tag
tag name: scikit-image
tags question: http://stackoverflow.com/q/50491716
tags question: http://stackoverflow.com/q/50444141

http://stackoverflow.com/q/50496336
has answer: http://stackoverflow.com/a/64741532
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python
has body: So I am using scipy.ndimage.filters.convolve function. I understood how it works for 2D matrices from the documentation. But when I apply this to 3D matrices it is giving results which I cannot interpret. For example: In[80]: a = np.array([[[1,2,3], [1,2,3], [1,2,3]],[[1,2,3], [1,2,3], [1,2,3]],[[1,2,3], [1,2,3], [1,2,3]]]) In[81]: b = np.array([[[1,2,3], [1,2,3], [1,2,3]],[[1,2,3], [1,2,3], [1,2,3]],[[1,2,3], [1,2,3], [1,2,3]]]) In[82]: scimg.convolve(a, b, output = None, mode = 'constant') Out[83]: array([[[ 16, 40, 48], [ 24, 60, 72], [ 16, 40, 48]], [[ 24, 60, 72], [ 36, 90, 108], [ 24, 60, 72]], [[ 16, 40, 48], [ 24, 60, 72], [ 16, 40, 48]]]) I understood convolution from this post. So according to me the (0, 0, 0) index should be 8. Similarly (0, 0, 1) should be 20. Where am I going wrong in the understanding? EDIT: I would be grateful even if someone tells me how the module works for n-D (or channel) images with n-D filters.
score: 2
has title: Understanding scipy.ndimage.filters.convolve function
tagged with: scipy
favorite count: 0
type: Question

http://stackoverflow.com/q/50430204
tagged with: numpy
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has body: I wish to compute the number of so-called distinctions from a given binary matrix G. Assuming the rows of G correspond to some individuals and its columns to some test cases, distinctions made by a test are defined as the number of pairs of individuals it differentiates. I've come up with a very simple implementation: distinctions = np.zeros(G.shape[1]) for p in itertools.combinations(np.arange(G.shape[0]), 2): distinctions += G[p[0], :] != G[p[1], :] But it's to slow for my needs. I would be very grateful if you could help me speed up this code.
favorite count: 0
accepted answer: http://stackoverflow.com/a/50430300
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50430300
score: 1
has title: Computing distinctions: speeding up an operation on all combinations of rows in a matrix
type: Question

http://stackoverflow.com/a/50455678
has body: The solution is probably simply to remove /usr/local/opt/python2/libexec/bin from your PATH environment variable. To do this you have to edit your ~/.bash_profile and remove the occurence of this directory.
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50439358
type: Answer
has comment: http://stackoverflow.com/comment/87924916
answers question: http://stackoverflow.com/q/50439358
has comment: http://stackoverflow.com/comment/87924949
downvote count: 0
has comment: http://stackoverflow.com/comment/87924882

http://stackoverflow.com/a/50508487
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50508473
has comment: http://stackoverflow.com/comment/110047451
accepted answer of: http://stackoverflow.com/q/50508473
type: Answer
has comment: http://stackoverflow.com/comment/110046892
has body: You need define one column after groupby, if use size each column working, else here get DataFrame - counts for each column: a = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'customer_id':list('aaabbc')}) print (a) A B C D E customer_id 0 a 4 7 1 5 a 1 b 5 8 3 3 a 2 c 4 9 5 6 a 3 d 5 4 7 9 b 4 e 5 2 1 2 b 5 f 4 3 0 4 c a['size'] = a.groupby(['customer_id'])['customer_id'].transform(np.size) #a['size'] = a.groupby(['customer_id'])['A'].transform(np.size) print (a) A B C D E customer_id size 0 a 4 7 1 5 a 3 1 b 5 8 3 3 a 3 2 c 4 9 5 6 a 3 3 d 5 4 7 9 b 2 4 e 5 2 1 2 b 2 5 f 4 3 0 4 c 1 #no define column get all columns counts print (a.groupby(['customer_id']).transform(np.size)) A B C D E size 0 3 3 3 3 3 3 1 3 3 3 3 3 3 2 3 3 3 3 3 3 3 2 2 2 2 2 2 4 2 2 2 2 2 2 5 1 1 1 1 1 1
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87943985
type: QuestionComment
comment on: http://stackoverflow.com/q/50465399
score: 0
has text: df.groupBy('A').pivot('B') should follow by some aggregation.
type: Comment

http://stackoverflow.com/a/50456109
has body: It's not a selenium oriented solution (all through) but it works. You can give it a try. from selenium import webdriver import requests from bs4 import BeautifulSoup url = 'https://www.macys.com/shop/featured/women-handbags' def find_page_items(driver,link): driver.get(link) item_link = [item.find_element_by_tag_name('a').get_attribute('href') for item in driver.find_elements_by_css_selector('li.productThumbnailItem')] for newlink in item_link: res = requests.get(newlink,headers={"User-Agent":"Mozilla/5.0"}) soup = BeautifulSoup(res.text,"lxml") name = soup.select_one("h1[itemprop='name']").text.strip() print(name) if __name__ == '__main__': driver = webdriver.Chrome() try: find_page_items(driver,url) finally: driver.quit() Output: Mercer Medium Bonded-Leather Crossbody Mercer Large Tote Nolita Medium Satchel Voyager Medium Multifunction Top-Zip Tote Mercer Medium Crossbody Kelsey Large Crossbody Medium Mercer Gallery Mercer Large Center Tote Signature Raven Large Tote However, If you stick to selenium then you need to create new instance of it everytime you browse a new url or may be a better option is to clear the cache.
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50454896
downvote count: 1
answers question: http://stackoverflow.com/q/50454896
score: 0
type: Answer

http://stackoverflow.com/comment/87890042
type: AnswerComment
comment on: http://stackoverflow.com/a/50438035
score: 0
type: Comment
has text: Hi, Thanks for the help. I replace the 'data' with data+" ". Now the output, I am getting is - hip2 p3 p10 p11 p12. There is no space between hi and p2.

http://stackoverflow.com/comment/88051227
type: QuestionComment
score: 5
has text: I don't think so and even if you could I highly suspect that it would significantly improve the performance as `float`s are already very efficient. Are you sure the precision is the bottleneck? Try converting all the numbers to `int`s and do a benchmark first. If that doesn't help, reducing the precision can't either.
comment on: http://stackoverflow.com/q/50519298
type: Comment

http://stackoverflow.com/comment/88004509
score: 0
type: Comment
type: QuestionComment
has text: Added an answer. Thanks for the incentive.
comment on: http://stackoverflow.com/q/50488084

http://stackoverflow.com/comment/87823097
score: 0
type: Comment
type: QuestionComment
has text: Thanks @SudhirBastakoti. It works perfectly.
comment on: http://stackoverflow.com/q/50403649

http://stackoverflow.com/comment/88055332
type: QuestionComment
comment on: http://stackoverflow.com/q/50517934
score: 0
has text: @D.J.Duff I just edited my question and will appreciate it if you can help
type: Comment

http://stackoverflow.com/q/50424308
has comment: http://stackoverflow.com/comment/87863525
has title: Pythont 3.6.5 SyntaxError
favorite count: 0
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/2535760
accepted answer: http://stackoverflow.com/a/50424354
linked to: http://stackoverflow.com/q/2535760
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50424398
has comment: http://stackoverflow.com/comment/87863490
has body: I have just started writing in python, and the indentation is taking the best of me. I have this code: import json if __name__ == '__main__': is_json('test') def is_json(str): try: json.loads(str) except ValueError, e: return False return True Which throws: File "so.py", line 9 except ValueError, e: ^ SyntaxError: invalid syntax I am using only tabs.
type: AnsweredQuestion
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/50424354
upvote count: 1
possible better answer: http://stackoverflow.com/a/50424398

http://stackoverflow.com/a/70734639
answers question: http://stackoverflow.com/q/50486083
score: 0
has body: Just create a new shutdown thread in the background: import threading import time class MyThread(threading.Thread): def __init__(self): super().__init__() self._quit_flag = False def run(self): while not self._quit_flag: print("Thread is alive!") time.sleep(0.500) print("shutting down.") def request_quit(self): self._quit_flag = True mt = MyThread() mt.start() # Shutdown thread threading.Thread( target=lambda: threading.main_thread().join() or mt.request_quit() ).start()
type: Answer

http://stackoverflow.com/q/50529590
has comment: http://stackoverflow.com/comment/88070929
has answer: http://stackoverflow.com/a/50529622
type: Question
tagged with: python-3.x
tagged with: strip
has title: How to strip a string with a "." properly in Python?
has comment: http://stackoverflow.com/comment/88070884
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/50293407
tagged with: python
has comment: http://stackoverflow.com/comment/88071017
linked to: http://stackoverflow.com/q/35904584
tagged with: substring
has comment: http://stackoverflow.com/comment/88070837
score: 0
duplicate of: http://stackoverflow.com/q/35904584
answer count: 2
has body: I would like to strip the ending from a string, as in following: da = "abc.com" print(da.strip(".com")) My expected outcome is abc. However, ab is returned instead. Why is that and how to solve it?
has answer: http://stackoverflow.com/a/50529663

http://stackoverflow.com/comment/87968331
has text: You are also [breaking PEP-8](https://www.python.org/dev/peps/pep-0008/#package-and-module-names) by giving your packages and modules names ike `BalancedTree` and `DictsOrganizations` :\ Anyway, you can set up the `PYTHONPATH` environment variable before running your script.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50476134
type: Comment

http://stackoverflow.com/a/59545206
has comment: http://stackoverflow.com/comment/105300750
type: Answer
has body: #here is my answer . you can do it using simple recursion # count digits recursively def reverse_digits(n): # base case if n == 0: pass #recursive case else: print(n%10,end='') return reverse_digits(n//10) # reverse 123 reverse_digits(123) ````````````````````````````````````````````````````
upvote count: 0
score: -2
downvote count: 2
answers question: http://stackoverflow.com/q/50474344
has comment: http://stackoverflow.com/comment/105300673

http://stackoverflow.com/a/50504571
type: Answer
answers question: http://stackoverflow.com/q/50504278
score: 11
upvote count: 11
has body: If you really just want the first 44 characters, you don't need a regex: you can simply use the Python string-slice operator: first_44_characters = s[:44] However, a regex is much more powerful, and could account for the fact that the length of the section you're interested in might change. For example, if the time is 10AM instead of 4AM the length of that part might change (or might not, maybe that's what the space padding is for?). In that case, you can capture it with a regex like this: &gt;&gt;&gt; re.match(r'\s+(High.*?)m', s).group(1) 'High 4:55AM 1.3' \s matches any whitespace character, + matches one or more of the preceding element, the parentheses define a group starting with High and containing a minimal-length sequence of any character, and the m after the parentheses says the group ends right before a lowercase m character. If you want, you can also use the regex to extract the individual parts of the sequence: &gt;&gt;&gt; re.match(r'\s+(High)\s+(\d+\:\d+)(AM|PM)\s+(\d+\.\d+)m', s).groups() ('High', '4:55', 'AM', '1.3')
downvote count: 0

http://stackoverflow.com/comment/87951176
score: 1
type: Comment
type: QuestionComment
has text: what is `an_other_list` and what is your expected output?
comment on: http://stackoverflow.com/q/50468926

http://stackoverflow.com/comment/88066458
type: QuestionComment
has text: Yes but I only pass the 1D-matrix to matplotlib too and it generates a 2D-matrix (image). It reshapes it for me in any way.
comment on: http://stackoverflow.com/q/50526033
score: 0
type: Comment

http://stackoverflow.com/q/50386860
tagged with: php
has comment: http://stackoverflow.com/comment/87790012
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
has body: I am trying to make my python code run on website. In my python code, I need to input one image and one video url, like this: import cv2 img = "1.jpg" cap = cv2.VideoCapture("https://www.youtube.com/watch?v=-OUhbw-XsTg") So I write a HTML code so that I can input image and video url: &lt;html&gt; &lt;body&gt; &lt;form action="upload1.php" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="file" id="file" /&gt;&lt;br/&gt;&lt;br/&gt; Video URLs:&lt;input type="url" name="url" id="myURL"&gt;&lt;br/&gt;&lt;br/&gt; &lt;button name = "Analyze" type="submit"&gt; Analyze &lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; I want that when I input an image and url, after clicking Analyze it can return the image and url path to python and run the code. I only know how to call python script but don't know how to get and return value to python. &lt;?php if (isset($_POST['Analyze'])){ exec("python code.py",$output); var_dump($output); } ?&gt; Can anyone help my how to get the path from HTML and return to python with PHP? Thank you.
has title: Calling python script from html/php
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87789319
has comment: http://stackoverflow.com/comment/87840739
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/comment/88049778
comment on: http://stackoverflow.com/q/50510090
type: Comment
type: QuestionComment
score: 0
has text: You could try using quadratics to calculate position movement. Just cut it off when you reach your point.

http://stackoverflow.com/q/50419664
score: 1
has answer: http://stackoverflow.com/a/50420039
answer count: 1
downvote count: 0
upvote count: 1
tagged with: queue
favorite count: 0
type: Question
tagged with: binary-search-tree
has comment: http://stackoverflow.com/comment/87866429
tagged with: python
has title: Breadth First Search on a Binary Search Tree in Python
has comment: http://stackoverflow.com/comment/87855343
has body: I've been working on building different data types and applying various sorting algorithms to them. I'm currently working on a breadth-first search on a binary search tree. My code is pretty much the same as what you'll find everywhere online, yet it consistently prints my values twice, and I'm now mind boggled. Any guidance would very much appreciated. # Remove (dequeue) function for Queue class def remove(self, current=''): if current == '': current = self.tail # start looping/recurring to find the front of the queue if current.next: if current.next.next: current = current.next return self.remove(current) # side note - I'm doubting the usefulness of recursion here else: n = current.next.value current.next = None self.size -= 1 return n elif current == self.tail: if current.value: n = current.value current = None self.size -= 1 # print("Queue is now empty - returning final number") return n else: return "Queue is already empty." else: raise ValueError("mind boggling error...") #never raised # Add (enqueue) function for my queue: def add(self,value): n = Node(value) # create the new node we're adding n.next = self.tail # point the new node to link to the old tail self.tail = n # now have the tail point to the new node self.size += 1 # Breadth First Search function for the Binary Search Tree def bfs(self): """ This is currently VERY inefficient from a memory standpoint, as it adds a subtree for EACH node...right? or is it just the names/addresses of the objects being stored in each node, and each node is still only in the same memory location? """ queue = Queue() queue.add(self) while queue.size &gt; 0: current = queue.remove() print(current.value) if current.left_child: queue.add(current.left_child) if current.right_child: queue.add(current.right_child) # how I typically test: bst = BinarySearchTree(50) for i in range(1,10): bst.insert_node(i*4) bst.bfs() Sample Output: 25 25 4 28 4 28 8 32 8 32 12 36 12 36 16 16 20 20 24 Seeing as it prints the root node twice on i…
has comment: http://stackoverflow.com/comment/87854984
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50420039
tagged with: breadth-first-search

http://stackoverflow.com/comment/87949961
has text: @glibdud yes, order may change though.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50468010
type: Comment

http://stackoverflow.com/a/50406757
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50406182
upvote count: 1
has body: A less performant but succinct solution is possible using dictionary and list comprehensions: lst = [[100, 100, 50, 40, 40, 20, 10, 5], [100, 100, 50, 40, 40, 25, 20, 10]] dicts = [{v: k for k, v in dict(enumerate(reversed(sorted(set(i))), 1)).items()}\ for i in lst] res = [[(n, dicts[i][n]) for n in j] for i, j in enumerate(lst)] For performance, I recommend you use a 3rd party library such as numpy or pandas: import pandas as pd data = pd.DataFrame(lst).T ranks = data.rank(method='dense', axis=0, ascending=False).astype(int) res = [list(zip(data[i], ranks[i])) for i in range(len(data.columns))] [[(100, 1), (100, 1), (50, 2), (40, 3), (40, 3), (20, 4), (10, 5), (5, 6)], [(100, 1), (100, 1), (50, 2), (40, 3), (40, 3), (25, 4), (20, 5), (10, 6)]]

http://stackoverflow.com/comment/87803114
comment on: http://stackoverflow.com/a/50389589
score: 0
has text: Great. Thank you. The updated answer works (though a minor change, d2 and d3 r blobs, not files). I wish the documentation is much more elaborate on these non implemented methods. Can you also kindly look into another similar issue [here](https://stackoverflow.com/questions/50390985/wand-creates-empty-frame-and-irregular-frame-rate) in which wand creates empty frame and irregular frame delays?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87839606
score: 0
comment on: http://stackoverflow.com/a/50411997
type: Comment
has text: @muniategui: It can't be done. A line of code is not an object that can be referred to.
type: AnswerComment

http://stackoverflow.com/q/50536250
tagged with: python
upvote count: 14
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pie-chart
accepted answer: http://stackoverflow.com/a/62068566
possible better answer: http://stackoverflow.com/a/75228105
has answer: http://stackoverflow.com/a/75228105
has body: I saw that matplotlib's pyplot.scatter() has an 'alpha' parameter that can be used to set the transparency of points. The pyplot.pie() doesn't have a similar parameter however. How can I set the transparency of certain wedges?
favorite count: 0
type: Question
score: 14
has title: Matplotlib pie chart wedge transparency?
has comment: http://stackoverflow.com/comment/89475213
has answer: http://stackoverflow.com/a/62068566
tagged with: matplotlib

http://stackoverflow.com/comment/87842971
type: QuestionComment
score: 0
has text: Also take a look at [help/on-topic] for the guidelines about what is considered "on topic" on this site.
type: Comment
comment on: http://stackoverflow.com/q/50413381

http://stackoverflow.com/q/50477793
answer count: 1
tagged with: flask-sqlalchemy
has answer: http://stackoverflow.com/a/50478887
type: AnsweredQuestion
score: 0
has body: I'm trying to use an outerjoin() from SQLAlchemy to join three tables, however when I try the query I think should be working it throws the following error: 1054, "Unknown column 'articles.id' in 'on clause'" I'm sure it could be done in an easier way by using the ORM references, but at the moment I'm trying to figure out how to make this work without that. Below are the tables and query. I also import and_ from SQLAlchemy class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True, nullable=False) class Articles(db.Model): id = db.Column(db.Integer, primary_key=True) article_name = db.Column(db.String(100), unique=True, nullable=False) class ReadArticles(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) article_id = db.Column(db.Integer, db.ForeignKey('articles.id'), nullable=False) and the query: r = db.session.query(Articles, User, ReadArticles).outerjoin(ReadArticles, and_(User.id == ReadArticles.user_id, Articles.id == ReadArticles.article_id)).all() Has anyone run into this or could point me in the direction of how to see what I'm doing wrong? Thanks!
tagged with: python
accepted answer: http://stackoverflow.com/a/50478887
tagged with: sqlalchemy
type: Question
has title: Flask SQLAlchemy outerjoin with three tables

http://stackoverflow.com/comment/88017365
type: Comment
comment on: http://stackoverflow.com/a/50501589
type: AnswerComment
score: 0
has text: hey . or other way, my output from function return is like [u'/var/www/cacti/rra/r1f-ktrx06zhry_traffic_in_14644.rrd'] [u'/var/www/cacti/rra/r1f-tsax02zhry_traffic_in_14954.rrd', u'/var/www/cacti/rra/r1f-tsax04zhry_traffic_in_14966.rrd'] [] [u'/var/www/cacti/rra/r1f-kyrx01zhry_traffic_in_14717.rrd'] . I want to output like {u'GDR': u'/var/www/cacti/rra/r1f-gdrx06zhry_traffic_in_14632.rrd', u'TSA': u'/var/www/cacti/rra/r1f-tsax02zhry_traffic_in_14954.rrd', u'/var/www/cacti/rra/r1f-tsax04zhry_traffic_in_14966.rrd'}` How can I do?

http://stackoverflow.com/comment/87813892
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50398982
has text: Your DB is avoiding duplicates as is, but I guess you mean that you'd like to eliminate duplicates from your input based on some criteria. That's not the session's job, but your application's. You could for example wrap each merge in a savepoint and flush, ignoring integrity errors caused by dupes, or just remove dupes before even passing the data to the session.

beautifulsoup
tags question: http://stackoverflow.com/q/50505169
tags question: http://stackoverflow.com/q/50430168
tags question: http://stackoverflow.com/q/50486567
tags question: http://stackoverflow.com/q/50400301
tags question: http://stackoverflow.com/q/50429282
tags question: http://stackoverflow.com/q/50437085
type: Tag
tags question: http://stackoverflow.com/q/50488151
tags question: http://stackoverflow.com/q/50419642
tags question: http://stackoverflow.com/q/50482770
tags question: http://stackoverflow.com/q/50415676
tags question: http://stackoverflow.com/q/50539837
tags question: http://stackoverflow.com/q/50533363
tags question: http://stackoverflow.com/q/50530775
tags question: http://stackoverflow.com/q/50445243
tags question: http://stackoverflow.com/q/50430887
tags question: http://stackoverflow.com/q/50520408
tags question: http://stackoverflow.com/q/50490944
tags question: http://stackoverflow.com/q/50442391
tags question: http://stackoverflow.com/q/50443463
tags question: http://stackoverflow.com/q/50514217
tags question: http://stackoverflow.com/q/50397805
tags question: http://stackoverflow.com/q/50397474
tags question: http://stackoverflow.com/q/50501778
tags question: http://stackoverflow.com/q/50480530
tags question: http://stackoverflow.com/q/50448198
tags question: http://stackoverflow.com/q/50482796
tags question: http://stackoverflow.com/q/50418432
tags question: http://stackoverflow.com/q/50471178
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/50450129
tags question: http://stackoverflow.com/q/50457545
tags question: http://stackoverflow.com/q/50493039
tags question: http://stackoverflow.com/q/50401977
tags question: http://stackoverflow.com/q/50503319
tags question: http://stackoverflow.com/q/50514919
tags question: http://stackoverflow.com/q/50459154
tags question: http://stackoverflow.com/q/50500210
tags question: http://stackoverflow.com/q/50497863
tags question: http://stackoverflow.com/q/50449457
tags question: http://stackoverflow.com/q/50521383
tags question: http://stackoverflow.com/q/50513674
tags question: http://stackoverflow.com/q/50530444
tags question: http://stackoverflow.com/q/50430780
tags question: http://stackoverflow.com/q/50527666
tags question: http://stackoverflow.com/q/50459203
tags question: http://stackoverflow.com/q/50396393
tags question: http://stackoverflow.com/q/50535976
tags question: http://stackoverflow.com/q/50487815
tags question: http://stackoverflow.com/q/50429780
tags question: http://stackoverflow.com/q/50534249
tags question: http://stackoverflow.com/q/50479820
tags question: http://stackoverflow.com/q/50413693
tags question: http://stackoverflow.com/q/50448447
tags question: http://stackoverflow.com/q/50513324
tags question: http://stackoverflow.com/q/50401789
tags question: http://stackoverflow.com/q/50527882
tags question: http://stackoverflow.com/q/50477634
tags question: http://stackoverflow.com/q/50482810
tags question: http://stackoverflow.com/q/50431651
tags question: http://stackoverflow.com/q/50492428
tags question: http://stackoverflow.com/q/50527790
tags question: http://stackoverflow.com/q/50496549
tags question: http://stackoverflow.com/q/50457043
tags question: http://stackoverflow.com/q/50449774
tags question: http://stackoverflow.com/q/50422711
tags question: http://stackoverflow.com/q/50422110
tags question: http://stackoverflow.com/q/50469087
tags question: http://stackoverflow.com/q/50490445
tags question: http://stackoverflow.com/q/50393811
tags question: http://stackoverflow.com/q/50482110
tags question: http://stackoverflow.com/q/50425704
tags question: http://stackoverflow.com/q/50427033
tags question: http://stackoverflow.com/q/50508759
tags question: http://stackoverflow.com/q/50441904
tags question: http://stackoverflow.com/q/50440209
tags question: http://stackoverflow.com/q/50538968
tags question: http://stackoverflow.com/q/50472985
tags question: http://stackoverflow.com/q/50423262
tags question: http://stackoverflow.com/q/50493703

http://stackoverflow.com/comment/87915474
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50450223
has text: I'm not sure how that would help. The session cookie may well have expired, but there is still no way for the server to know that.
score: 0

http://stackoverflow.com/comment/88024401
type: QuestionComment
comment on: http://stackoverflow.com/q/50506200
score: 0
type: Comment
has text: "with cmd, but not working either" meaning?

http://stackoverflow.com/q/50456832
has comment: http://stackoverflow.com/comment/87927434
tagged with: python
has comment: http://stackoverflow.com/comment/87927187
has comment: http://stackoverflow.com/comment/87927409
linked to: http://stackoverflow.com/q/49910762
has title: converting datetime for entire column
answer count: 1
linked to: http://stackoverflow.com/q/26763344
has answer: http://stackoverflow.com/a/50456970
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -2
has body: [Still unanswered] Hello I recently identified a solution to convert a time format into hours and minutes. from datetime import datetime x = datetime.strptime('2017-01-01T19:33:28+0000', '%Y-%m-%dT%H:%M:%S%z')\ .strftime('%H:%M') However I can only do this for one value in a column. How do you apply it to all values in an entire column? Here are the column values I want to convert: image Edit 1: Here is my failed attempt The error says "TypeError: strptime() argument 1 must be str, not Series" Edit 2: Here is my 2nd attempt This error says SyntaxError: unexpected character after line continuation character and also NameError: name 'pandas' is not defined (even though I'm using pandas which is confusing?) Thanks!
downvote count: 2
tagged with: datetime

http://stackoverflow.com/comment/88078853
type: QuestionComment
type: Comment
has text: I'm going to guess that `sympy.plot` is using MatPlotLib to do the actual work here.
score: 1
comment on: http://stackoverflow.com/q/50533422

http://stackoverflow.com/comment/88080743
score: 3
type: Comment
type: QuestionComment
has text: There is an issue open for my [problem](https://github.com/pandas-dev/pandas/issues/21158) . Apparently handling of nested None changed.
comment on: http://stackoverflow.com/q/50534269

http://stackoverflow.com/q/50422648
upvote count: 1
has comment: http://stackoverflow.com/comment/87860076
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50422687
has title: How to make a function inside another function quit both functions at once?
has comment: http://stackoverflow.com/comment/87860261
tagged with: python
accepted answer: http://stackoverflow.com/a/50422687
type: AnsweredQuestion
tagged with: python-2.7
has body: I'm making a program that asks the users some questions and uses different functions to react to what the user gives as input. I need to make it such that if the user ever types "Cancel", it will not only end the function they are currently in but even the function that called the prior function. def func1(x): func2(x+5) print 5 def func2(x): func3(x+5) print 5 def func3(x): print x return func1(20) print 10 # 30 # 5 # 5 # 10 So currently this will print 30, exit func3, print 5, exit func2, print 5, exit func1. I need a way for it to just stop after func3 prints 30. Any ideas? So the desired output would be. #30 #10 Edit: This is an extremely simplified version, they wouldn't type cancel in this specific code. It would be in a raw_input.
score: 1
tagged with: function
has comment: http://stackoverflow.com/comment/87860088
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50492239
has comment: http://stackoverflow.com/comment/88018157
has body: In case you want to use the matplotlib.dates locators and formatters on a plot generated by pandas, you need to plot in compatibility mode, df.plot(..., x_compat=True)
accepted answer of: http://stackoverflow.com/q/50492185
type: Answer
answers question: http://stackoverflow.com/q/50492185
upvote count: 3
downvote count: 0
type: AcceptedAnswer
score: 3

http://stackoverflow.com/comment/87971235
type: AnswerComment
score: 0
has text: Thanks everyone for your reply. The data is in string, rather than int, hence the plus concatenate the values
type: Comment
comment on: http://stackoverflow.com/a/50445823

http://stackoverflow.com/q/50497841
duplicate of: http://stackoverflow.com/q/3876229
has comment: http://stackoverflow.com/comment/88008679
has body: I got a bit of a noob question. I want to add the floats from the 3 entries, so the total float is shown in the label. My solution is this and I can't get it to work, what I'm doing wrong? Thx in advance.. from tkinter import * class App(Frame): def __init__(self, root=None): Frame.__init__(self, root) self.var = DoubleVar() self.var.set(float(0.00)) self.var2 = DoubleVar() self.var2.set(float(0.00)) self.var3 = DoubleVar() self.var3.set(float(0.00)) self.entry1 = Entry(root, textvariable=self.var) self.entry1.grid(row=2, column=1) self.entry2 = Entry(root, textvariable=self.var2) self.entry2.grid(row=3, column=1) self.entry3 = Entry(root, textvariable=self.var3) self.entry3.grid(row=4, column=1) self.total = DoubleVar() self.total.set(float(0.00)) self.totalSum = Label(root, textvariable=self.total, relief='sunken') self.totalSum.grid(row=5, column=1) def totalSum(self): self.total.set(self.var.get() + self.var2.get() + self.var3.get()) root = Tk() app = App(root) root.title("help") root.mainloop()
type: UnansweredQuestion
tagged with: python
tagged with: label
tagged with: tkinter
score: 1
has comment: http://stackoverflow.com/comment/88008692
has comment: http://stackoverflow.com/comment/88008900
linked to: http://stackoverflow.com/q/3876229
has title: Add and get the sum off floats from entry in label
has answer: http://stackoverflow.com/a/50497977
downvote count: 0
answer count: 1
tagged with: tkinter-entry
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/50424455
has comment: http://stackoverflow.com/comment/121188497
upvote count: 1
has body: I fix this by resetting my database. python manager.py flush remove all files under migrations directory python manager.py makemigrations python manager.py migrate The price is high when dropping a whole database. A better way is to check migration files and rollback to a proper state and do the migratxxx actions from that point.
answers question: http://stackoverflow.com/q/50423659
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/comment/88123168
comment on: http://stackoverflow.com/q/50537777
type: QuestionComment
type: Comment
score: 0
has text: @SalihF.Canpolat The questions and answers in SO should not only serve you but the entire community so if you delete many things no one will understand or be useful, I recommend reading [ask] and [answer], consider SO as a book of questions and answers, it would not be annoying to answer the same question many times, that is why we want quality questions and answers that help the community and save us time.

http://stackoverflow.com/q/50418903
tagged with: python
linked to: http://stackoverflow.com/q/588004
score: 4
upvote count: 4
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50419018
has title: Change calculator only works if one type of coin needed
answer count: 2
has answer: http://stackoverflow.com/a/50419018
downvote count: 0
possible better answer: http://stackoverflow.com/a/50419000
favorite count: 0
has answer: http://stackoverflow.com/a/50419000
type: Question
has body: I'm currently trying to learn python and have been going through beginner projects on /r/learnpython. My idea for the change calculator project was to create a dictionary with keys 'quarter', 'dime', 'nickel', and 'penny', each with values initialized to 0. My code, shown below, appears to only work when the change I input only requires one type of coin, i.e. 0.75 --> 3 quarters, 0.1 --> 1 dime, etc. change_map = { 'quarter' : 0, 'dime' : 0, 'nickel' : 0, 'penny' : 0 } def calculator(change): while change &gt; 0: if change &gt;= 0.25: change -= 0.25 change_map['quarter'] += 1 elif change &lt; 0.25 and change &gt;= 0.10: change -= 0.10 change_map['dime'] += 1 elif change &lt; 0.10 and change &gt;= 0.05: change -= 0.05 change_map['nickel'] += 1 elif change &lt; 0.05 and change &gt;= 0.01: change -= 0.01 change_map['penny'] += 1 print "You need the following: " print change_map change = raw_input("Please enter amount of change: ") change = float(change) calculator(change)

http://stackoverflow.com/comment/87890987
score: 0
has text: no i'm asking that if there is a response it opens a browser an the human behind does the captcha solver. you have no idea of what i'm doing. and a lot of requests form ask for captcha
comment on: http://stackoverflow.com/q/50438288
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87854115
type: Comment
type: QuestionComment
has text: I did, the linked answer is here https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe
comment on: http://stackoverflow.com/q/50419159
score: 0

http://stackoverflow.com/a/50453629
has body: You just have to change directory into your project folder and then run scrapyd command with “nohup” and that will make sure that scrapyd doesn’t get closed after you disconnect with server cd /path/to/your/project &amp;&amp; nohup scrapyd &gt;&amp; /dev/null &amp;
has comment: http://stackoverflow.com/comment/87920692
has comment: http://stackoverflow.com/comment/87920747
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50409623
has comment: http://stackoverflow.com/comment/87956320
has comment: http://stackoverflow.com/comment/87957298
has comment: http://stackoverflow.com/comment/87920724
answers question: http://stackoverflow.com/q/50409623
has comment: http://stackoverflow.com/comment/87957178
has comment: http://stackoverflow.com/comment/87956229
type: Answer

http://stackoverflow.com/comment/88043269
type: Comment
comment on: http://stackoverflow.com/q/50515323
score: 0
type: QuestionComment
has text: This stackoverflow maybe helpful: telling you that u cannot lock a s3 actually: https://stackoverflow.com/questions/3431418/locking-with-s3

http://stackoverflow.com/a/50516780
has body: One way may be to use apply with if and else condition as below: df['Age'] = df.apply(lambda row: age_df.loc[row.Title, row.Pclass] if pd.isnull(row.Age) else row.Age, axis=1)
accepted answer of: http://stackoverflow.com/q/50516390
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50516390
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50472039
has body: group the strings 2 by 2 in the inner list comprehension, use an outer list comprehension to iterate on the sublists. Add a little trickery to join by 3 if reaches the end of the list so you don't have orphans. And make sure you're iterating up to an even range so the orphan isn't repeated (finetuned with trial and error :)) lst = [['Start', 'двигаться', 'конгресс', 'сша'], ['Start', 'двигаться', 'сторона', 'в'], ['Start', 'двигаться', 'сторона', 'признание', 'суверенитет', 'израильский'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'на'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'оккупировать'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'Голанский'], ['Start', 'двигаться', 'сторона', 'признание', 'и']] result = [[" ".join(subl[i:i+(2 if i &lt; len(subl)-3 else 3)]) for i in range(0,(len(subl)//2)*2,2)] for subl in lst] result: [['Start двигаться', 'конгресс сша'], ['Start двигаться', 'сторона в'], ['Start двигаться', 'сторона признание', 'суверенитет израильский'], ['Start двигаться', 'сторона признание', 'высот на'], ['Start двигаться', 'сторона признание', 'высот оккупировать'], ['Start двигаться', 'сторона признание', 'высот Голанский'], ['Start двигаться', 'сторона признание и']]
answers question: http://stackoverflow.com/q/50471870
upvote count: 1
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/57094398
type: Answer
score: 3
has body: As provided in the comment use this answer for more information. TL;DR: setup( ... install_requires=[ 'repo @ https://github.com/user/archive/master.zip#egg=repo-1.0.0'], ... ) DEPRECATED: According to the docs, you need to specify dependency_links in your setup arguments: DEPRECATED
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/101149900
answers question: http://stackoverflow.com/q/50521033

http://stackoverflow.com/comment/87928281
has text: So... say I had another array of readings like: nextReadings = [0.04, 0.09, 0.21, 0.01, 0.06, 0.08, 0.13, 0.01, 0.01, 0.02, 0.04, 0.06] that still indexed in order with allFeatures. Is there an easy way to find the values from each array that were largest for a given allFeatures element? (In the example above, the readings for 845 and 853 would change to 0.13 and 0.04, respectively). Also, in the real world, allFeatures and allReadings each have 2.4 million elements, and aoiFeatures has 67,000 elements. I have 17 other arrays of readings like allReadings to compare
score: 0
comment on: http://stackoverflow.com/a/50456802
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50426104
tagged with: django
tagged with: python
type: UnansweredQuestion
has body: I have an .xml file with country and continent data, which looks like this South America sa Andorra Andorra la Vella ad 84000 468 6 The first object is to a continent, the second one is to a country. I'm trying to build models for them so that I can use manage.py loaddata command to parse through the .xml, but I'm having trouble with the ManyToOneRel -part. My models.py is from django.db import models class Continent(models.Model): name = models.CharField(max_length=60, default='') code = models.CharField(max_length=3, default='') class Country(models.Model): name = models.CharField(max_length=60, default='') code = models.CharField(max_length=3, default='') capital = models.CharField(max_length=60, default='') population = models.PositiveIntegerField(default=0) area = models.PositiveIntegerField(default=0) , but I'm not sure what I need to add to Country in order to be able to read the 6 line. I tried fiddling around with foreignkey and manytoonerel, but got neither of them working. Latest attempt example: continent = models.ForeignKey(Continent) and I get the error "Country has no field named 'continent'", so it leads me to believe that I'm establishing the model field in a wrong way, but I'm not sure how I need to establish it. Edit: class Continent(models.Model): name = models.CharField(max_length=60, default='') code = models.CharField(max_length=3, default='') countries = models.ManyToManyField( 'Country', through='Country', ) class Country(models.Model): name = models.CharField(max_length=60, default='') code = models.CharField(max_length=3, default='') capital = models.CharField(max_length=60, default='') population = models.PositiveIntegerField(default=0) area = models.PositiveIntegerField(default=0) group = models.ForeignKey(Continent, on_delete=models.CASCADE) gives me the error ERRORS: countrydata.Country: (fields.E336) The model is used as an intermediate model by 'countrydata.Continent.countries', but it does not have a foreign key to 'Continent' or 'C…
score: 0
has comment: http://stackoverflow.com/comment/87867221
has comment: http://stackoverflow.com/comment/87867242
answer count: 1
has answer: http://stackoverflow.com/a/50432489
type: Question
has title: Using loaddata to add a ManyToOneRel into a django models class

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

http://stackoverflow.com/comment/87910021
type: Comment
has text: this is also comparatively a small web app . but few users uses simultaneousely. so didnt look for a better platform than flask. I would definitely look at one of these above.
comment on: http://stackoverflow.com/q/50407729
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87810859
has text: They are not in the question. Also there are some indentation errors. Could you edit and correct the question?
comment on: http://stackoverflow.com/q/50396873
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50416848
type: Question
has title: Python operation on either an array or dataframe that requires updating every row
tagged with: numpy
has comment: http://stackoverflow.com/comment/87851414
has comment: http://stackoverflow.com/comment/87849436
upvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87851780
tagged with: pandas
has body: I am trying to learn python/pandas and have no idea how to approach this Given: df = P1 P2 P3 P4 P5 Date 2017-01-20 808.23 135.60 107.64 53.20 57.66 2017-01-27 835.77 138.30 109.29 53.18 56.13 2017-02-03 810.07 137.92 110.28 52.34 55.05 2017-02-10 827.48 139.87 109.27 56.23 56.22 2017-02-17 845.06 142.91 110.02 56.74 57.35 2017-02-24 845.23 145.89 110.29 57.83 57.48 2017-03-03 849.85 147.77 111.20 56.68 57.09 2017-03-10 852.20 146.88 110.95 56.45 54.54 2017-03-17 852.31 149.57 111.67 57.79 55.79 2017-03-24 845.60 147.77 112.17 56.37 56.81 Lets say I had an updating variable initially set at x = 1000. After an operation is done on the first row where I used x as a part of an equation, let's say I got final result of first row = 1005. Then I want x = 1005, and do the said equation with x on the second row where the final result of the second row = 1010. Then I would want to update x = 1010 and do the same thing throughout the dataframe. I imagine it would have to do something with a for loop, and I was thinking it might be easier/better to do this after converting said dataframe into a numpy array but I was hoping to get some tips on iterating over the dataset and updating a variable based on the result of the row before it. Any tips would be great! Thank you so much.
answer count: 1
score: -1
has comment: http://stackoverflow.com/comment/87851844
has answer: http://stackoverflow.com/a/50416949
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50512644
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88042240
linked to: http://stackoverflow.com/q/50507417
has comment: http://stackoverflow.com/comment/88039645
score: 0
tagged with: google-sheets-api
type: Question
has title: Google Sheets API quickstart tutorial for python produces 403 error for valid OAuth2 credentials
answer count: 2
has answer: http://stackoverflow.com/a/50515856
linked to: http://stackoverflow.com/q/50501811
type: UnansweredQuestion
tagged with: python
has body: I am following the Google Sheets API quickstart tutorial for Python (2.7) for a project I'm working on and I have hit a wall that I cannot figure out how to get past. I followed the tutorial very closely and set up my OAuth2 credentials as they laid out, put the file in my quickstart.py script's directory, and renamed it client_secret.json. However, running the script from terminal brings me to an Error: 403 page, with the error message "Error: restricted_client" The treminal output from executing the script: nik@debian:~/Documents/Misc/Py$ python quickstart.py /usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access credentials.json: No such file or directory warnings.warn(_MISSING_FILE_MESSAGE.format(filename)) Your browser has been opened to visit: https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets.readonly&amp;redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&amp;response_type=code&amp;client_id=(I probably shouldn't give this out)&amp;access_type=offline If your browser is on a different machine then exit and re-run this application with the command-line parameter --noauth_local_webserver I've tried touch'ing a credentials.json file in the script's directory, and that does stop the warning message from appearing, but it still doesn't populate the credentials file with anything. It was my understanding that the script was supposed to create a credentials file for me, given the scope in the script and that this would need to be updated if the scope changed. This is the missing piece in what has been a fruitful project so far, and I'm really at a loss. What am I missing here? EDIT: Commenters have pointed out that OAuth2 is broken for multiple people. In the meantime, while thats being sorted out, generate an API Key in your developer console and use this bit of code to auth your service module service = build('sheets', 'v4', developerKey=yourAPIKey)
has answer: http://stackoverflow.com/a/50513698

http://stackoverflow.com/a/51994353
answers question: http://stackoverflow.com/q/50398584
type: Answer
score: 0
has body: This is due to a change that came about following a sympy refactor (apparently). Polynomial matrices need to be created using the PolyMatrix type. The following code will work on both 1.0 and 1.1.1: try: from sympy.polys.polymatrix import PolyMatrix as sym_matrix except ImportError: from sympy.matrices import Matrix as sym_matrix And then create your matrix using sym_matrix.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50398584

http://stackoverflow.com/q/50458794
type: Question
has title: How to disable function calls for some time
tagged with: python
has answer: http://stackoverflow.com/a/50458932
accepted answer: http://stackoverflow.com/a/50458932
type: AnsweredQuestion
score: 0
has body: I'm relativity new to Python, having only worked with it about a month or so, and I wanted to make a text rpg on Python 2.7.2. So for some commands, such as mining or fishing for example,I wanted to have some time after they used the command where they can't use the command again for a specific period of time. while True: command = raw_input("Say something") if command = "mine": print "You found 2 Rocks! etc." I want to make it so that you can only use the command every 1 minute, for example. If the time wasn't finished yet, it'll print print "Please wait a moment(%s seconds remaining)" % timeleft
answer count: 2
has answer: http://stackoverflow.com/a/50458972
possible better answer: http://stackoverflow.com/a/50458972

http://stackoverflow.com/q/50506610
has comment: http://stackoverflow.com/comment/88025392
has comment: http://stackoverflow.com/comment/88027683
tagged with: pandas
has title: pandas add() two dataframes with parcially overlapping indexes?
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88027786
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88025304
has answer: http://stackoverflow.com/a/50506693
has comment: http://stackoverflow.com/comment/88027761
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/88026943
downvote count: 0
upvote count: 1
tagged with: python
tagged with: merge
has comment: http://stackoverflow.com/comment/88028145
has comment: http://stackoverflow.com/comment/88027800
has comment: http://stackoverflow.com/comment/88027068
has comment: http://stackoverflow.com/comment/88027656
has body: Python/Pandas So I have n many dataframes consisting of only 3 columns as follows: 02-10-2017 09:00:00, 0, 2.23, -2.24 02-10-2017 09:01:00, 0, 2.23, -2.23 ... with the datetime being the index (of the format DatetimeIndex). Now every dataframe has m many indexes/rows and every dataframe starts a specific amount of time after the other. For example dataframe 1 is from 02-10-2017 09:00 until 02-10-2017 15:00 and dataframe 2 from 02-10-2017 10:00 until 02-10-2017 16:00. I want to add these such that I have one dataframe from 09:00 until 16:00 with added values. The closest function I found is pandas.add(), however, when I add two dataframes then the non-coinciding indexes get value NaN. So in my example that would mean NaN values from 09:00 until 10:00 and from 15:00 until 16:00. Suggestions?

http://stackoverflow.com/a/68578276
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50432152
has body: The list of authors where the book is not the empty dict. Author.objects.filter(~Q(book__exact={}))

http://stackoverflow.com/comment/87953478
has text: @AyushGiri could you let me know where you got the data from? So I can try things...
comment on: http://stackoverflow.com/a/50437222
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50476501
tagged with: anaconda
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87966562
tagged with: python
tagged with: conda
type: AnsweredQuestion
score: 1
tagged with: plotly
has body: I managed to install on my conda the plotly package with: conda install -c plotly plotly And the matplotlib with: conda create --name mpl33 python=3.3 matplotlib ipython-notebook But I cant create one env with both of them inside because the plotly uses python 2.7 and matplotlib python 3.3 Thanks for the help!
answer count: 1
downvote count: 0
upvote count: 1
has title: Creating an Enviroment for plotly and matplotlib in python 2.7
accepted answer: http://stackoverflow.com/a/50476828
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50476828

http://stackoverflow.com/comment/88068921
type: Comment
comment on: http://stackoverflow.com/a/50526429
type: AnswerComment
score: 0
has text: Please explain what you did differently. Code-only answers are discouraged on this site, as it requires the reader to compare your code to the original line-by-line and character-by-character.

http://stackoverflow.com/q/50450051
has comment: http://stackoverflow.com/comment/87913203
has answer: http://stackoverflow.com/a/50460224
has answer: http://stackoverflow.com/a/50450119
tagged with: python
type: Question
has title: Python 3.5 Threading: Is this implemented correctly?
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87913273
tagged with: multithreading
has body: I am trying to investigate threading by looking for primes in lists of random values. I expected to find that using threading made this faster but the times for threaded and un-threaded are the same. Is this because I have implemented this incorrectly? How can I demonstrate the benefits of threading using an example like this? import time import threading from math import sqrt from random import randint def findPrimes(aList): for testValue in aList: isPrime = True for i in range(2,int(sqrt(testValue)+1)): if testValue % i == 0: isPrime = False if isPrime: #print(testValue) pass testValues1 = [] testValues2 = [] for i in range(1000): testValues1.append(randint(10,100)) testValues2.append(randint(10,100)) t = time.process_time() findPrimes(testValues1) findPrimes(testValues2) print('The long way',time.process_time() - t) # runs in 0.006 to 0.007 t = time.process_time() thread1 = threading.Thread(target=findPrimes(testValues1)) thread2 = threading.Thread(target=findPrimes(testValues2)) thread1.start() thread2.start() print('The threading way',time.process_time() - t) # also runs in 0.006 to 0.007
linked to: http://stackoverflow.com/q/44521931
linked to: http://stackoverflow.com/q/2846653
has comment: http://stackoverflow.com/comment/87913248
linked to: http://stackoverflow.com/q/18114285
score: 0

http://stackoverflow.com/q/50452467
has title: Grouping by datetime by hour in dataframe
tagged with: group-by
downvote count: 0
upvote count: 1
tagged with: python
has body: I try to use this: casa_consumo_h = casa_consumo['date'].groupby(lambda x: x.hour).mean() I get the following error: AttributeError: 'int' object has no attribute 'hour' My date is of this type: date 55535 non-null datetime64[ns] How can I group by hour my dataframe? date Ac f I Pf R V 0 2017-08-01 00:00:00 37 59.97 1.49 0.4 10 22 1 2017-08-01 00:00:01 302 59.97 1.51 0.8 10 22 2 2017-08-01 00:00:03 3077 59.97 1.49 0.8 10 22 3 2017-08-01 00:00:05 300 59.97 1.50 0.8 15 22
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50452716
has comment: http://stackoverflow.com/comment/87918153
has answer: http://stackoverflow.com/a/50452716
score: 1
answer count: 1
favorite count: 0
type: Question

dbus
type: Tag
tags question: http://stackoverflow.com/q/50484969
tag name: dbus

scrapy
tags question: http://stackoverflow.com/q/50437741
tags question: http://stackoverflow.com/q/50483836
tags question: http://stackoverflow.com/q/50504818
tags question: http://stackoverflow.com/q/50430547
tags question: http://stackoverflow.com/q/50499816
tags question: http://stackoverflow.com/q/50416841
tags question: http://stackoverflow.com/q/50451165
tags question: http://stackoverflow.com/q/50470658
tags question: http://stackoverflow.com/q/50438903
tags question: http://stackoverflow.com/q/50409623
tags question: http://stackoverflow.com/q/50469764
tags question: http://stackoverflow.com/q/50482770
tags question: http://stackoverflow.com/q/50453479
tag name: scrapy
tags question: http://stackoverflow.com/q/50437162
tags question: http://stackoverflow.com/q/50471676
tags question: http://stackoverflow.com/q/50431637
tags question: http://stackoverflow.com/q/50498246
tags question: http://stackoverflow.com/q/50425247
tags question: http://stackoverflow.com/q/50489366
tags question: http://stackoverflow.com/q/50467085
tags question: http://stackoverflow.com/q/50467770
tags question: http://stackoverflow.com/q/50541429
tags question: http://stackoverflow.com/q/50433349
tags question: http://stackoverflow.com/q/50430237
tags question: http://stackoverflow.com/q/50460905
tags question: http://stackoverflow.com/q/50521609
tags question: http://stackoverflow.com/q/50469221
type: Tag
tags question: http://stackoverflow.com/q/50487815
tags question: http://stackoverflow.com/q/50429780
tags question: http://stackoverflow.com/q/50422477
tags question: http://stackoverflow.com/q/50505573
tags question: http://stackoverflow.com/q/50417842
tags question: http://stackoverflow.com/q/50492234
tags question: http://stackoverflow.com/q/50493828
tags question: http://stackoverflow.com/q/50452405
tags question: http://stackoverflow.com/q/50541457
tags question: http://stackoverflow.com/q/50493548

http://stackoverflow.com/comment/87792753
type: Comment
score: 0
type: AnswerComment
has text: I tried this before, it didn't work, i also tried thousands=","
comment on: http://stackoverflow.com/a/50388564

http://stackoverflow.com/comment/87896065
type: QuestionComment
comment on: http://stackoverflow.com/q/50440686
has text: This last comment is the version of the webdriver
type: Comment
score: 0

http://stackoverflow.com/a/50401698
has comment: http://stackoverflow.com/comment/132208146
downvote count: 0
has body: I think you have an old version of python. try upgrading to the latest version of python. F-string literals have been added to python since python 3.6. you can check more about it here
has comment: http://stackoverflow.com/comment/132224738
accepted answer of: http://stackoverflow.com/q/50401632
answers question: http://stackoverflow.com/q/50401632
type: AcceptedAnswer
type: Answer
upvote count: 74
score: 74

http://stackoverflow.com/comment/87942604
has text: @BhoomiPatel i try already create ACL but same error. How to assign user rights.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50459664
type: Comment

http://stackoverflow.com/comment/88069630
comment on: http://stackoverflow.com/q/50528947
type: Comment
type: QuestionComment
score: 0
has text: @DeepSpace https://stackoverflow.com/questions/19158339/why-are-global-variables-evil

teradata
type: Tag
tags question: http://stackoverflow.com/q/50458188
tag name: teradata

http://stackoverflow.com/q/50403041
tagged with: python
has comment: http://stackoverflow.com/comment/87821789
has title: Replacing indices in a list without repeat index positions
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: list
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50403066
accepted answer: http://stackoverflow.com/a/50403066
favorite count: 0
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/87821782
has body: So I have a list of 10 0's. [0,0,0,0,0,0,0,0,0,0]. I have to insert 4 random 1's into the list. [0,1,0,0,0,1,0,1,1,0]. How do I insert the 1's with no repeat indices. def init_positions(n_cells, n_veh): lst = [0] * n_cells for i in range(n_veh): newL = random.randint(0, n_cells) lst[newL] = 1 return lst position = init_positions(10,4) print(position)

http://stackoverflow.com/q/50526997
type: Question
has body: I am updating some rows in a sqlite database using the sqlite3 package in the following Python code. sql = """ UPDATE measurements SET value=? WHERE value IS NULL AND counter IS NOT NULL; """ with self.conn: cur = self.conn.execute(sql, [value]) cur.rowcount This runs inside a docker container. Basing its image on Python 3.5 I get the expected row count. As soon as the image is based on Python 3.6 the update is performed but rowcount is always -1. Does anybody have an idea?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88067504
answer count: 0
has title: Python sqlite3 rowcount of update depends on Python version
has comment: http://stackoverflow.com/comment/88364679
has comment: http://stackoverflow.com/comment/88090392
has comment: http://stackoverflow.com/comment/88066646
tagged with: sqlite
score: 0

http://stackoverflow.com/comment/87895281
type: QuestionComment
comment on: http://stackoverflow.com/q/50440487
score: 0
has text: It's tough to confirm my answer for this is good since you don't share the csv that must be processed. Can you share the csv or at least the header visible in the question?
type: Comment

http://stackoverflow.com/q/50540370
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50541441
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50540898
possible better answer: http://stackoverflow.com/a/50549390
has comment: http://stackoverflow.com/comment/88093117
has answer: http://stackoverflow.com/a/50541441
has comment: http://stackoverflow.com/comment/88093106
has answer: http://stackoverflow.com/a/50542047
has body: I have JSON file which contains followingly encoded strings: "sender_name": "Horn\u00c3\u00adkov\u00c3\u00a1", I am trying to parse this file using the json module. However I am not able to decode this string correctly. What I get after decoding the JSON using .load() method is 'HornÃ\xadkovÃ¡'. The string should be correctly decoded as 'Horníková' instead. I read the JSON specification and I understasnd that after \u there should be 4 hexadecimal numbers specifing Unicode number of character. But it seems that in this JSON file UTF-8 encoded bytes are stored as \u-sequences. What type of encoding is this and how to correctly parse it in Python 3? Is this type JSON file even valid JSON file according to the specification?
has answer: http://stackoverflow.com/a/50549390
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: utf-8
linked to: http://stackoverflow.com/q/53242216
answer count: 4
score: 12
tagged with: python-3.x
has title: Decode UTF-8 encoding in JSON string
tagged with: encoding
upvote count: 12
downvote count: 0

http://stackoverflow.com/comment/92150455
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50527125
type: AnswerComment
has text: thanks for pointing out that possibility of providing a dict as filter_fields. Works like a charm!

http://stackoverflow.com/comment/87895055
score: 0
comment on: http://stackoverflow.com/q/50436121
type: Comment
has text: Nothing wrong with your code, the url returns 404 with a browser (and propably `curl`) too. You can get the content with `r.text`
type: QuestionComment

http://stackoverflow.com/comment/88078805
type: QuestionComment
has text: The code you have posted will always throw an error the first time through the i,j loops, because i and j will always be 1 larger than the max bound for those dimensions.
comment on: http://stackoverflow.com/q/50532385
score: 0
type: Comment

http://stackoverflow.com/comment/87922864
score: 0
has text: @ScottBoston This crashes while extracting the multi index columns. Line 0 and Line 1 are identical anyway, so I'm not sure why that would be the problem
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50454630

http://stackoverflow.com/q/50410799
type: Question
has title: Load graph and then use it to build tflite?
tagged with: tensorflow-lite
tagged with: python
has body: I am very new to tensorflow,I am trying converting my .pb(proto buffer) file to lite version. But i am facing some issues. import time,sys,warnings,glob,random,cv2,base64,json,csv,os import numpy as np import tensorflow as tf from collections import OrderedDict def load_graph(frozen_graph_filename): with tf.gfile.GFile(frozen_graph_filename, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def( graph_def, input_map=None, return_elements=None, name="prefix", op_dict=None, producer_op_list=None ) return graph This function loads a graph for me and now i want to convert this graph to tflite for which i used the following script. CD_graph = load_graph("CD_Check_k.pb") CD_input = CD_graph.get_tensor_by_name('prefix/input_node:0') CD_output = CD_graph.get_tensor_by_name('prefix/output_node:0') x_single = tf.placeholder(tf.float32, [1, 256 , 256, 3], name="input_node") with tf.Session() as sess: tflite_model = tf.contrib.lite.toco_convert(CD_graph, input_tensors=[x_single ], output_tensors=[CD_output]) with open('./mnist.tflite', "wb") as f: f.write(tflite_model) Error msg: 'Graph' object has no attribute 'SerializeToString'
tagged with: deep-learning
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51093030
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/87887157
type: Comment
score: 0
type: AnswerComment
has text: as you know i'm a beginner so if you can give me the example with the code so i'll thankful to you
comment on: http://stackoverflow.com/a/50433944

http://stackoverflow.com/comment/87935662
type: AnswerComment
comment on: http://stackoverflow.com/a/50439853
type: Comment
has text: did you try with the dataset i linked? Its still not working for me :(
score: 0

http://stackoverflow.com/comment/88083723
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50535832
has text: Can you get key status as the first thing program does while opening? If shift is held, it should detect as the first job, if not well... rest of the code works.

http://stackoverflow.com/comment/88094297
has text: Ok, the edit has thoroughly confused me. What are we looking at here? Is this a single dataframe?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50541508

http://stackoverflow.com/comment/88057329
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/50522534
has text: Asyncio will not help you because it runs single-threaded, but you could try [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html).

http://stackoverflow.com/a/50452840
has comment: http://stackoverflow.com/comment/87919116
type: Answer
has comment: http://stackoverflow.com/comment/87918964
accepted answer of: http://stackoverflow.com/q/50452635
score: 2
has comment: http://stackoverflow.com/comment/87919443
upvote count: 2
answers question: http://stackoverflow.com/q/50452635
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87918919
has comment: http://stackoverflow.com/comment/87919642
has body: You can use: In [98]: d = data.set_index('iteration') In [99]: np.sum(d.loc[i].values for i in d.index.drop_duplicates().values) Out[99]: array([[ 68, 7, 30, 9, 3], [ 7, 8, 30, 8, 3], [ 8, 10, 38, 18, 10], [ 4, 3, 38, 36, 32], [ 28, 20, 92, 95, 235]]) Or alternatively, use groupby(): np.sum(e[1].iloc[:, :-1].values for e in data.groupby('iteration')) array([[ 68, 7, 30, 9, 3], [ 7, 8, 30, 8, 3], [ 8, 10, 38, 18, 10], [ 4, 3, 38, 36, 32], [ 28, 20, 92, 95, 235]])
has comment: http://stackoverflow.com/comment/87919311

http://stackoverflow.com/q/50386566
upvote count: 1
has body: I am using read_html() pandas function to read a html table and then finally convert it to excel using ExcelWriter and to_excel. But as my table has a index column so this is what I get when I use read_html(): data = pd.read_html(url) Output: [ Unnamed: 0 1 3 0 0 3 5 1 1 5 6 2 2 7 2 3 3 4 4 4 4 5 6 5 5 6 7 6 6 4 8 7 7 7 7 8 8 8 8 9 9 9 9] And when I do writer = pd.ExcelWriter('example1.xlsx') data[0].to_excel(writer,sheet_name= 'Sheet1', index=False) I get an index unnamed column in my excel files. I have also used index = False and drop function but it give an error as Can't drop None.
favorite count: 0
has comment: http://stackoverflow.com/comment/87789133
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: python
type: Question
has title: Pandas Drop first column Error
tagged with: pandas.excelwriter
accepted answer: http://stackoverflow.com/a/50386786
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50386786

http://stackoverflow.com/comment/87958815
type: AnswerComment
comment on: http://stackoverflow.com/a/50472474
has text: it's doesn't work also after I added. I don't know why.
score: 0
type: Comment

http://stackoverflow.com/comment/87973345
comment on: http://stackoverflow.com/a/50479976
has text: Note that this is only work if you decrypt only one letter. It wouldn't work if you decrypt a word.
score: 3
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50463580
has comment: http://stackoverflow.com/comment/87940872
favorite count: 0
type: Question
has body: This is my Dictionary: {{'count': 5, 'leftCount': 5, 'length': '5', 'submittedTime': 1526815239}, {'count': 10, 'leftCount': 10, 'length': '5', 'submittedTime': 1526814198}, {'count': 5, 'leftCount': 5, 'length': '25', 'submittedTime': 1526815326}, {'count': 8, 'leftCount': 8, 'length': '25', 'submittedTime': 1526815326}, {'count': 5, 'leftCount': 5, 'length': '30', 'submittedTime': 1526815239}} I want to sort it by the value of the key="submittedTime". I have no idea how to make it work. I tried lambda but I think I'm doing something wrong because the result was exactly the same.
upvote count: 0
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/87940280
score: -4
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50463757
accepted answer: http://stackoverflow.com/a/50463757
has answer: http://stackoverflow.com/a/50463783
possible better answer: http://stackoverflow.com/a/50463783
has title: Sorting nested dictionary in python by value

http://stackoverflow.com/a/53197104
answers question: http://stackoverflow.com/q/50429056
type: Answer
has body: What solved for me was using : pip install --only-binary :all: mysqlclient
score: 0

python-3.6
tags question: http://stackoverflow.com/q/50464140
tags question: http://stackoverflow.com/q/50461657
tags question: http://stackoverflow.com/q/50432207
tags question: http://stackoverflow.com/q/50530679
tags question: http://stackoverflow.com/q/50408941
tags question: http://stackoverflow.com/q/50502485
tags question: http://stackoverflow.com/q/50484558
tags question: http://stackoverflow.com/q/50446707
tags question: http://stackoverflow.com/q/50524246
tags question: http://stackoverflow.com/q/50533072
tags question: http://stackoverflow.com/q/50534911
tags question: http://stackoverflow.com/q/50503934
tags question: http://stackoverflow.com/q/50519102
tags question: http://stackoverflow.com/q/50539516
tags question: http://stackoverflow.com/q/50400621
tags question: http://stackoverflow.com/q/50438334
tags question: http://stackoverflow.com/q/50405946
tags question: http://stackoverflow.com/q/50503913
tags question: http://stackoverflow.com/q/50402861
tags question: http://stackoverflow.com/q/50530959
tags question: http://stackoverflow.com/q/50405177
tags question: http://stackoverflow.com/q/50432450
tags question: http://stackoverflow.com/q/50439564
tags question: http://stackoverflow.com/q/50522699
tags question: http://stackoverflow.com/q/50454455
tags question: http://stackoverflow.com/q/50486381
type: Tag
tags question: http://stackoverflow.com/q/50461887
tag name: python-3.6
tags question: http://stackoverflow.com/q/50428661
tags question: http://stackoverflow.com/q/50500023
tags question: http://stackoverflow.com/q/50426277
tags question: http://stackoverflow.com/q/50409212
tags question: http://stackoverflow.com/q/50397705
tags question: http://stackoverflow.com/q/50394250
tags question: http://stackoverflow.com/q/50420917
tags question: http://stackoverflow.com/q/50431700
tags question: http://stackoverflow.com/q/50510385
tags question: http://stackoverflow.com/q/50526408
tags question: http://stackoverflow.com/q/50445870
tags question: http://stackoverflow.com/q/50530645
tags question: http://stackoverflow.com/q/50540475
tags question: http://stackoverflow.com/q/50471654
tags question: http://stackoverflow.com/q/50455784
tags question: http://stackoverflow.com/q/50531181
tags question: http://stackoverflow.com/q/50517757
tags question: http://stackoverflow.com/q/50443248
tags question: http://stackoverflow.com/q/50537407

http://stackoverflow.com/comment/87980823
type: Comment
type: QuestionComment
has text: What is the problem? Any advise on the errors you are facing?
comment on: http://stackoverflow.com/q/50483587
score: 1

http://stackoverflow.com/q/50398654
tagged with: anaconda
has body: I install Anaconda for jupyter notebooks and suddenly all my python environments are a mess. If I run which python I get a path to a python install within Anaconda. Does anyone know how to install Anaconda without it taking over Python? There is a confusing section in the conda wiki that says you can install Anaconda even if you have Python running, but it then explains that the Python path would be changed, which is I think what one would not want to happen. In my case, I use pyenv and it's not clear how Anaconda would work with that kind of a setup.
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50399054
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87813067
upvote count: 5
has title: Anaconda took over my Python path
has comment: http://stackoverflow.com/comment/87813134
tagged with: python
score: 4

http://stackoverflow.com/comment/87871211
type: Comment
has text: @Ivanovitch, changed the name, still same error
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50428173

http://stackoverflow.com/comment/88296967
score: 0
has text: @SuperShoot Great ;))!
type: QuestionComment
comment on: http://stackoverflow.com/q/50443781
type: Comment

http://stackoverflow.com/comment/87860246
type: Comment
has text: Have you tried using the [find_all](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class) method? You can retrieve the value using the [dictionary-style format](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes). Please post your attempt in the OP so we can see the specific problem you have
type: QuestionComment
comment on: http://stackoverflow.com/q/50422711
score: 0

http://stackoverflow.com/q/50393744
has body: I am new to mininet. I created a topology in mininet and want to write a python code which can help me to send 100 TCP packets from one host to another. any idea please?
type: Question
tagged with: mininet
has comment: http://stackoverflow.com/comment/87803150
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50527690
score: 0
tagged with: pox
answer count: 1
has title: How to send TCP packets from one host to another in mininet by using a python script?

http://stackoverflow.com/a/50521915
type: Answer
has comment: http://stackoverflow.com/comment/88090725
has comment: http://stackoverflow.com/comment/88090892
score: 1
answers question: http://stackoverflow.com/q/50521865
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50521865
upvote count: 1
has body: Try to filter Quiz_Question by quiz and learnerquestionanswer__learner fields: quiz = all_quizes[0] learner= User.objects.get(id=1) Quiz_Question.objects.filter(quiz=quiz, learnerquestionanswer__learner=learner)

http://stackoverflow.com/q/50434710
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/53919184
has title: Keras An operation has None for gradient when train_on_batch
tagged with: python
tagged with: artificial-intelligence
type: AnsweredQuestion
tagged with: deep-learning
upvote count: 3
has body: Google Colab to reproduce the error None_for_gradient.ipynb I need a custom loss function where the value is calculated according to the model inputs, these inputs are not the default values (y_true, y_pred). The predict method works for the generated architecture, but when I try to use the train_on_batch, the following error appears. ValueError: An operation has None for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval. My custom function of loss (below) was based on this example image_ocr.py#L475, in the Colab link has another example based on this solution Custom loss function y_true y_pred shape mismatch #4781, it also generates the same error: from keras import backend as K from keras import losses import keras from keras.models import TimeDistributed, Dense, Dropout, LSTM def my_loss(args): input_y, input_y_pred, y_pred = args return keras.losses.binary_crossentropy(input_y, input_y_pred) def generator2(): input_noise = keras.Input(name='input_noise', shape=(40, 38), dtype='float32') input_y = keras.Input(name='input_y', shape=(1,), dtype='float32') input_y_pred = keras.Input(name='input_y_pred', shape=(1,), dtype='float32') lstm1 = LSTM(256, return_sequences=True)(input_noise) drop = Dropout(0.2)(lstm1) lstm2 = LSTM(256, return_sequences=True)(drop) y_pred = TimeDistributed(Dense(38, activation='softmax'))(lstm2) loss_out = keras.layers.Lambda(my_loss, output_shape=(1,), name='my_loss')([input_y, input_y_pred, y_pred]) model = keras.models.Model(inputs=[input_noise, input_y, input_y_pred], outputs=[y_pred, loss_out]) model.compile(loss={'my_loss': lambda y_true, y_pred: y_pred}, optimizer='adam') return model g2 = generator2() noise = np.random.uniform(0,1,size=[10,40,38]) g2.train_on_batch([noise, np.ones(10), np.zeros(10)], noise) I need help to verify which operation is generating this error, because as far as I know the keras.losses.binary_crossentropy…
has answer: http://stackoverflow.com/a/53919184
downvote count: 0
answer count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/88035042
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50511329
has text: e.g. `gen = iter_commit(strSiteMap); first = next(gen); second = next(gen)`

http://stackoverflow.com/comment/87867329
comment on: http://stackoverflow.com/q/50420559
type: QuestionComment
type: Comment
has text: Thank you very much!!! Now it doesn't stay the same and goes below 1. =) But the loss still starts with values greater than 1 and even after a while there are still some losses greater than 1 from time to time. If I'm right the loss should always be between 0 and 1, shouldn't it? Do you have any idea why that is?
score: 0

http://stackoverflow.com/comment/87801395
has text: Can't reproduce your error on my side
comment on: http://stackoverflow.com/q/50392823
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/q/50444489
score: 1
upvote count: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87903641
has body: I am trying to plot 'n' lines whose x and y coordinates are defined by sk_x(t, tau) and sk_y(t, tau) respectively. If I plot them with the same function outside of the loop it plots the function fine but I can't make them work within the animate(i) function. An empty plot appears for a fraction of a second and then disappears. The problem definitely is how I'm handling the animate function but I can't quite figure out what's wrong, it worked with tau being the parameter instead of t but not the other way round (see second bit of code). import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation v = 1 k = 1 b = 1 c = 100 f = 200 def sk_y(t, tau): y = v*(t-tau) return y def sk_x(t, tau): x = v*(np.log((1+k*t)/(1+k*tau)))/k return x fig = plt.figure() ax = plt.axes(xlim=(0, sk_x(c,0)), ylim=(0, sk_y(c,0))) lines = [plt.plot([], [])[0] for _ in range(200)] def init(): m = 0 while m &lt; c: lines[m].set_data([], []) m+=1 return lines def animate(i): n=-1 while n&lt;c: n+=1 t = np.linspace(0,i/2-n,100) x = sk_x(t+n, n) y = sk_y(t+n, n) lines[n].set_data(x, y) return lines #edited in anim = animation.FuncAnimation(fig, animate, init_func=init, frames=f, interval=20, blit=True) plt.show() Using this bit for the animate function works fine def animate(i): tau = np.linspace(i*c/f, 0,100) x = sk_x(c, tau) y = sk_y(c, tau) lines[0].set_data(x, y) return lines Any help would be greatly appreciated! Edit: Added the return function in the animate function, but it still doesn't work for all the lines simultaneously as I want it to.
has comment: http://stackoverflow.com/comment/87902896
has comment: http://stackoverflow.com/comment/87903056
has comment: http://stackoverflow.com/comment/87903250
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Matplotlib animation of multiple lines being defined in a while loop
answer count: 0
downvote count: 0

http://stackoverflow.com/q/50491984
answer count: 2
has body: I have a list of dicts: my_list = [ {'name': 'AAA', 'date': '2018-05-14', 'price': 20.0}, {'name': 'AAA', 'date': '2018-05-15', 'price': 22.0}, {'name': 'AAA', 'date': '2018-05-16', 'price': 30.0}, {'name': 'BBB', 'date': '2018-05-14', 'price': 15.0}, {'name': 'BBB', 'date': '2018-05-15', 'price': 32.0} ] My question is how can I iterate over that list to produce a list in this format? parsed_list = [ {'name': 'AAA', 'data': [['2018-05-14', 20.0], ['2018-05-15', 22.0], ['2018-05-16', 30.0]]}, {'name': 'BBB', 'data': [['2018-05-14', 15.0], ['2018-05-15', 32.0]]} ] I tried approach described in this question: Python: group list items in a dict but I need a different output format and I can't figure out what I need to change.
downvote count: 1
linked to: http://stackoverflow.com/q/31071888
favorite count: 0
type: Question
has title: Iterate over list of dict and group item by key
has answer: http://stackoverflow.com/a/50492140
accepted answer: http://stackoverflow.com/a/50492140
upvote count: 10
tagged with: grouping
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50492063
possible better answer: http://stackoverflow.com/a/50492063
score: 9
type: AnsweredQuestion

http://stackoverflow.com/q/50508848
has comment: http://stackoverflow.com/comment/88030229
answer count: 1
has body: I've followed the official docs to use paginator in Django and it not working, it shows the right page count but on every page, the whole list displayed instead of slicing it into many pages views.py def home(request): current_user = request.user all_dress = Item.objects.all().filter(dress_active=True).order_by('-created_at') all_good = Item.objects.all().filter(dress_special=True) all_name = Name.objects.all() all_ads = Ads.objects.all() #pig paginator = Paginator(all_dress, 3) # Show 12 dress per page page = request.GET.get('page') dresss = paginator.get_page(page) context = { 'all_dress': all_dress, 'all_name': all_name, 'current_user': current_user, 'all_good':all_good, 'all_ads':all_ads, 'dresss':dresss, } return render(request, 'fostan/index.html',context) HTML &lt;div class="row"&gt; &lt;div class="col"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/div&gt; &lt;div class="col"&gt; &lt;div dir="ltr"&gt; &lt;div class="pagination" align="left"&gt; &lt;span class="step-links" align="left"&gt; {% if dresss.has_previous %} &lt;a href="?page=1"&gt;&amp;laquo; first &lt;/a&gt; &lt;a href="?page={{ dresss.previous_page_number }}"&gt; previous&lt;/a&gt; {% endif %} &lt;span class="current"&gt; Page number {{ dresss.number }} of {{ dresss.paginator.num_pages }} &lt;/span&gt; &lt;br&gt; {% if dresss.has_next %} &lt;a href="?page={{ dresss.next_page_number }}"&gt;next &lt;/a&gt; &lt;a href="?page={{ dresss.paginator.num_pages }}"&gt;last &amp;raquo;&lt;/a&gt; {% endif %} &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/div&gt; &lt;/div&gt; I have 9 items, and I asked the paginator to show only 3 items per page, the result is 3 pages with the same 9 items on every page! item list &lt;ul class="thumbnails" &gt; {% for dress in all_dress %…
accepted answer: http://stackoverflow.com/a/50509131
has comment: http://stackoverflow.com/comment/88037083
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50509131
has title: paginator is not working in django
score: 0
upvote count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88030167
downvote count: 1
has comment: http://stackoverflow.com/comment/88030736
type: AnsweredQuestion

http://stackoverflow.com/q/50447683
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/50447798
has answer: http://stackoverflow.com/a/50447798
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87908789
tagged with: pandas
has title: Merge 2 dataframe an add NaN if no hit
has body: I have 2 dataframes: qseqid sseqid pident length mismatch seq1 seq24 78 789 45 seq2 seq12 73 790 44 seq3 seq34 12 77 42 seq4 seq90 70 790 41 and another one such: seq2_id tax_inf seq3 Virus seq1 Eucaryote and I would to merge these two df such as: qseqid sseqid pident length mismatch tax_inf seq1 seq24 78 789 45 Eucaryote seq2 seq12 73 790 44 NaN seq3 seq34 12 77 42 Virus seq4 seq90 70 790 41 NaN
tagged with: python
tagged with: merge
type: Question
score: 0
upvote count: 2

http://stackoverflow.com/comment/87872853
has text: Added, let me know if you need anything else
comment on: http://stackoverflow.com/q/50428919
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87911053
score: 0
has text: @percusse But that's not what OP wants
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50448857

http://stackoverflow.com/a/50484865
has comment: http://stackoverflow.com/comment/87985330
answers question: http://stackoverflow.com/q/50484645
has comment: http://stackoverflow.com/comment/87985000
has body: I think you need to encapsulate each variable in try-except block. E.g: try: objektid_container = container.find_all("div", {"class":"is24-scoutid__content padding-top-s"}) objektid = objektid_container[0].get_text().strip() except: objektid = "" Do this for all variables For Second issue Move your headers outside loop Remove this code: filename = "results_"+current_datetime+".csv" f = open(filename, "a") headers = "Objekt-ID##Titel##Adresse##Merkmale##Kosten##Bausubstanz und Energieausweis##Beschreibung##Ausstattung##Lage\n" f.write(headers) And add it before: for number in numbers:
has comment: http://stackoverflow.com/comment/87983135
has comment: http://stackoverflow.com/comment/87984868
type: Answer
score: 0

subprocess
tags question: http://stackoverflow.com/q/50479130
tag name: subprocess
tags question: http://stackoverflow.com/q/50476747
type: Tag
tags question: http://stackoverflow.com/q/50434204
tags question: http://stackoverflow.com/q/50449082
tags question: http://stackoverflow.com/q/50526724
tags question: http://stackoverflow.com/q/50402801
tags question: http://stackoverflow.com/q/50519176
tags question: http://stackoverflow.com/q/50518438
tags question: http://stackoverflow.com/q/50423726
tags question: http://stackoverflow.com/q/50495937
tags question: http://stackoverflow.com/q/50535533
tags question: http://stackoverflow.com/q/50425008
tags question: http://stackoverflow.com/q/50386143
tags question: http://stackoverflow.com/q/50535941
tags question: http://stackoverflow.com/q/50514046
tags question: http://stackoverflow.com/q/50497978
tags question: http://stackoverflow.com/q/50530655
tags question: http://stackoverflow.com/q/50397391
tags question: http://stackoverflow.com/q/50401312
tags question: http://stackoverflow.com/q/50463238
tags question: http://stackoverflow.com/q/50435773
tags question: http://stackoverflow.com/q/50457421

http://stackoverflow.com/a/50486902
downvote count: 0
has body: You can use regex and strip i.e df[0] = df[0].str.strip("[]").str.replace("u'|'",'') 0 one_element 1 two_elememts, two_elements 2 three_elements, three_elements, three_elements Name: 0, dtype: object
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50486821
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50486821

http://stackoverflow.com/a/50411893
answers question: http://stackoverflow.com/q/50411854
type: Answer
score: 0
has body: setDaemon(True) from threading.Thread class more here https://docs.python.org/2/library/threading.html#threading.Thread.daemon

http://stackoverflow.com/comment/88014836
type: AnswerComment
comment on: http://stackoverflow.com/a/50501215
has text: If the name dict really has to be in a list, you easy could implement this by changing the line where the row_dict is created.
type: Comment
score: 0

http://stackoverflow.com/a/50511537
accepted answer of: http://stackoverflow.com/q/50504112
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50504112
type: AcceptedAnswer
has body: I don't really know Python, but extrapolating from the code snippet you show us, see how to assign the entire body of the document to a Word.Range (as opposed to Excel.Range) object. Then you need to collapse the Range, either to its starting or its end point - think of it like pressing the left or right arrow key to "collapse" a selection to a point. Then you can insert new content without disturbing the existing content. from win32com import client excel = client.Dispatch("Excel.Application") word = client.Dispatch("Word.Application") doc = word.Documents.Open("C:/word_file.docx") book = excel.Workbooks.Open("C:/excel_file.xlsx") sheet = book.Worksheets(1) sheet.Range("A1:D20").Copy() # Selected the table I need to copy wdRange = doc.Content wdRange.Collapse(1) #start of the document, use 0 for end of the document wdRange.PasteExcelTable(False, False, False)
type: Answer

http://stackoverflow.com/a/50528608
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88071835
has body: json.loads creates a list of key/value pairs, and the default action is to apply dict to that and return it. object_pairs_hook does whatever you want to the list instead of dict. If you set object_pairs_hook to lambda x: x (just return each element as is), it will just return a list of key_value pairs in the order they are read. &gt;&gt;&gt; x = '{"3": 3, "0": 0, "1": 1, "2": 2, "3": 3, "4": 4}' &gt;&gt;&gt; json.loads(x, object_pairs_hook=lambda el: el) [('3', 3), ('0', 0), ('1', 1), ('2', 2), ('3', 3), ('4', 4)] You can then use your ordered key/value pairs to make any kind of object you please. This will be a very effective way to keep order and keep duplicates. Unless you are creating your own object, I'm not aware of a dictionary-like class that accepts duplicate keys. A list might be your best bet, or your own class. class SillyClass(object): def __init__(self, a_list): self._list = a_list[:] def show(self): return self._list[:] to_test = json.loads(x, object_pairs_hook=SillyClass) print(to_test.show()) output => [('3', 3), ('0', 0), ('1', 1), ('2', 2), ('3', 3), ('4', 4)]
type: Answer
accepted answer of: http://stackoverflow.com/q/50527608
downvote count: 0
answers question: http://stackoverflow.com/q/50527608

http://stackoverflow.com/comment/112993806
has text: Sorry, it was so long ago, I can't remember if I solved the problem or not
score: 0
comment on: http://stackoverflow.com/q/50412411
type: Comment
type: QuestionComment

decision-tree
type: Tag
tag name: decision-tree
tags question: http://stackoverflow.com/q/50455722

http://stackoverflow.com/a/55732519
answers question: http://stackoverflow.com/q/50408941
score: 18
type: Answer
has comment: http://stackoverflow.com/comment/99982820
upvote count: 18
downvote count: 0
has body: There is now a python3-pip package in the CentOS 7 base repository as of 2019-08-22. There is no longer a need for third-party repositories or packages. Installing python3-pip will also install libtirpc, python3, python3-libs, and python3-setuptools: yum install --assumeyes python3-pip You can now verify the version (yes, it is old, but it's what is coming from the base repository): $ pip3 --version pip 9.0.3 from /usr/lib/python3.6/site-packages (python 3.6) If you don't want to stray from the files provided by the python3-pip package, and you don't want to see warnings about pip being old, see https://stackoverflow.com/a/46288945/534275 for silencing the messages.

http://stackoverflow.com/comment/88009191
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50498167
type: AnswerComment
has text: Question mark after `*` makes it non-greedy.

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

http://stackoverflow.com/a/76595800
score: -1
has comment: http://stackoverflow.com/comment/135098202
upvote count: 0
answers question: http://stackoverflow.com/q/50446949
has body: (I cannot comment, on the above post) Small correction on the above code: img.putpalette(p) (instead of setpalette)
downvote count: 1
type: Answer

http://stackoverflow.com/q/50499619
downvote count: 0
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50499626
tagged with: sorting
has comment: http://stackoverflow.com/comment/88011950
tagged with: dictionary
has answer: http://stackoverflow.com/a/50499626
accepted answer: http://stackoverflow.com/a/50499662
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
has body: I have a list of strings that represents playing cards. Ranks can be A23456789TJQK Here is my list # L2 ['5', '6', '7', 'A', 'K'] And I'm trying to make a function to call with the key in the sorted function to return the card rank numerical values in order. So here is my function: def sortYo(): myDict = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10} And here is my call: L4 = sorted(L2, key = sortYo()) But my L4 ends up the same: # L4 ['5', '6', '7', 'A', 'K'] Why isn't my sortYo() function changing the values? Thank you in advance. EDIT: from collections import Counter from itertools import combinations import sys myList = sys.argv myList.pop(0) Suits = ['H', 'S', 'D', 'C'] Nums = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] SuitsTwo = {'♥': 'H', '♦': 'D', '♣': 'C', '♠': 'S'} print(myList) L1 = [] # Suits L2 = [] # Ranks L3 = [i for i in myList[0]] # Cut for i in myList: for x in i: if x in SuitsTwo: L1.append(SuitsTwo[x]) elif x in Suits: L1.append(x) else: L2.append(x) print('L1:' print(L1) print('L2:') print(L2) print('L3:') print(L3) score = 0 # straight sC = 0 myDict = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9\ ': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10} L4 = sorted(L2, key = lambda x: myDict.get(x,11)) print('L4') print(L4) #RUN python3 as13.py AS 5H 6C 7S KH ['AS', '5H', '6C', '7S', 'KH'] L1: ['S', 'H', 'C', 'S', 'H'] L2: ['A', '5', '6', '7', 'K'] L3: ['A', 'S'] L4 ['A', '5', '6', '7', 'K'] 0
answer count: 2
has title: How do I use the sorted key function call in Python?
has answer: http://stackoverflow.com/a/50499662

http://stackoverflow.com/comment/87890031
has text: I always thought the convention was .pkl!
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50438070

http://stackoverflow.com/comment/88054701
comment on: http://stackoverflow.com/a/50446092
score: 0
has text: @Knight please see updated answer. Directly putting `func1`,`func2` into function`test_multiprocessing` would give you pickling error. You can use class instead.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50441120
has body: I imported the dataset with the code below. dataset_csv = np.loadtxt('/home/user/Downloads/dataset.csv', delimiter=',') x_train=dataset_csv[:3000000,0:3] y_train=dataset_csv[:3000000,3] x_test=dataset_csv[3000000:,0:3] y_test=dataset_csv[3000000:,3] The total data set is 3193739. Each dataset has the following form. (value1 ,value2,value3, class) I tried to insert data by setting the input layer as follows. model =Sequential() model.add(Dense(128, input_shape=3, activation='relu')) However, the following error occurred. TypeError: 'int' object is not iterable I'm wondering why you can not read integer types and how you can make a dataset readable.
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50441137
type: Question
has answer: http://stackoverflow.com/a/50441137
answer count: 1
tagged with: python
tagged with: keras
has title: keras TypeError: 'int' object is not iterable

http://stackoverflow.com/comment/87880950
has text: Oh, I didn't know the solution is that simple. How come I didn't notice the green box in the documentation and spend almost half day figuring out what's going on...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50433278
score: 0

http://stackoverflow.com/q/50534786
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88081826
has title: Imbricated loops and Python syntax
answer count: 1
has answer: http://stackoverflow.com/a/50534969
tagged with: loops
tagged with: analysis
favorite count: 0
type: Question
tagged with: nltk
linked to: http://stackoverflow.com/q/364802
has body: I am currently learning about NLP in Python and I am getting problems with a Python syntax. cfd = nltk.ConditionalFreqDist( #create conditional freq dist (target, fileid[:4]) #create target (Y) and years (X) for fileid in inaugural.fileids() #loop through all fileids for w in inaugural.words(fileid) #loop through each word of each fileids for target in ['america','citizen'] #loop through target if w.lower().startswith(target)) #if w.lower() starts with target words cfd.plot() # plot it I do not understand the purpose of line 2. Moreover, I do not understand why each loop doesn't end with ":" like any loops in Python. Can someone explain me this code ? The code works, but I do not fully understand its syntax. Thank you
accepted answer: http://stackoverflow.com/a/50534969
tagged with: python
tagged with: nlp
type: AnsweredQuestion

branch
tag name: branch
tags question: http://stackoverflow.com/q/50516148
type: Tag

http://stackoverflow.com/comment/88084368
score: 0
has text: Can you do `print(dataframe.columns)`? It seems like your dataframes are empty.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50535847

http://stackoverflow.com/q/50498672
has body: This question has been asked several times around the site, but the answer frequently seems to be an omission of the install_requires arg. Not the case here. I'm trying to build a wheel that can be pip installed in a way that also installs a required package that's not on PyPI. my setup.py includes: setup( install_requires= ['shotgun-api3'] dependency_links = [ "git+https://github.com/shotgunsoftware/python-api.git@v3.0.36#egg=shotgun_api3" ], # ... ) From the commandline I then run python setup.py sdist bdist_wheel to generate the /dist/mypackage-0.1.0-py2-none-any.whl. Rather than upload my package to an index, I'm trying to install my package from the filesystem; so in a clean virtualenv, I then run: pip -v install mypackage --no-index --find-links file:///F:/RyDev/myproject/dist --process-dependency-links. And I get: DistributionNotFound: No matching distribution found for shotgun-api3 (from mypackage) and because I used the verbose flag, I see: Collecting shotgun-api3 (from mypackage) 0 location(s) to search for versions of shotgun-api3: Skipping link file:///F:/RyDev/mypackage/dist/mypackage-4.0.0-py2-none-any.whl; wrong project name (not shotgun-api3) Skipping link file:///F:/RyDev/mypackage/dist/mypackage-4.0.0.tar.gz; wrong project name (not shotgun-api3) It's maybe worth noting: if I remove the install_requires arg from setup.py, mypackage will pip install without errors...just without the dependency. I can run pip install git+https://github.com/shotgunsoftware/python-api.git@v3.0.36#egg=shotgun_api3 and it successfully installs the shotgun-api3 package. ...but for the life of me, I can't seem to get shotgun-api3 to install as a dependency for mypackage. It looks to me like the (git) URL I provided to dependency_links isn't being included in the list of locations, so I'm wondering if I'm missing something around that? Environment: Python 2.7.13 (cannot upgrade) Windows 7 (cannot switch OS) pip 10.0.1 setuptools 39.2.0 virtualenv 16.0.0 wheel 0.31.1
has comment: http://stackoverflow.com/comment/92397041
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88040073
downvote count: 0
answer count: 1
tagged with: pip
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/26061610
has answer: http://stackoverflow.com/a/59543345
has title: setup.py dependency_links not searched for install_requires
score: 1
has comment: http://stackoverflow.com/comment/88032346
tagged with: setuptools
favorite count: 0
has comment: http://stackoverflow.com/comment/88040134
linked to: http://stackoverflow.com/q/52735269
type: Question

datetime
tags question: http://stackoverflow.com/q/50510947
tags question: http://stackoverflow.com/q/50397885
tags question: http://stackoverflow.com/q/50452919
tags question: http://stackoverflow.com/q/50489198
tag name: datetime
tags question: http://stackoverflow.com/q/50510136
tags question: http://stackoverflow.com/q/50520682
tags question: http://stackoverflow.com/q/50419277
tags question: http://stackoverflow.com/q/50445140
tags question: http://stackoverflow.com/q/50422329
tags question: http://stackoverflow.com/q/50404559
tags question: http://stackoverflow.com/q/50413291
tags question: http://stackoverflow.com/q/50397195
tags question: http://stackoverflow.com/q/50474488
tags question: http://stackoverflow.com/q/50492765
tags question: http://stackoverflow.com/q/50500512
tags question: http://stackoverflow.com/q/50393581
tags question: http://stackoverflow.com/q/50465673
tags question: http://stackoverflow.com/q/50399569
type: Tag
tags question: http://stackoverflow.com/q/50400210
tags question: http://stackoverflow.com/q/50411201
tags question: http://stackoverflow.com/q/50454573
tags question: http://stackoverflow.com/q/50392796
tags question: http://stackoverflow.com/q/50425177
tags question: http://stackoverflow.com/q/50387853
tags question: http://stackoverflow.com/q/50443443
tags question: http://stackoverflow.com/q/50423729
tags question: http://stackoverflow.com/q/50503033
tags question: http://stackoverflow.com/q/50437679
tags question: http://stackoverflow.com/q/50385200
tags question: http://stackoverflow.com/q/50388683
tags question: http://stackoverflow.com/q/50420900
tags question: http://stackoverflow.com/q/50429197
tags question: http://stackoverflow.com/q/50505284
tags question: http://stackoverflow.com/q/50445544
tags question: http://stackoverflow.com/q/50456832
tags question: http://stackoverflow.com/q/50410044
tags question: http://stackoverflow.com/q/50415469
tags question: http://stackoverflow.com/q/50449453
tags question: http://stackoverflow.com/q/50455797
tags question: http://stackoverflow.com/q/50499196
tags question: http://stackoverflow.com/q/50411641
tags question: http://stackoverflow.com/q/50510407
tags question: http://stackoverflow.com/q/50412933
tags question: http://stackoverflow.com/q/50443305
tags question: http://stackoverflow.com/q/50431611
tags question: http://stackoverflow.com/q/50441627
tags question: http://stackoverflow.com/q/50394097
tags question: http://stackoverflow.com/q/50470133
tags question: http://stackoverflow.com/q/50400168
tags question: http://stackoverflow.com/q/50442808
tags question: http://stackoverflow.com/q/50462309
tags question: http://stackoverflow.com/q/50444576

http://stackoverflow.com/comment/88007971
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50496114
has text: Thank you so much. Knowing the information you provided (that quotes have about 10-20 different uses in Unicode as compared to the standard ASCII quotes), I did a little more digging and discovered the library unidecode. Simply passing the tweet: tweet = unidecode(tweet), it converts any problematic Unicode characters into standard ASCII to then follow my logic.
type: Comment

http://stackoverflow.com/comment/88070123
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50529186
type: Comment
has text: short answer: dictionaries. `self.btn[date] = ttk.Button(...)`

http://stackoverflow.com/comment/87877634
score: 0
has text: Why do you create a 1-d zeros array, add rows to it then delete the original 1-d zeros array?
type: QuestionComment
comment on: http://stackoverflow.com/q/50431401
type: Comment

http://stackoverflow.com/a/50535487
type: AcceptedAnswer
has body: dict.update is a mutating function, it is modifying the original dict. By default python functions return None, hence when calling update it is returning nothing so None. The way to do this is simple, use a for loop instead: for r in lod: r.update({"new_key": "new_value"})
type: Answer
has comment: http://stackoverflow.com/comment/88083422
accepted answer of: http://stackoverflow.com/q/50535455
has comment: http://stackoverflow.com/comment/88083317
answers question: http://stackoverflow.com/q/50535455
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/50579387
has comment: http://stackoverflow.com/comment/88189852
has comment: http://stackoverflow.com/comment/88191581
has comment: http://stackoverflow.com/comment/88189564
type: Answer
score: 11
answers question: http://stackoverflow.com/q/50537967
has body: If you are willing to use the networkx library, you can take advantage of its fast bfs implementation. I know, adding another dependency is annoying, but the performance gain seems huge, see below. import numpy as np from scipy import spatial import networkx vertices = np.array([[[2.0, 1.0, 3.0],[3.0, 1.0, 2.0],[1.2, 2.5, -2.0]], [[3.0, 1.0, 2.0],[1.0, 2.0, 3.0],[1.2, -2.5, -2.0]], [[1.0, 2.0, 3.0],[2.0, 1.0, 3.0],[3.0, 1.0, 2.0]], [[1.0, 2.0, 3.0],[2.0, 1.0, 3.0],[2.2, 2.0, 1.0]], [[1.0, 2.0, 3.0],[2.2, 2.0, 1.0],[4.0, 1.0, 0.0]], [[2.0, 1.0, 3.0],[2.2, 2.0, 1.0],[-4.0, 1.0, 0.0]]]) vertices1 = np.array([[[2, 1, 3], [3, 1, 2], [1, 2, -2]], [[3, 1, 2], [1, 2, 3], [1, -2, 2]], [[1, 2, 3], [2, 1, 3], [3, 1, 2]], [[1, 2, 3], [2, 1, 3], [2, 2, 1]], [[1, 2, 3], [2, 2, 1], [4, 1, 0]], [[2, 1, 3], [2, 2, 1], [-4, 1, 0]], [[3, 1, 3], [2, 2, 1], [-4, 1, 0]], [[8, 1, 2], [1, 2, 3], [1, -2, 2]]]) def make(N=3000): """create a N random points and triangulate""" points= np.random.uniform(-10, 10, (N, 3)) tri = spatial.Delaunay(points[:, :2]) return points[tri.simplices] def bfs_tree(triangles, root=0, return_short=True): """convert triangle list to graph with vertices = triangles, edges = pairs of triangles with shared edge and compute bfs tree rooted at triangle number root""" # use the old view as void trick to merge triplets, so they can # for example be easily compared tr_as_v = triangles.view(f'V{3*triangles.dtype.itemsize}').reshape( triangles.shape[:-1]) # for each triangle write out its edges, this involves doubling the # data becaues each vertex occurs twice tr2 = np.concatenate([tr_as_v, tr_as_v], axis=1).reshape(-1, 3, 2) # sort vertices within edges ... tr2.sort(axis=2) # ... and glue them together tr2 = tr2.view(f'V{6*triangles.dtype.itemsize}').reshape( triangles.shape[:-1]) # to find shared edges, sort them ... idx = tr2.ravel().argsort() tr2s = tr2.ravel()[idx] # ... and then compare consecutive ones pairs, = np.where(tr2s[:-1] == tr2s[1:]) assert np.all(np.diff(…
upvote count: 11
accepted answer of: http://stackoverflow.com/q/50537967
has comment: http://stackoverflow.com/comment/88192157
has comment: http://stackoverflow.com/comment/88187058
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88186674
has comment: http://stackoverflow.com/comment/88191372
has comment: http://stackoverflow.com/comment/88188690
has comment: http://stackoverflow.com/comment/88186896

http://stackoverflow.com/comment/88032893
type: AnswerComment
has text: OP is getting syntax errot in `dict-comprehension`, your answer does not address that.
comment on: http://stackoverflow.com/a/50510201
type: Comment
score: 0

http://stackoverflow.com/comment/88159953
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50530049
type: Comment
has text: Clearly, the problem is with your first line of code.

http://stackoverflow.com/a/50399063
has body: The last line of code in your main.py file is calling the function TakeSnapAndSave when the file is imported rather than when the option is selected in the GUI. Remove that call to TakeSnapAndSave from main.py and Novel's advice should work: subMenu.add_command(label="Web Cam", command=main.TakeSnapAndSave) Check out the thread on guarding code from being automatically run: Why is Python running my module when I import it, and how do I stop it?
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50398159
answers question: http://stackoverflow.com/q/50398159
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87906942
comment on: http://stackoverflow.com/a/50446602
has text: Thanks DebanjanB, this indeed add extension in the chrome but is disabled. is there any any that browser open with enabled extension? or what would be the best way to enable extension so that this may be used.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50428047
has comment: http://stackoverflow.com/comment/87871107
answers question: http://stackoverflow.com/q/50428033
type: Answer
has comment: http://stackoverflow.com/comment/87870791
has body: the following code will work lst = [1,2,3,4] result = {i:j for i,j in enumerate(lst)}
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/87928800
comment on: http://stackoverflow.com/q/50457589
type: QuestionComment
score: 0
has text: Your question is confusing. Do you want to keep the rows in the first dataframe only if they do _not_ have matches in the second dataframe? Or if the _do_ have matches? Or what?
type: Comment

http://stackoverflow.com/comment/88013462
has text: Thanks! Not exactly sure OP means `3, 3, 6, and 7 indexes` as comma-separated but it could be.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50500402

http://stackoverflow.com/comment/88039041
type: AnswerComment
comment on: http://stackoverflow.com/a/50512116
has text: I need to merge two dataframe on datetime, and also need to insert it to the table that I created in database, when I do some query, I will do some operation on the datetime.
type: Comment
score: 0

http://stackoverflow.com/comment/87866194
comment on: http://stackoverflow.com/q/50425739
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [/usr/lib/libstdc++.6.dylib: mach-o, but wrong architecture](https://stackoverflow.com/questions/18928586/usr-lib-libstdc-6-dylib-mach-o-but-wrong-architecture)

http://stackoverflow.com/a/50416593
score: 3
has comment: http://stackoverflow.com/comment/87848901
answers question: http://stackoverflow.com/q/50416562
type: Answer
has body: The Button class forwards all its keyword agruments (**kw) to its base class (Widget). You can see how it does that here class Button(Widget): """Button widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, repeatdelay, repeatinterval, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS command, compound, default, height, overrelief, state, width """ Widget.__init__(self, master, 'button', cnf, kw)
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87848843

http://stackoverflow.com/q/50520096
has comment: http://stackoverflow.com/comment/88053165
score: 0
has comment: http://stackoverflow.com/comment/88053263
has comment: http://stackoverflow.com/comment/88053095
answer count: 2
has comment: http://stackoverflow.com/comment/88053054
duplicate of: http://stackoverflow.com/q/30336324
possible better answer: http://stackoverflow.com/a/65426320
has answer: http://stackoverflow.com/a/65426320
type: Question
has comment: http://stackoverflow.com/comment/88053080
tagged with: seaborn
has body: I am trying to utilize Seaborn to create a visualization. Here is what I have thus far: import os.path directory = os.path.dirname(os.path.abspath(__file__)) import pandas as pd import seaborn as sns sns.set(style="whitegrid", color_codes=True) tel = pd.read_csv('nyc.csv') nyctel = sns.load_dataset(tel) sns.stripplot(x="installation_id", y="mounting", hue="mounting", data=nyctel) The official documentation for load_dataset is completely useless, so I found that someone had already asked a question about how it works here: https://stackoverflow.com/a/30337377/6110631 I followed the format listed in the answer and imported pandas so I could use a local file (saved in the same folder). When I run the program however, I get IOError: File nyc.csv does not exist If I use an absolute path I get IOError: ('http protocol error', 0, 'got a bad status line', None) It seems the problem is with this line: nyctel = sns.load_dataset(tel) because if I omit this line and the line beneath it and add print tel beneath the pd.read_csv line then the program works and it prints out the contents of the file. Somehow load_dataset is not letting me use that file though! I am using the exact same code as in the answer linked above. Why would this not work for this local file?
has comment: http://stackoverflow.com/comment/88052818
has title: Using local data in Python Seaborn returns file does not exist
has comment: http://stackoverflow.com/comment/88053254
tagged with: python
linked to: http://stackoverflow.com/q/30336324
duplicate of: http://stackoverflow.com/q/67084303
has answer: http://stackoverflow.com/a/50520201
accepted answer: http://stackoverflow.com/a/50520201
type: AnsweredQuestion

http://stackoverflow.com/comment/87974893
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50480818
score: 1
has text: Yeah but OP wants last value always, ie str[-1]

http://stackoverflow.com/q/50509597
downvote count: 0
has answer: http://stackoverflow.com/a/50509691
has answer: http://stackoverflow.com/a/50509645
favorite count: 0
type: Question
has title: How to extract specific lines in Pandas
tagged with: object
has body: I have a pandas's df that is: df['timestamp'] 26600 58161.0 26628 58161.0416667 26656 58161.0833333 26684 58161.125 26712 58161.1666667 26740 58161.2083333 26768 58161.25 26796 58161.2916667 26824 58161.3333333 26852 58161.375 26880 58161.4166667 26908 58161.4583333 26936 58162.0 26964 58162.0416645 26992 58162.0833333 I would like to extract only the two rows that end with ".0" I have tried with this command: df['timestamp'].str.startswith(".0", na=False) but it returns: AttributeError: 'Series' object has no attribute 'startswith' Is there a simple way to do this job? Thanks
score: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/88031246
has comment: http://stackoverflow.com/comment/88031318
tagged with: python
has comment: http://stackoverflow.com/comment/88031267
tagged with: startswith
answer count: 2
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/50412193
linked to: http://stackoverflow.com/q/14264313
favorite count: 0
has body: I'd like to fetch topics with a specified 'log' tag: Within the nested function get_topics_with_log_tag, I set variable topics_with_log_tag nonlocal: def log(request): """Show all topics and entries with log tags""" topics = Topic.objects.all() #select entries with log tag def get_topics_with_log_tag(topics): nonlocal topics_with_log_tag topics_with_log_tag = [] for topic in topics: for entry in topic.entry_set.all(): if "#log" in entry.tags: topics_with_log_tag.append(topic) get_topics_with_log_tag(topics) It throw SyntaxError: SyntaxError: no binding for nonlocal 'topics_with_log_tag' found Actually, I did bind it topics_with_log_tag = [] The above code could be rewrite in a redundant way as topics = Topic.objects.all() #select entries with log tag def get_topics_with_log_tag(topics): # nonlocal topics_with_log_tag topics_with_log_tag = [] for topic in topics: for entry in topic.entry_set.all(): if "#log" in entry.tags: topics_with_log_tag.append(topic) return topics_with_log_tag topics_with_log_tag = get_topics_with_log_tag(topics) What's the problem with my usage of nonlocal? I found the error. Willem Van Onsem introduces database level filter instead of the nested for loop. The models.py class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic) title = models.CharField(max_length=200) text = models.TextField() tags = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True)
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87839882
has comment: http://stackoverflow.com/comment/87840207
has comment: http://stackoverflow.com/comment/87839969
has answer: http://stackoverflow.com/a/66268250
downvote count: 0
has title: `SyntaxError: no binding for nonlocal 'topics_with_log_tag' found` although it's bounded
score: 16
tagged with: django
upvote count: 16
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87840066
accepted answer: http://stackoverflow.com/a/50412512
possible better answer: http://stackoverflow.com/a/66268250
has comment: http://stackoverflow.com/comment/87840543
has answer: http://stackoverflow.com/a/50412512
tagged with: python

http://stackoverflow.com/comment/88030455
has text: Can you add some sample?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50509187
type: QuestionComment

http://stackoverflow.com/a/50527891
upvote count: 1
score: 1
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50525633
has body: Pass a callable that passes parse_float=decimal.Decimal to json.loads() as json_deserializer. A simple function such as def json_deserializer(*args, **kwgs): return json.loads(*args, parse_float=decimal.Decimal, **kwgs) should do.
answers question: http://stackoverflow.com/q/50525633

http://stackoverflow.com/q/50492713
tagged with: dictionary
has answer: http://stackoverflow.com/a/50492796
type: AnsweredQuestion
downvote count: 0
answer count: 3
score: 1
has title: Accessing values from Python sub-dictionary
upvote count: 1
tagged with: request
possible better answer: http://stackoverflow.com/a/50492796
has answer: http://stackoverflow.com/a/50494644
accepted answer: http://stackoverflow.com/a/50494644
has body: I've scraped a webpage using an API and want to access one part of the results, but am having difficulty accessing it: import requests import json headers = {'x-api-key': 'my_key'} test_url= "https://api.propublica.org/congress/v1/statements/date/2018-05- 22.json" resp = requests.get(test_url, headers=headers).json() The results are coming out in a dictionary format that looks like this: [{'chamber': 'Senate', 'congress': 115, 'party': 'R', 'state': 'NC', 'url': 'url1_goes_here'}, {'chamber': 'Senate', 'congress': 115, 'party': 'R', 'state': 'ND', 'url': 'url2_goes_here'}] I want to extract the 'url' value from each entry, but the entries doesn't seem to have a key by which I can drill down. How can I go about accessing these? I thought that: resp["url] Would work, but I didn't have any luck. The output I'd ideally want would be something like: [url1, url2]
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88039164
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50492858
tagged with: http://stackoverflow.com/tag/json
tagged with: python

http://stackoverflow.com/comment/88085873
score: 0
has text: If you only answer a fraction of the questions you're asked, nobody can help you. Also, please edit the question to include important info, don't just put it in comments. I'm assuming you actually read the page you linked to. Are you actually using a Python 2.7 version before 2.7.9? If not, why are you running `get-pip.py`? If, say, it's because you're using a distro-supplied (or Apple-supplied) Python, you're doing the wrong thing, and we can explain why—but if you won't tell us anything about what you're using except that it's 2.7, all we can tell is that you must be doing something wrong.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50535136

http://stackoverflow.com/a/50393022
downvote count: 0
has comment: http://stackoverflow.com/comment/87802700
has comment: http://stackoverflow.com/comment/87802616
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/87802526
has comment: http://stackoverflow.com/comment/87802672
has comment: http://stackoverflow.com/comment/87802380
has comment: http://stackoverflow.com/comment/87802327
has body: Update your dictionary The best approach would be to update your brailleDict to account for capital letters. Your initial solution would then work. Although, this allows you to use the str.translate method which is arguably an even better solution. brailleDict = {'a' : '100000', 'b': '110000', ...} # Add the capital letter Braille representations to your dict brailleDict.update({char.upper(): '000001' + code for char, code in brailleDict.items()}) # Create a translation dict to be used by `str.translate` brailleTranslation = str.maketrans(brailleDict) print('bob'.translate(brailleTranslation)) # '110000101010110000' print('Bob'.translate(brailleTranslation)) # '000001110000101010110000' The downside is that str.translate will leave characters it does not recognize unchanged. You can either check your string is translatable with str.isalpha and raise a ValueError if it isn't or update your translation table so it removes unknown characters. from collections import defaultdict ... brailleTranslation = defaultdict(lambda: None, str.maketrans(brailleDict)) print('#bob'.translate(brailleTranslation)) # still prints '110000101010110000' If you populate your dict with all Braille characters, you can check for s.isprintable() instead in the above function. Use str.upper Alternatively, you can check if a string is composed of uppercase characters using str.isupper. brailleDict = {'a' : '100000', 'b': '110000', ...} def braille(string): return ''.join(('000001' if char.isupper() else '') + brailleDict[char.lower()] for char in string) print(braille('bob')) # '110000101010110000' print(braille('Bob')) # '000001110000101010110000'
upvote count: 3
answers question: http://stackoverflow.com/q/50392926

http://stackoverflow.com/comment/88008472
type: Comment
type: QuestionComment
has text: For the final output, check this out https://github.com/datamade/probablepeople. I am using it at the moment, not perfect but certainly beats implementing it from scratch.
comment on: http://stackoverflow.com/q/50497642
score: 0

http://stackoverflow.com/comment/88289935
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50449114
score: 0
has text: Hey @Pam, accuracy doesn't rise after >1 epoch. As you said y_pred_cls contain my predicted class labels. I add a line to my network exactly after confusion matrix summation: `sess.run(y_pred_cls, {x:batch_tx})` where batch_tx is my test RGB data and I got my predicted labels. Now, How am I going to find images from these labels and save them in a folder?

http://stackoverflow.com/q/50456961
tagged with: python
score: -1
tagged with: cerberus
upvote count: 0
tagged with: validation
answer count: 1
has title: Dictionary validation Cerberus use reserved keyword
downvote count: 1
has answer: http://stackoverflow.com/a/50669060
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I have a python dictionary I am trying to validate using cerberus. However, one of the fields in my dict is called "type" which conflicts with the keyword "type" reserved by the cerberus parser. Is there any way to get around this without having to change the original dictionary? Part in question { { ... "db": { "type": "AzureTables", ... } } }

http://stackoverflow.com/q/50509148
has comment: http://stackoverflow.com/comment/88176291
has comment: http://stackoverflow.com/comment/88221673
downvote count: 0
has comment: http://stackoverflow.com/comment/88036202
has title: Python HTTP debuger
answer count: 1
accepted answer: http://stackoverflow.com/a/50649046
favorite count: 0
tagged with: debugging
has answer: http://stackoverflow.com/a/50649046
has comment: http://stackoverflow.com/comment/88176556
type: Question
has comment: http://stackoverflow.com/comment/88137456
tagged with: python
score: 6
upvote count: 6
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/88188163
has comment: http://stackoverflow.com/comment/88030243
type: AnsweredQuestion
has body: I would like to set some debugging command (like import ipdb; ipdb.set_trace()) that would run debugger in jupyter (I would have to run a HTTP server). Does anybody know about something like this? Context: I have a long running tasks that are processed by a scheduler (not interactive mode). I would like to be able to debug such a task while running it the same way.

http://stackoverflow.com/a/50530290
has body: You should be mocking with respect to where you are testing. Based on the example provided, this means that the Escli class you are using in the settings.py module needs to be mocked with respect to settings.py. So, more practically, your patch call would look like this inside setUp instead: self.patcher = patch('escli.settings.Escli') With this, you are now mocking what you want in the right place based on how your tests are running. Furthermore, to add more robustness to your testing, you might want to consider speccing for the Elasticsearch instance you are creating in order to validate that you are in fact calling valid methods that correlate to Elasticsearch. With that in mind, you can do something like this, instead: self.patcher = patch('escli.settings.Escli', Mock(Elasticsearch)) To read a bit more about what exactly is meant by spec, check the patch section in the documentation. As a final note, if you are interested in exploring the great world of pytest, there is a pytest-elasticsearch plugin created to assist with this.
type: AcceptedAnswer
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50506310
downvote count: 0
answers question: http://stackoverflow.com/q/50506310

http://stackoverflow.com/a/52710122
type: Answer
has body: I don't think your spider is correctly inheriting from the crawler class. When I ran into this error, I was able to solve it by adding a super() call in the from_crawler() method that brings in the crawler attributes/methods into your custom spider Here's an example of this (see the from_crawler method): from scrapy import signals from scrapy import Spider class DmozSpider(Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/", ] @classmethod def from_crawler(cls, crawler, *args, **kwargs): spider = super(DmozSpider, cls).from_crawler(crawler, *args, **kwargs) crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed) return spider def spider_closed(self, spider): spider.logger.info('Spider closed: %s', spider.name) def parse(self, response): pass Source: https://doc.scrapy.org/en/latest/topics/signals.html
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50492234
has comment: http://stackoverflow.com/comment/92346820

http://stackoverflow.com/comment/128922684
score: 1
type: Comment
comment on: http://stackoverflow.com/a/70946983
type: AnswerComment
has text: @Zhenia it only works in one direction: You have a Company, and you have a Car. Car has a manufacturer. Like this: `manufacturer = ForeignKey(to=Company, models.CASCADE)`. So if you delete a Company, manufacturer will become non-existent, so the car will be deleted too. But if you delete a Car, nothing happens with company: it just doesn't have any links to the car which require some resolving (like casacade deleting or setting it to null)

http://stackoverflow.com/a/50536353
answers question: http://stackoverflow.com/q/50536266
downvote count: 0
has body: The query can be improved like the following: queryset = User.objects.filter(is_online=True,profile__reputation__gte=200) .order_by('profile__reputation')
type: Answer
upvote count: 4
score: 4

http://stackoverflow.com/q/50517271
accepted answer: http://stackoverflow.com/a/50549110
has comment: http://stackoverflow.com/comment/88049874
has answer: http://stackoverflow.com/a/50549110
has comment: http://stackoverflow.com/comment/88071890
has comment: http://stackoverflow.com/comment/88048915
type: Question
has title: Python Selenium Click Next Button
has body: I need to click the "next" button on the following page: <a href="https://www.amazon.com/gp/goldbox/ref=gbps_ftr_s-4_bedf_wht_29726380?gb_f_deals1=dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL%252CEXPIRED%252CSOLDOUT%252CUPCOMING,includedAccessTypes:,sortOrder:BY_SCORE,enforcedCategories:2972638011&amp;pf_rd_p=afc45143-5c9c-4b30-8d5c-d838e760bedf&amp;pf_rd_s=slot-4&amp;pf_rd_t=701&amp;pf_rd_i=gb_main&amp;pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_r=60XTK6YDM9WEAFXB6519&amp;ie=UTF8" rel="nofollow noreferrer">https://www.amazon.com/gp/goldbox/ref=gbps_ftr_s-4_bedf_wht_29726380?gb_f_deals1=dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL%252CEXPIRED%252CSOLDOUT%252CUPCOMING,includedAccessTypes:,sortOrder:BY_SCORE,enforcedCategories:2972638011&amp;pf_rd_p=afc45143-5c9c-4b30-8d5c-d838e760bedf&amp;pf_rd_s=slot-4&amp;pf_rd_t=701&amp;pf_rd_i=gb_main&amp;pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_r=60XTK6YDM9WEAFXB6519&amp;ie=UTF8 I have the following code that will not find xpath element for the "next button": browser.find_element_by_xpath("//ul[@class='a-pagination']/li[@class='a-last']/a").click() # Click on next button I have also tried this variation: browser.find_element_by_xpath("//div[@id='pagination-next-6885645543374035']/ul/li[@class='a-last']/a") I also tried directly copying the xpath from the inspector. Neither of these three options work. Thanks in advance for your help.
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/100600616
has text: Yep, it is NTFS. But although I have both `.exe` and `.EXE` in my `PATHEXT` env variable, it doesn't work unless I add the `.exe` manually as explained in my answer above.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/57003275

http://stackoverflow.com/comment/87870868
type: QuestionComment
comment on: http://stackoverflow.com/q/50427896
has text: Huh. I didn't know it required 3.5+ on Windows. We both learned something!
type: Comment
score: 0

http://stackoverflow.com/q/50478761
has title: How to get the pandas DataFrame in this specified format ?
upvote count: 0
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/50478838
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87973320
score: -2
tagged with: python
has body: I have a timetable dataframe like this :- subjectid facultyid day hour mon 1 4CCI02 5 2 FR 42 3 4CS01 39 4 4MAT2 46 5 4CCI01 29 6 4MAT2 46 7 4CCI04 47 8 4CCI03 21 tue 1 MC03 48 2 FR 42 3 4CCI04 47 4 4CCI02 5 5 4MAT2 46 6 4MAT2 46 7 4CCI01 29 8 4CS01 39 wed 1 4CCI01 29 2 4MAT2 46 3 4CCI02 5 4 4CCI04 47 5 4MAT2 46 6 FR 42 7 4CCI03 21 8 4CS01 39 thu 1 4CS01 39 2 4MAT2 46 3 4CCI02 5 4 4MAT2 46 5 4CCI01 29 6 MC03 48 7 FR 42 8 4CCI03 21 fri 1 4CS01 39 2 4CCI02 5 3 4MAT2 46 4 4CCI03 21 5 4CCI04 47 6 4MAT2 46 7 FR 42 8 4CCI01 29 sat 1 MC03 48 2 4MAT2 46 3 4CCI04 47 4 4CCI03 21 5 4CCI01 29 6 4MAT2 46 7 4CS01 39 8 FR 42 I want to group all this so that hour comes as columns and the subject and faculty come as the values for this particular day and hour ... I want a format like this ... 1 2 3 4 5 6 7 8 mon 4CCI02 FR 5CS01 so on 5 42 29 Tue MC03 48 Wed so on Is it possible to get a DataFrame like that format ? What's the closest way to get the above mentioned view ? I am using pandas library in python for the DataFrames .
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50478838
tagged with: pandas

http://stackoverflow.com/q/50454716
upvote count: 3
has answer: http://stackoverflow.com/a/61876616
tagged with: chatterbot
has answer: http://stackoverflow.com/a/55534943
downvote count: 0
has answer: http://stackoverflow.com/a/56617271
favorite count: 0
has body: I have used: | + - lib | | | + - chatterbot | | | + - chatterbot_corpus + - main.py I am getting this error: Traceback (most recent call last): File "main.py", line 1, in &lt;module&gt; from lib.chatterbot.chatterbot import ChatBot File "D:\Workspace\PYTHON\phraser\lib\chatterbot\chatterbot\__init__.py", line 4, in &lt;module&gt; from .chatterbot import ChatBot File "D:\Workspace\PYTHON\phraser\lib\chatterbot\chatterbot\chatterbot.py", line 3, in &lt;module&gt; from .storage import StorageAdapter File "D:\Workspace\PYTHON\phraser\lib\chatterbot\chatterbot\storage\__init__.py", line 2, in &lt;module&gt; from .django_storage import DjangoStorageAdapter File "D:\Workspace\PYTHON\phraser\lib\chatterbot\chatterbot\storage\django_storage.py", line 1, in &lt;module&gt; from chatterbot.storage import StorageAdapter ModuleNotFoundError: No module named 'chatterbot' How can I solve this? I don't want to install the module in python.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87922946
has comment: http://stackoverflow.com/comment/87923039
has answer: http://stackoverflow.com/a/59190573
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57015717
has answer: http://stackoverflow.com/a/50454934
answer count: 6
has title: cannot properly import the chatterbot and its corpus
tagged with: python-install
score: 3

http://stackoverflow.com/comment/135982240
type: AnswerComment
has text: Sorry Krishnang, I'm late, yes you are correct the idea would be kind of one-versus-rest classifie logic, as you are mentioning but see my adjusted answer. What you are doing with your equation is creating the probability of 'other class' . Secondly, why am I multiplying the ratio of class probaiblites? See it for your self in the docs, https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.BernoulliNB.html (see method feature_log_prob , what you have is not the individidual class probabilities. Instead you have the conditional probabilities as stated in the documentation.
type: Comment
comment on: http://stackoverflow.com/a/62175164
score: 0

http://stackoverflow.com/q/50493225
type: Question
type: UnansweredQuestion
tagged with: pyinstaller
has title: Tkinter button doesn't work in exe file but do when the script is executed
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/88070931
has comment: http://stackoverflow.com/comment/88030735
tagged with: tkinter
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88005037
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88020139
has body: I'm new on this forum and on Tkinter and I need your help. I'm trying to create a GUI. My program works perfectly when I run the file with Python 2.7, but one of the button doesn't work when I create an exe file thanks to pyinstaller. My program is pretty simple : I select a camera in the list of the available ones, click on the "Display" button and the video frame from the selected camera should be displayed in a new window, thanks to opencv. The 'quit' button is here to quit the app. When I create an executable file thanks to pyinstaller, the window is displayed, I can select a camera, but the 'Display' button doesn't work. I really do not understand why, and no error message is displayed. Thanks a lot for your help import cv2 from Tkinter import * class Gui: def __init__(self): self.root = Tk() self.root.title("Rééducation posturale") self.root.config(background="#FA8066") self.root.rowconfigure(0, weight=1) self.root.rowconfigure(1, weight=1) self.root.columnconfigure(0, weight=1) self.root.columnconfigure(1, weight=1) self.boutonquitter=Button(self.root,text='Quit',font=("Helvetica", 10),command=self.Quitapp) self.boutonquitter.pack() self.boutonquitter.grid(row=1, column=1) camIndices=self.detectNumCameras() camIndex = [] for n in xrange(camIndices): camIndex.append(n) # LIST OF AVAILABLE CAMERA Label(self.root, text="Camera",font=("Helvetica", 10), bg="#ECA7A6").grid(row=0, column=0) self.cameraIndex = StringVar(self.root) self.cameraIndex.set("Choose camera") dropCamera = apply(OptionMenu, (self.root, self.cameraIndex) + tuple(camIndex)) dropCamera.grid(row=0, column=1) #CLICK TO DISPLAY self.bouton = Button(self.root, text="Display", font=("Helvetica", 10), command=self.checkCamera) self.bouton.pack() self.bouton.grid(row=1, column=0) imageFrame = Frame(self.root, width=600, height=400) self.display = Label(imageFrame) self.root.mainloop() # DETECT CAMERAS def detectNumCameras(self): ind = 0 while True: vc = cv2.VideoCapture(ind) if (vc.isOpened()): ind += …
tagged with: user-interface
has comment: http://stackoverflow.com/comment/88025536
favorite count: 0

http://stackoverflow.com/comment/88043048
type: Comment
type: QuestionComment
has text: -BlackVegetable That's a good place to start. Will do tonight, but my /home/pi/cigarbox.log captures the last comment in the script, "About to connect" when I remove the job command to put it in the background, e.g. &. So, I'm thinking that it runs and something gets messed up with what's returned by MQTT. Is there a way to execute the script using /etc/rc.local and then wait 10 seconds before putting it in the background and thereby fending off the the last line in rc.local which does an exit 0.....which may be blocking the return from MQTT? Anyway, back to the basics tonight. Thanks!
score: 0
comment on: http://stackoverflow.com/q/50495330

http://stackoverflow.com/comment/88056136
has text: Sure: `apply()` to create the ranges, `stack()` to flatten and `join()` to bring it back into the original `df`.
comment on: http://stackoverflow.com/a/50521985
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87957546
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50469989
has text: The good thing about Python is you can always put those two lines of code in a file and test it yourself. Or even better/faster, throw it into [IPython](https://ipython.org/). Asking on SO however takes time and nowadays you risk a lot of downvotes for questions not reusable to others. ;)
type: Comment

http://stackoverflow.com/comment/87962320
comment on: http://stackoverflow.com/q/50474314
type: Comment
type: QuestionComment
has text: Use another REST endpoint that takes parameters and have your Javascript make REST calls to fetch the response.
score: 0

http://stackoverflow.com/comment/88082749
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50534113
has text: `Debugger2` is a dispatch-only interface?

http://stackoverflow.com/comment/87912286
type: QuestionComment
has text: When we are using newDate = datetime.datetime.strptime(abc, "%Y-%m-%d %H:%M:%S") then its showing date as per required
comment on: http://stackoverflow.com/q/50445140
score: 0
type: Comment

http://stackoverflow.com/comment/87884477
comment on: http://stackoverflow.com/q/50425700
type: QuestionComment
has text: It may actually be that one of your files listed in the CSV isn't an image / isn't properly encoded, hence `tf.read_file()` returning a string (starting with "`\"\"\"\n flickr.p`" cf. your trace) which can't be decoded as an image.
type: Comment
score: 0

http://stackoverflow.com/q/50405430
tagged with: python
has body: I have written the following code to extract zip files in a directory and a delete a particular excel file in the extracted directory : def extractZipFiles(dest_directory): "This function extracts zip files in the destination directory for further processing" fileFullPath = dest_directory + '\\' extractedDirList = list() for file in os.listdir(dest_directory): dn = fileFullPath+file dn = re.sub(r'\.zip$', "", fileFullPath+file) #remove the trailing .zip. extractedDirList.append(dn) zf = zipfile.ZipFile(fileFullPath+file, mode='r') zf.extractall(dn) # extract the contents of that zip to the empty directory zf.close() return extractedDirList def removeSelectedReports(extractedDirList): "This function removes the selected reports from extracted directory" for i in range(len(extractedDirList)): for filename in os.listdir(extractedDirList[i]): if filename.startswith("ABC_8"): logger.info("File to be removed::"+filename) fullPathName= "%s/%s" % (extractedDirList[i],filename) os.remove(fullPathName) return extractedDirList = extractZipFiles(attributionRptDestDir) logger.info("ZIP FILES EXTRACTED:"+str(extractedDirList)) removeSelectedReports(extractedDirList) I am getting the following intermittent issue even though I have closed the zip file handler. [WinError 32] The process cannot access the file because it is being used by another process: '\\\\share\\Workingdirectory\\report.20180517.zip' Can you please help resolve this issue
has answer: http://stackoverflow.com/a/50405554
has comment: http://stackoverflow.com/comment/87899199
score: 3
upvote count: 3
downvote count: 0
answer count: 1
has title: WinError 32 :The process cannot access the file because it is being used by another process
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87842917

scikit-learn
tags question: http://stackoverflow.com/q/50531995
tags question: http://stackoverflow.com/q/50507456
tags question: http://stackoverflow.com/q/50537651
tags question: http://stackoverflow.com/q/50414823
tags question: http://stackoverflow.com/q/50394099
tags question: http://stackoverflow.com/q/50457331
tags question: http://stackoverflow.com/q/50441669
tags question: http://stackoverflow.com/q/50387302
tags question: http://stackoverflow.com/q/50529050
tags question: http://stackoverflow.com/q/50480156
tags question: http://stackoverflow.com/q/50402758
tag name: scikit-learn
tags question: http://stackoverflow.com/q/50527117
tags question: http://stackoverflow.com/q/50410659
tags question: http://stackoverflow.com/q/50410037
tags question: http://stackoverflow.com/q/50436634
tags question: http://stackoverflow.com/q/50538626
tags question: http://stackoverflow.com/q/50452300
tags question: http://stackoverflow.com/q/50408327
tags question: http://stackoverflow.com/q/50387089
tags question: http://stackoverflow.com/q/50404893
type: Tag
tags question: http://stackoverflow.com/q/50460930
tags question: http://stackoverflow.com/q/50454871
tags question: http://stackoverflow.com/q/50509177
tags question: http://stackoverflow.com/q/50433130
tags question: http://stackoverflow.com/q/50506566
tags question: http://stackoverflow.com/q/50473381
tags question: http://stackoverflow.com/q/50483601
tags question: http://stackoverflow.com/q/50499893
tags question: http://stackoverflow.com/q/50392783
tags question: http://stackoverflow.com/q/50484278
tags question: http://stackoverflow.com/q/50425068
tags question: http://stackoverflow.com/q/50515740
tags question: http://stackoverflow.com/q/50506065
tags question: http://stackoverflow.com/q/50431164
tags question: http://stackoverflow.com/q/50428825
tags question: http://stackoverflow.com/q/50526898
tags question: http://stackoverflow.com/q/50515476
tags question: http://stackoverflow.com/q/50426857
tags question: http://stackoverflow.com/q/50518706
tags question: http://stackoverflow.com/q/50523930
tags question: http://stackoverflow.com/q/50478758
tags question: http://stackoverflow.com/q/50520310
tags question: http://stackoverflow.com/q/50538563
tags question: http://stackoverflow.com/q/50494956
tags question: http://stackoverflow.com/q/50484488
tags question: http://stackoverflow.com/q/50446257
tags question: http://stackoverflow.com/q/50533659
tags question: http://stackoverflow.com/q/50502999
tags question: http://stackoverflow.com/q/50442427
tags question: http://stackoverflow.com/q/50412872
tags question: http://stackoverflow.com/q/50406096
tags question: http://stackoverflow.com/q/50499539
tags question: http://stackoverflow.com/q/50460115
tags question: http://stackoverflow.com/q/50446132

http://stackoverflow.com/a/50410587
answers question: http://stackoverflow.com/q/50410304
downvote count: 0
type: Answer
has body: I will recommend you should use panda. I haven't run this script but something like this should work. import panda as pd import csv frame = pd.read_csv('my.csv') df=frame'date','data2' with open('test2.csv', 'a', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerow(df)
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87836568

http://stackoverflow.com/a/50486126
type: Answer
has body: Use apply with iloc: df = df.groupby('id', group_keys=False).apply(lambda x:x.iloc[1:]) #also working, not sure if generally #df = df.groupby('id', group_keys=False).apply(lambda x:x[1:]) print (df) id values 1 1 6 2 1 3 4 2 6 5 2 3 6 2 9 Or duplicated with boolean indexing: df = df[df['id'].duplicated()] print (df) id values 1 1 6 2 1 3 4 2 6 5 2 3 6 2 9 Detail: print (df['id'].duplicated()) 0 False 1 True 2 True 3 False 4 True 5 True 6 True Name: id, dtype: bool
has comment: http://stackoverflow.com/comment/87985037
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87985061
answers question: http://stackoverflow.com/q/50486098
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50486098

http://stackoverflow.com/comment/87898997
type: Comment
has text: Hey Sorry, that was a mistake. I edited my question with command line argument
score: 0
comment on: http://stackoverflow.com/q/50442423
type: QuestionComment

http://stackoverflow.com/q/50400329
tagged with: python-datetime
answer count: 1
has comment: http://stackoverflow.com/comment/87816789
linked to: http://stackoverflow.com/q/10048249
favorite count: 0
has answer: http://stackoverflow.com/a/50400745
type: Question
accepted answer: http://stackoverflow.com/a/50400745
has body: For my script I need to use Python 2.6 with only the standard library. I am trying to write a script that walks a logs directory that has a condition defined that only matches the logs that have the appropriate timestamp. The timestamp I am using is derived from the filename. I do not want to use the OS timestamps because there are times the files get copied off to a different directory to prevent them from being overwritten and this changes the file modified time. A new file gets created every 200MB. The timestamp on the filename is the time the file was created and represents the oldest log entry in the file. import datetime # One event might span multiple log files. call_start = datetime.datetime(2018, 5, 15, 5, 25, 9) call_stop = datetime.datetime(2018, 5, 15, 5, 37, 38) # Timestamp values of file generated from file's naming convention t1 = datetime.datetime(2018, 5, 15, 4, 48, 16) t2 = datetime.datetime(2018, 5, 15, 5, 3, 53) t3 = datetime.datetime(2018, 5, 15, 5, 19, 14) t4 = datetime.datetime(2018, 5, 15, 5, 35) t5 = datetime.datetime(2018, 5, 15, 5, 49, 19) file_times = [t1, t2, t3, t4, t5] matching_times = [] for ftime in file_times: # Logic I can't figure out if scratches_head: matching_times.append(ftime) # I would expect the matching_times list to contain t3 and t4 Edit Clarification from the comments: t3 is a file that was created at 5:19:14am. The call_start is the first entry I would see in the log. It begins at 5:25:09am. Since t4 didn't get created until 5:35:00am, the call_start has to be in t3. The call_stop is the last log entry I want to find. I would be in t4 because t5 was created at 5:49:19am.
has comment: http://stackoverflow.com/comment/87816814
tagged with: python
has title: Python 2: Compare a timestamp between two points in time
has comment: http://stackoverflow.com/comment/87816660
upvote count: 2
has comment: http://stackoverflow.com/comment/87816895
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87816659
linked to: http://stackoverflow.com/q/325933

http://stackoverflow.com/a/50436578
answers question: http://stackoverflow.com/q/50436267
type: Answer
has body: Probably the fastest would be to allocate zeros and then set the ones: &gt;&gt;&gt; def f_preall(a): ... m, n = a.size, a.max()+1 ... out = np.zeros((m, n)) ... out[np.arange(m), a] = 1 ... return out ... &gt;&gt;&gt; from timeit import timeit &gt;&gt;&gt; &gt;&gt;&gt; a = np.random.randint(0, 10, (10,)) &gt;&gt;&gt; timeit(lambda: f_preall(a), number=10000) 0.04905537283048034 &gt;&gt;&gt; timeit(lambda: np.eye(a.max()+1)[a], number=10000) 0.09359440207481384 &gt;&gt;&gt; &gt;&gt;&gt; a = np.random.randint(0, 100, (100,)) &gt;&gt;&gt; timeit(lambda: f_preall(a), number=10000) 0.10055362526327372 &gt;&gt;&gt; timeit(lambda: np.eye(a.max()+1)[a], number=10000) 0.16951417503878474
downvote count: 0
upvote count: 3
score: 3

http://stackoverflow.com/a/50498807
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88051458
has body: The shape of the data you feed to your placeholders is inconsistent with the shape of the placeholders. inputs = tf.placeholder('float', [None, 2], name='input') vs inp = [[0.1], [0.2], [1.0],[1.1]] Either change your inputs shape to be [None, 1] or add a second value for each entry of inp.
has comment: http://stackoverflow.com/comment/88010648
answers question: http://stackoverflow.com/q/50498755
type: Answer

http://stackoverflow.com/comment/127724689
type: AnswerComment
comment on: http://stackoverflow.com/a/71469936
type: Comment
has text: I use `tox`, and because `tox.ini` does not support multi-line install commands, keyring was too much of a pain to use. `PIP_EXTRA_INDEX_URL` was the way to go.
score: 0

http://stackoverflow.com/a/50416076
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50415989
score: 2
answers question: http://stackoverflow.com/q/50415989
has body: Not sure what AutoMap does. Inspect may help. not sure from sqlalchemy.inspection import inspect relations = inspect(Base.classes.&lt;classname&gt;).relationships.items()
upvote count: 2
has comment: http://stackoverflow.com/comment/87858124
downvote count: 0

http://stackoverflow.com/q/50412552
downvote count: 0
score: 1
upvote count: 1
tagged with: kivy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50412724
accepted answer: http://stackoverflow.com/a/50412724
tagged with: python-3.x
tagged with: kivy-language
has body: I'm trying to call a custom widget method from its ids. But I received an AttributeError: 'LabelBox' object has no attribute 'change_first_text'. As a simple as possible working example can be found here with the PanelApp.py file: from kivy.app import App from kivy.uix.tabbedpanel import TabbedPanel from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder Builder.load_file("panel.kv") class LabelBox(BoxLayout): def __init__(self, *args, **kwargs): super(LabelBox, self).__init__(*args, **kwargs) def change_first_text(self, text): self.ids.first.text = text class ButtonList(BoxLayout): pass class Test(TabbedPanel): pass class TabbedPanelApp(App): def build(self): self.test = Test() self.btn_list = ButtonList() self.vbox = BoxLayout(orientation="vertical") self.vbox.add_widget(self.btn_list) self.vbox.add_widget(self.test) return self.vbox def change_first(self, value): print("Button clicked and new value is: '{}'".format(value)) self.test.ids.lbs.change_first_text(value) if __name__ == '__main__': TabbedPanelApp().run() and the panel.kv file: &lt;ButtonList@ButtonList&gt;: orientation: "horizontal" Button: text: "change fisrt to me" on_press: app.change_first(self.text) Button: text: "change two to me" &lt;LabelBox@BoxLayout&gt;: Label: id: first text: "first" Label: id: two text: "two" &lt;Test&gt;: size_hint: .5, .5 pos_hint: {'center_x': .5, 'center_y': .5} do_default_tab: False TabbedPanelItem: text: 'first tab' LabelBox: id: lbs Calling the script cause a runtime error that I can't understand. Have you any clue on how to manage such event callback through the application?
answer count: 1
tagged with: python
type: AnsweredQuestion
has title: Kivy callback custom widget call from ids raise AttributeError

http://stackoverflow.com/comment/88056942
score: 0
type: QuestionComment
type: Comment
has text: Umm, dates aren't floats. Either tell it to load column 0 as a date, tell it to skip column 0, or use pandas.
comment on: http://stackoverflow.com/q/50522437

http://stackoverflow.com/a/50464774
score: 104
type: Answer
has comment: http://stackoverflow.com/comment/87945347
downvote count: 0
answers question: http://stackoverflow.com/q/50444988
upvote count: 104
has body: We sorted by just updating to celery==4.1.1 it seems the latest release for the 4.1.X sorted out the module name change on kombu

http://stackoverflow.com/comment/117527769
type: QuestionComment
has text: This problem has been reported here https://github.com/tensorflow/tensorflow/issues/19982
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50399547

http://stackoverflow.com/comment/88014240
has text: You said 'removing the last microsecond digit, and removing the last :'. This may be simple enough.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50500512

http://stackoverflow.com/q/50529050
answer count: 1
has body: I have a dataset consisting of around 500 different paragraphs. For each paragraph, I am trying to see whether there is a link to any of the other paragraphs. Based on this I've created paragraph pairs. I previously tried to approach this problem as a binary issues (0 or 1, is there a link or not), but I now want to try ranking (assigning a probability to each paragraph pair). My issue is: How do I split out my test and train set randomly but keep all paragraph pairs for each paragraph in the same set? For example, for paragraph 1, I want all associated pairs (1-2, 1-3, 1-4, 1-5...1-500) in either the test or train set. My ranking will not work if half the pairs are in the training set for example, since then the ranking for the test set will be missing some pairs... Format Paragraph A | Paragraph B | Label | Features... Paragraph 1 | Paragraph 4 | 1 | ... Paragraph 2 | Paragraph 6 | 1 | ... Paragraph 6 | Paragraph 8 | 0 | ... Paragraph 10 | Paragraph 2 | 1 | ... I am using the sklearn train_test_split: import pandas as pd from sklearn.model_selection import train_test_split feature_headers = ['tfidf_cosine', 'count_vec_cosine', 'lda_50topics_cosine', 'lda_200topics_cosine'] target_header = ['label'] train_x, test_x, train_y, test_y = train_test_split(result[feature_headers], result[target_header], train_size=0.7)
upvote count: 1
tagged with: scikit-learn
tagged with: train-test-split
has title: Creating test & train set while keeping certain items together in one set
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50529193
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88069897
tagged with: python
score: 0
tagged with: pandas

http://stackoverflow.com/q/50393604
has title: Iterating through the pandas df rows and do an operation
has comment: http://stackoverflow.com/comment/87806276
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50394010
has comment: http://stackoverflow.com/comment/87803312
has answer: http://stackoverflow.com/a/50395490
accepted answer: http://stackoverflow.com/a/50395490
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87803219
upvote count: 1
has comment: http://stackoverflow.com/comment/87805298
has comment: http://stackoverflow.com/comment/87806706
downvote count: 0
possible better answer: http://stackoverflow.com/a/50394010
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87803660
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87805371
has body: I have a pandas dataframe which looks as below Date SKU Balance 0 1/1/2017 X1 8 1 1/1/2017 X2 45 2 1/1/2017 X1 47 3 1/1/2017 X2 16 4 2/1/2017 X1 14 5 2/1/2017 X2 67 6 2/1/2017 X2 9 8 2/1/2017 X1 66 9 2/1/2017 X1 158 My first goal is to generate multiple dataframe filtered by every single day for which I coded df_1stjan = df.query("Date == \"1/1/2017\"") And I got the below result Date SKU Balance 0 1/1/2017 X1 8 1 1/1/2017 X2 45 2 1/1/2017 X1 47 3 1/1/2017 X2 16 My second goal is to groupby SKU's and I coded df_1stjan_uSKU = df_1stjan.groupby(['SKU','Date'], \ as_index=False).agg({'Balance':'sum'}) And I got the below result Date SKU Balance 0 1/1/2017 X1 55 1 1/1/2017 X2 61 At the moment I could only code to generate df for only one date at a time a But I need to write a function or loop to automate it for all the days of 2017. Note the Date column has string dtype
has comment: http://stackoverflow.com/comment/87804671
tagged with: pandas
score: 1
tagged with: group-by

http://stackoverflow.com/q/50472447
has answer: http://stackoverflow.com/a/50472680
tagged with: data-cleaning
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/87958530
possible better answer: http://stackoverflow.com/a/50473148
has answer: http://stackoverflow.com/a/50473153
has comment: http://stackoverflow.com/comment/87958689
has comment: http://stackoverflow.com/comment/87958557
favorite count: 0
has comment: http://stackoverflow.com/comment/87958616
type: Question
accepted answer: http://stackoverflow.com/a/50473162
has answer: http://stackoverflow.com/a/50473162
tagged with: python
has answer: http://stackoverflow.com/a/50473310
has answer: http://stackoverflow.com/a/50473914
has answer: http://stackoverflow.com/a/50473037
has answer: http://stackoverflow.com/a/50473148
has comment: http://stackoverflow.com/comment/87959429
has body: How can I convert the dataset a | a b c d s | e f g h f | i j k l to a | a | b | c | d s | e | f | g | h f | i | j | k | l
type: AnsweredQuestion
score: 3
tagged with: split
has title: Split a column of values delimited by a space into separate columns for each value in python
has comment: http://stackoverflow.com/comment/87959058
tagged with: pandas
upvote count: 3

http://stackoverflow.com/comment/87887241
has text: before I suggest anything... do you want really to create an album when creating creating a song. I mean a song might not have an album, like a single
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50433944
score: 0

http://stackoverflow.com/comment/87802128
score: 0
has text: It says `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/`. But I have install wxPython
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50393065

http://stackoverflow.com/comment/87914254
comment on: http://stackoverflow.com/a/50437148
score: 1
type: Comment
has text: @ilvthsgm Each iteration of `find_paths` will get its own version of `count`. So when we increment `count += 1` it is only in scope in the call of the function. After looking at all the children it will represent how many nodes we visited after this one before coming back.
type: AnswerComment

http://stackoverflow.com/comment/87917732
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50452295
score: 0
has text: A quick google led me to https://developers.google.com/api-client-library/python/start/installation, perhaps that'd be what you are looking for?

http://stackoverflow.com/a/50540188
has body: adding export PYTHONPATH="." to bash_profile solved the issue
score: 0
answers question: http://stackoverflow.com/q/50539314
type: Answer

http://stackoverflow.com/comment/87900172
type: Comment
type: QuestionComment
score: 0
has text: Yes, only one occurence in each item
comment on: http://stackoverflow.com/q/50443117

http://stackoverflow.com/a/50428631
downvote count: 1
has body: Given that an IP has to contain four different parts, you can use recursion to generate a list of possibilities with groupings: s = "19216811" def ips(d, current = []): if not d: yield current else: for i in range(1, len(s)): yield from ips(d[i:], current + [d[:i]]) final_ips = list(filter(lambda x:all(len(i) &gt; 1 for i in x[:2]), [i for i in ips(s) if len(list(filter(None, i))) == 4])) new_ips = ['.'.join(a) for i, a in enumerate(final_ips) if a not in final_ips[:i]] Output: ['19.21.6.811', '19.21.68.11', '19.21.681.1', '19.216.8.11', '19.216.81.1', '19.2168.1.1', '192.16.8.11', '192.16.81.1', '192.168.1.1', '1921.68.1.1']
type: Answer
score: -1
answers question: http://stackoverflow.com/q/50428376
upvote count: 0

http://stackoverflow.com/a/63822728
upvote count: 12
type: Answer
answers question: http://stackoverflow.com/q/50473381
has body: The results of OneHotEncoder() and LabelBinarizer() are almost similar [there might be differences in the default output type. However, to the best of my understanding, LabelBinarizer() should ideally be used for response variables and OneHotEncoder() should be used for feature variables. Although, at present, I am not sure why do we need different encoders for similar tasks. Any pointer in this direction would be appreciated. A quick summary: LabelEncoder – for labels(response variable) coding 1,2,3… [implies order] OrdinalEncoder – for features coding 1,2,3 … [implies order] Label Binarizer – for response variable, coding 0 &amp; 1 [ creating multiple dummy columns] OneHotEncoder - for feature variables, coding 0 &amp; 1 [ creating multiple dummy columns] A quick example can be found here.
score: 12
downvote count: 0

http://stackoverflow.com/q/50421361
has comment: http://stackoverflow.com/comment/87857907
tagged with: python
downvote count: 4
has answer: http://stackoverflow.com/a/50421666
has comment: http://stackoverflow.com/comment/87857973
upvote count: 2
has comment: http://stackoverflow.com/comment/87858597
score: -2
has comment: http://stackoverflow.com/comment/87858027
answer count: 1
has title: How do I randomly generate a variable name?
tagged with: variables
favorite count: 0
accepted answer: http://stackoverflow.com/a/50421666
type: Question
type: AnsweredQuestion
has body: In python, I need to know how to randomly generate a variable name for a list, but I am unsure how to go about doing this. Right now, I have something like this written. name = random.randint(0,9) name = [a,b,c,d] I know this will just change the 'name' variable to be the list. What I want to do is get my randomly generated number to be assigned as a variable to the list. How do I do this? I'm fairly new to python as well, so if there is a better way of doing this, I would be open to suggestions.
has comment: http://stackoverflow.com/comment/87857970
tagged with: list
has comment: http://stackoverflow.com/comment/87857918

http://stackoverflow.com/a/50465610
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87949593
has body: The assumption that append mode would append to the existing stream is wrong. Instead it concatenates a new stream to the existing gzip file. When decompressing these are then concatenated transparently as if you had compressed a single file. But each stream contains its own header and footer and those add up. Inspecting your file reveals % hexdump -C output.gz|head -n5 00000000 1f 8b 08 08 2e e7 03 5b 02 ff 6f 75 74 70 75 74 |.......[..output| 00000010 00 33 e0 02 00 12 cd 4a 7e 02 00 00 00 1f 8b 08 |.3.....J~.......| 00000020 08 2e e7 03 5b 02 ff 6f 75 74 70 75 74 00 33 e4 |....[..output.3.| 00000030 02 00 53 fc 51 67 02 00 00 00 1f 8b 08 08 2e e7 |..S.Qg..........| 00000040 03 5b 02 ff 6f 75 74 70 75 74 00 33 e2 02 00 90 |.[..output.3....| Note the repetition of the magic number 1f 8b, which marks the beginning of a new stream. In general it's usually a bad idea to repeatedly open a file in append mode in a loop. Instead open the file once for writing and write the contents in a loop: with gzip.open('output.gz', 'wb') as f: for idx in range(100000): line = (str(idx) + '\n').encode() f.write(line) The resulting file is around 200 kiB, compared to the original 3 MiB.
type: Answer
score: 3
answers question: http://stackoverflow.com/q/50464559
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50464559

http://stackoverflow.com/q/50476771
tagged with: python-3.x
answer count: 0
tagged with: spacy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88018443
has comment: http://stackoverflow.com/comment/88018368
has comment: http://stackoverflow.com/comment/87967233
has comment: http://stackoverflow.com/comment/88042321
duplicate of: http://stackoverflow.com/q/20082730
has comment: http://stackoverflow.com/comment/88045792
has comment: http://stackoverflow.com/comment/88043018
duplicate of: http://stackoverflow.com/q/36250353
score: 0
linked to: http://stackoverflow.com/q/36250353
has title: bad magic number error while installing spacy
upvote count: 1
downvote count: 1
tagged with: python
has body: I am getting this error when I try to install the english model for spacy ImportError: bad magic number in 'random': b'\x03\xf3\r\n' Any help would be seriously appreciated This is the traceback error: Traceback (most recent call last): File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 183, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 142, in _get_module_details return _get_module_details(pkg_main_name, error) File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 109, in _get_module_details __import__(pkg_name) File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\spacy\__init__.py", line 4, in &lt;module&gt; from .cli.info import info as cli_info File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\spacy\cli\__init__.py", line 1, in &lt;module&gt; from .download import download File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\spacy\cli\download.py", line 10, in &lt;module&gt; from .link import link File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\spacy\cli\link.py", line 8, in &lt;module&gt; from ..compat import symlink_to, path2str File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\spacy\compat.py", line 9, in &lt;module&gt; from thinc.neural.util import copy_array File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\thinc\neural\__init__.py", line 1, in &lt;module&gt; from ._classes.model import Model File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\thinc\neural\_classes\model.py", line 2, in &lt;module&gt; from numpy import prod File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\__init__.py", line 142, in &lt;module&gt; from .…
has comment: http://stackoverflow.com/comment/87967212
tagged with: nlp
favorite count: 0
type: Question

http://stackoverflow.com/comment/88004633
has text: @A.Kot The x-axis in the plot is sorted by date (see the figure in the question) so hasn't that already been done by pandas?
type: QuestionComment
comment on: http://stackoverflow.com/q/50495848
score: 0
type: Comment

http://stackoverflow.com/comment/87791771
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50387354
has text: Which Java / JDK version do you use?
type: Comment

http://stackoverflow.com/comment/88079540
has text: Actually, "rbf" kernel improves with more data. Another interesting thing would be to try the "poly" kernel and trying different degrees starting from 3. For smaller datasets, maybe polynomial kernels would be better.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50533717
type: Comment

http://stackoverflow.com/comment/88081769
type: QuestionComment
has text: An alternative thing to try is to specify the class_weight parameter of the classifier and pass to this parameter a dictionary with a higher weight for the minority class than for the majority class.
comment on: http://stackoverflow.com/q/50533659
score: 0
type: Comment

http://stackoverflow.com/comment/88051309
comment on: http://stackoverflow.com/q/50519298
has text: If it's a professional engagement, it's bad. Two things would be better for such large calculations. The first thing is binary data (CSV is stupid with so many numbers). The second thing is to increase the computing power by leaving Python Interpréter, so write a code for calculations in C or Assembler (unfortunately Assembler has a non-transferable machine code after compiling it)...
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87835577
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50410098
has text: Well that's pretty neat
type: Comment

http://stackoverflow.com/a/50441657
downvote count: 0
has body: You can do that with something like this: with open('file1', 'rU') as f: for line in f: # split the line (only once) on a comma value, rest = line.split(',', 1) # join the line back together, but change the 1/0 to true/false print(','.join(('true' if int(value) else 'false', rest))) Results: false,@rodriigoCabrera y tu vaso tu silla y tu baÃ±o true,Mexican rival demands vote recount: The leader of Mexico's leftist Party of the Democratic Revolution, Andres Ma... false,Queretaro 0 - 3 Morelia Tarjeta amarilla a Carlos AdriÃ¡n Morales Higuera
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50441612

http://stackoverflow.com/comment/87896939
comment on: http://stackoverflow.com/a/50441197
score: 1
type: Comment
type: AnswerComment
has text: What makes you think `VARCHAR(50)` will be long enough? That seems entirely arbitrary. [Windows file paths can be at least 260 characters long](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx), and "The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters".

http://stackoverflow.com/a/50426619
has body: Like was said in the comments, None is a null value. It is useful when writing a code where "if" statements require a value to proceed.... import numpy x=numpy.array([1.0,2.0,3.0]) if array_ is None: pass else: x+=array_**2 where array_ is a numpy array that was assigned a value from arguments to the command line or gathered from a file (if the file exists). It is used in the code if present and is not used if not assigned a value (tends to be not crucial for the code to work).
type: Answer
answers question: http://stackoverflow.com/q/50426417
score: 0

http://stackoverflow.com/q/50457731
type: AnsweredQuestion
score: 0
has body: My link looks like this: &lt;link rel="stylesheet" type="text/css" href="{% static 'css/background.css' %}"&gt; This is fine because it gets the path I want which is href="/static/css/background.css". I use {% load static}. I have django.contrib.staticfiles in my INSTALLED_APPS. This is some more relevant info on my settings.py: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] But I'm pretty sure this is right too. My problem is that static/css/background.css cannot be found by my local server. I know this because http://localhost:8000/static/css/background.css gives me a 404 error. I don't know why this is the case because this is my project file path: Project Project src static css background.css
has comment: http://stackoverflow.com/comment/87929079
has title: Django: my css static path does not exist
has comment: http://stackoverflow.com/comment/87929216
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87929250
accepted answer: http://stackoverflow.com/a/50498089
possible better answer: http://stackoverflow.com/a/50457755
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50498089
tagged with: css
has answer: http://stackoverflow.com/a/50457755
has comment: http://stackoverflow.com/comment/87929166

http://stackoverflow.com/a/50609040
score: 2
upvote count: 2
downvote count: 0
has body: I resolved this by reading more about apache-beam and figuring out that I had to use the ParDo function to split the job between my resources, in the ParDo I call my DoFn function which takes in an element and does all the processing needed for it and yields a dic. refer to this post Apache Beam: How To Simultaneously Create Many PCollections That Undergo Same PTransform? class ExtractMetadata(beam.DoFn): def process(self, element): &quot;&quot;&quot; Takes in a blobName, fetches the blob and its values and returns a dictionary of values &quot;&quot;&quot; metadata = element.metadata if metadata is not None: event_count = int(metadata['count']) else: event_count = None event_type = self.determine_event_type(element.id) cluster = self.determine_cluster(element.id) customer = self.determine_customer(element) # date = datetime.strptime(element.time_created, '%a, %d %b %Y %H:%M:%S') # date = date.isoformat() dic = { 'blob_name': element.name, 'event_path': element.path, 'size': int(element.size), 'time_of_creation': element.time_created.isoformat(), 'event_count': event_count, 'event_type': event_type, 'cluster': cluster, 'customer': customer } yield dic
type: Answer
answers question: http://stackoverflow.com/q/50515274

http://stackoverflow.com/q/50475611
tagged with: autobahn
has body: I'm using the older Autobahn|Python subclassing API so that I can include ticket authentication for connecting to a WAMP bus. When I run all parts of the environment on my local machine, everything works fine and dandy - connection, challenge, authentication, publication of messages - but when I move over to my testing environment on an external server, the challenge for authentication doesn't seem to happen. My subclass looks like this: class ClientSession(ApplicationSession): def onConnect(self): log("Session connected") self.join(self.config.realm, [u"ticket"], ROLE_ID) def onChallenge(self, challenge): log("Authentication challenged") if challenge.method == u"ticket": return TICKET @inlineCallbacks def onJoin(session, details): log("Connected to WAMP") while True: session.publish(u"topic", message) yield(60) if __name__ == "__main__": RUNNER = ApplicationSession(url=WAMP_URL, realm=u"my-realm") RUNNER.run(ClientSession) When I run the full application on my computer, it goes through all of the steps perfectly fine, but when I run it on my test server that has a slightly different configuration, the only output that is logged is from the onConnect method. I need the authentication to be able to publish messages. Help!
has title: How to force WAMP Ticket Authentication?
tagged with: python
score: 0
tagged with: twisted
has comment: http://stackoverflow.com/comment/87998214
has comment: http://stackoverflow.com/comment/87965590
type: Question
tagged with: wamp-protocol
answer count: 0
has comment: http://stackoverflow.com/comment/87995702
type: UnansweredQuestion

http://stackoverflow.com/q/50518889
tagged with: python
favorite count: 0
type: Question
tagged with: django-templates
has comment: http://stackoverflow.com/comment/88051104
has comment: http://stackoverflow.com/comment/88051114
downvote count: 0
has title: How do you display a views.py's variable linked to annotated queryset in a django template?
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/88051141
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88051125
accepted answer: http://stackoverflow.com/a/50519373
has comment: http://stackoverflow.com/comment/88050445
score: 1
has body: How do you display a views.py's variable linked to annotated queryset in a django template? I know the annotated queryset returns correct data when I printed it out, but somehow the template for loop is not retrieving the data on the html page. Can someone please advise me on how to fix this issue? Thanks. VIEWS.PY from django.shortcuts import render from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from myapp.models import Pastry from myapp.forms import PastryForm from django.db.models import F This line ps = Pastry.objects.values('pastry').annotate(total=Count('pastry')) returns correct data: {'pastry': 'Brownie', 'total': 1} {'pastry': 'Cake', 'total': 1} {'pastry': 'Cupcake', 'total': 1} {'pastry': 'Fruit Tart', 'total': 1} {'pastry': 'Muffin', 'total': 2} class PollsListView(ListView): model = Pastry def get_queryset(self): return Pastry.objects.all() class PollsDetailView(DetailView): model = Pastry class PollsCreateView(CreateView): success_url = reverse_lazy('pastry_list') form_class = PastryForm model = Pastry class PollsUpdateView(UpdateView): success_url = reverse_lazy('pastry_list') form_class = PastryForm model = Pastry class PollsDeleteView(DeleteView): model = Pastry success_url = reverse_lazy('pastry_list') pastry_list.html (template) {% extends "base.html" %} {% block content %} New Poll Voting for the favorite pastry Somehow this code here is not displaying any data. {% for p in ps %} {% for k, v in p.items %} {{k}}{{v}} {% endfor %} {% endfor %} {% for pastry in pastry_list %} {{ pastry.pastry }} {% endfor %} {% endblock %}
has comment: http://stackoverflow.com/comment/88051080
answer count: 1
has answer: http://stackoverflow.com/a/50519373

http://stackoverflow.com/comment/88105451
comment on: http://stackoverflow.com/q/50536129
score: 0
type: Comment
has text: @Dan Loewenherz thanks for the edit!
type: QuestionComment

http://stackoverflow.com/q/50451884
has answer: http://stackoverflow.com/a/50453759
accepted answer: http://stackoverflow.com/a/50453759
tagged with: curve-fitting
tagged with: python
has answer: http://stackoverflow.com/a/50739186
has comment: http://stackoverflow.com/comment/87925283
score: 2
type: AnsweredQuestion
has body: I am trying to characterize the spreading of carbon isotopes caused by nuclear test in the 70's in an ocean model. The atmospheric signal is a strong spike, which will be carried to depth with the ocean currents (deeper currents are much slower). My goal is to detect the onset of the rise in concentration and the rate of increase at various depth levels. I assume that the oceanic concentration of carbon isotopes behaves like a piecewise linear function with 3 segments: A constant initial value (b) up until time (t_0) A linear increase in concentrations from time (t_0) to (t_1) with the rate m1. A linear decrease in concentration after time(t_1) with the rate m2 I am representing the function using this code in python: import numpy as np import matplotlib.pyplot as plt import scipy.optimize as sio def piecewise_linear( t, t0, t1, b, m1, m2 ): condlist = [ t &lt; t0, (t &gt;= t0 ) &amp; ( t &lt; t1 ), t &gt;= t1 ] funclist = [lambda t: b, lambda t: b + m1 * ( t - t0 ), lambda t: b + m1 * ( t - t0 ) + m2 * ( t - t1 ) ] return np.piecewise( t, condlist, funclist ) For a given time array t I want to be able to fit two 'types' of this function: A full 3-segment line, which is representative of the upper ocean, where the signal propagates fast and the spike is fully captured. A special case, where at the end of the time series the concentration has not peaked (this would represent the signal in the deep ocean, where it takes a long time to propagate the signal) As example t = np.arange( 0, 15, 0.1 ) y_full = piecewise_linear( t, 5, 10, 2, 2, -4 ) y_cut = piecewise_linear( t, 5, 15, 2, 2, -4 ) plt.plot( t, y_full ) plt.plot( t, y_cut ) plt.legend( [ 'surface', 'deep ocean' ] ) For the first case I am getting good results, when I try to fit the function to the signal after adding some random noise: noise = np.random.normal( 0, 1, len( y_full ) ) * 1 y = y_full yy = y_full + noise bounds = ( [ 0, 0, 0, 0, -np.inf ], [ np.inf, np.inf, np.inf, np.inf, 0 ] ) fit,_ = sio.curve_fi…
has answer: http://stackoverflow.com/a/50464158
answer count: 3
possible better answer: http://stackoverflow.com/a/50464158
downvote count: 0
has title: Is there a way to add a dependency between parameters for scipy.optimize.curve_fit
has comment: http://stackoverflow.com/comment/87922776
tagged with: scipy
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/a/50419610
accepted answer of: http://stackoverflow.com/q/50418779
type: Answer
answers question: http://stackoverflow.com/q/50418779
score: 0
has body: Your programFile is a string. Strings are immutable. If you want to update it you'll have to collect it back after being processed through the multiValuesChange() function, so do: programFile = multiValuesChange(programFile, valuesDic)
type: AcceptedAnswer

http://stackoverflow.com/a/50527146
answers question: http://stackoverflow.com/q/50526926
score: 0
has body: EDIT: Since OP is asking to print the complete line of match then following should be used. awk 'match($0,/[a-zA-Z]+@[a-zA-Z]+\.com/)' Input_file Following awk may help you here. awk 'match($0,/[a-zA-Z]+@[a-zA-Z]+\.com/){print substr($0,RSTART,RLENGTH)}' Input_file
has comment: http://stackoverflow.com/comment/88252949
type: Answer

http://stackoverflow.com/comment/88090642
has text: thanks! , up-vote the question if you can just so other's can see this, I was confused on this for like an hour.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50539420

http://stackoverflow.com/q/50410775
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/50410816
downvote count: 1
has title: Pandas, get elements in an specific order
has body: I have a pandas dataframe col1 col2 Apple 70 Lemon 80 Banana 90 and I have a list with the elements of col1 in a specific order: my_list = ['Banana', 'Apple', 'Lemon'] I need to get the values of col2 following the order of my_list result = [90, 70, 80] How could I achieve that? Thanks PS: I see several solutions to my problem, so maybe I oversimplified it, because some of the solutions will not be efficient for my real problem (my fault for oversimplifying). The problem is a little more complex, my dataframe has more columns and a lot of rows. col1 col2 col3 Apple 70 red Lemon 80 red Banana 90 red Lemon 2 blue Apple 3 blue Banana 4 blue Lemon 67 green Banana 68 green Apple 69 green Basically the values of col1 repeat for each value of col3 (but the order might be different!) What I need is for each value of col3 to get a vector of values from col2 but always with the same order. So I obtain my_list by doing: my_list = np.unique(df['col2']) and then I iterate for each element of col3 obtaining the simplyfied example that I posted. This doesn't change the answers, but I might pick one or another taking in account the whole picture.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50410814
has answer: http://stackoverflow.com/a/50410845
upvote count: 5
accepted answer: http://stackoverflow.com/a/50410893
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50410893
possible better answer: http://stackoverflow.com/a/50410814
answer count: 4

http://stackoverflow.com/a/50464219
has comment: http://stackoverflow.com/comment/87942547
answers question: http://stackoverflow.com/q/50464149
score: 1
has body: Add sep="\t" into pd.read_csv. The data is messy, thus double tab needs to be replaced: df = pd.read_csv( io.StringIO(s.decode('utf-8').replace("\t\t", "\t")), header=None, sep="\t")
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50464149
has comment: http://stackoverflow.com/comment/87941958
has comment: http://stackoverflow.com/comment/87944211
downvote count: 0
type: Answer

http://stackoverflow.com/a/50485476
has comment: http://stackoverflow.com/comment/87985204
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88020908
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50484197
has comment: http://stackoverflow.com/comment/88003393
has comment: http://stackoverflow.com/comment/87986571
answers question: http://stackoverflow.com/q/50484197
has comment: http://stackoverflow.com/comment/87984912
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/88017279
has comment: http://stackoverflow.com/comment/88021248
has body: You can try something like that : from flask import make_response, url_for, redirect, abort @app.route('/&lt;int:id_product&gt;') def product(id_product): # Load you path with id_product to get nice url (in database) if id_product == 123: path = '/machines/cars/modern/Lexus LX570' else: abort(404) return redirect(url_for('product_friendly_url', product_category_hierarchy=path)) @app.route('/&lt;path:product_category_hierarchy&gt;') def product_friendly_url(product_category_hierarchy): # Retrieve product from his product_category_hierarchy (in database) product_item = {'id': 123, 'product_category_hierarchy': product_category_hierarchy, 'blabla': 'test'} return make_response(str(product_item)) Call /123 in your browser will redirect (302) you to '/machines/cars/modern/Lexus LX570' and print : {'id': 123, 'product_category_hierarchy': 'machines/cars/modern/Lexus LX570', 'blabla': 'test'}
has comment: http://stackoverflow.com/comment/88016688

http://stackoverflow.com/q/50456812
score: 0
has comment: http://stackoverflow.com/comment/87927520
has answer: http://stackoverflow.com/a/50457189
answer count: 1
has comment: http://stackoverflow.com/comment/87927480
type: Question
has comment: http://stackoverflow.com/comment/87954260
has title: Python: what is the best way to iterate through a dataset to pass the values into a dict?
tagged with: google-dfp
accepted answer: http://stackoverflow.com/a/50457189
tagged with: python
has comment: http://stackoverflow.com/comment/87927775
has comment: http://stackoverflow.com/comment/87927750
has body: I have a function that sends data to my ad server via the Google DFP API. The function works when my variables (order_id, targeted_placement_id, etc..) have the data hard-coded to it. My data comes from 'ad_data.csv' where each column is the key and the data in the associated row is the value. I want to loop through this dataset and pass the values of each row inside the csv file into the correct value inside the line_item dict. Below is my pandas DataFrame.head() order_id targeted_placement_id campaign 0 3494982232 5555666677 Ad Campaign 1 1 8494984434 1112666177 Ad Campaign 2 3 4494922232 0992666677 Ad Campaign 3 4 1494984234 9494939499 Ad Campaign 4 However, inside the for loop, I want to pass each row 'ad_data.csv' from googleads import dfp import pandas as pd df = pd.read_csv('ad_data.csv') order_id = df['order'].tolist() targeted_placement_id = df['placement_id'].tolist() campaign_name = df['campaign'].tolist() def main(client, order_id, targeted_placement_ids, campaign_name): line_item_service = client.GetService('LineItemService') # Create line item objects. line_items = [] for _ in range(1): line_item = { 'orderId': order_id, 'name': campaign_name, 'targeting': { 'inventoryTargeting': {'targetedPlacementIds': targeted_placement_ids}, } } line_items.append(line_item) line_items = line_item_service.createLineItems(line_items) for line_item in line_items: print('Target id "%s", in order id "%s", named"%s" was created' %(line_item['targetedPlacementId'], line_item['orderId'], line_item['name'])) if __name__ == '__main__': dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client, order_id, targeted_placement_id, campaign_name) If done correctly, line_item should print: Target id 5555666677 in order id 3494982232, named Ad Campaign 1 was created Target id 1112666177 in order id 8494984434, named Ad Campaign 2 was created Target id 0992666677 in order id 4494922232, named Ad Campaign 3 was created Target id 9494939499 in order id 1494984234, named Ad Campaign …
type: AnsweredQuestion

http://stackoverflow.com/comment/88019542
type: QuestionComment
type: Comment
has text: yes tried. its not working :(..it is not showing error also.
score: 0
comment on: http://stackoverflow.com/q/50464584

http://stackoverflow.com/q/50530520
downvote count: 0
answer count: 1
upvote count: 1
has title: Pandas: duplicate columns, cannot remove them
has body: I all, I have a strange and somewhat frustrating problem. When I give the following command: gpd_cinc_merged.columns I get the following output: Index(['level_0', 'index', 'SU_gdppc', 'SU_gdppcl', 'year', 'US_gdppc', 'US_gdppcl', 'year', 'index', 'SU_milex', 'SU_cinc', 'US_milex', 'US_cinc', 'year', 'year'], dtype='object') You may notice the presence of multiple year columns. They all have the same value and I would like to remove all but one. However, I am unable to do so gpd_cinc_merged.drop('year', axis=1, inplace=True) Removes all of them, but I need one of them to remain there. So instead I counted their index numbers, so I would remove just one. gpd_cinc_merged.drop(gpd_cinc_merged.columns[[7]], axis=1, inplace=True) However, this command also removes all of them. gpd_cinc_merged.year Returns a dataframe with four year columns with identical value. Yet I am unable to use the variable in a merge operation, as it returns to many values. Does anyone know a way to reduce these 4 duplicate columns to just 1?
favorite count: 0
accepted answer: http://stackoverflow.com/a/50530590
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50530590
tagged with: pandas
score: 1
tagged with: python
type: Question

amazon-elastic-beanstalk
tags question: http://stackoverflow.com/q/50519687
tag name: amazon-elastic-beanstalk
tags question: http://stackoverflow.com/q/50479052
type: Tag
tags question: http://stackoverflow.com/q/50474000
tags question: http://stackoverflow.com/q/50425644

http://stackoverflow.com/q/50518977
has answer: http://stackoverflow.com/a/50519436
answer count: 1
type: Question
has title: How to make the widget (ball) start on bottom of the screen - Python/Kivy
tagged with: python
tagged with: kivy
accepted answer: http://stackoverflow.com/a/50519436
type: AnsweredQuestion
score: 0
has body: I'm trying to make a basic visual exercise in Python and Kivy, but i'm stuck in this part of the code, how to make the ball start on the bottom of the screen? Here's the .py file: from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty,\ ObjectProperty from kivy.vector import Vector from kivy.clock import Clock class PongBall(Widget): velocity_x = NumericProperty(0) velocity_y = NumericProperty(0) velocity = ReferenceListProperty(velocity_x, velocity_y) def move(self): self.pos = Vector(*self.velocity) + self.pos class PongGame(Widget): ball = ObjectProperty(None) def serve_ball(self, vel=(0, 4)): self.ball.center = self.center self.ball.velocity = vel def update(self, dt): self.ball.move() # bounce ball off bottom or top or left or right if (self.ball.y &lt; self.y) or (self.ball.top &gt; self.top): self.ball.velocity_y = -2 self.ball.velocity_x = -4 # bounce ball off if(self.ball.x &lt; 0): self.ball.velocity_x = 4 self.ball.velocity_y = 0 if(self.ball.x + self.ball.width &gt; self.right): self.ball.velocity_x *= -1 self.ball.velocity_y = 4 class PongApp(App): def build(self): game = PongGame() game.serve_ball() Clock.schedule_interval(game.update, 1.0 / 60.0) return game if __name__ == '__main__': PongApp().run() .kv file: &lt;PongBall&gt;: size: 50, 50 canvas: Ellipse: pos: self.pos size: self.size &lt;PongGame&gt;: ball: pong_ball PongBall: id: pong_ball center: self.parent.center This code make the widget starts on center of the screen, i'm trying to make start on bottom, without success Thanks for any tips!

http://stackoverflow.com/q/50491134
tagged with: sockets
has comment: http://stackoverflow.com/comment/87995167
tagged with: python
score: -1
has title: How to add socket into listWidget
type: AnsweredQuestion
has body: I need help with adding python's socket object to PyQt5 listWidget. First of all, I do this thing in threading server client, addr = self.s.accept() self.clients.append(client) and then in the QTclass I'm trying to do this stuff class win(QtWidgets.QMainWindow): def __init__(self, parent=None): self.ui = Ui_MainWindow() self.ui.setupUi(self) self.server = Server() self.timer = QTimer() self.timer.timeout.connect(self.update) def clUpdate(self): self.ui.ListWidget.addItems(self.server.clients) but when the client is connected to the server I've got this exception TypeError: index 0 has type 'socket' but 'str' is expected so how can I add the socket to listWidget? I want to use it later, for example, to send the message to specific clients from a listWidget
has comment: http://stackoverflow.com/comment/87995862
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87996285
tagged with: pyqt5
downvote count: 1
accepted answer: http://stackoverflow.com/a/50504841
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87995510
tagged with: qlistwidget
has answer: http://stackoverflow.com/a/50504841
has comment: http://stackoverflow.com/comment/87995451

http://stackoverflow.com/comment/87866921
has text: Thank you very much. It worked! had to update 'ADMIN_URL' in settings.py for solr and build_solr_schema with RELOAD_CORE worked.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50424991
type: Comment

http://stackoverflow.com/comment/98214171
type: AnswerComment
score: 5
comment on: http://stackoverflow.com/a/50502803
type: Comment
has text: Is which situation shall we use `LabelBinarizer` then, if at all?

http://stackoverflow.com/q/50473197
score: 0
tagged with: django-views
has comment: http://stackoverflow.com/comment/87962248
has comment: http://stackoverflow.com/comment/87959988
has comment: http://stackoverflow.com/comment/87959957
answer count: 1
has comment: http://stackoverflow.com/comment/87961549
type: Question
has answer: http://stackoverflow.com/a/50473621
has comment: http://stackoverflow.com/comment/87960131
has comment: http://stackoverflow.com/comment/87960199
type: UnansweredQuestion
has body: I have a few models and I'd like to filter out specific fields, but I keep getting the error: Cannot resolve keyword 'Unique' into field. Choices are:Parent, id, unique. Here are my model and my filter lookup: #models class Parent(models.Model): parent_name = models.CharField(max_length=30) objects = models.Manager() class Unique(models.Model): unique_name = models.CharField(max_length=10) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) objects = models.Manager() class Name(models.Model): name_name = models.CharField(max_length=20) unique = models.ForeignKey(Unique, on_delete=models.CASCADE) objects = models.Manager() class Item(models.Model): item_name = models.CharField(max_length=30) name = models.ForeignKey(Name, on_delete=models.CASCADE) objects = models.Manager() Here is the query I've been trying: if Parent.objects.filter(parent_name__iexact = new_parent.parent_name, unique__unique_name__iexact = new_unique.unique_name, unique__name__name_name__iexact = new_name.name_name, unique__name__item__item_name__iexact = new_item.item_name).exists(): I want to ensure that certain models spanning through a ForeignKey relationship exist within the database. The New_ variables are form inputs. edit: I got the code to work, I must have messed up something pretty small. The current code works, and I'll be using PEP8 from now on to spot mistakes better, thanks :)
has comment: http://stackoverflow.com/comment/87960388
has comment: http://stackoverflow.com/comment/87960492
has comment: http://stackoverflow.com/comment/87960576
tagged with: django
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/87960896
has title: Django: Can't filter spanned relationships
has comment: http://stackoverflow.com/comment/87960251

http://stackoverflow.com/q/50527882
score: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/88069899
accepted answer: http://stackoverflow.com/a/50928103
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/50928103
tagged with: python-3.x
has body: I have an element extractor, and have an issue with removing it in source BeautifulSoup object Example: def extract_element(soup: bs4.BeautifulSoup) -&gt; bs4.Tag: tag = soup.select('my-css-selector-or-something-else') return copy.copy(tag) ## main body code soup = bs4.BeautifulSoup('my-html-code', 'my-parser') ignore_tag = extract_element(soup) if ignore_tag is not None: ignore_tag.decompose() # doesn't modifies soup object extract_element contains complicated logic and uses for element extraction, so it shouldn't modify existing soup object in function body
has title: How to decompose BeautifulSoup Tag copy in source HTML code?
answer count: 1
has comment: http://stackoverflow.com/comment/88072490
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/87876686
type: Comment
type: QuestionComment
has text: Your solution also returns a list of tuples that you'll have to `' '.join` to get the same name strings.
comment on: http://stackoverflow.com/q/50431093
score: 0

http://stackoverflow.com/a/50538605
type: Answer
answers question: http://stackoverflow.com/q/50538486
score: 0
has body: Memory efficient solution Use a toggling flag which you toggle every second line and print content to output file (thus, your memory has to hold only the content of mximum 2 lines at a time): with open('infile.txt') as in_file, open('outfile.txt', 'w') as out_file: flag = 0 for line in in_file: if not flag: s3 = [line] flag = 1 else: s1, s2 = line.split() print(s1, end = "\n", file = out_file) print(s2, end = "\n", file = out_file) print(repr(s3), end = "\n", file = out_file) flag = 0

http://stackoverflow.com/a/50392651
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50391703
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87801331
type: Answer
answers question: http://stackoverflow.com/q/50391703
has comment: http://stackoverflow.com/comment/87801683
score: 2
has body: Using torch.argmax() (for PyTorch +0.4): prediction = torch.argmax(tensor, dim=1) # with 'dim' the considered dimension prediction = prediction.unsqueeze(1) # to reshape from (24, 224, 224) to (24, 1, 224, 224) If the PyTorch version is below 0.4.0, one can use tensor.max() which returns both the max values and their indices (but which isn't differentiable over the index values): _, prediction = tensor.max(dim=1) prediction = prediction.unsqueeze(1) # to reshape from (24, 224, 224) to (24, 1, 224, 224)

http://stackoverflow.com/q/50398154
upvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has body: My RNN Gan network which consists of two RNN networks, a generator and a discriminator is ment to generate audio. But it's doing the complete opposit of what it's ment to do, it's really weird. The discriminator loss is decreasing and the generator loss is increasing, so it's doing the complete opposit of what it's ment to do. But it's getting even more weird because the losses are actually dec/inc linear just if they were suppost to do but obviously they're not. So, by what could such a behaviour be caused? Did I swap something out? Losses: https://pastebin.com/78BmS8iK Discriminator/Generator Code: def build_audio_generator(frame_size): model = Sequential() model.add(LSTM(512, input_shape=(frame_size, 1), return_sequences=True)) model.add(Dropout(0.3)) model.add(LSTM(512, return_sequences=True)) model.add(Dropout(0.3)) model.add(LSTM(512)) model.add(Dense(256)) model.add(Dropout(0.3)) model.add(Dense(256*frame_size)) model.add(Activation('softmax')) model.add(Reshape((frame_size, 256))) model.summary() noise = Input(shape=(frame_size, 1)) sound = model(noise) return Model(noise, sound) def build_audio_discriminator(audio_shape): model = Sequential() model.add(Conv1D(32, kernel_size=(2), padding="same", input_shape=audio_shape)) model.add(MaxPooling1D(pool_size=(2))) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dropout(0.25)) model.add(Dense(128)) model.summary() audio = Input(shape=audio_shape) # Extract feature representation features = model(audio) # Determine validity and label of the audio validity = Dense(1, activation="sigmoid")(features) return Model(audio, validity) Main(combining both models): frame_size = 500 frame_shift = 128 num_classes = 1 audio_shape_disc = (frame_size,256) optimizer = Adam(0.0002, 0.5) losses = ['binary_crossentropy'] # Build and compile the discriminator audio_discriminator = build_audio_discriminator(audio_shape_disc) audio_discriminator.compile(loss=losses, optimizer=optimizer, metrics=['accuracy'])…
tagged with: neural-network
tagged with: python
tagged with: generative-adversarial-network
has comment: http://stackoverflow.com/comment/87853623
answer count: 0
has comment: http://stackoverflow.com/comment/87851123
has title: GAN network Disc. loss decreasing and Gen. increasing instead of decreasing
type: UnansweredQuestion
score: 1
downvote count: 0

http://stackoverflow.com/comment/87939164
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50462707
has text: I'm not sure why you can't just use something like `df = df.groupby(by=['year', 'month', 'day']).size().reset_index()`. This will count occurrences of a particular date.
type: Comment

http://stackoverflow.com/q/50456635
type: Question
tagged with: firefox-profile
has body: I m trying to open the webpage in Tor Browser using Python Code: # Start :Code For TOR Browser from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.common.desired_capabilities import DesiredCapabilities # path to TOR binary binary = FirefoxBinary(r'C:\\Tor Browser\\Browser\\firefox.exe') # binary = FirefoxBinary(r'C:\\Program Files (x86)\\Vidalia Bridge Bundle\\Tor\\tor.exe') #path to TOR profile profile = FirefoxProfile(r'C:\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default') # cap = DesiredCapabilities().FIREFOX # cap["marionette"] = False # driver = webdriver.Firefox(firefox_binary= binary, executable_path="C:\\Python\\scrapy-master\\Projects\\kgooglecom\\WithScreenshot\\geckodriver.exe") driver = webdriver.Firefox(firefox_profile= profile, firefox_binary= binary, executable_path="C:\\Python\\scrapy-master\\Projects\\kgooglecom\\WithScreenshot\\geckodriver.exe") # driver = webdriver.Firefox(firefox_profile=profile, firefox_binary= binary, executable_path=r"C:\\Python\\scrapy-master\\Projects\\kgooglecom\\WithScreenshot\\geckodriver.exe") driver.get("https://www.google.com") driver.save_screenshot("screenshot1.png") driver.quit() # End :Code For TOR Browser I Use this link to download the geckodriver Error: Please suggest me how to resolve this error
type: UnansweredQuestion
tagged with: python
tagged with: tor
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/53761277
has title: How to initiate Tor Browser using Selenium and Python
downvote count: 0
tagged with: selenium
answer count: 1
favorite count: 0
tagged with: proxy

http://stackoverflow.com/a/50413008
has comment: http://stackoverflow.com/comment/87842571
answers question: http://stackoverflow.com/q/50411516
has body: The problem is not with the pickle module but the line that reads: all_posts = previous_posts.extend(current_posts) What actually happens is that the extend method is called, extending previous_posts in place, which once it has successfully completed returns the keyword None. You then have this keyword being assigned to all_posts instead of the contents of previous_posts, and then it gets written to the file. Try modifying it as follows: if new_post_count &gt; 0: file_name = 'all_posts' + user previous_posts = pickle.load(open(file_name, 'rb')) current_posts = get_posts(client, user, start_from_posts=0, total_posts=new_post_count) previous_posts.extend(current_posts) f = open(file_name, 'wb') pickle.dump(previous_posts, f) f.close() Even better would be to include Jean-Francois' suggestion: if new_post_count &gt; 0: file_name = 'all_posts' + user with open(file_name, 'rb') as f: previous_posts = pickle.load(f) current_posts = get_posts(client, user, start_from_posts=0, total_posts=new_post_count) previous_posts.extend(current_posts) with open(file_name, 'wb') as f: pickle.dump(previous_posts, f)
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87843086
type: Answer
has comment: http://stackoverflow.com/comment/87842189
has comment: http://stackoverflow.com/comment/87842022
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50411516

http://stackoverflow.com/q/50457569
answer count: 1
has answer: http://stackoverflow.com/a/50472472
accepted answer: http://stackoverflow.com/a/50472472
favorite count: 0
type: Question
has title: Json key lookup with variable in Python
has comment: http://stackoverflow.com/comment/87930289
score: -3
has comment: http://stackoverflow.com/comment/87930636
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/87928816
type: AnsweredQuestion
has body: json1 [{'one.10': 'eno', 'three': 1, 'two': False}, {'one.21': 'eon', 'three': 2, 'two': True}, {'one.31': 'noe', 'three': 3, 'two': False}] #{'one.x': 'oen', 'three': y, 'two': True} With above as json1 file in this format, and with json2 heavily nested: json2['Item']["21"] A bit convoluted but can "21" be replaced by a variable? and if so could you have the variable set to x value of one.x in json1 by searching for the y value of "'three': y" ie search for 3 and get an x of 31? json2['Item'][x] # for known y Edit. json1 in reality is switched a bit: [{"TextKey": "ItemName.x", "Name": "y", ...} ...] json2 is like: { "Item": { "10": { "djdj": True, ... "hduf": "dpdk" } "11": { "djdj": True, "info": { ... } ... "hduf": "dppk" } ... } }
has comment: http://stackoverflow.com/comment/87930791
has comment: http://stackoverflow.com/comment/87928836
has comment: http://stackoverflow.com/comment/87930426
has comment: http://stackoverflow.com/comment/87929796
upvote count: 1
has comment: http://stackoverflow.com/comment/87929310
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/87805020
has text: I'm not claiming that it definitely doesn't but I tried searching it and skimming the src code and I couldn't find it. I think it would be safer to keep it out of the discussion in the answer itself haha.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50394217

http://stackoverflow.com/comment/87966729
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50476489
has text: what is `RadialBar` and `MyClass`?, We can not help you if you do not provide a [mcve], please check the link information.
score: 0

http://stackoverflow.com/q/50479401
tagged with: function
possible better answer: http://stackoverflow.com/a/50479537
downvote count: 3
has answer: http://stackoverflow.com/a/50479420
has title: Python: printing dictionary values in a function
tagged with: loops
has body: So I've been trying to get this to work for a while. I'm trying to get these dictionaries to list all the values in the two dictionaries through a function, if that makes sense. It runs however it only prints the line of the final values of the two dictionaries. dictionary = { "grades": "O", "grades": "E", "grades": "A", "grades": "P", "grades": "D", "grades":"T", } dictionary_means = { "means": "O is for Outstanding! You're top level now!", "means": "E is for Exceeds Expectations! Very well done, almost perfect!", "means": "A for Acceptable. That's okay, hopefully it'll get you somewhere...", "means": "P is for Poor. Is that the best you can do?", "means": "D is for Dreadful. Well at least it's not T...", "means": "T is for Troll. Wow, you're an idiot." } def owls_grades (grades): for v in grades.values(): print("Your grade is {}. ".format(v)) def owls_means (means): for value in means.values(): print ("{}".format(value)) print (owls_grades(dictionary)) print (owls_means(dictionary_means))
has answer: http://stackoverflow.com/a/50479537
favorite count: 0
type: Question
type: AnsweredQuestion
score: -3
tagged with: python
tagged with: dictionary
answer count: 2
accepted answer: http://stackoverflow.com/a/50479420
upvote count: 0

http://stackoverflow.com/a/62056828
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50434297
has body: From what @Ali Yilmaz stated, that might be a bit outdated. It works this way on a 32-bit arm processor with Debian Buster with kernel 4.19.x and python3. from moviepy.editor import VideoFileClip clip = VideoFileClip("/path/to/yourfile.mp4") start = 10 # start at 10 seconds end = 25 # plays for 15 seconds and ends at 25 seconds subclip = clip.subclip(start, end) subclip.write_videofile("/path/to/yournewfile.mp4") I think the only difference in my moviepy setup and Ali's set up was the fact that in two years things changed with moviepy distributions and installations.

http://stackoverflow.com/comment/87869352
has text: In your last loop, what is the purpose of `x` and `y`???
score: 0
comment on: http://stackoverflow.com/q/50426050
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88681179
type: AnswerComment
comment on: http://stackoverflow.com/a/50725455
score: 0
has text: Thank you @JeruLuke! (I already +1 yours too since a few days ;) )
type: Comment

http://stackoverflow.com/q/50416538
has answer: http://stackoverflow.com/a/68684775
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53465177
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/87848826
tagged with: phantomjs
score: 20
has title: Python, PhantomJS says I am not using headless?
has comment: http://stackoverflow.com/comment/90871506
has body: my code is: from selenium import webdriver driver = webdriver.PhantomJS(executable_path='driver/bin/phantomjs.exe') driver.get("https://www.test.com") print(driver.current_url) It seems to run fine but before it runs I always get this error: UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless Why am I getting this error? I thought my PhantomJS was headless as it still works and no browser pops-up is this error save to ignore?
has comment: http://stackoverflow.com/comment/87848941
has answer: http://stackoverflow.com/a/53791690
linked to: http://stackoverflow.com/q/46753393
tagged with: selenium
has comment: http://stackoverflow.com/comment/87848783
upvote count: 21
has comment: http://stackoverflow.com/comment/87848968
has answer: http://stackoverflow.com/a/50416768
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/88059633
type: QuestionComment
has text: `xgboost` is actually not problematic to install. On Ubuntu itcomes in smooth. There are more problematic packages to deal with. In the worst (or most advanced, to be precise) case, you always have the opportunity to build the package by hand following instructions on the package web page. That's what also `conda install` or `pip install` are doing under the hood, but you are in full control of each step and see what fails.
comment on: http://stackoverflow.com/q/50420693
score: 0
type: Comment

http://stackoverflow.com/q/50431585
has comment: http://stackoverflow.com/comment/87877757
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87877820
has comment: http://stackoverflow.com/comment/87877710
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87877690
has title: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
has comment: http://stackoverflow.com/comment/87878255
tagged with: http://stackoverflow.com/tag/json
score: 10
has comment: http://stackoverflow.com/comment/87877643
tagged with: python
has answer: http://stackoverflow.com/a/50431723
has comment: http://stackoverflow.com/comment/87877840
upvote count: 11
has comment: http://stackoverflow.com/comment/87877667
has body: looked at previous answers but cant solve it, the json.loads wont work. the code: import json import operator Data_to_python ={} Bank_Data_note= open('Data_for_python.txt','r') # open file Bank_Data_str = Bank_Data_note.read() print(Bank_Data_str) Data_to_python =json.loads(Bank_Data_str) # dictinary print(Data_to_python) the json format from text file: {{"Transaction_1":{"Name":"Magnolia","Location":"Ayilon male","Amount":289,"Date":"5/5/18"}, {"Transaction_2":{"Name":"Landver,"Location":"Cinima-city Ramat-hashron","Amount":15,"Date":"15/5/18"}, {"Transaction_3":{"Name":"Superfarm","Location":"Shivat-hacochvim male","Amount":199,"Date":"7/5/18"}, {"Transaction_4":{"Name":"Printing solutions","Location":"Afeka tel-aviv","Amount":16,"Date":"25/5/18"}} I got this: obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
has comment: http://stackoverflow.com/comment/87877680
answer count: 1
has comment: http://stackoverflow.com/comment/87877836
has comment: http://stackoverflow.com/comment/87877718

http://stackoverflow.com/comment/87908796
comment on: http://stackoverflow.com/q/50447162
has text: In your actual case what's `vectors_number` and `population_size`?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50520268
tagged with: dataframe
has answer: http://stackoverflow.com/a/50521427
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50520669
has title: Pandas duplicate rows with time sequence
has answer: http://stackoverflow.com/a/50520669
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: refactoring
possible better answer: http://stackoverflow.com/a/50521427
has body: I am trying to duplicate my pandas' data frame's rows and also adding an additional column for a time sequence in minutes between column FROM and TO. For example, I have this data frame. ID FROM TO A 15:30 15:33 B 16:40 16:44 C 15:20 15:22 What I want the output to be is ID FROM TO time A 15:30 15:33 15:30 A 15:30 15:33 15:31 A 15:30 15:33 15:32 A 15:30 15:33 15:33 B 16:40 16:41 16:40 B 16:40 16:41 16:41 C 15:20 15:22 15:20 C 15:20 15:22 15:21 C 15:20 15:22 15:22 In R, I could do this: new_df = setDT(df)[, .(ID, FROM, TO, time=seq(FROM,TO,by="mins")), by=1:nrow(df)], but I am having trouble finding the Python equivalent of this. Thank you in advance!

http://stackoverflow.com/q/50505485
tagged with: python
score: -1
tagged with: forms
tagged with: templates
has body: I am new to Django I have two models are user and address, here user having two foreign key fields are 'localaddress', 'permanentaddress' Address model: class Address(models.Model): fulladdress = models.CharField(max_length=1000, null=True, blank=True) additional_address = models.CharField(max_length=1000, null=True, blank=True) street_address = models.CharField(max_length=150, null=True, blank=True) route = models.CharField(max_length=150, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) pincode = models.IntegerField(null=True, blank=True) class Meta: db_table = 'address' User model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): localaddress = models.ForeignKey(Address, on_delete=models.CASCADE, related_name="localaddress", null=True, blank=True) permanentaddress = models.ForeignKey(Address, on_delete=models.CASCADE, related_name="permanentaddress", null=True, blank=True) class Meta: db_table = 'user' settings.py: AUTH_USER_MODEL = 'student.User'# changes built-in user model to ours here both localaddress and permanentaddress having same foreign key (Address model only) Edit form: forms.py: class LocaladdressForm(forms.ModelForm): class Meta: model = Address fields = ['fulladdress', 'additional_address', 'street_address', 'route', 'city', 'state', 'country', 'pincode'] def save(self, commit=True): user = super(LocaladdressForm, self).save(commit=False) user.fulladdress = self.cleaned_data['fulladdress'] user.additional_address = self.cleaned_data['additional_address'] user.street_address = self.cleaned_data['street_address'] user.route = self.cleaned_data['route'] user.city = self.cleaned_data['city'] user.state = self.cleaned_data['state'] user.pincod…
favorite count: 0
type: Question
tagged with: model
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
downvote count: 1
has answer: http://stackoverflow.com/a/50505648
has title: How can I persist ForeignKey fields into database using Django

http://stackoverflow.com/q/50416655
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: ecdsa
favorite count: 0
type: Question
has body: I'm trying to implement ECDSA using python as part of my homework, I have a function named multiplication which takes two arguments Point P and t calculates B= tP.I have implemented this algorith based on iterative double and add algorithm on this wikipedia page the problem is when p coordination is small(one or two digits), the algorithm works fine but when coordination is large (about 70 digits) the result is different than what it supposed to be. here is the part of my code which calculates multiplication: def addition(self, p, q): if p.is_infinite: return q elif q.is_infinite: return p else : if (q.x - p.x) == 0: point = Point.Point(0, 0) point.is_infinite = True return point s = int(((q.y - p.y) * Utils.Utils.mode_inverse(q.x - p.x, self.prime)) % self.prime) xr = int((math.pow(s, 2) - p.x - q.x) % self.prime) yr = int(((s * (p.x - xr)) - p.y) % self.prime) r = Point.Point(xr, yr) return r def double(self, p): if p.is_infinite: return p if p.y == 0: point = Point.Point(0, 0) point.is_infinite = True return point s = int((((3 * math.pow(p.x, 2)) + self.a) * Utils.Utils.mode_inverse(2 * p.y, self.prime)) % self.prime) xr = int((math.pow(s, 2) - p.x - p.x) % self.prime) yr = int(((s * (p.x - xr)) - p.y) % self.prime) r = Point.Point(xr, yr) return r def multiplication(self, p, t): bin_t = bin(t)[2:] Q = Point.Point(p.x, p.y) Q.is_infinite = True for i, digit in enumerate(bin_t): Q = self.double(Q) if digit == '1': Q = self.addition(Q, p) return Q Here is my Util class: class Utils(object): @staticmethod def mode_inverse(a, m): return pow(a, m - 2, m) Here is my Point class: class Point(object): def __init__(self, x, y): self.x = x self.y = y self.is_infinite = False I use Curve P-224 parameters which are: p = 26959946667150639794667015087019630673557916260026308143510066298881 a = -3 b = 18958286285566608000408668544493926415504680968679321075787234672564 Gx = 19277929113566293071110308034699488026831934219452440156649784352033 Gy = 1992680875803447097019797437088…
tagged with: algorithm
has title: python ECDSA implementation miscalculation on big integers
tagged with: python
accepted answer: http://stackoverflow.com/a/50417314
has comment: http://stackoverflow.com/comment/87849272
has comment: http://stackoverflow.com/comment/87849060
has answer: http://stackoverflow.com/a/50417314
type: AnsweredQuestion

http://stackoverflow.com/comment/88035029
type: AnswerComment
comment on: http://stackoverflow.com/a/50446092
score: 0
type: Comment
has text: Thanks for reply Chanda, it works on Windows. If I need to put `func1`, `func2` into function `test_multiprocessing`, is that possible?

pipeline
type: Tag
tag name: pipeline
tags question: http://stackoverflow.com/q/50389955

http://stackoverflow.com/comment/87925997
comment on: http://stackoverflow.com/q/50456101
score: 0
type: Comment
type: QuestionComment
has text: so you want `None` and it is `null` in database, which is actually `None`. What's the problem?

http://stackoverflow.com/comment/87951450
type: QuestionComment
comment on: http://stackoverflow.com/q/50469021
has text: please show what you have attempted so far..
score: 0
type: Comment

http://stackoverflow.com/comment/87876036
type: Comment
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/50430795
has text: This is not something pep8 will prescribe. Do it where you need to do it.

http://stackoverflow.com/q/50486563
type: AnsweredQuestion
tagged with: redis
accepted answer: http://stackoverflow.com/a/50488373
has title: Faster way to iterate all keys and values in redis db
score: 7
has answer: http://stackoverflow.com/a/50488373
tagged with: python
has comment: http://stackoverflow.com/comment/87986343
type: Question
tagged with: redis-py
has comment: http://stackoverflow.com/comment/87986166
answer count: 2
has body: I have a db with about 350,000 keys. Currently my code just loops through all keys and gets its value from the db. However this takes almost 2 minutes to do, which seems really slow, redis-benchmark gave 100k reqs/3s. I've looked at pipelining but I need each value returned so that I end up with a dict of key, value pairs. At the moment I'm thinking of using threading in my code if possible to speed this up, is this the best way to handle this usecase? Here's the code I have so far. import redis, timeit start_time = timeit.default_timer() count = redis.Redis(host='127.0.0.1', port=6379, db=9) keys = count.keys() data = {} for key in keys: value = count.get(key) if value: data[key.decode('utf-8')] = int(value.decode('utf-8')) elapsed = timeit.default_timer() - start_time print('Time to read {} records: '.format(len(keys)), elapsed)
downvote count: 0
possible better answer: http://stackoverflow.com/a/63448378
upvote count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/63448378

http://stackoverflow.com/q/50424167
favorite count: 0
has answer: http://stackoverflow.com/a/50425863
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50425863
score: 15
upvote count: 15
has body: Is it possible to concatenate two tensors with different dimensions without using for loop. e.g. Tensor 1 has dimensions (15, 200, 2048) and Tensor 2 has dimensions (1, 200, 2048). Is it possible to concatenate 2nd tensor with 1st tensor along all the 15 indices of 1st dimension in 1st Tensor (Broadcast 2nd tensor along 1st dimension of Tensor 1 while concatenating along 3rd dimension of 1st tensor)? The resulting tensor should have dimensions (15, 200, 4096). Is it possible to accomplish this without for loop ?
tagged with: pytorch
type: AnsweredQuestion
has title: Concatenating two tensors with different dimensions in Pytorch
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50480034
downvote count: 0
answers question: http://stackoverflow.com/q/50474886
type: AcceptedAnswer
has body: You set V0 = np.array([Vx,Vy,Vz]) for the old basis, V1 = np.array([Vx1,Vy1,Vz1]) for the new basis, where the basis vectors are the matrix rows and have the relation for the transposed matrices where the basis vectors are the columns M * V0.T = V1.T &lt;==&gt; V0 * M.T = V1 This can be nicely solved as M = np.linalg.solve(V0,V1).T
accepted answer of: http://stackoverflow.com/q/50474886
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/137348837
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50504635
has text: @user924 - either prepend `r` to your string containing your RegEx pattern to make it a raw string literal, as shown in the answer (`r'% [...]`), or escape the backslash with another backslash (`[...] [\\d] [...]`).

http://stackoverflow.com/comment/87818042
type: AnswerComment
comment on: http://stackoverflow.com/a/50401062
score: 1
type: Comment
has text: I didn't downvote, but it seems to me you can just `astype(str)` and then use `+` without `apply`.

http://stackoverflow.com/q/50501277
has comment: http://stackoverflow.com/comment/88018277
has comment: http://stackoverflow.com/comment/88017260
has comment: http://stackoverflow.com/comment/88017432
tagged with: tkinter-layout
favorite count: 0
type: Question
tagged with: python-3.x
has title: Tkinter Python 3 create_rectangle parameters - relheight,relwidth,relx,rely
answer count: 1
type: UnansweredQuestion
has body: I've made an UI and I've used relheight,relwidth,relx,rely as the parameters for all my labels such as: panel = Label(window, image=img,bg="#e8f3ff") panel.image = img panel.place(relheight=.15,relwidth=0.0425,relx=0.785,rely=0.51) But for creating rectangles, I'm using: canvas = Canvas() canvas.create_rectangle(0,0,2000,2000,fill="#e8f3ff") canvas.create_rectangle(0,5,8000,100,outline="#110f71", fill="#004091") canvas.create_rectangle(20,210,575,542,outline="#000000") canvas.create_rectangle(600,380, 750,850,outline="#000000") canvas.create_rectangle(600,100,778,542,outline="#000000") canvas.pack(fill=BOTH, expand=1) I tried using rel parameters for create_retangle and it gave an error, so is it possible to create rectangles with borders and bg fills using relative parameters? This is because i want my UI to auto align itself when maximized.
score: 1
has comment: http://stackoverflow.com/comment/88018012
has comment: http://stackoverflow.com/comment/88015865
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88025856
tagged with: tkinter-canvas
downvote count: 0
has answer: http://stackoverflow.com/a/50508937
upvote count: 1

http://stackoverflow.com/comment/87924536
has text: i cant understand why... could you edit your question to add the new code, and the traceback of error ?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50455080
score: 0

http://stackoverflow.com/comment/87936131
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50454420
has text: @univerio I am not using a unique contraint but primarykeyconstraint, this is not a dup

http://stackoverflow.com/a/50494543
score: 0
has comment: http://stackoverflow.com/comment/88015245
type: Answer
has comment: http://stackoverflow.com/comment/88047605
answers question: http://stackoverflow.com/q/50472023
has body: You need to retrain the last layer of your inception model with old and new data. See the tensorflow image retraining tutorial for more information.

http://stackoverflow.com/q/50396975
favorite count: 0
has comment: http://stackoverflow.com/comment/87809876
tagged with: python-2.7
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87809902
has title: String Methods: For 8-bit strings, this method is locale-dependent
has comment: http://stackoverflow.com/comment/87810227
type: Question
has answer: http://stackoverflow.com/a/50397107
type: UnansweredQuestion
has body: I've tried to figure out what 'locale-dependent' means in relation with the string methods as isalpha, isdigit, islower, isDigit have that following line in the doc's For 8-bit strings, this method is locale-dependent. What is locale?
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87892603
type: QuestionComment
comment on: http://stackoverflow.com/q/50391853
has text: @bestyasser: sorry, don't understand what you mean.
type: Comment
score: 0

http://stackoverflow.com/a/50520669
accepted answer of: http://stackoverflow.com/q/50520268
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88054710
type: Answer
upvote count: 1
has body: Two steps to solve your problem: pd.date_range with apply and strftime df['duration'] = df.apply( lambda row: [ i.strftime('%H:%M') for i in pd.date_range( row['FROM'], row['TO'], freq='60s' ) ], axis=1) ID FROM TO duration 0 A 15:30 15:33 [15:30, 15:31, 15:32, 15:33] 1 B 16:40 16:44 [16:40, 16:41, 16:42, 16:43, 16:44] 2 C 15:20 15:22 [15:20, 15:21, 15:22] apply with stack df.set_index(['ID', 'FROM', 'TO']) \ .duration.apply(pd.Series) \ .stack().reset_index(level=3, drop=True) \ .reset_index() \ .set_index('ID') # Result FROM TO 0 ID A 15:30 15:33 15:30 A 15:30 15:33 15:31 A 15:30 15:33 15:32 A 15:30 15:33 15:33 B 16:40 16:44 16:40 B 16:40 16:44 16:41 B 16:40 16:44 16:42 B 16:40 16:44 16:43 B 16:40 16:44 16:44 C 15:20 15:22 15:20 C 15:20 15:22 15:21 C 15:20 15:22 15:22
answers question: http://stackoverflow.com/q/50520268
score: 1

http://stackoverflow.com/comment/87842082
has text: :) -- Welcome to Stackoverflow -- When you consider an answer is satisfactory, please mark it as answered so you can flag to everyone that this is valid.
type: AnswerComment
comment on: http://stackoverflow.com/a/50410911
type: Comment
score: 0

http://stackoverflow.com/q/50439980
has answer: http://stackoverflow.com/a/50440929
tagged with: anaconda
has title: How to transfer tensorflow environment to root environment in anaconda navigator
tagged with: python
has body: I installed tensorflow successfully using anaconda terminal. Guide - https://www.tensorflow.org/install/install_windows But this guide create new environment called tensorflow therefore I want install this tensorflow in my root environment because it has 217 packagers and when I run a python program in tensorflow environment can't import root environment packagers. therefor I want to transfer or re-install tensorflow in root environment. Anaconda Navigator I opened anaconda terminal and activate root. Then I typed pip install --ignore-installed --upgrade tensorflow-gpu like I did in tensorflow environment. Then I get following error. Exception: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "C:\ProgramData\Anaconda3\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "C:\ProgramData\Anaconda3\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "C:\ProgramData\Anaconda3\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "C:\ProgramData\Anaconda3\lib\shutil.py", line 121, in copyfile with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: 'C:\\ProgramData\\Anaconda3\\Lib\\site-packages\\six.py' You are using pip version 9.0.1, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. How to install tensorfow in my root environment because I want use some of ther…
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/113350847
score: 0
comment on: http://stackoverflow.com/q/50502537
has text: Does this answer your question? [What does on\_delete do on Django models?](https://stackoverflow.com/questions/38388423/what-does-on-delete-do-on-django-models)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87968895
score: 1
comment on: http://stackoverflow.com/q/50477528
has text: @CathyQian open a terminal, type 'python3' without the quotes, and type 'type(input)' without the quotes. It should say `<class 'builtin_function_or_method'>`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50515245
answers question: http://stackoverflow.com/q/50474233
has body: I finally figured this by using the following code: data = mySocket2.recv(4) newData = int.from_bytes(data, byteorder='big', signed=False) The sender is sending uint32 data, that is obviously not-signed and is bigEndian. This has to be specified at the receiver side as well (my python3 script). If the sender changes and starts sending int8 data then I will need to update the receiver code to the following: data = mySocket2.recv(1) newData = int.from_bytes(data, byteorder='big', signed=True) P.S. serial or TCP/IP receiving seem to follow the same logic in python, this means that data received requires the same encoding.
type: Answer
score: 0

http://stackoverflow.com/q/50497250
has comment: http://stackoverflow.com/comment/88154401
has answer: http://stackoverflow.com/a/50634340
score: 0
has body: I'm programming a bit of server code and the MQTT side of it runs in it's own thread using the threading module which works great and no issues but now I'm wondering how to proceed. I have two MariaDB databases, one of them is local and the other is remote (There is a good and niche reason for this.) and I'm writing a class which handles the databases. This class will start new threads of classes that submits the data to their respected databases. If conditions are true, then it tells the data to start a new thread to push data to one database, if they are false, the data will go to the other database. The MQTT thread has a instance of the "Database handler" class and passes data to it through different calling functions within the class. Will this work to allow a thread to concentrate on MQTT tasks while another does the database work? There are other threads as well, I've just never combined databases and threads before so I'd like an opinion or any information that would help me out from more seasoned programmers.
has comment: http://stackoverflow.com/comment/88273209
answer count: 1
tagged with: mariadb
type: Question
has title: Calling database handler class in a python thread
type: UnansweredQuestion
tagged with: multithreading
tagged with: database
tagged with: python

http://stackoverflow.com/a/50490928
has body: Okay with the knowledge that the problem is uniquely solvable becuae of construction, here is how it should look like: import random import numpy as np def crossover(mum, dad): """Implements ordered crossover""" size = len(mum.vertices) # Choose random start/end position for crossover alice, bob = [-1] * size, [-1] * size start, end = sorted([random.randrange(size) for _ in range(2)]) # Replicate mum's sequence for alice, dad's sequence for bob alice_inherited = [] bob_inherited = [] for i in range(start, end + 1): alice[i] = mum.vertices[i] bob[i] = dad.vertices[i] alice_inherited.append(mum.vertices[i]) bob_inherited.append(dad.vertices[i]) print(alice, bob) #Fill the remaining position with the other parents' entries current_dad_position, current_mum_position = 0, 0 fixed_pos = list(range(start, end + 1)) i = 0 while i &lt; size: if i in fixed_pos: i += 1 continue test_alice = alice[i] if test_alice==-1: #to be filled dad_trait = dad.vertices[current_dad_position] while dad_trait in alice_inherited: current_dad_position += 1 dad_trait = dad.vertices[current_dad_position] alice[i] = dad_trait alice_inherited.append(dad_trait) #repeat block for bob and mom i +=1 return alice, bob with class Mum(): def __init__(self): self.vertices =[ 4, 9, 2, 8, 3, 1, 5, 7, 6 ] class Dad(): def __init__(self): self.vertices = [ 6 , 4 , 1 , 3 , 7 , 2 , 8 , 5 , 9 ] mum = Mum() dad = Dad() a, b = crossover(mum, dad) # a = [6, 4, 2, 8, 3, 1, 5, 7, 9]
answers question: http://stackoverflow.com/q/50489450
has comment: http://stackoverflow.com/comment/87996532
has comment: http://stackoverflow.com/comment/87995280
score: 0
has comment: http://stackoverflow.com/comment/87996550
has comment: http://stackoverflow.com/comment/87994813
type: Answer

http://stackoverflow.com/comment/88051915
score: 0
has text: roger that. I couldn't think of a way to keep it concise (minimal) but I'll put in some extra effort to see
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50517837

http://stackoverflow.com/a/50525042
has comment: http://stackoverflow.com/comment/102139475
has body: I solved my problem by abandoning the .apply function and using this instead (where old is a list of the old variable names) for index, row in df.iterrows(): if row['SU_SUP'] == 1: nation = 'SU_' for col in old: df[index: index + 1][nation + col] = int(row[col]) if row['US_SUP'] == 1: nation = 'US_' for col in old: df[index: index + 1][nation + col] = int(row[col]) This did the trick!
answers question: http://stackoverflow.com/q/50520125
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50520125
type: AcceptedAnswer

http://stackoverflow.com/q/50495317
has title: Github API get the last commit for every repository with a search term response
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50495427
tagged with: git
has body: I'm working on a project using Python(3.6) in which I have implemented GitHub JSON APIs by using the Python's requests package.I'm getting the list of public repos for a specific serach term provided by user.It's providing a response object which includes information about repos but I need to get the last commit infor of every repo, how can I get this info from response object from Github api. Here's how I have implemented this: class GhNavigator(CreateView): def get(self, request, *args, **kwargs): term = request.GET.get('search_term') username = 'arycloud' token = 'API_TOKEN' login = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token)) response = login.json() print(response) return render(request, 'navigator/template.html', {'response': response, 'term': term}) Here's a sample response: {'total_count': 4618, 'incomplete_results': False, 'items': [{'id': 6750871, 'name': 'arrow', 'full_name': 'crsmithdev/arrow', 'owner': {'login': 'crsmithdev', 'id': 1596037, 'avatar_url': 'https://avatars1.githubusercontent.com/u/1596037?v=4', 'gravatar_id': '', 'url': 'https://api.github.com/users/crsmithdev', 'html_url': 'https://github.com/crsmithdev', 'followers_url': 'https://api.github.com/users/crsmithdev/followers', 'following_url': 'https://api.github.com/users/crsmithdev/following{/other_user}', 'gists_url': 'https://api.github.com/users/crsmithdev/gists{/gist_id}', 'starred_url': 'https://api.github.com/users/crsmithdev/starred{/owner}{/repo}', 'subscriptions_url': 'https://api.github.com/users/crsmithdev/subscriptions', 'organizations_url': 'https://api.github.com/users/crsmithdev/orgs', 'repos_url': 'https://api.github.com/users/crsmithdev/repos', 'events_url': 'https://api.github.com/users/crsmithdev/events{/privacy}', 'received_events_url': 'https://api.github.com/users/crsmithdev/received_events', 'type': 'User', 'site_admin': False}, 'private': False, 'html_url': 'https://github.com/crsmithdev/arrow', 'description': 'Better …
tagged with: github-api
tagged with: http://stackoverflow.com/tag/json
tagged with: python-requests
has answer: http://stackoverflow.com/a/50497577
downvote count: 1
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/87985037
type: AnswerComment
has text: what is group_keys
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50486126

http://stackoverflow.com/q/50536713
answer count: 0
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/88085838
has comment: http://stackoverflow.com/comment/88085645
has comment: http://stackoverflow.com/comment/88087106
has title: numpy.where produces inconsistent results
has comment: http://stackoverflow.com/comment/88085721
score: 0
has body: I have a piece of code where I need to look for an index of a value in a numpy array. For this task, I use numpy.where. The problem is that numpy.where produces a wrong result, i.e. returns an empty array, in situations where I am certain that the searched value is in the array. To make things worse, I tested that the element is really in the array with a for loop, and in case it is found, also look for it with numpy.where. Oddly enough, then it finds a result, while literally a line later, it doesnt. Here is how the code looks like: # progenitors, descendants and progenitor_outputnrs are 2D-arrays that are filled from reading in files. # outputnrs is a 1d-array. ozi = 0 for i in range(descendants[ozi].shape[0]): if descendants[ozi][i] &gt; 0: if progenitors[ozi][i] &lt; 0: oind = outputnrs[0] - progenitor_outputnrs[ozi][i] - 1 print "looking for prog", progenitors[ozi][i], "with outputnr", progenitor_outputnrs[ozi][i], "in", outputnrs[oind] for p in progenitors[oind]: if p == -progenitors[ozi][i]: # the following line works... print "found", p, np.where(progenitors[oind]==-progenitors[ozi][i])[0][0] # the following line doesn't! iind = np.where(progenitors[oind]==-progenitors[ozi][i])[0][0] I get the output: looking for prog -76 with outputnr 65 in 66 found 76 79 looking for prog -2781 with outputnr 65 in 66 found 2781 161 looking for prog -3797 with outputnr 63 in 64 found 3797 163 looking for prog -3046 with outputnr 65 in 66 found 3046 163 looking for prog -6488 with outputnr 65 in 66 found 6488 306 Traceback (most recent call last): File "script.py", line 1243, in &lt;module&gt; main() File "script.py", line 974, in main iind = np.where(progenitors[oind]==-progenitors[out][i])[0][0] IndexError: index 0 is out of bounds for axis 0 with size 0 I use python 2.7.12 and numpy 1.14.2. Does anyone have an idea why this is happening?
has comment: http://stackoverflow.com/comment/88085885
type: Question
tagged with: numpy

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

http://stackoverflow.com/comment/87808348
has text: The variables `j` or `i` do not exist outside of the scope of `printsum`. I suggest taking some time to read over this [nice article by Sebastian Raschka](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) to better understand Python namespaces.
type: Comment
comment on: http://stackoverflow.com/q/50396264
score: 2
type: QuestionComment

http://stackoverflow.com/comment/87887707
has text: Please paste your *code* itself (not images) into your question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50436833

http://stackoverflow.com/a/50438143
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50437722
has body: The most important principle is to organize your code so that the complexity resides in functions (or methods) that are amenable to straightforward unit testing -- in other words, in functions that don't deal with the command-line or interactive nature of the larger program. Then glue those functions to a thin outer layer that provides the command-line or interactive functionality. That glue will tend to be very simple and might not be worth the trouble of testing. If it does need any testing, you can often do it with a small number of basic end-to-end executions (e.g. for the command-line scenario a test that uses Python's subprocess module to run your program exactly the way a user would). More details can be found in Gary Bernhardt's excellent Boundaries talk.
score: 1
type: Answer

http://stackoverflow.com/a/50463232
answers question: http://stackoverflow.com/q/50463095
has body: Even if it's not the most elegant solution, you may decide to raise an exception (built-in or custom) in your check function and catch that in the explorer function. Be sure that you're catching only your exception. def check(): if True: raise ValueError("MyError") else: return 1 # here return to f2 def cannot_be_modified(): check() # inserted print("hello from cannot_be_modified") return 2 def explore(): try: cannot_be_modified() except ValueError as e: print(e) print("hello from explore") return 0 explore() output: MyError hello from explore
has comment: http://stackoverflow.com/comment/87955264
downvote count: 0
has comment: http://stackoverflow.com/comment/87940762
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87940492
upvote count: 1

http://stackoverflow.com/comment/88003862
has text: You're asking a question about whether it's ok to ask a question? It's fine if you can boil it down to an [MCVE](https://stackoverflow.com/help/mcve) but from your post it sounds like it might be quite broad.
comment on: http://stackoverflow.com/q/50495330
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50652157
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50446859
score: 1
type: Answer
has body: According to appJar documentation, you need to pass an XML string to .addTree(), not an ElementTree. According to ElementTree documentation, you can use xml.etree.ElementTree.tostring() to build an XML string from your Element: xml_string = et.tostring(xml) app.addTree('REGISTER', xml_string)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50446859

http://stackoverflow.com/comment/88033135
has text: Possible duplicate of [How to convert string to lowercase in Python](https://stackoverflow.com/questions/6797984/how-to-convert-string-to-lowercase-in-python)
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50510456

http://stackoverflow.com/q/50453529
accepted answer: http://stackoverflow.com/a/50453814
type: AnsweredQuestion
tagged with: anaconda
has comment: http://stackoverflow.com/comment/87921577
tagged with: python
has title: Will installing 2 conda on one computer mess up anything?
linked to: http://stackoverflow.com/q/37926940
tagged with: conda
type: Question
has answer: http://stackoverflow.com/a/50453814
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has body: Currently I have installed a software called ArcGIS Pro 2.1 in C:\Program Files and it comes with a conda that is the only python I have on this computer. Now I need python for other projects and I don't want to go through IT department every time I need to install some python packages because I don't have the admin right. Will installing another conda in a folder that I have right to edit mess up anything of the ArcGIS conda? Or can I use the ArcGIS conda to create another python environment outside C:\Program Files in a folder I have right to edit? Thanks.
has comment: http://stackoverflow.com/comment/87922310
favorite count: 0
tagged with: arcgis

http://stackoverflow.com/comment/88093265
type: Comment
has text: BTW, `import` statements should be at the start of the script. They definitely should not be placed inside loops. It won't make the program malfunction, since Python doesn't re-import a module that it's already loaded, but it still has to check if it's loaded every time it hits the `import` inside the loop, which is inefficient.
comment on: http://stackoverflow.com/q/50540817
type: QuestionComment
score: 0

http://stackoverflow.com/a/50492029
has comment: http://stackoverflow.com/comment/88023310
accepted answer of: http://stackoverflow.com/q/50491834
score: 1
answers question: http://stackoverflow.com/q/50491834
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88025413
has comment: http://stackoverflow.com/comment/88025358
type: Answer
has comment: http://stackoverflow.com/comment/88023337
has body: This is one way using collections.defaultdict. from collections import defaultdict from operator import itemgetter d = defaultdict(list) for code, attr, rank in df.itertuples(index=False): d[code].append((attr, rank)) d = {k: sorted(v, key=itemgetter(1), reverse=True)[:3] for k, v in d.items()} res = pd.DataFrame(d).T.reset_index() print(res) index 0 1 2 0 394 (Feminine, 9) (Fresh, 9) (Heavy, 8) 1 418 (Soft, 13) (Fresh, 12) (Clean, 11) 2 539 (Fresh, 14) (Soft, 14) (Feminine, 11) 3 555 (Feminine, 9) (Heavy, 8) (Soft, 7) You can change column names and provide additional formatting as necessary. In my opinion, it is a better idea to store tuples than converting numeric data to strings. If you really need a string representation... You can use pd.Series.apply: for col in [0, 1, 2]: res[col] = res[col].apply(lambda x: '{0} ({1})'.format(x[0], x[1]))

http://stackoverflow.com/q/50413511
has comment: http://stackoverflow.com/comment/87938640
upvote count: 1
has comment: http://stackoverflow.com/comment/87938542
favorite count: 0
tagged with: postgresql
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87842836
linked to: http://stackoverflow.com/q/14254315
type: Question
has title: Django : Dynamically create a database
has body: I Would like to implement a web page in Django which allow a user to dynamically create a Data Base. The Django model stored will always be the same. (a generic user) Scenario : The user fills up a form with fields like user.firstname, user.lastname .. Then after the submit, django creates a brand new DB on the DBMS. The model is then stored in this new DB. Django save/store this DB setting for further use. I find out Here that it's possible to set up multiple DB's in Django but that implies that they already have been created (Which is obviously not my case). To create my DB I can think of executing an custom SQL query directly on the DBMS like that from django.db import connection def createNewDB(self,id): with connection.cursort() as cursor: queryStr = "\"CREATE DATABASE " + id + "\"" cursor.execute(queryStr) But then I have no clues about : How to save the new DB settings in Django DB (see below). How to migrate and save the model user in the DB Migrate : from django.core.management import call_command call_command("migrate", interactive=False) Save model : user.save(using='db_id') I find this post talking about how to add a connection dynamically with : from django.db import connections connections.databases['new-alias'] = { ... } conn = connections['new-alias'] But again in, this case the sqlite DB exist before, so I'm not sure if it is what I need. So is it possible to create a DB link to a model and then add it to django's database setting ? Or should I review all my data structure ? (like one DB but multiple user model table) I am using django 2.0.5 and postgreSQL 9.6 but I can change if the solution is not compatible (sqlite for example).
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/87867163
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50426050
has text: something like [4,8,7,6,8,,8...... not [999,.999, 0,0,0,0....

http://stackoverflow.com/q/50465541
has answer: http://stackoverflow.com/a/50631813
downvote count: 6
type: AnsweredQuestion
score: -5
tagged with: pandas
tagged with: dataframe
has title: pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
favorite count: 0
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/50631813
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87944244
has body: If anybody can explain me this? How i get these decimal values and whats the meaning of np.random.randn(6,4) ? In [8]: df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) In [9]: df Out[9]: A B C D 2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 2013-01-02 1.212112 -0.173215 0.119209 -1.044236 2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 2013-01-04 0.721555 -0.706771 -1.039575 0.271860 2013-01-05 -0.424972 0.567020 0.276232 -1.087401 2013-01-06 -0.673690 0.113648 -1.478427 0.524988

http://stackoverflow.com/q/50521364
downvote count: 0
has answer: http://stackoverflow.com/a/50521583
upvote count: 1
has comment: http://stackoverflow.com/comment/88055446
has comment: http://stackoverflow.com/comment/88089531
linked to: http://stackoverflow.com/q/44427415
has answer: http://stackoverflow.com/a/50521543
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88055267
has title: How to alter timestamps on specific rows in a pandas df
has comment: http://stackoverflow.com/comment/88125479
possible better answer: http://stackoverflow.com/a/50521479
has body: I have a pandas df that contains different timestamps and strings within the same column. An example is displayed below: Once time goes past midnight the data spits out this weird 351 code and then reverts back to 12 hr time. So below the time for row 5 is actually 12:01:42 and row 8 will be 13:00:00. I can add 12 hours to these timestamps but I need to get rid of the first 3 values. I have tried to do this by indexing the appropriate times (after midnight) and applying [x[3:] for x in df]. But this removes the strings within this column. So AA and BB are removed as well. I'm a bit stuck on how to achieve this without removing unspecified values. Is it possible to select the appropriate times (only timestamps) after midnight, remove 351, and add 12 hours without losing any data? import pandas as pd k = 5 N = 10 d = ({'Time' : ['18:00:00','AA','BB', '23:00:00','AA','35112:01:42','AA','AA','35113:00:00','AA'], 'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL','DEF','JKL'], 'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx', 'xx', 1]}) df = pd.DataFrame(data=d) Output: Events Number1 Time 0 ABC xx 18:00:00 1 DEF xx AA 2 GHI 1 BB 3 JKL xx 23:00:00 4 ABC xx AA 5 DEF xx 35112:01:42 6 GHI 2 AA 7 JKL xx AA 8 DEF xx 35113:00:00 9 JKL 1 AA Intended Output: Output: Events Number1 Time 0 ABC xx 18:00:00 1 DEF xx AA 2 GHI 1 BB 3 JKL xx 23:00:00 4 ABC xx AA 5 DEF xx 24:01:42 6 GHI 2 AA 7 JKL xx AA 8 DEF xx 25:00:00 9 JKL 1 AA
duplicate of: http://stackoverflow.com/q/44427415
has answer: http://stackoverflow.com/a/50521479
has comment: http://stackoverflow.com/comment/88074061
accepted answer: http://stackoverflow.com/a/50521543
has comment: http://stackoverflow.com/comment/88099144
tagged with: python
has answer: http://stackoverflow.com/a/50521514
answer count: 4
tagged with: indexing
type: AnsweredQuestion
tagged with: pandas
score: 1

http://stackoverflow.com/comment/98644834
has text: To make consistency with other parts of the `django-filter` library, I would rename `filter_fields` to `filterset_fields`
comment on: http://stackoverflow.com/a/50527125
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50438020
downvote count: 0
linked to: http://stackoverflow.com/q/4529815
upvote count: 1
has answer: http://stackoverflow.com/a/50438321
has body: I've just started learning Python and I'm running into a problem where I want to save an integer to use again if the program is shutdown. I've been looking around, but can't find anything about it. The code I've written so far: from __future__ import print_function collatz = open("collatz.txt", "w+") Num = 5 calcNum = Num while Num&gt;0: if calcNum % 2 == 0: calcNum /= 2 print(calcNum, file = collatz) else: calcNum = (calcNum*3)+1 print(calcNum, file = collatz) if calcNum == 4: print("The infinite loop has been reached, moving on to the next number.", file = collatz) Num += 1 print(Num, file = collatz) calcNum = Num I tried to save Num into another file and then use that to keep it. However, it saves as a string instead of an int, so I tried to use int() which still didn't help. Thanks in advance for any help.
duplicate of: http://stackoverflow.com/q/4529815
tagged with: persistence
favorite count: 0
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50438321
has answer: http://stackoverflow.com/a/50438070
possible better answer: http://stackoverflow.com/a/50438070
tagged with: python
has title: Is it possible to save an integer to use again?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87890159

matplotlib-widget
tags question: http://stackoverflow.com/q/50524613
type: Tag
tag name: matplotlib-widget

http://stackoverflow.com/comment/88084162
type: QuestionComment
has text: @Evan I see, it's such a pity, if only I could press that button with Python, it'd be easier. Anyway, thank you a lot for your time!
score: 0
comment on: http://stackoverflow.com/q/50528569
type: Comment

http://stackoverflow.com/comment/88034268
type: AnswerComment
has text: No problem! Glad I could be of assistance
comment on: http://stackoverflow.com/a/50468029
type: Comment
score: 0

http://stackoverflow.com/q/50472657
has title: Distance matrix to coordinates points
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87964906
type: Question
upvote count: 4
tagged with: geometry
has body: Given a set of n (n > 4) points and its distances and knowing that the Menger determinant is equal to zero, how can I obtain the coordinates in R^3 of these points? Similar questions in: [1] Using distance matrix to find coordinate points of set of points [2] Finding the coordinates of points from distance matrix I've used [1] as my main reference however I do not know how to handle this algorithm in a 3D plot.
linked to: http://stackoverflow.com/q/10963054
answer count: 0
has comment: http://stackoverflow.com/comment/108944797
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18096783
tagged with: python
tagged with: http://stackoverflow.com/tag/r
score: 4
tagged with: distance
tagged with: math

http://stackoverflow.com/comment/87817395
score: 1
comment on: http://stackoverflow.com/q/50400715
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ nah, I still don't think it's a good, clear question. How does it deviate from the expected behavior?
type: Comment

http://stackoverflow.com/a/50464221
upvote count: 1
downvote count: 0
type: Answer
has body: res = [] for i in X_test: res.append(x.index(i))
answers question: http://stackoverflow.com/q/50464123
score: 1

http://stackoverflow.com/q/50438334
tagged with: chess
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87890611
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/87890597
has comment: http://stackoverflow.com/comment/87913497
has title: Bishop movement in chess
has body: I'm doing a chess game for a school project in python3. I'm stuck at the bishop movement. I did everything move for all the pieces but the bishop is really hard. Here is how I code my board: board=[["R1W","C1W","F1W","K1W","D1W","F2W","C2W","R2W"], ["P1W","P2W","P3W","P4W","P5W","P6W","P7W","P8W"], ["___","___","___","___","___","___","___","___"], ["___","___","___","___","___","___","___","___"], ["___","___","___","___","___","___","___","___"], ["___","___","___","___","___","___","___","___"], ["P1N","P2N","P3N","P4N","P5N","P6N","P7N","P8N"], ["R1N","C1N","F1N","D1N","K1N","F2N","C2N","R2N"]] and here is how I program my bishop: def fou_valide(piece,l,m,c,n): if piece[0]=="F": if (abs(m-l)+abs(n-c))%2==0 and l!=m and n!=c and board_fou_dame[l][c]==board_fou_dame[m][n] and abs(l-m)==abs(c-n): if m&gt;l and n&gt;c: for x in range(l+1,m):# on scanne les cases ou va passer la piece si elle ne passe par-dessus une pieces en effet elle ne peut pas sauter au dessus d\'une autre piece for y in range(c+1,n): if board[x][y]!="___": print ("faux") return False return True elif m&gt;l and n&lt;c: for z in range(l+1,m):# on scanne les cases ou va passer la piece si elle ne passe par-dessus une pieces en effet elle ne peut pas sauter au dessus d\'une autre piece for j in range(c-1,n,-1): if board[z][j]!="___": print ("fau") return False That's just half the code only l, m, n, and c are changing. My problem is that even though n&gt;c, it shows "fau" instead of "faux" Here is how I ask for position: l = int(input("ligne de selection?:\n"))-1 #on demande au joueur la ligne de la piece a selectionné c = int(input("colonne de selection?:\n"))-1#on demande au joueur la colonne de la piece a selectionné m = int(input("ligne de destination ?:\n"))-1#on demande au joueur la ligne ou il veut pose la piece n = int(input("colonne de destination?:\n"))-1#on demande au joueur la colonne ou il veut pose la piece piece = board[l][c] # piece correspond a la piece selectionné
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50438556
possible better answer: http://stackoverflow.com/a/50438556
has answer: http://stackoverflow.com/a/50475766
has comment: http://stackoverflow.com/comment/87913790
accepted answer: http://stackoverflow.com/a/50475766
has comment: http://stackoverflow.com/comment/87890856
has comment: http://stackoverflow.com/comment/87890698
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87890760
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/87913761

http://stackoverflow.com/comment/87921836
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50453603
score: 1
has text: IP of the server could be in target site's blacklist. Often happens with AWS.

http://stackoverflow.com/a/50515847
type: Answer
answers question: http://stackoverflow.com/q/50515651
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88046776
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50515651
upvote count: 7
has body: The default sys.excepthook uses a separate, C-level implementation of traceback printing, not the traceback module. (Perhaps this is so it still works even if the system is too borked to use traceback.py.) The C implementation doesn't try to use linecache. You can see the code it uses to retrieve source lines in _Py_DisplaySourceLine. If you want tracebacks to use the traceback module's implementation, you could replace sys.excepthook with traceback.print_exception: import sys import traceback sys.excepthook = traceback.print_exception
score: 7

racing
tags question: http://stackoverflow.com/q/50527763
tag name: racing
type: Tag

http://stackoverflow.com/comment/87998855
comment on: http://stackoverflow.com/a/50424605
type: AnswerComment
score: 0
has text: i m running the code in python 3 and can i know how to diff the protocol version?
type: Comment

http://stackoverflow.com/comment/87911953
type: AnswerComment
comment on: http://stackoverflow.com/a/50448355
has text: I just edit my question. When the number is changed, how can I define an unified 's'?
score: 0
type: Comment

http://stackoverflow.com/q/50411947
score: 2
type: AnsweredQuestion
has body: My task is to write a python code (pytest test) in .py file, which runs jupyter notebook and asserts that output is 1. I have method for running notebook: def _notebook_run(path): args = ["jupyter", "nbconvert", "--execute", path] a = subprocess.check_call(args) return a And a test: def test_test(): a = _notebook_run('./file.ipynb') assert a == 1 when I run it with this test it returns 0, although, when I run jupyter notebook separately it returns 1 as expected. Why is the output different? Did I make some mistake in method, which runs notebook? Can somebody help? UPDATE: As I've figured out it always returns 0, no matter what code is executed in notebook. Does someone know how to make it work?
answer count: 1
has answer: http://stackoverflow.com/a/50501645
favorite count: 0
tagged with: jupyter-notebook
type: Question
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50501645
tagged with: python
has title: pytest test for running jupyter notebook

http://stackoverflow.com/q/50499813
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: I am trying to import Biopython modules on my Mac terminal but its throwing following error. It will be very helpful if someone could help me fix this issue. &gt;&gt;&gt; from Bio import SeqIO Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.7/site-packages/Bio/SeqIO/__init__.py", line 317, in &lt;module&gt; from Bio._py3k import basestring File "/Library/Python/2.7/site-packages/Bio/_py3k/__init__.py", line 235, in &lt;module&gt; from urllib2 import urlopen, Request File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 94, in &lt;module&gt; import httplib File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1230, in &lt;module&gt; import ssl File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 133, in &lt;module&gt; PROTOCOL_SSLv23 = PROTOCOL_TLS NameError: name 'PROTOCOL_TLS' is not defined Thank you!!!
favorite count: 0
score: 3
tagged with: python-2.7
has title: NameError: name 'PROTOCOL_TLS' is not defined
tagged with: python
tagged with: biopython
type: Question
has answer: http://stackoverflow.com/a/50499917
upvote count: 3

http://stackoverflow.com/q/50539573
tagged with: string
tagged with: request.querystring
favorite count: 0
type: Question
tagged with: python-3.x
has title: how to get query string parameters from url in aiohttp?
accepted answer: http://stackoverflow.com/a/50541655
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50541655
upvote count: 4
type: AnsweredQuestion
tagged with: aiohttp
has body: I tried to get query string parameters from url by using aiohttp, but this code does not work : async def call_answer(request): print("request", request) params = request.rel_url.query print("parameters +++++", params["call_id"]) conn = psycopg2.connect(connect_str) cursor = conn.cursor() sql = """ update calls set status = %s where id = %s; """ % (params["status"], params["call_id"]) cursor.execute(sql) conn.commit() return web.Response( content_type='application/json', text=json.dumps({ 'status': 'success' })) if __name__ == '__main__': parser = argparse.ArgumentParser(description='WebRTC audio / video / data-channels demo') parser.add_argument('--port', type=int, default=8080, help='Port for HTTP server (default: 8080)') parser.add_argument('--verbose', '-v', action='count') args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) app = web.Application() app.router.add_get('/{call_id}&amp;{status}', call_answer) I searched in the internet and everywhere it was written that you should use request.rel_url.query to get all parameters from query string, but I get error when running the code!!!!!
answer count: 1
downvote count: 0

shell
tags question: http://stackoverflow.com/q/50502266
tags question: http://stackoverflow.com/q/50395613
tags question: http://stackoverflow.com/q/50401312
tags question: http://stackoverflow.com/q/50523869
tags question: http://stackoverflow.com/q/50503913
tags question: http://stackoverflow.com/q/50539618
type: Tag
tags question: http://stackoverflow.com/q/50533871
tag name: shell
tags question: http://stackoverflow.com/q/50400686
tags question: http://stackoverflow.com/q/50482667
tags question: http://stackoverflow.com/q/50527600
tags question: http://stackoverflow.com/q/50483586
tags question: http://stackoverflow.com/q/50397391

http://stackoverflow.com/comment/87821227
has text: Glad I could help. Please don't forget to mark this as the answer :)
comment on: http://stackoverflow.com/a/50402434
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87804770
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50394183
score: 0
has text: Yes I didnt observed that

http://stackoverflow.com/comment/88029509
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50504762
has text: I don't understand your answer: in your function `findindex` how are you supposed to specify which number to find?
score: 0

http://stackoverflow.com/a/50518559
answers question: http://stackoverflow.com/q/50391853
type: AcceptedAnswer
has body: Solved Density-based spatial clustering of applications with noise (DBSCAN) Identify each hole according to estimated number of clusters, the diameter can be calculated using the Convex hull
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50391853

http://stackoverflow.com/q/50392231
score: 0
tagged with: turtle-graphics
answer count: 1
has answer: http://stackoverflow.com/a/50394582
type: Question
tagged with: reinforcement-learning
tagged with: algorithm
has title: Reinforcement learning algorithm using turtle graphics not functioning
tagged with: python
has body: Currently trying to implement a Q table algorithm in my environment created using turtle graphics. When i try running the algorithm which uses Q learning I get an error stating: File "&lt;ipython-input-1-cf5669494f75&gt;", line 304, in &lt;module&gt; rl() File "&lt;ipython-input-1-cf5669494f75&gt;", line 282, in rl A = choose_action(S, q_table) File "&lt;ipython-input-1-cf5669494f75&gt;", line 162, in choose_action state_actions = q_table.iloc[state, :] File "/Users/himansuodedra/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1367, in __getitem__ return self._getitem_tuple(key) File "/Users/himansuodedra/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1737, in _getitem_tuple self._has_valid_tuple(tup) File "/Users/himansuodedra/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 204, in _has_valid_tuple if not self._has_valid_type(k, i): File "/Users/himansuodedra/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1674, in _has_valid_type return self._is_valid_list_like(key, axis) File "/Users/himansuodedra/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py", line 1723, in _is_valid_list_like raise IndexingError('Too many indexers') IndexingError: Too many indexers I cannot seem to pinpoint the problem. The logic to me looks fine. Also I am able to build the environment thereafter the script gets stuck and i am forced to terminate it. Any help would be great. The code is below: """ Reinforcement Learning using table lookup Q-learning method. An agent "Blue circle" is positioned in a grid and must make its way to the green square. This is the end goal. Each time the agent should improve its strategy to reach the final Square. There are two traps the red and the wall which will reset the agent. """ import turtle import pandas as pd import numpy as np import time np.random.seed(2) """ Setting Parameters """ #N_STATES = 12 # the size of the 2D world ACTIONS = ['left', 'right', 'down…
accepted answer: http://stackoverflow.com/a/50394582
type: AnsweredQuestion

http://stackoverflow.com/a/50503324
has comment: http://stackoverflow.com/comment/88019092
has comment: http://stackoverflow.com/comment/88019050
type: Answer
has comment: http://stackoverflow.com/comment/88019699
answers question: http://stackoverflow.com/q/50503290
has body: I think to_datetime with a specified format should be enough: df['Date'] = pd.to_datetime(df['Date'], format='%m%Y') print (df) Index Date 0 0 2018-01-01 1 1 2018-10-01 2 2 2018-03-01 3 3 2018-12-01 4 4 2019-11-01 5 5 2019-03-01 6 6 2019-04-01 print (df.dtypes) Index int64 Date datetime64[ns] dtype: object Thank you @Vivek Kalyanarangan for solution - add strftime for custom string format (but lost datetimes): df['Date'] = pd.to_datetime(df['Date'], format='%m%Y').dt.strftime('%d-%m-%Y') print (df) Index Date 0 0 01-01-2018 1 1 01-10-2018 2 2 01-03-2018 3 3 01-12-2018 4 4 01-11-2019 5 5 01-03-2019 6 6 01-04-2019 print (df.dtypes) Index int64 Date object dtype: object print (df['Date'].apply(type)) 0 &lt;class 'str'&gt; 1 &lt;class 'str'&gt; 2 &lt;class 'str'&gt; 3 &lt;class 'str'&gt; 4 &lt;class 'str'&gt; 5 &lt;class 'str'&gt; 6 &lt;class 'str'&gt; Name: Date, dtype: object
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88019545
has comment: http://stackoverflow.com/comment/88019676
has comment: http://stackoverflow.com/comment/88022377
has comment: http://stackoverflow.com/comment/88022405
has comment: http://stackoverflow.com/comment/88019177
accepted answer of: http://stackoverflow.com/q/50503290

http://stackoverflow.com/comment/87984444
type: Comment
type: QuestionComment
has text: `word1.replace(w[i],'')` replaces all instances of `w[i]` in `word1`
comment on: http://stackoverflow.com/q/50485559
score: 1

http://stackoverflow.com/comment/87813865
score: 0
type: Comment
type: QuestionComment
has text: Works now. Thanks.
comment on: http://stackoverflow.com/q/50398159

http://stackoverflow.com/comment/88243312
score: 0
has text: Works fine now, thank you so much. Am not very comfortable with cython yet. Appreciate it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50527187

http://stackoverflow.com/a/50529810
has body: Using pd.crosstab: df = pd.crosstab(df.Rank, df.ID).iloc[:5].unstack().reset_index() df.loc[(df[0]==0),'Rank'] = np.nan del df[0] Output: ID Rank 0 a 1.0 1 a 2.0 2 a 3.0 3 a 4.0 4 a 5.0 5 c 1.0 6 c 2.0 7 c NaN 8 c NaN 9 c NaN 10 e 1.0 11 e 2.0 12 e 3.0 13 e NaN 14 e NaN Another approach, assuming the maximum group size in df is exactly 5. In [251]: df.groupby('ID').Rank.apply(np.array).apply(pd.Series).stack(dropna=False) Out[251]: ID a 0 1.0 1 2.0 2 3.0 3 4.0 4 5.0 c 0 1.0 1 2.0 2 NaN 3 NaN 4 NaN e 0 1.0 1 2.0 2 3.0 3 NaN 4 NaN dtype: float64 Full explanation: import pandas as pd import numpy as np df = pd.read_csv(pd.compat.StringIO("""Rank ID 0 1 a 1 2 a 2 3 a 3 4 a 4 5 a 6 1 c 7 2 c 8 1 e 9 2 e 10 3 e"""), sep=r' +') df = pd.crosstab(df.Rank, df.ID).iloc[:5].T.stack().reset_index() df.loc[(df[0]==0),'Rank'] = np.nan del df[0] # pd.crosstab(df.Rank, df.ID) produces: # ID a c e # Rank # 1.0 1 1 1 # 2.0 1 1 1 # 3.0 1 0 1 # 4.0 1 0 0 # 5.0 1 0 0 # applying .T.stack().reset_index() yields: # ID Rank 0 # 0 a 1.0 1 # 1 a 2.0 1 # 2 a 3.0 1 # 3 a 4.0 1 # 4 a 5.0 1 # 5 c 1.0 1 # 6 c 2.0 1 # 7 c 3.0 0 # 8 c 4.0 0 # 9 c 5.0 0 # 10 e 1.0 1 # 11 e 2.0 1 # 12 e 3.0 1 # 13 e 4.0 0 # 14 e 5.0 0 # finally, use df[0] to filter df['Rank']
has comment: http://stackoverflow.com/comment/88071465
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50529459
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50529459

http://stackoverflow.com/comment/87921000
type: QuestionComment
comment on: http://stackoverflow.com/q/50448026
score: 0
type: Comment
has text: Yes, I tried that already.

http://stackoverflow.com/comment/88084270
type: Comment
has text: The query returns one row. Write a loop in Python.
type: AnswerComment
comment on: http://stackoverflow.com/a/50535415
score: 0

http://stackoverflow.com/q/50423507
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87863306
answer count: 1
has title: Move files depending on occurence in a python list
has answer: http://stackoverflow.com/a/50423621
has body: do you know if it is possible if you have a folder filled by fasta files such as : seq1.fa seq2.fa seq3.fa seq4.fa seq5.fa seq6.fa seq7.fa ... seq1000.fa and to only keep, or move into a new folder, the sequences which are present in a dataframe such as: seq_names seq1 seq3 seq8 seq89 And that with python exclusively? the new folder would be then: seq1.fa seq3.fa seq8.fa seq89.fa Thank you for you help :)
accepted answer: http://stackoverflow.com/a/50423621
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50487586
score: 0
has comment: http://stackoverflow.com/comment/87990237
tagged with: weasyprint
has comment: http://stackoverflow.com/comment/87989309
answer count: 0
has body: I was trying to install weasyprint using command "pip install weasyprint". It gave me error: requests 2.18.4 has requirement chardet&lt;3.1.0,&gt;=3.0.2, but you'll have chardet 2.3.0 which is incompatible. tensorboard 1.8.0 has requirement html5lib==0.9999999, but you'll have html5lib 1.0.1 which is incompatible. bleach 1.5.0 has requirement html5lib!=0.9999,!=0.99999, &lt;0.99999999,&gt;=0.999, but you'll have html5lib 1.0.1 which is incompatible. Does anyone know how to fix it?
tagged with: python
type: UnansweredQuestion
has title: weasyprint - installation in ubuntu.
has comment: http://stackoverflow.com/comment/87988172
type: Question

http://stackoverflow.com/q/50415121
type: Question
type: AnsweredQuestion
has title: Calling Google cloud Vision API's on numpy matrices
has body: I'm using the Google Text detection API for performing OCR on images. I've found that my OCR results are much better when I perform some pre-processing on the images using opencv. My question is - how can I call the Google cloud Vision API's on images I have in memory as Numpy arrays? The official Google docs only show the vision api accepting an image in disk as the input. I want to avoid unnecessary disk writes.
tagged with: google-cloud-functions
tagged with: python
score: 7
has answer: http://stackoverflow.com/a/50554499
possible better answer: http://stackoverflow.com/a/50432263
favorite count: 0
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/50432263
tagged with: google-api
downvote count: 0
accepted answer: http://stackoverflow.com/a/50554499
tagged with: google-compute-engine
upvote count: 7

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/50469877
tags question: http://stackoverflow.com/q/50504447
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/50436692
tags question: http://stackoverflow.com/q/50530049

http://stackoverflow.com/q/50439859
has answer: http://stackoverflow.com/a/50455389
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has title: garbage collection - does mark+sweep have to be monolithic/atomic
accepted answer: http://stackoverflow.com/a/50455389
favorite count: 0
type: Question
tagged with: garbage-collection
tagged with: python
tagged with: memory
has body: This discussion will use the micropython code but since it's so simple, I hope it will be useful to the general discussion of mark+sweep Micropython uses garbage collection, specifically mark-and-sweep; let's define that. Mark During the mark phase, the gc follows memory references and literally marks the used memory blocks to indicate they are reachable from the set of root blocks. Sweep After the mark phase is complete, the sweeper loops over the entire heap and if a memory block is used but not marked it means it is unreachable by the code so it is "freed" i.e. tagged as free. The memory blocks which were marked during the mark phase have that mark removed. The current implementation requires an atomic call to perform garbage collection aka gc but I've been wondering if it's possible to split it up into multiple calls as opposed to a monolithic/atomic call. This would help reduce jitter: instead of one big timing hit, you'd have a bunch of smaller calls spread out. (The implementation details of how you'd "spread out" the gc calls are not discussed here . . . unless someone thinks it would add to the discussion.) If gc is running "in the background" - in-between bytecodes or after pre-defined bytecodes - then an allocation (or deallocation) at the wrong point could result in a race-condition and heap corruption. Before we can split up gc execution, we have to determine the possible race conditions. The two operations that can be performed are: allocation and deallocation. Allocation What could happen if the user performs an allocation in the middle of either the mark or sweep phase? Let's look at a concrete code example &gt;&gt; var1 = SomeAllocation() Allocation during mark In the above example, a statement is executed in the REPL so any additions to the dictionary would be to the global dictionary which is an entry in the GC Roots. If an entry is added to globals before it is scanned, nothing "bad" happens: the new memory block will be marked as it should be. T…
type: AnsweredQuestion
tagged with: micropython

http://stackoverflow.com/q/50418649
tagged with: large-files
has body: I'm reading in large sets of data from an .h5 file, (200,000 points per dataset) and I currently don't need all of it so what I've been doing is reading in the data, then truncating it after. Is there a way to only read the first X items of an h5 dataset?
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87853071
score: 4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/54209593
upvote count: 5
tagged with: h5py
has title: read part of h5 dataset python
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/54209593

http://stackoverflow.com/q/50526451
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/31489121
has comment: http://stackoverflow.com/comment/88064887
has comment: http://stackoverflow.com/comment/88094060
tagged with: python
accepted answer: http://stackoverflow.com/a/50542563
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: tkinter
has title: Indeterminate Progress bar while function is running
downvote count: 0
has body: I have a GUI which has two buttons and a progressbar stacked on a single column. Each button calls a different function which takes some time to execute. I want the progress bar to move when someone clicks any of the two buttons and keep moving (indeterminately) until the function finishes and then stop. I know I need to use multi-threading but I can't seem to get the code right! Code from tkinter import Tk import time from tkinter import * from tkinter import Button from tkinter import Frame from tkinter import ttk import threading def sample_function(): time.sleep(2) # SAMPLE FUNCTION BEING CALLED def prepare_clicked(): sample_function() def social_clicked(): sample_function() def anomaly_clicked(): sample_function() window = Toplevel() # Tried using Tk but I am using image to design each buttons through the button config in my actual code and tk throws error topFrame = Frame(window) topFrame.pack() prepare_btn = Button(topFrame, command=prepare_clicked,text='Button1') anomaly_btn = Button(topFrame,command=anomaly_clicked,text='Button2') social_btn = Button(topFrame, command=social_clicked,text='Button3') processing_bar = ttk.Progressbar(topFrame, orient='horizontal', mode='indeterminate') window.rowconfigure((0,1), weight=1) # make buttons stretch when window.columnconfigure((0,3), weight=1) # when window is resized prepare_btn.grid(row=0, column=1, columnspan=1, sticky='EWNS') anomaly_btn.grid(row=1, column=1, columnspan=1, sticky='EWNS') social_btn.grid(row=2, column=1, columnspan=1, sticky='EWNS') processing_bar.grid(row=3, column=1, columnspan=1, sticky='EWNS') window.mainloop()
has comment: http://stackoverflow.com/comment/88096537
answer count: 1
linked to: http://stackoverflow.com/q/37508720
has answer: http://stackoverflow.com/a/50542563

http://stackoverflow.com/a/50529193
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/88070073
has comment: http://stackoverflow.com/comment/88070014
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/88070733
has body: You are asking us how to make it so you can overfit your model... My ranking will not work if half the pairs are in the training set for example, since then the ranking for the test set will be missing some pairs... Your ranking must work if some (most!) of your pairs are not in the test set, otherwise what is the point of generating the network? In any case, what you are asking is mathematically impossible. The only way you could seperate out the paragraphs the way you ask is if you have two completely unrelated sets with no overlap at all. If you imagine your paragraphs as nodes in a graph and the connections as vectors, your best case scenario is that you end up with two islands with only a single connection between them. If that connection is between paragraphs 1 and 2, then it's clear that both of those must have at least one pairing in each set.
answers question: http://stackoverflow.com/q/50529050

http://stackoverflow.com/comment/87949273
type: Comment
score: 0
type: AnswerComment
has text: @Abhishek. Sorry I do not understand. Your output is the same as I have
comment on: http://stackoverflow.com/a/50467786

http://stackoverflow.com/comment/88053564
score: 0
type: Comment
has text: If you're looking for a complete solution that creates the 2D array, see [my answer](https://stackoverflow.com/a/50520595/1938859)
type: AnswerComment
comment on: http://stackoverflow.com/a/50520509

http://stackoverflow.com/a/50530675
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50530440
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50530440
has comment: http://stackoverflow.com/comment/89373920
has comment: http://stackoverflow.com/comment/89373887
type: Answer
has body: You can pipe the data to grep to select the last line with tail containing "t_room", then print the 3rd column separated by space using awk. For example, if your data is saved in log.txt: cat log.txt | grep t_room | tail -n 1 | awk -F" " '{print $3}'
has comment: http://stackoverflow.com/comment/89493156

http://stackoverflow.com/comment/114783524
has text: Which one do you think works better, MonkeyType or pyannotate?
score: 7
type: Comment
comment on: http://stackoverflow.com/a/50416746
type: AnswerComment

http://stackoverflow.com/comment/87877931
comment on: http://stackoverflow.com/q/50412058
has text: this is our post request as per setting So please provide m solution how We set time for push notification
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/87906001
comment on: http://stackoverflow.com/a/50445946
type: AnswerComment
score: 1
has text: Please don't answer duplicates.
type: Comment

http://stackoverflow.com/comment/88049697
score: 0
comment on: http://stackoverflow.com/q/50518339
type: Comment
type: QuestionComment
has text: Nope. As a quick trial, I copied a request from the spec demo section and replaced strings inside it. body = '{"jsonrpc": "2.0", "method": "#METHOD#", "params": #PRMS#, "id": #ID#}'.replace("#METHOD#",self.method,1).replace("#PRMS#",json.dumps(self.prms),1).replace("#ID#",str(self.client.id),1)

http://stackoverflow.com/comment/88092486
type: QuestionComment
comment on: http://stackoverflow.com/q/50540332
has text: Possible duplicate of [Foursquare api consumer disabled](https://stackoverflow.com/questions/40725074/foursquare-api-consumer-disabled)
score: 0
type: Comment

http://stackoverflow.com/q/50395170
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50395406
has title: Multi-label classification loss function
tagged with: python
favorite count: 0
has body: I have seen in many places that, for multi-label classification using neural networks, one useful loss function to use is the binary cross entropy for each of the output nodes. In Tensorflow it looks like this: cost = tf.nn.sigmoid_cross_entropy_with_logits() This gives an array with as many values as output nodes we have. My question is, should this cost function be averaged over the number of output nodes? Which in Tensorflow would look like: cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits()) Or each loss is treated independently? Thanks
upvote count: 4
accepted answer: http://stackoverflow.com/a/50395406
type: AnsweredQuestion
tagged with: classification
answer count: 1
downvote count: 0
tagged with: neural-network
tagged with: multilabel-classification
score: 4

http://stackoverflow.com/comment/88090062
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50539117
score: 0
has text: If I hadd `%z` I'm getting the following error: `ValueError: 'z' is a bad directive in format '%d/%b/%Y:%H:%M:%S:%f%z'`

http://stackoverflow.com/q/50460267
tagged with: properties
linked to: http://stackoverflow.com/q/21640714
has comment: http://stackoverflow.com/comment/87934260
tagged with: class
tagged with: python-2.7
linked to: http://stackoverflow.com/q/31590152
tagged with: dynamic
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/24509737
has answer: http://stackoverflow.com/a/50460410
linked to: http://stackoverflow.com/q/962962
type: Question
has body: I have a class instance with several properties: class MyClass(object): @property def func(self): return [1,4,5] @property def func2(self): return 6 I would like to dynamically change a property from a user supplied new method, for example: obj = MyClass() def patch_property(name, new_return): source = '@property\ndef %s(self):\n return %s' % (parameter_name, new_return) code = compile(source, file_name, 'exec')` class SubMyClass(MyClass): eval(code) obj.__class__ = SubMyClass patch_property('func', [6,7,8]) This works, however it changes type(obj), which messes up some other stuff. Doing the following does not: cls = type(obj) new_cls = type(cls.__name__, (cls,), {}) obj.__class__ = new_cls However, I can't figure out how to properly get the eval(code) from above in the new_cls. Any ideas on how to solve this? I also tried monkeypatching the property: def patch_fun(code): def patched_fun(self): eval(code) return patched_fun patched_fun = patch_fun(code) setattr(cls, name, property(patched_fun)) or the bound method: patched_fun = patch_fun(code).__get__(obj, type(obj)) setattr(cls, name, property(patched_fun)) (I couldn't figure it out from these: Dynamically adding a property to a class , Dynamically adding @property in python, Monkey Patching an attribute within a class, Monkey patching a @property , Python: changing methods and attributes at runtime
has title: Dynamically add @property to python class from user defined string
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2954331
tagged with: python

http://stackoverflow.com/comment/87923308
type: QuestionComment
has text: Start by trying to fix the .py file association using the GUI. You can use the control panel or the "open with" "choose another app" dialog. Make sure it's set to "Python" with a rocket on the icon, which should be the py.exe launcher as configured by the "Python.File" ProgId, which should be set up to pass command line arguments, unless some other program messed with it.
comment on: http://stackoverflow.com/q/50440889
score: 0
type: Comment

http://stackoverflow.com/comment/88002823
comment on: http://stackoverflow.com/a/50494986
type: Comment
has text: what is the name of the environment in which you are trying to run tensorflow on a gpu?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/115458979
has text: As an added comment, for those who wonder, this solution works on both linux and windows.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/55978589
type: AnswerComment

http://stackoverflow.com/comment/87892241
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50439035
type: Comment
has text: How does that make sense? Why would this be intentional, if the first line of your code says print that should be printed before the next line of your code no? Apparently this issue doesn't happen across others users Jupyter Notebooks. I am running Mac High Sierra with Safari 11.1

http://stackoverflow.com/a/50538742
has comment: http://stackoverflow.com/comment/88089656
has comment: http://stackoverflow.com/comment/88089529
has comment: http://stackoverflow.com/comment/88089455
type: Answer
has comment: http://stackoverflow.com/comment/88089486
has comment: http://stackoverflow.com/comment/88094506
has comment: http://stackoverflow.com/comment/88089640
has comment: http://stackoverflow.com/comment/88089439
has body: Your error message is saying that the function topDownPlayerControls is not defined. This is because you are trying to call it as a free function. However, this function is defined within the playerMovement class. So, you would first need to create a playerMovement object, and then call the topDownPlayerControls function on that object. It would look something like this: player = playerMovement() player.topDownPlayerControls() It looks like you will have a number of other fails after that, but I'll leave that as an exercise :)
has comment: http://stackoverflow.com/comment/88089564
has comment: http://stackoverflow.com/comment/88094541
has comment: http://stackoverflow.com/comment/88089552
has comment: http://stackoverflow.com/comment/88090024
score: 0
answers question: http://stackoverflow.com/q/50538606

http://stackoverflow.com/a/50441142
has comment: http://stackoverflow.com/comment/87903457
type: Answer
answers question: http://stackoverflow.com/q/50441027
score: 9
accepted answer of: http://stackoverflow.com/q/50441027
has body: With recursion, you can build a dictionary comprehension that accomplishes that. This solution also takes into account that you might want to later merge more than two dictionaries, flattening the list of values in that case. def update_merge(d1, d2): if isinstance(d1, dict) and isinstance(d2, dict): # Unwrap d1 and d2 in new dictionary to keep non-shared keys with **d1, **d2 # Next unwrap a dict that treats shared keys # If two keys have an equal value, we take that value as new value # If the values are not equal, we recursively merge them return { **d1, **d2, **{k: d1[k] if d1[k] == d2[k] else update_merge(d1[k], d2[k]) for k in {*d1} &amp; {*d2}} } else: # This case happens when values are merged # It bundle values in a list, making sure # to flatten them if they are already lists return [ *(d1 if isinstance(d1, list) else [d1]), *(d2 if isinstance(d2, list) else [d2]) ] Example: a = {"name": "john", "phone":"123123123", "owns": {"cars": "Car 1", "motorbikes": "Motorbike 1"}} b = {"name": "john", "phone":"123", "owns": {"cars": "Car 2"}} update_merge(a, b) # {'name': 'john', # 'phone': ['123123123', '123'], # 'owns': {'cars': ['Car 1', 'Car 2'], 'motorbikes': 'Motorbike 1'}} Example with more than two objects merged: a = {"name": "john"} b = {"name": "jack"} c = {"name": "joe"} d = update_merge(a, b) d = update_merge(d, c) d # {'name': ['john', 'jack', 'joe']}
has comment: http://stackoverflow.com/comment/87939701
type: AcceptedAnswer
downvote count: 0
upvote count: 9

http://stackoverflow.com/comment/88091406
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50539880
type: QuestionComment
has text: Anyway, I don't see why you can't just create a mask from whatever condition and call `mask.sum()` on it.

http://stackoverflow.com/comment/87861390
comment on: http://stackoverflow.com/q/50417795
score: 0
type: Comment
type: QuestionComment
has text: It's windows 10

http://stackoverflow.com/a/50392854
upvote count: 2
type: Answer
has body: I believe this is worth a shot: class Foo: complete = False def set_complete_true(self): self.complete = True a = Foo() a.set_complete_true() print(a.complete) # should be True now
answers question: http://stackoverflow.com/q/50392787
score: 1
downvote count: 1

http://stackoverflow.com/comment/87871552
has text: I'm not sure I understand what you're asking, but it seems to me that you'll need to ask for user input within the while loop, and then branch off with a bunch of if/else statements.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50428381
type: Comment

http://stackoverflow.com/comment/88002375
type: QuestionComment
has text: Isn't the server supposed to send the token expiry along with the token? That's how token auth is supposed to be done I think.
score: 0
comment on: http://stackoverflow.com/q/50494664
type: Comment

http://stackoverflow.com/comment/87850496
has text: You don't want to create variables on-the-fly like that...how will you write code to reference the name since you won't know what it will be until runtime? Also see [Why you don't want to dynamically create variables](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html).
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50417265

http://stackoverflow.com/comment/88166682
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50513539
has text: Yes I tried unsuccessfully.. Can you try on your pc and let me know if you get the same results?

http://stackoverflow.com/comment/129512527
has text: [Dask SQL](https://dask-sql.readthedocs.io/en/latest/) has a [create_table](https://dask-sql.readthedocs.io/en/latest/api.html?highlight=create_table#dask_sql.Context.create_table) method which can create many tables of different widths. Each table will be a different parquet file, and the `dask_sql` context will manage them.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50456673
score: 0

http://stackoverflow.com/comment/87880104
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50420198
has text: It's incomplete currently only works on one page, but that can be added one you get the basics working
score: 0

http://stackoverflow.com/comment/87818309
comment on: http://stackoverflow.com/q/50401187
score: 0
has text: However, there is a bug in your code that would sort of look like what you're asking about: if you pay exactly 200, first it does `moneyihave = moneyihave - 200`, and then it prints `moneyihave - 200`. So, instead of showing you how much you have left after buying coffee, it shows you $200 _less_ than you have left after buying coffee. It's not actually deducting double, but it's lying to you about the effect of deducting single, which is confusing.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50415632
duplicate of: http://stackoverflow.com/q/41825978
has title: How to select top n row from each group after group by in pandas?
tagged with: python
accepted answer: http://stackoverflow.com/a/50415831
linked to: http://stackoverflow.com/q/41825978
has answer: http://stackoverflow.com/a/50415831
type: AnsweredQuestion
score: 8
has comment: http://stackoverflow.com/comment/87847118
has comment: http://stackoverflow.com/comment/87846981
answer count: 1
downvote count: 0
favorite count: 0
type: Question
upvote count: 8
tagged with: pandas
has body: I have a pandas dataframe with following shape open_year, open_month, type, col1, col2, .... I'd like to find the top type in each (year,month) so I first find the count of each type in each (year,month) freq_df = df.groupby(['open_year','open_month','type']).size().reset_index() freq_df.columns = ['open_year','open_month','type','count'] Then I want to find the top n type based on their freq (e.g. count) for each (year_month). How can I do that? I can use nlargest but I'm missing the type freq_df.groupby(['open_year','open_month'])['count'].nlargest(5) but I'm missing the column type

http://stackoverflow.com/comment/135532802
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50391941
score: 0
has text: In my case it has just corrupted py files sent over with scp and re-doing it fixed it.

http://stackoverflow.com/comment/87888063
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50436896
has text: that's the problem, I have no idea... here is the link https://stackoverflow.com/questions/46393162/how-to-validate-a-recaptcha-response-server-side-with-python

bit
tag name: bit
type: Tag
tags question: http://stackoverflow.com/q/50451184

http://stackoverflow.com/q/50409212
type: Question
tagged with: python-3.x
tagged with: zodb
has title: ZODB python database with Filestorage: why do temporary files stay on the disk?
tagged with: database
tagged with: python
has body: I'm experimenting with the ZODB database module in Python 3.6. In my experiment, I create a TreeSet() and fill it with data. Then I commit the transaction (which saves the changes to disk) and close the database. from ZODB.FileStorage import FileStorage from ZODB import DB from persistent import Persistent from BTrees.OOBTree import TreeSet import transaction if __name__ == '__main__': # 1. Create ZODB database # ------------------------ storage = FileStorage("C:/database_test/mydb.db") db = DB(storage) conn = db.open() root = conn.root() root.files = TreeSet() # 2. Fill the TreeSet # -------------------- ... # 3. Save and close # ------------------ transaction.commit() conn.close() db.close() # &lt;- is this even necessary? I look at the files remaining on my harddrive. As you can see, there are three temporary files remaining there - even after I've closed the database. Did I close something (database, connection, storage, transaction, ...) not properly? Note: I don't know if this is important, but my system is as follows: Windows 10, 64-bit Python 3.6.3 ZODB 5.4.0 (is latest version as of now - 18 May 2018)
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/50409890
possible better answer: http://stackoverflow.com/a/50409718
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50409890
score: 3
answer count: 2
has answer: http://stackoverflow.com/a/50409718
upvote count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50452104
has body: I want to interpolate a list of values (a pandas' series) using scipy.interpolate.interp1d setting a constant value when the input is a NAN. The reason for this is that I need to multiply another series for the output of the interpolation, and I would like to multiply by 1 is the input is NAN Right now i did import pandas as pd import numpy as np from scipy.interpolate import interp1d X = [0,180,360] Y = [1,10,1] df = pd.DataFrame({'a':[1,2,3,4,5], 'b':[0,180, np.nan, 270, 999]}) interp= interp1d(X, Y, kind='linear', bounds_error= False) K = interp(df['b']) Knp.isnan(K) = 1 df['a'] = df['a'] * K In [15]: df.a Out[15]: 0 1.0 1 20.0 2 3 3 22.0 4 5.0 However, since df is rather large, I was looking for something a bit more direct that didn't require the creation of the variable K and to check with np.isnan the vector. Moreover this produce also annoying warnings during interp1d. For points outside of interpolating boundaries I can do interp= interp1d(X, Y, kind='linear', bounds_error= False, fill_value = 1) that would allow me to do df['a'] = df['a'] * interp(df['b']) but sadly this does not handles "nan" in df['b']. Is there a better way to achieve this result?
type: UnansweredQuestion
tagged with: python
tagged with: pandas
answer count: 0
has title: setting nan value when interpolating in scipy
score: 1
downvote count: 0
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87974127
comment on: http://stackoverflow.com/q/50480175
score: 0
type: Comment
type: QuestionComment
has text: @AChampion if i use dictionary then what to do when I have to concatenate these two dataframe into new dataframe, when i tried doing it, i got following error.. ``` first argument must be an iterable of pandas objects, you passed an object of type "DataFrame ```

http://stackoverflow.com/a/50485299
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50484946
type: Answer
answers question: http://stackoverflow.com/q/50484946
has comment: http://stackoverflow.com/comment/88251368
has body: Just use networkx: &gt;&gt;&gt; import networkx as nx &gt;&gt;&gt; G = nx.Graph() &gt;&gt;&gt; G.add_nodes_from([1, 2, 3, 4]) &gt;&gt;&gt; G.add_edges_from([(1, 2), (2, 3), (3, 4)]) &gt;&gt;&gt; nx.algorithms.shortest_path(G, 1, 4) [1, 2, 3, 4]
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/50538941
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50538563
downvote count: 0
answers question: http://stackoverflow.com/q/50538563
upvote count: 1
type: AcceptedAnswer
has body: You never call fit_transform() on test, only transform() and use the same vectorizer which is used on training data. Do this: def featureExtraction(data): vectorizer = TfidfVectorizer(min_df=10, max_df=0.75, ngram_range=(1,3)) tfidf_data = vectorizer.fit_transform(data) # Here I am returning the vectorizer as well, which was used to generate the training data return vectorizer, tfidf_data ... ... tfidf_vectorizer, tfidf_data = featureExtraction(data) ... ... # Now using the same vectorizer on test data X_test= tfidf_vectorizer.transform(Xnew) ... In your code, you are using a new TfidfVectorizer which obviously will not know about the training data and also not know that training data has 8581 features. The test data should be prepared in the same way as you prepare the train data, always. Else even if you not get error, the results are wrong and model will not perform like that in real case scenarios. See my other answers explaining similar situation for different feature preprocessing techniques: https://stackoverflow.com/a/47205199/3374996 https://stackoverflow.com/a/50461140/3374996 https://stackoverflow.com/a/44671967/3374996 I would have tagged this question as a duplicate of one of these, but seeing you are using a new vectorizer altogether and have a different method for transforming train data, I answered this. From next time, please search the issue first and try understanding whats happening in similar scenarios, before posting a question.

http://stackoverflow.com/q/50538833
has comment: http://stackoverflow.com/comment/88090020
score: -5
tagged with: python-3.x
favorite count: 0
has comment: http://stackoverflow.com/comment/88089906
type: Question
has comment: http://stackoverflow.com/comment/88092799
upvote count: 0
type: UnansweredQuestion
has title: Failed to Print the Length of List for Each Line Read?
has answer: http://stackoverflow.com/a/50539417
answer count: 1
has comment: http://stackoverflow.com/comment/88089629
downvote count: 5
tagged with: python
has body: After reading text file and loop through each line, I tried to output the 2nd item from a list, which is a list as well as below. with open('xxx.txt','r') as f: for l in f.readlines(): s=l.split("\t") s[1]=s[1].replace('/','') s[1]=s[1].replace('\n','') s[1]=s[1].split(',') print(s[1])) Below is the result after running code above in ipython notebook. However, I got the error saying the int is not callable when I tried to print(len(s[1])). I'm not sure what went wrong.

http://stackoverflow.com/a/50535234
has body: I just had to create an array for the first set of results, and then iterate each id separately: user_id_array = [] for user_collection in user_ref.get(): user_id_array.append(user_collection.id) for user_id in user_id_array: try: suscription_ref = doc_ref.document(user_id).collection(u'suscriptions').document(user_id).get() print(suscription_ref.id,file = sys.stderr) except google.cloud.exceptions.NotFound: pass It takes more time, but it'll get you there.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50533791
downvote count: 0
type: Answer

http://stackoverflow.com/a/50480841
has body: You can try like this: total = int(input( ' enter any number: ' )) output = [[p + ((9 - q) * q) // 2 for q in range(p)] for p in range(1,total+1)] for ele in output: print(ele) Output: enter any number: 3 [1] [2, 6] [3, 7, 10]
answers question: http://stackoverflow.com/q/50480726
type: Answer
score: 0

http://stackoverflow.com/comment/88106752
score: 0
comment on: http://stackoverflow.com/q/50539925
type: QuestionComment
has text: I'm voting to close this question as off-topic because it's not directly related to programming but mathematical way of thinking.
type: Comment

http://stackoverflow.com/comment/87963193
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50462188
has text: Ah, I didn' t notice that your data has dates as x-values. At first, let me mention that you please shall not post code nor text file content/samples as images. This just not nice to those people who want to help you, because nothing is copy/pastable for testing or to check what's going wrong. For lists or arrays you can simply post the output of `my_list[:5]` or for a dataframe there is the nice little function `df.head()`.

http://stackoverflow.com/comment/87874419
type: Comment
score: 0
type: AnswerComment
has text: Ah, whatever, the person that asked the question seemed to get it.
comment on: http://stackoverflow.com/a/50428759

http://stackoverflow.com/a/50490977
has comment: http://stackoverflow.com/comment/87996527
has comment: http://stackoverflow.com/comment/87995643
has comment: http://stackoverflow.com/comment/87997856
has comment: http://stackoverflow.com/comment/87995175
has comment: http://stackoverflow.com/comment/87995483
type: Answer
score: -2
has body: matplotlib hist accepts the data as the first argument, so it should be: n, bins, patches = plt.hist(Y, X, normed=1, facecolor='g', alpha=0.75) Or if that is not what you want, use bar instead. Why is this being downvoted? I just corrected a false statement of the question, while the question itself was so unclear that it is not possible to give an answer which is solving the problem. Fairness and good manners are not everyone's strength.
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/87996072
has comment: http://stackoverflow.com/comment/87995289
answers question: http://stackoverflow.com/q/50490902

http://stackoverflow.com/q/50521033
downvote count: 0
score: 10
upvote count: 10
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: pip
tagged with: python
has body: I'm working on a project where one of the dependencies is actually a .whl that isn't on pypi (i.e. I had to download the wheel direct from the author and pip install it directly). In my setup.py file, is there a way to do something like: install_requires=[ 'library.whl', 'matplotlib==2.2.2', 'numpy==1.14.2', 'opencv-python==3.4.0.12', 'Pillow==5.1.0', 'PyYAML==3.12', ], Or something along these lines since its not on pypi (and I would just add the library.whl in the MANIFEST.in file or something)? If not, is there a recommended way to do this for this type of situation? I'd ideally like to solve this in the setup.py file so I can install my library easily with a single pip install
linked to: http://stackoverflow.com/q/12518499
has answer: http://stackoverflow.com/a/57094398
has answer: http://stackoverflow.com/a/50521277
has title: Add a custom wheel file as a dependency in setup.py?
tagged with: setuptools

http://stackoverflow.com/a/50519174
answers question: http://stackoverflow.com/q/50518653
type: Answer
has comment: http://stackoverflow.com/comment/88087253
has body: A naive solution will be to use groupby and a simple Counter, here's a working solution: In [1]: from itertools import groupby In [2]: from collections import Counter In [3]: whatever = [['060710080013011', 9], ['060710080013011', 9], ['060710080013011', 9], ['060710080013011', 9], ['06071008001 ...: 3011', 9], ['060710080013011', 9], ['060710080013011', 9], ['060710080013011', 9], ['060710080013011', 9], ['06071008001 ...: 3033', 8], ['060710080013033', 8], ['060710080013033', 8], ['060710080013033', 8], ['060710080013033', 8], ['06071008001 ...: 3033', 8], ['060710080013033', 8], ['060710080013033', 8], ['060710080021000', 15], ['060710080021000', 15], ['060710080 ...: 021000', 15], ['060710080021000', 15], ['060710080021000', 15], ['060710080021000', 15], ['060710080021000', 15], ['0607 ...: 10080021000', 15], ['060710080021000', 15], ['060710080021000', 15], ['060710080021000', 15], ['060710080021000', 15], [ ...: '060710080021000', 15], ['060710080021000', 15], ['060710080021000', 15]] In [7]: counter = [] ...: # we use groupby to group the inner list by key, i.e. the first label ...: for key, grouped in groupby(whatever, lambda x: x[0]): ...: # here, we decide if we need to append the label if the item counts great than multiple of 7 ...: for idx, item in enumerate(grouped): ...: # to get the LABEL_INDEX as new keyed keyed = key if int(idx / 7) == 0 else "{}_{}".format(key, int(idx / 7) + 1) ...: counter.append(keyed) ...: # simply use a counter to re-count the new label items ...: counted = Counter(counter) ...: answer = [] ...: for keyed in sorted(counted): ...: for _ in range(counted[keyed]): ...: answer.append([keyed, counted[keyed]]) ...: ...: print(answer) ...: ...: ...: ...: [['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011', 7], ['060710080013011_2', 2], ['060710080013011_2', 2], ['060710080013033', 7], ['060710080013033', 7], ['060710080013…
score: 0

http://stackoverflow.com/comment/88029542
type: Comment
has text: http://www.tornadoweb.org/en/stable/gen.html , according to this we can either use coroutines or asynchronous right ?
comment on: http://stackoverflow.com/a/50508734
type: AnswerComment
score: 0

http://stackoverflow.com/a/50415293
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50414527
score: 1
type: Answer
has body: To install packages for Jupyter notebooks there are a couple of ways of approaching it. One way is to pip install from the terminal. The other (proper) way is to use Conda install as explained here - updated link 21-Sep-2019
accepted answer of: http://stackoverflow.com/q/50414527

http://stackoverflow.com/comment/87870734
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50422208
has text: Thank you a lot! It worked like a charm. The eToken has 3 pieces. Rsa private and public keys, and the certificate, which is the trust chain, right? So, I tried to create a file.pem with the created certificate appended to certificate from token. So, the file.pem has become something like this: ----BEGIN CERTIFICATE----- ... ----END CERTIFICATE---- ----BEGIN CERTIFICATE----- ... ----END CERTIFICATE---- I tried to join then in the same BEGIN/END block. In both cases, the https://lapo.it/asn1j shows only the attributes from the token certificate. I'm a bit confused about this
type: Comment

http://stackoverflow.com/a/50530590
accepted answer of: http://stackoverflow.com/q/50530520
type: Answer
has body: Use duplicated with invert mask by ~ for boolean mask and then filter by boolean indexing with loc, before filter by columns: c = pd.Index(['level_0', 'index', 'SU_gdppc', 'SU_gdppcl', 'year', 'US_gdppc', 'US_gdppcl', 'year', 'index', 'SU_milex', 'SU_cinc', 'US_milex', 'US_cinc', 'year', 'year']) df = pd.DataFrame(columns=c) df = df.loc[:, ~df.columns.duplicated()] print (df) Empty DataFrame Columns: [level_0, index, SU_gdppc, SU_gdppcl, year, US_gdppc, US_gdppcl, SU_milex, SU_cinc, US_milex, US_cinc] Index: [] Detail: print (~df.columns.duplicated()) [ True True True True True True True False False True True True True False False]
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50530520
has comment: http://stackoverflow.com/comment/88073505
score: 3

http://stackoverflow.com/comment/87970347
has text: I think it's because the `type(f)` is `types.FunctionType` and special methods are not looked-up in the instance's dictionary, but the instance's class instead.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50478364

http://stackoverflow.com/comment/87915233
type: AnswerComment
score: 0
has text: try adding `input_length=98` I didn't realise you were using fixed length.
type: Comment
comment on: http://stackoverflow.com/a/50446946

http://stackoverflow.com/q/50538826
has comment: http://stackoverflow.com/comment/88089712
answer count: 2
type: UnansweredQuestion
has title: IndexError: list index out of range in pygame
has comment: http://stackoverflow.com/comment/88089571
tagged with: python
has answer: http://stackoverflow.com/a/50538922
has comment: http://stackoverflow.com/comment/88089601
score: 0
has answer: http://stackoverflow.com/a/50538936
tagged with: pygame
has body: The error appears on the last line of the code segment below, and i'm not sure why. I'm attempting to learn from a video i found online, which has the same code, even when i've checked multiple times and seems to work fine. class Snake: def __init__(self): self.position=[50,50] self.body=[[100,50], [90.50], [80,50]] self.direction = "RIGHT" self.changeDirectionTo=self.direction def getBody(self): return self.body window=pygame.display.set_mode((500,500)) snake = Snake() while True: for pos in snake.getBody(): pygame.draw.rect(window, pygame.Color(0,225,0), pygame.Rect(pos[0], pos[1], 10,10))
type: Question
has comment: http://stackoverflow.com/comment/88092115

http://stackoverflow.com/q/50439086
has body: in the code below I am trying to figure out the best way to share data from the "Data_Class" Class to the "Tab_2" Class. Specifically I am trying to get the values from "Data_Class" in tab1 to fill in the QLineEdit in tab2 when the buttons are clicked. I have tried using signals and sending direct to the "Tab_2" class as well but the best I can get is the values to print out in "Tab_2" but not fill the QLineEdit. In the "MainWindow" Class I build and seperate the data and then embed "Data_Class" using FlowLayout while sending the data to "Data_Class" to create the buttons and also set the values to them but now I can't get the data sent over to "Tab_2" Class. Also, the signal in "Data_Class" doesn't work, I just left it in anyway. Does anyone know what I should do to receive the values properly or have any suggestions? Thanks. import functools import sys from PyQt5.QtCore import pyqtSignal, QSize, QRect, Qt, QPoint from PyQt5.QtWidgets import QLineEdit, QPushButton,QVBoxLayout, QScrollArea, QWidget, \ QApplication, QTabWidget, QStyle, QSizePolicy, QLayout class Data_Class(QWidget): data_Signal = pyqtSignal(str) def __init__(self, item_num=None, item_data=None): super(Data_Class, self).__init__() self.tab_2 = Tab_2 self.num = item_num self.dat = item_data self.setFixedWidth(150) self.layout = QVBoxLayout() self.btn = QPushButton() self.btn.setText(str(self.num)) self.layout.addWidget(self.btn) self.setLayout(self.layout) self.btn_click = functools.partial(self.set_btns, btn_data=self.dat) self.btn.clicked.connect(self.btn_click) def set_btns(self, btn_data): print(btn_data) self.data_Signal.emit(btn_data) class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.resize(368,315) self.vbox = QVBoxLayout() self.tabWidget = QTabWidget() self.tabWidget.setTabPosition(QTabWidget.North) self.vbox.addWidget(self.tabWidget) self.tab1 = QWidget() self.tabWidget.addTab(self.tab1, ("tab1")) self.tab2 = QWidget() self.tabWidget.addTab(self.tab2, ("tab…
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/50439825
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50439825
score: 0
answer count: 2
tagged with: pyqt
has answer: http://stackoverflow.com/a/50440013
has title: PyQt Issue sending values to different class
accepted answer: http://stackoverflow.com/a/50440013
tagged with: qt-signals

http://stackoverflow.com/comment/87952869
score: 0
type: Comment
type: AnswerComment
has text: I am not sure how to do that, and I have been trying to fix it for the past day and no answer I have read has helped me, so at this point I am just frustrated and if Rakesh's answer gives me the correct end result I am fine with that.
comment on: http://stackoverflow.com/a/50468801

http://stackoverflow.com/a/50456648
type: Answer
has body: Your issue stems from the fact that you're trying to concatenate types that Python natively doesn't know how to concatenate - in your case bytes (message), str () and an int (timestamp). You need to convert your data to a common type (string, for example) before attempting to natively concatenate them, or you can let str.format() do that for you: concatenated_payload = "{} {}".format(message, timestamp) Mind you, this is still naive converting, it just doesn't inconvenience you to str() every argument you want to concatenate into a string. This could still fail, tho, if your message contains data that cannot be encoded as Unicode on Python 3.x.
accepted answer of: http://stackoverflow.com/q/50455701
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50455701
type: AcceptedAnswer

http://stackoverflow.com/q/50464674
has body: How do I get the fixed window size at one point in time? (s.t. this value will not change later) I would like to add an image: Image: width: self.parent.width height: self.parent.height size_hint: None, None which should keep its initial size when rescaling the window. I can do this like Image: width: 800 height: 800 size_hint: None, None But I can't get the windows current dimensions in a way that they stay constant when rescaling the window later. Thanks for your help.
favorite count: 0
accepted answer: http://stackoverflow.com/a/50466473
type: Question
score: 1
tagged with: python
tagged with: kivy
has title: Kivy: property to fixed value
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50466473
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/88003830
type: Comment
has text: I'd sooner guess the problem is that the class is `model.classification.Model` (so `Model` in the package `model.classification`), and not `Model` (or `Model.java` as your code tries) in the `model/classification` folder.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50495443

http://stackoverflow.com/comment/87936929
comment on: http://stackoverflow.com/q/50461868
has text: try `atomic_write('foo.txt', 'wb')` to write bytes to file
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/135098202
score: 0
has text: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34627377)
type: Comment
comment on: http://stackoverflow.com/a/76595800
type: AnswerComment

http://stackoverflow.com/comment/87922720
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50453603
has text: @Vaviloff have you got any idea how can I check if you are right ?

http://stackoverflow.com/a/54355558
answers question: http://stackoverflow.com/q/50472873
score: 2
type: Answer
upvote count: 2
downvote count: 0
has body: The shared library you just installed with anaconda shall be located here: &lt;PATH-TO-YOUR-ANACONDA&gt;/envs/&lt;YOUR-ACTIVE-CONDA-ENV&gt;/lib/ That said you can just add this path to you LD_LIBRARY_PATH so the linker can find the newly installed cudnn.so.6 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:&lt;PATH-TO-YOUR-ANACONDA&gt;/envs/&lt;YOUR-ACTIVE-CONDA-ENV&gt;/lib/ Good luck!

http://stackoverflow.com/comment/87804221
type: Comment
type: QuestionComment
has text: Possible duplicate of [Dynamic border around text in python](https://stackoverflow.com/questions/35381065/dynamic-border-around-text-in-python) (The answer to OP's question is in the other user's question.)
score: 2
comment on: http://stackoverflow.com/q/50394197

http://stackoverflow.com/q/50416036
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50416235
tagged with: pandas
downvote count: 1
has answer: http://stackoverflow.com/a/50416105
possible better answer: http://stackoverflow.com/a/50416105
has body: I am a python/pandas user and have a question about it. I have an Excel file as below. C1 C2 C3 C4 C5 C6 ID Value 0 aa ee ii mm aaaaa bbbb 1 100 1 bb ff jj nn cccc ddddd 2 50 2 aa ee ii mm eeee ffff 3 20 3 dd hh ll pp gggg hhhh 4 10 4 aa ee ii mm abcd efgh 5 5 5 bb ff jj nn aaaaa bbbb 6 2 Code to reproduce— df = pd.DataFrame({'Value': [100,50,20,10,5,2], 'ID': [1,2,3,4,5,6], 'C1': ['aa','bb','aa','dd','aa','bb'], 'C2': ['ee','ff','ee','hh','ee','ff'], 'C3': ['ii','jj','ii','ll','ii','jj'], 'C4': ['mm','nn','mm','pp','mm','nn'], 'C5': ['aaaaa','cccc','eeee','gggg','abcd','aaaaa'], 'C6': ['bbbb','ddddd','ffff','hhhh','efgh','bbbb']}) Some rows are duplicates in column1-4 (ex. ID1, ID3 and ID5 or ID2 and ID6 are duplicates). Is there any way to combine duplicate rows? (I am focusing on column1-4 and I do not care about column 5&amp;6) I want to combine the "Value" of the duplicate rows and leave the top column's sequence. For example, here is output file which I want to make. Value ID C1 C2 C3 C4 C5 C6 0 125 1 aa ee ii mm aaaaa bbbb 1 52 2 bb ff jj nn cccc ddddd 2 10 4 dd hh ll pp gggg hhhh If you could give me your opinion, I would be grateful for that very much.
favorite count: 0
type: Question
answer count: 2
has title: Combine value using python/pandas
accepted answer: http://stackoverflow.com/a/50416235
tagged with: python
upvote count: 4

http://stackoverflow.com/a/50522165
answers question: http://stackoverflow.com/q/50522104
has comment: http://stackoverflow.com/comment/88056377
type: AcceptedAnswer
has body: This is the faulty line, cast your input to integer. user_choice = int(input("Enter desired password strength (1-5) : "))
has comment: http://stackoverflow.com/comment/88056457
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50522104

http://stackoverflow.com/comment/87876075
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50428446
has text: This is amazing! Thanks a Million for your Help!

http://stackoverflow.com/comment/88066869
comment on: http://stackoverflow.com/q/50516244
has text: It works by defining `cdef public master` before the __cinit__() function.Thank you.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50406347
tagged with: text
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50406378
answer count: 3
has answer: http://stackoverflow.com/a/50406378
possible better answer: http://stackoverflow.com/a/50406509
type: Question
has title: How to read a specific line from a text file in python
tagged with: python
has answer: http://stackoverflow.com/a/50406509
has answer: http://stackoverflow.com/a/50407011
has body: I am trying to make a game that requires me to read specific lines from a text (.txt) file in python 3.6. I have figured out a way to do this if I just want to print the line. However, I want to use the line in an if statement: Note* The text file is called 'text' and has '1' on line 1, '2' on line 2 etc etc. file = open("text.txt", "r") line1 = file.readline() line2 = file.readline() line3 = file.readline() print(line1) print(line2) print(line3) if line1 == "1": print("True") else: print("False") file.close() I know that it is reading the lines correctly, because of the print testing. However the if statement is printing false. I don't know what I am doing wrong, and I haven't found anything in my research.

http://stackoverflow.com/q/50519619
tagged with: python
has title: Python variables not sent as values to batch file
has comment: http://stackoverflow.com/comment/88052113
score: 0
tagged with: batch-file
has answer: http://stackoverflow.com/a/50520604
has comment: http://stackoverflow.com/comment/88052032
has comment: http://stackoverflow.com/comment/88052109
type: Question
has comment: http://stackoverflow.com/comment/88061785
type: UnansweredQuestion
answer count: 1
has body: I have a python script where I am extracting values from a dataframe and trying to send them to a batch file. However, the values of the variables are not sent - the batch file is receiving them as variable names. Assuming all imports are in place. for i,row in ftp_df.iterrows(): if row['client_name']==client_name: a_ftp_host=row['ftp_host'] a_ftp_user=row['ftp_username'] a_ftp_pass=row['ftp_password'] print(a_ftp_host) print(a_ftp_user) print(a_ftp_pass) os.system("C:\\Temp\\ftp_test.bat a_ftp_user a_ftp_pass filename") the batch file ftp_test.bat is as follows. Echo "****----****----****" Echo "Uploading test.txt" Echo "****----****----****" Echo %1% Echo %2% Echo %3% user="%1%" pass="%2%" file="%file%" "WinSCP.com" ^ /log="C:\temp\WinSCP.log" /ini=nul ^ /command ^ "open sftp://%user%:%pass%@xx.xx.xxx/ -hostkey=""ssh- xxxxxxxxxxxxxxxxxxxxxxxxxx""" ^ "put -nopermissions -nopreservetime %file%" ^ "exit" When executing this, it fails with error: C:>Searching for host... Host does not exist No session. Host does not exist No session. it looks like the username and password being sent are handles not the values. independently, when executing the batch file with hard-coded credentials, it works. what am i doing wrong?
has comment: http://stackoverflow.com/comment/88052994

http://stackoverflow.com/q/50535725
answer count: 1
downvote count: 1
has body: I need to store the data from a .txt file to a database in Sqlite3. I first try to read the txt file: f = open("path", 'r') if f.mode=='r': content = f.read() then i printed the "content" to know the structure of the data print (content) Rank Male Female 1 Noah Emma 2 Liam Olivia 3 William Ava 4 Mason Sophia 5 James Isabella How can i manage the data from the variable "content" to store it in a database with a table separated as rank, name and sex.
favorite count: 0
has comment: http://stackoverflow.com/comment/88083548
accepted answer: http://stackoverflow.com/a/50536260
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/2887878
has comment: http://stackoverflow.com/comment/88083571
has title: Manage data from .txt file to store it to SQLite3 in Python
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/88083448
score: -1
linked to: http://stackoverflow.com/q/2887878
type: Question
has answer: http://stackoverflow.com/a/50536260
upvote count: 0

http://stackoverflow.com/q/50480468
has title: Merge variable number of rows in pandas dataframe
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50480503
has body: I'm new to pandas and working with dataframes. I have a rather simple problem that I think should have a straightforward solution which is not clear to me (and I do not know pandas that well). So I have many occurrences of rows with same index in my data frame: Glucose Insulin Carbs Hour 2018-05-16 06:43:00 156.0 0.0 0.0 2018-05-16 06:43:00 NaN 0.0 65.0 2018-05-16 06:43:00 NaN 7.0 0.0 And I would like to merge them to get this, a row which contains all the information available at a given time index: Glucose Insulin Carbs Hour 2018-05-16 06:43:00 156.0 7.0 65.0 2018-05-16 06:43:00 NaN 0.0 65.0 2018-05-16 06:43:00 NaN 7.0 0.0 Afterwards I would drop all rows which contain NaN in any column to get: Glucose Insulin Carbs Hour 2018-05-16 06:43:00 156.0 7.0 65.0 The problem is that in the same dataframe I have duplicates with less information, maybe only Carbs or Insulin. Glucose Insulin Carbs Hour 2018-05-19 06:15:00 NaN 1.5 0.0 2018-05-19 06:15:00 229.0 0.0 0.0 I already know the indices of these entries: bad_indices = _df[ _df.Glucosa.isnull() ].index What I would like to know is if there's like a nice Pythonic way to do such a task (both for the two, and three rows cases). Maybe a pandas built-in method or something which is semi standard or at least readable because I don't want to write ugly (and easily breakable) code that has explicit considerations for each case.
has answer: http://stackoverflow.com/a/50480503
tagged with: dataframe
tagged with: python
type: Question
tagged with: pandas
score: 1

http://stackoverflow.com/q/50500341
tagged with: google-cloud-vision
has answer: http://stackoverflow.com/a/62749798
has comment: http://stackoverflow.com/comment/88014549
tagged with: python
type: AnsweredQuestion
score: 0
has title: How to run python app on server through browser
answer count: 2
has body: I just started using PYTHON and now i want to run a google vision cloud app on the server but I'm not sure how to start. I do have a server up and running at http://18.217.137.107 and the app source code looks like https://cloud.google.com/vision/docs/detecting-landmarks#vision-landmark-detection-python. Any help would be greatly appreciated.
possible better answer: http://stackoverflow.com/a/51598485
has answer: http://stackoverflow.com/a/51598485
accepted answer: http://stackoverflow.com/a/62749798
type: Question
has comment: http://stackoverflow.com/comment/88110002

http://stackoverflow.com/a/50520866
has comment: http://stackoverflow.com/comment/88054874
upvote count: 2
has comment: http://stackoverflow.com/comment/88055005
answers question: http://stackoverflow.com/q/50520802
type: Answer
has body: Python's builtin min can take an iterable. You can also put the &gt; 100 filter in a genexpr. Python dicts can also return an iterable of values only, since you dont' care about the keys. lowest_value = min(value for value in d.values() if value &gt; 100) You can get the list of keys in a list comp separately. list_of_keys = [key for key, value in d.items() if value &gt; 100] This iterates twice, but that's OK unless your dict is really large (in which case, consider using pandas dataframes instead.) To avoid duplicating the filter step, you can use a dict comp first. d2 = {k: v for k, v in d.items() if v &gt; 100} lowest_value = min(d2.values()) list_of_keys = list(d2.keys())
score: 2
downvote count: 0

http://stackoverflow.com/q/50432668
has answer: http://stackoverflow.com/a/50432859
type: Question
has comment: http://stackoverflow.com/comment/87879706
possible better answer: http://stackoverflow.com/a/50432698
score: 9
answer count: 5
has answer: http://stackoverflow.com/a/50432949
has answer: http://stackoverflow.com/a/50432782
tagged with: python
has body: When line 2 in the text file has 'nope' then it will ignore the line and continue the next one. Is there another way to write this without using try and except? Can I use if else statement to do this? Example of text file: 0 1 0 2 nope 1 3 2 5 nope Code: e = open('e.txt') alist = [] for line in e: start = int(line.split()[0]) target = int(line.split()[1]) try: if line.split()[2] == 'nope': continue except IndexError: alist.append([start, target])
linked to: http://stackoverflow.com/q/7274310
linked to: http://stackoverflow.com/q/1835756
accepted answer: http://stackoverflow.com/a/50432686
type: AnsweredQuestion
has title: Other options instead of using try-except
tagged with: filter
has answer: http://stackoverflow.com/a/50432686
tagged with: try-except
has answer: http://stackoverflow.com/a/50432698
linked to: http://stackoverflow.com/q/2522005
tagged with: file
linked to: http://stackoverflow.com/q/16138232
upvote count: 10
has comment: http://stackoverflow.com/comment/87879590
downvote count: 1
linked to: http://stackoverflow.com/q/11360858
favorite count: 0

regex
tags question: http://stackoverflow.com/q/50410262
tags question: http://stackoverflow.com/q/50403310
tags question: http://stackoverflow.com/q/50410956
tags question: http://stackoverflow.com/q/50437984
tags question: http://stackoverflow.com/q/50476377
tags question: http://stackoverflow.com/q/50506553
tags question: http://stackoverflow.com/q/50443144
tags question: http://stackoverflow.com/q/50534417
tags question: http://stackoverflow.com/q/50401430
tags question: http://stackoverflow.com/q/50496586
tags question: http://stackoverflow.com/q/50497777
tags question: http://stackoverflow.com/q/50410283
tags question: http://stackoverflow.com/q/50452906
tags question: http://stackoverflow.com/q/50477503
tags question: http://stackoverflow.com/q/50437614
tags question: http://stackoverflow.com/q/50538989
tags question: http://stackoverflow.com/q/50418602
tags question: http://stackoverflow.com/q/50388647
tags question: http://stackoverflow.com/q/50396347
tags question: http://stackoverflow.com/q/50526926
tags question: http://stackoverflow.com/q/50508759
tags question: http://stackoverflow.com/q/50513186
tags question: http://stackoverflow.com/q/50520106
tags question: http://stackoverflow.com/q/50539010
tags question: http://stackoverflow.com/q/50463602
tags question: http://stackoverflow.com/q/50500209
tags question: http://stackoverflow.com/q/50538335
tag name: regex
tags question: http://stackoverflow.com/q/50469021
tags question: http://stackoverflow.com/q/50494560
tags question: http://stackoverflow.com/q/50482402
tags question: http://stackoverflow.com/q/50529508
tags question: http://stackoverflow.com/q/50408357
tags question: http://stackoverflow.com/q/50502353
tags question: http://stackoverflow.com/q/50414438
tags question: http://stackoverflow.com/q/50504500
tags question: http://stackoverflow.com/q/50493390
tags question: http://stackoverflow.com/q/50474751
tags question: http://stackoverflow.com/q/50516666
tags question: http://stackoverflow.com/q/50401664
tags question: http://stackoverflow.com/q/50525652
tags question: http://stackoverflow.com/q/50403483
tags question: http://stackoverflow.com/q/50506478
tags question: http://stackoverflow.com/q/50478971
tags question: http://stackoverflow.com/q/50496846
tags question: http://stackoverflow.com/q/50446004
tags question: http://stackoverflow.com/q/50400211
tags question: http://stackoverflow.com/q/50539399
tags question: http://stackoverflow.com/q/50504795
tags question: http://stackoverflow.com/q/50501926
tags question: http://stackoverflow.com/q/50396833
tags question: http://stackoverflow.com/q/50462670
tags question: http://stackoverflow.com/q/50485154
tags question: http://stackoverflow.com/q/50403871
tags question: http://stackoverflow.com/q/50437194
tags question: http://stackoverflow.com/q/50389128
tags question: http://stackoverflow.com/q/50514971
tags question: http://stackoverflow.com/q/50525822
tags question: http://stackoverflow.com/q/50417423
tags question: http://stackoverflow.com/q/50449774
tags question: http://stackoverflow.com/q/50437901
tags question: http://stackoverflow.com/q/50504278
tags question: http://stackoverflow.com/q/50445529
tags question: http://stackoverflow.com/q/50386772
tags question: http://stackoverflow.com/q/50493621
tags question: http://stackoverflow.com/q/50477991
tags question: http://stackoverflow.com/q/50534911
tags question: http://stackoverflow.com/q/50409701
tags question: http://stackoverflow.com/q/50472985
tags question: http://stackoverflow.com/q/50450198
tags question: http://stackoverflow.com/q/50479773
tags question: http://stackoverflow.com/q/50477410
tags question: http://stackoverflow.com/q/50441703
tags question: http://stackoverflow.com/q/50533629
tags question: http://stackoverflow.com/q/50492900
tags question: http://stackoverflow.com/q/50414378
tags question: http://stackoverflow.com/q/50463669
tags question: http://stackoverflow.com/q/50395461
tags question: http://stackoverflow.com/q/50442500
tags question: http://stackoverflow.com/q/50522799

http://stackoverflow.com/comment/87904158
type: QuestionComment
comment on: http://stackoverflow.com/q/50443970
has text: @l'L'l Python's `float` is the collection of double precision floating points (see e.g. [the tutorial](https://docs.python.org/3.6/tutorial/floatingpoint.html)); any irrational number, such as sqrt(2), has infinite decimal expansion (and no irrational number is representable as a double precision `float`).
score: 0
type: Comment

http://stackoverflow.com/q/50444049
tagged with: apache-superset
has body: I would like to install python module - superset in my Windows 10, however, some errors stop me to install further more. After I typed in "pip install superset", Belows are the 3 errors executed in cmd: Failed building wheel for python-geohash flask-appbuilder 1.11.1 has requirement Flask-SQLAlchemy==2.1, but you'll have flask-sqlalchemy 2.3.2 which is incompatible. Command "c:\pythonvir\env\scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\Lawrence\AppData\Local\Temp\pip-install-1lqhahdp\python-geohash\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\Lawrence\AppData\Local\Temp\pip-record-f4lpe14x\install-record.txt --single-version-externally-managed --compile --install-headers c:\pythonvir\env\include\site\python3.6\python-geohash" failed with error code 1 in C:\Users\Lawrence\AppData\Local\Temp\pip-install-1lqhahdp\python-geohash\ Any thoughts? I tried to install VS2015 and VS2017 and sasl, but still have error messages.
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52569789
answer count: 2
type: UnansweredQuestion
tagged with: python
has title: errors while Installing superset under Windows system
score: 0
has answer: http://stackoverflow.com/a/57450074

http://stackoverflow.com/comment/88044612
type: Comment
type: QuestionComment
score: 0
has text: @Flaming_Dorito, before the data there will be only one string/name including underline.
comment on: http://stackoverflow.com/q/50515266

http://stackoverflow.com/q/50407780
type: UnansweredQuestion
tagged with: database
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87831320
score: 1
downvote count: 0
answer count: 1
has title: Django query engine - Migrating from 1.11 to 2.0
has body: I'm trying to migrate from Django 1.11 to 2.0. After running my test suite, I'm getting in many db transactions the error: django.db.utils.ProgrammingError: subquery has too many columns , which didn't happen while running the test suite with 1.11. The database I'm using is postgres (with psycopg2-binary v2.7.4 module). Did anything change in the query engine between Django 1.11 to 2.0? I can't see anything like that in the release notes, nor anywhere else.
upvote count: 1
has comment: http://stackoverflow.com/comment/87833218
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50408889
has comment: http://stackoverflow.com/comment/87833685

http://stackoverflow.com/a/50478003
type: Answer
accepted answer of: http://stackoverflow.com/q/50477280
has body: Shape [3751, 4] cannot be reshaped to [-1,11,11,31,4] directly since 3751*4 = 15004 is not evenly divisible by 11*11*31*4 = 14964. EDIT after comment from OP You can flatten your dataset and feed it as a single example. See below Assuming that tf.shape(input_feat)==[3751, 4]: input_layer = tf.reshape(input_feat, [1,-1]) first_hidden_layer = tf.layers.dense(input_layer, 4, activation=tf.nn.relu) second_hidden_layer = tf.layers.dense(first_hidden_layer, 5, activation=tf.nn.relu) output_layer = tf.layers.dense(second_hidden_layer, 6) Original answer Not reshaping the input features at the beginning of the network will work just fine and provide similar results since you are using dense layers. The only difference is that weights in the layer will shift positions but this will not affect your results. If we assume tf.shape(input_feat) == [3751, 4], the following code snippet should work fine input_layer = tf.identity(input_feat) first_hidden_layer = tf.layers.dense(input_layer, 4, activation=tf.nn.relu) second_hidden_layer = tf.layers.dense(first_hidden_layer, 5, activation=tf.nn.relu) output_layer = tf.layers.dense(second_hidden_layer, 6)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87969947
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87970657
answers question: http://stackoverflow.com/q/50477280
score: 1

http://stackoverflow.com/comment/87910976
has text: @Anonymousmiliana Could you help me please ? i 'm gonna be thankfulfor that
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50447652

http://stackoverflow.com/a/50505886
downvote count: 0
upvote count: 1
has body: try this, df.groupby('Keys')['Values'].unique().to_dict() Output: {1: array([1, 6, 9]), 2: array([3]), 3: array([1, 4])}
answers question: http://stackoverflow.com/q/50505784
type: Answer
score: 1

http://stackoverflow.com/comment/87909636
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50447637
has text: Can you give an example for how you would like to store them?
type: Comment

http://stackoverflow.com/comment/87836675
type: Comment
comment on: http://stackoverflow.com/q/50410189
type: QuestionComment
has text: Sorry, I'll try to be more clear. My input is the following: X_train: sentences where each word has been transformed to index, y_label: one single label per sentence, in this case the label corresponds to a verb (converted to index) since I am trying to only predict verbs. I want to restrict my vocabulary, so instead of having a model that has to pick a verb among 5925 others, I want, for each input sentence, to predict between for example 5 verbs that I choose.
score: 0

http://stackoverflow.com/a/50482886
has body: There is no way to poll the state of the connection to the broker from the client. The on_disconnect callback should be called when the connection to the broker is dropped. This should be kicked off when the keep alive times out, but also as the result of a failure to publish (if you try to publish data before the timeout expires). Also the rc from a call to the publish command will indicate if the connection has dropped.
score: 0
has comment: http://stackoverflow.com/comment/87998042
has comment: http://stackoverflow.com/comment/87997682
has comment: http://stackoverflow.com/comment/87997458
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87997632
accepted answer of: http://stackoverflow.com/q/50472441
has comment: http://stackoverflow.com/comment/87997841
type: Answer
answers question: http://stackoverflow.com/q/50472441

http://stackoverflow.com/comment/108215151
type: Comment
score: 0
type: AnswerComment
has text: @DieterMeemken , see above
comment on: http://stackoverflow.com/a/61144544

http://stackoverflow.com/q/50392129
favorite count: 0
has answer: http://stackoverflow.com/a/50392951
has body: I have masked arrays for latitude (Xpos) and longitude(Ypos) with dimensions (125,800,000). I want to calculate the difference in latitude and longitude within the arrays. Here's the array Xpos (Ypos is similar). masked_array( data = [ [-2.0551843643188477, -2.637551784515381, -2.720881223678589, ..., 2.2812530994415283, 2.281250476837158, 2.281254768371582 ], [-2.3242127895355225, -2.804257869720459, -2.8825504779815674, ..., 2.2812530994415283, 2.281250476837158, 2.281254768371582 ], [-2.073770523071289, -2.6198980808258057, -2.708889961242676, ..., 2.2812530994415283, 2.281250476837158, 2.281254768371582 ], ..., [-3.517531633377075, -2.908338785171509, -2.9069409370422363, ..., 2.2812530994415283, 2.281250476837158, 2.281254768371582 ], [-3.688690662384033, -3.0086288452148438, -3.010164260864258, ..., 2.2812530994415283, 2.281250476837158, 2.281254768371582 ], [-3.520817518234253, -2.943941116333008, -2.941941738128662, ..., 2.2812530994415283, 2.281250476837158, 2.281254768371582 ] ], mask = [ [ False, False, False, ..., False, False, False ], [ False, False, False, ..., False, False, False], [ False, False, False, ..., False, False, False], ..., [ False, False, False, ..., False, False, False], [ False, False, False, ..., False, False, False], [ False, False, False, ..., False, False, False] ], fill_value = 1e+20, dtype = float32 ) This is my code, which works, but takes super long to compute. Dist= np.zeros((len(XposApr),len(XposApr[0]))) DiffLon=np.zeros((len(XposApr),len(XposApr[0]))) DiffLat=np.zeros((len(XposApr),len(XposApr[0]))) for i in range (1,len(XposApr),12): for j in range (0,len(XposApr[0])): DiffLon[i][j]=(XposApr[i][j]-XposApr[i-1][j]) DiffLat[i][j]=(YposApr[i][j]-YposApr[i-1][j]) I don't really know how to make the famous one-liners, this is what I tried, but does not work: DistLon = [XposApr[i][j]-XposApr[i-1][j] for i in enumerate (XposApr) and j in enumerate (XposApr[0])] Is it possible to make a oneliner or another code which makes the cal…
type: Question
has comment: http://stackoverflow.com/comment/87799993
has title: How to setup a smart oneliner for calculating with very large data?
tagged with: performance
score: 1
has answer: http://stackoverflow.com/a/50392999
tagged with: python
accepted answer: http://stackoverflow.com/a/50392951
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/50392999
tagged with: arrays
downvote count: 0
tagged with: loops
upvote count: 1

http://stackoverflow.com/q/50472129
has comment: http://stackoverflow.com/comment/87959705
has comment: http://stackoverflow.com/comment/87990768
type: UnansweredQuestion
has body: I have code that opens a webpage, clicks a button, then logs on with userid/password. I recently moved the code to a Windows 10 laptop and now the code gets the error below. Here is the code: time.sleep(2) inputElement = driver.find_element_by_class_name('hpui-primary-button') inputElement.click() Here's the error I get: selenium.common.exceptions.WebDriverException: Message: unknown error: Element https://cf.passport.hpe.com/hppcf/login.do?cc=US&amp;lang=EN&amp;applandingpage=https://h22204.www2.hpe.com/NEP/Logon/NewHome?hpappid=115940_NONSTOP_PRO_HPE';"> is not clickable at point (710, 300). Other element would receive the click: ... I tried adding a longer delay, but the page loads fine. Worked on Windows 7, not on Windows 10.
has comment: http://stackoverflow.com/comment/87990735
tagged with: python
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/87961309
duplicate of: http://stackoverflow.com/q/44912203
has comment: http://stackoverflow.com/comment/87975141
linked to: http://stackoverflow.com/q/44724185
score: 0
has comment: http://stackoverflow.com/comment/88000600
has comment: http://stackoverflow.com/comment/87985362
has comment: http://stackoverflow.com/comment/87958413
tagged with: selenium
duplicate of: http://stackoverflow.com/q/44724185
type: Question
has comment: http://stackoverflow.com/comment/87961073
has title: Using Chrome/Python/Selenium to click button - After porting code to Windows 10 getting error
answer count: 0

http://stackoverflow.com/comment/87925227
comment on: http://stackoverflow.com/q/50455246
type: QuestionComment
score: 4
has text: scipy.optimize.minimize doesn't provide algorithms suitable for integer programs, so you may need a more suitable tool for this (there are many other optimization libraries for Python).
type: Comment

http://stackoverflow.com/a/50407949
has comment: http://stackoverflow.com/comment/87831732
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87831497
has comment: http://stackoverflow.com/comment/87831504
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87831427
answers question: http://stackoverflow.com/q/50407849
has comment: http://stackoverflow.com/comment/87832115
has body: You can use numpy: import numpy as np L = np.array([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]) id = np.where(test == 1)[0] # id = array([0, 3, 4, 6], dtype=int64) res = [id[i]-id[i-1] for i in range(1, len(id))] # [3, 1, 2] # Last distance missing: res.append(len(L)- id[-1]) res = [3, 1, 2, 4] Note that the information you ask for is comprised above, but maybe the output format is wrong. You were not really specific... Edit: How to convert list to an array since you generate random list L = [1, 0, 0, 1, 1, 0, 1, 0, 0, 0] np.asarray(L) Edit2: How to check if there is no 1 in the list: import numpy as np L = np.array([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]) id = np.where(test == 1)[0] if len(id) == 0: res = [] else: res = [id[i]-id[i-1] for i in range(1, len(id))] res.append(len(L)- id[-1]) OR: try: res = [id[i]-id[i-1] for i in range(1, len(id))] res.append(len(L)- id[-1]) except: res = []

http://stackoverflow.com/a/50421735
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50417842
has body: You need this code (your XPath expressions are wrong): def parse(self, response): for row in response.xpath('//table[@class="member-table"]//tr[position() &gt; 1]'): item = FinalItem() item['name'] = row.xpath('./td[2]//a/text()').extract_first() profile_url = row.xpath('./td[2]//a/@href').extract_first() yield scrapy.Request( url=response.urljoin(profile_url), callback=self.parse_profile, meta={"item": item } ) next_page_url = response.xpath('//div[@class="page-nav-btm"]//li[last()]/a/@href').extract_first() if next_page_url: yield scrapy.Request( url=response.urljoin(next_page_url), callback=self.parse ) def parse_profile(self, response): item = response.meta['item'] item['travelog'] = response.xpath('//div[@class="statistics-btm"]/ul//li[ ./span[contains(., "Travelogues")] ]/a/text()').extract_first() yield item
answers question: http://stackoverflow.com/q/50417842
type: Answer
has comment: http://stackoverflow.com/comment/87862854
has comment: http://stackoverflow.com/comment/87862772
downvote count: 0

http://stackoverflow.com/a/50491099
answers question: http://stackoverflow.com/q/50490902
downvote count: 1
has body: A 2D histogram is created with plt.hist2d n, xbins, ybins, image = plt.hist2d(X, Y, normed=1)
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/comment/87850229
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50401576
has text: Thank you ! This will do the job! Meanwhile I ended up using selenium for date picking.

http://stackoverflow.com/q/50492605
tagged with: pandas
has title: Index DataFrame with MultiIndex Rows and Columns via another DataFrame containing row and column indices as columns
type: Question
accepted answer: http://stackoverflow.com/a/50494334
has body: I have a list of particle pairs within which each pair is referred to by a combination of a chain-index and an intra-chain-index of both particles. I have saved those in a Dataframe (let's call it index_array) and now I want to plot a matrix of all particle pairs, where I plot all matrix elements that correspond to a pair in the list in one color and all others in another color. My idea was thus to produce a DataFrame (let's call it to_fill) with chain- and intra-chain-index as a MultiIndex for both rows and columns, which thus has two entries per pair and then use index_array to index to_fill to change the corresponding values, such that I can then plot the values of to_fill via matplotlib.pyplot.pcolormesh. So to break it down into a more or less well-defined problem: I have a boolean DataFrame to_fill that has multiindexed rows and columns (2 levels each) that contains only Falses. I also have another DataFrame index_array that has four columns, containing the index values for the levels of both rows and columns. Now I want to set all elements pointed to by index_array to True. A toy version of those could for example be produced with the code below: import numpy as np import pandas as pd lengths = pd.Series(data=[2, 4], index=[1, 2]) # Corresponds to the chains' lengths index = pd.MultiIndex.from_tuples([(i, j) for i in lengths.index for j in np.arange(1, lengths.loc[i]+1)]) to_fill = pd.DataFrame(index=index, columns=index, dtype=np.bool) to_fill.loc[slice(None), slice(None)] = 0 print(to_fill) # 1 2 # 1 2 1 2 3 4 # 1 1 False False False False False False # 2 False False False False False False # 2 1 False False False False False False # 2 False False False False False False # 3 False False False False False False # 4 False False False False False False index_array = pd.DataFrame([[1, 1, 1, 1], [1, 1, 1, 2], [2, 3, 2, 3], [2, 3, 2, 4]], columns=["i_1", "j_1", "i_2", "j_2"]) print(index_array) # i_1 j_1 i_2 j_2 # 0 1 1 1 1 # 1 1 1 1 2 # 2 2 3 2 3 # 3 2 3 2 4 Now…
has answer: http://stackoverflow.com/a/50494334
tagged with: python
possible better answer: http://stackoverflow.com/a/50493859
has answer: http://stackoverflow.com/a/50493859
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/a/50463935
has comment: http://stackoverflow.com/comment/87942364
has comment: http://stackoverflow.com/comment/87941333
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87945204
answers question: http://stackoverflow.com/q/50463669
has body: s = '({[test1, test2 ; test3 (New) ]})' Based on your comment below I assume that the number of opening brackets of the whole string is equal to the number of closing brackets. So removing the outer brackets first needs to know their number: m = re.match('[({[]*', s) n_brckt = m.span()[1] - m.span()[0] Then remove the outer brackets ( - dependent on if there were found any...): if n_brckt &gt; 0: s = s[n_brckt:-n_brckt] s = s.strip() In: s Out: 'test1, test2 ; test3 (New)' Then you can split at all occurences of commas or colons optionally followed by a space: In: re.split('[,;]+ *', s) Out: ['test1', 'test2', 'test3 (New)']
accepted answer of: http://stackoverflow.com/q/50463669
has comment: http://stackoverflow.com/comment/87944899
type: Answer
has comment: http://stackoverflow.com/comment/87941245
has comment: http://stackoverflow.com/comment/87941172

http://stackoverflow.com/a/50476542
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87966713
answers question: http://stackoverflow.com/q/50476436
has comment: http://stackoverflow.com/comment/87966745
downvote count: 0
upvote count: 1
has body: A second way (in addition to Alex Hall's answer) could be the following: years = range(1990,2000) type_c = ["U", "R", "K", "B"] temp_list = [] for i in years: for j in type_c: temp_list.append("TEMP%s_%s" % (i,j))
has comment: http://stackoverflow.com/comment/87966724
has comment: http://stackoverflow.com/comment/87966695

http://stackoverflow.com/q/50508949
type: UnansweredQuestion
has title: Event handling with kivy Checkboxes
has answer: http://stackoverflow.com/a/50509307
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/88030555
score: 0
has body: I'm able to launch an event upon checking a checkbox on kivy, but how to do the same with uncheking?
linked to: http://stackoverflow.com/q/47040513
answer count: 1
duplicate of: http://stackoverflow.com/q/47040513
type: Question

http://stackoverflow.com/comment/117113043
has text: @variable See https://stackoverflow.com/questions/20212894/how-do-i-get-flask-to-run-on-port-80
score: 0
comment on: http://stackoverflow.com/a/50389564
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87853465
comment on: http://stackoverflow.com/q/50418697
type: Comment
score: 0
type: QuestionComment
has text: @Wen yes those are the data frames

http://stackoverflow.com/a/50423791
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: You forgot to extract words from your file: filepath = "common.txt" words_file_content = open(filepath, "r").read() words = set(words_file_content.split()) # get separate words from file for word in words: text = text.replace(word, "")
answers question: http://stackoverflow.com/q/50423772

http://stackoverflow.com/a/51989594
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50525301
has body: When you use django-polymorphic in your base model, you'll get this casting behavior for free: class MyModel(PolymorphicModel): pass Each model that extends from it (proxy model or concrete model), will be casted back to that model when you do a MyModel.objects.all()
score: 2
downvote count: 1

http://stackoverflow.com/q/50407731
tagged with: h2o
has answer: http://stackoverflow.com/a/50416990
has title: Python/H2o : Plot tree/Extract rules from H2ORandomForestEstimator model
upvote count: 6
has body: Is there any "simple" way to plot trees from an H2O random forest model. I am also interestred in extracting the resulting rules ?
has answer: http://stackoverflow.com/a/53795115
favorite count: 0
type: Question
answer count: 2
tagged with: random-forest
type: UnansweredQuestion
downvote count: 0
score: 6
tagged with: python

http://stackoverflow.com/comment/89049453
comment on: http://stackoverflow.com/a/50970152
has text: This should be the accepted answer because it doesn't need to change any files to work.
score: 12
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88081653
comment on: http://stackoverflow.com/a/50534771
type: AnswerComment
has text: Ah, thank you. I read that the retweeted attribute should be sufficient. Apparently not.
score: 0
type: Comment

http://stackoverflow.com/comment/88084949
has text: `inked = inked.loc[:,'AA':'DD'].fillna(0)` didn't work either. I get an error : AttributeError: 'NoneType' object has no attribute 'loc'
comment on: http://stackoverflow.com/a/50536358
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87972992
score: 0
comment on: http://stackoverflow.com/q/50479788
type: Comment
type: QuestionComment
has text: How did you install it?

http://stackoverflow.com/comment/87998663
comment on: http://stackoverflow.com/a/50492154
type: AnswerComment
score: 1
has text: TypeError: must use keyword argument for key function. I've changed the code to for k, v in sorted(size_images.items(),key= lambda kv: kv[1]['heigth']): print (k, '-->', v) and it works great. thanks
type: Comment

http://stackoverflow.com/q/50465122
upvote count: 1
has comment: http://stackoverflow.com/comment/87947112
favorite count: 0
has comment: http://stackoverflow.com/comment/87947650
type: Question
linked to: http://stackoverflow.com/q/13081532
has comment: http://stackoverflow.com/comment/87952934
accepted answer: http://stackoverflow.com/a/50470316
has title: python as Backend and HTML as front end
has body: I am building a simple web application using HTML and Python to display image on canvas. Also I am using Flask framework for it. Where Image is uploaded from HTML and processed it in Opencv(Python) and then displayed on HTML made canvas, what I have done so far is uploaded image only. But I couldn't displayed on canvas. here is the CSS and HTML code p { font-family: verdana; font-size: 20px; } h2 { margin-left: 20px; text-align: center; } CV - Rogier Study Asset Tag: Try it And Python code from flask import Flask, render_template, request import cv2 app = Flask(__name__) @app.route('/') def index(): return render_template('test.html') @app.route('/hello', methods=['GET','POST']) def hello(): if request.method == 'POST': image = request.form['Image'] get_image = cv2.imread(image,0) return cv2.imshow(get_image) else: return render_template('test.html') if __name__ == '__main__': app.run(host = 'localhost', port = 3000, debug=True) please tell me what I am missing and whats wrong!! Thanks
has comment: http://stackoverflow.com/comment/87944444
tagged with: http://stackoverflow.com/tag/html
tagged with: javascript
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87950878
has answer: http://stackoverflow.com/a/50470316
answer count: 1
has comment: http://stackoverflow.com/comment/87945045
downvote count: 0
has comment: http://stackoverflow.com/comment/87947867

http://stackoverflow.com/q/50475303
type: Question
tagged with: w3.css
has body: I'm a total beginner, just starting to get familiar with html, css and other stuff. I just tried creating a code block using w3.css. They have this pretty w3-code thing I used for putting Python code as an example. It looks good but I also need to highlight the syntax. I tried using w3codecolor.js as suggested but unfortunately it doesn't do the thing. Why? I can clearly see a Python mode in the library, but it isn't listed as a class in the tutorial. Here is my code: Example code, oh yeah baby df = pd.read_csv('UCI_Credit_Card.csv') def valuation_formula(limit): if limit<=10000.: return 'A' elif limit<=100000. and limit>10000.: return 'B' elif limit<=200000. and limit>100000.: return 'C' elif limit<=400000. and limit>200000.: return 'D' elif limit<=700000. and limit>400000.: return 'E' else: return 'F' df['NEW_COLUMN'] = df.apply(lambda row: valuation_formula(row['LIMIT_BAL']), axis=1) df.head(10) It actually does some coloring but it clearly isn't alike to one I can see in Jupyter Notebook which I use for Python coding (this is what I'm trying to achieve). P.S. - As you can see there is not many regular html tags, because I'm doing this whole thing on EdX platform, which could be the case but I have no clue. Here, this is how it looks like: screenshot
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: css
has title: How to highlight Python syntax using w3codecolor.js?
answer count: 0
score: 1
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/87964350
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87851586
type: QuestionComment
comment on: http://stackoverflow.com/q/50414900
type: Comment
score: 1
has text: What have you tried with `torch.sparse`? It describes a `COO` input. It's not identical to the `sparse.coo_matrix`, but close enough. How did you construct the `csc` matrix?

http://stackoverflow.com/a/50473053
has body: np.concatenate(array) The only problem, in your example, array in the list array (now, do you see how bad it is to use confusing names) should become np.array and you should add commas after each numpy.ndarray in the list array: array = [np.array([100000., 100848.06652142, 99648.67144694, 102047.67944271, 103655.99048427, 104602.87678005, 104597.83419837, 103505.42736768, 104976.01311214, 104457.34603404, 105855.46549162, 105613.30235519, 105212.71840922, 107647.5054673 ]), np.array([107647.5054673 , 106891.82007643, 106979.91405552, 106030.74186486, 107856.04281712, 108502.71948581, 106557.2401056 , 105659.59829843, 105663.01875745, 107300.69453018, 106336.34733019, 107584.99034227, 108089.2320392 , 106786.91702337]), np.array([106786.91702337, 104416.74000465, 101289.12525402, 101932.58219813, 102625.04352578, 101767.46209616, 103345.4263012 , 102816.73322055, 102417.59316407, 104439.37518975, 103755.22627215, 103817.9744686 , 107872.40234863, 108110.9662065 ]), np.array([108110.9662065 , 109544.86827069, 111072.22392645, 112618.46235766, 113847.1768898 , 116708.86391903, 115790.02599715, 115614.72242411, 119225.88436354, 121991.38468934, 123304.85972848, 125571.38040251, 122456.3667249 ]), np.array([122456.3667249 , 127497.74699282, 128659.85495604, 125813.77115906, 129008.46450085, 128111.00914756, 123039.92607546, 124723.87932757, 124181.57385836, 125134.9276196 , 126027.8631434 , 129304.85119148, 128912.58600657])]
downvote count: 0
answers question: http://stackoverflow.com/q/50472775
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50472775
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87820026
score: 0
type: Comment
type: AnswerComment
has text: @user4505419, Hmm, I don't see this problem on pandas v0.20.3. I've included the complete code.
comment on: http://stackoverflow.com/a/50402071

http://stackoverflow.com/q/50478715
tagged with: pandas-datareader
favorite count: 0
type: Question
score: 3
tagged with: python
has title: The tickers used in pandas morningstar API
upvote count: 3
has answer: http://stackoverflow.com/a/50688333
type: UnansweredQuestion
has body: Here is what I done for obtaining the price of the stock "TSLA" using the DataReader with morningstar API import pandas_datareader.data as web df = web.DataReader('TSLA', 'morningstar', start, end) However, if I input a wrong ticker for the first parameter of the creator of DataReader, Python just keep running the line. How to check whether a ticker is input correctly for the first parameter?
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/87942414
has text: Well, did you do what the error message tells you to do? If you did and it doesn't help, probably you can get some help on the project's [issues page](https://github.com/adafruit/Adafruit_Python_DHT/issues).
type: QuestionComment
comment on: http://stackoverflow.com/q/50464551
type: Comment
score: 0

http://stackoverflow.com/q/50484937
has comment: http://stackoverflow.com/comment/87983653
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87983415
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87984295
has answer: http://stackoverflow.com/a/50485713
has title: Operations on items of dictionary object in list, if duplicate found
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87983277
score: 0
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50485789
has body: If dictionary object in list is duplicate based on two or more items , then these two object should be merged by doing arithmetic operation on items. Example -> 'CUSTOMER' and 'ID' item makes duplicate. 'USAGE' item should be added resulting object. First 'COUNTRY CODE' should be retained in resulting object, if it differs. Input : [ { "CUSTOMER": "XYZ", "COUNTRY CODE": "US", "ID": "Essential", "USAGE": 500 }, { "CUSTOMER": "XYZ", "COUNTRY CODE": "US", "ID": "Seats", "USAGE": 20 }, { "CUSTOMER": "XYZ", "COUNTRY CODE": "FR", "ID": "Essential", "USAGE": 50 } ] Output : [ { "CUSTOMER": "XYZ", "COUNTRY": "US", "ID": "Essential", "USAGE": 550 }, { "CUSTOMER": "XYZ", "COUNTRY CODE": "US", "ID": "Seats", "USAGE": 20 } ]
has comment: http://stackoverflow.com/comment/87983055
has comment: http://stackoverflow.com/comment/87983489
type: Question
has comment: http://stackoverflow.com/comment/87985770

http://stackoverflow.com/q/50492607
has title: python **kwags Error: function takes 6 positional arguments but 8 were given
tagged with: gradient-descent
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
downvote count: 0
tagged with: function
answer count: 1
has answer: http://stackoverflow.com/a/50492704
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/87998202
favorite count: 0
type: Question
has body: When I was trying to develop a gradient descent, I discovered an interesting problem that I cannot use **kwargs effectively. My function looks like def gradient_descent(g,x,y,alpha,max_its,w,**kwargs): # switch for verbose verbose = True if 'verbose' in kwargs: verbose = kwargs['verbose'] # determine num train and batch size num_train = y.size()[1] batch_size = num_train if 'batch_size' in kwargs: batch_size = kwargs['batch_size'] ........ and the Error looks like: TypeError Traceback (most recent call last) &lt;ipython-input-12-f71adb8a241b&gt; in &lt;module&gt;() 3 w_train = Variable(torch.Tensor(w_init), requires_grad=True) 4 g = softmax; alpha_choice = 10**(-1); max_its = 100; num_pts = y.size; batch_size = 10; ----&gt; 5 weight_hist_2,train_hist_2 = gradient_descent(g,x_train,y_train,alpha_choice,max_its,w_train,num_pts,batch_size,verbose = False) TypeError: gradient_descent() takes 6 positional arguments but 8 were given. Is there anything I didn't notice for developing this function?

http://stackoverflow.com/q/50450800
has body: I am new to PyTorch, and don't understand how to fit a network using this framework. I have a simple model in Keras: model = Sequential() model.add(Embedding(vocab_size, embedding_size, input_length=55, weights=[pretrained_weights])) model.add(Bidirectional(LSTM(units=len(X_train)))) model.add(Dense(n_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer = RMSprop(lr=0.0005), metrics=['accuracy']) model.fit(np.array(X_train), np.array(y_train), epochs=100, validation_data=(np.array(X_val), np.array(y_val))) In Keras I can just feed the network with my X_train (a 2D array containing indices) and my y_train(a 2D array containing a single index for each input). Now, in order to feed my PyTorch model I transformed my matrix into a tensor like this: M = torch.tensor(X_train) And defined my network: # Bidirectional recurrent neural network (many-to-one) class BiRNN(nn.Module): def __init__(self, input_size, hidden_size, num_layers, num_classes): super(BiRNN, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True) self.fc = nn.Linear(hidden_size*2, num_classes) # 2 for bidirection def forward(self, x): # Set initial states h0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device) # 2 for bidirection c0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device) # Forward propagate LSTM out, _ = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size*2) # Decode the hidden state of the last time step out = self.fc(out[:, -1, :]) return out model = BiRNN(input_size, hidden_size, num_layers, num_classes).to(device) # Loss and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) But what I don't understand is how to call the function and use my own data for the predictions.
tagged with: lstm
score: 0
answer count: 0
tagged with: pytorch
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88024640
tagged with: neural-network
has comment: http://stackoverflow.com/comment/87915019
has title: How to feed input into a pytorch lstm layer
tagged with: python
has comment: http://stackoverflow.com/comment/87943013

http://stackoverflow.com/comment/87812870
comment on: http://stackoverflow.com/a/50398561
type: Comment
has text: The reason I want to loop through is so I can apply it when I collect more months of data.
score: 0
type: AnswerComment

python-2.7
tags question: http://stackoverflow.com/q/50490481
tags question: http://stackoverflow.com/q/50526859
tags question: http://stackoverflow.com/q/50414255
tags question: http://stackoverflow.com/q/50522464
tags question: http://stackoverflow.com/q/50526408
tags question: http://stackoverflow.com/q/50480997
tags question: http://stackoverflow.com/q/50518518
tags question: http://stackoverflow.com/q/50440799
tags question: http://stackoverflow.com/q/50486927
tags question: http://stackoverflow.com/q/50436644
tags question: http://stackoverflow.com/q/50427397
tags question: http://stackoverflow.com/q/50476811
tags question: http://stackoverflow.com/q/50480827
tags question: http://stackoverflow.com/q/50463207
tags question: http://stackoverflow.com/q/50491115
tags question: http://stackoverflow.com/q/50429692
tags question: http://stackoverflow.com/q/50456133
tags question: http://stackoverflow.com/q/50489136
tags question: http://stackoverflow.com/q/50484977
tags question: http://stackoverflow.com/q/50441434
tags question: http://stackoverflow.com/q/50498254
tags question: http://stackoverflow.com/q/50450481
tags question: http://stackoverflow.com/q/50456856
tags question: http://stackoverflow.com/q/50426987
tags question: http://stackoverflow.com/q/50541662
tags question: http://stackoverflow.com/q/50457873
tags question: http://stackoverflow.com/q/50460267
tags question: http://stackoverflow.com/q/50509026
tags question: http://stackoverflow.com/q/50453299
tags question: http://stackoverflow.com/q/50400846
tags question: http://stackoverflow.com/q/50520083
tags question: http://stackoverflow.com/q/50445895
tags question: http://stackoverflow.com/q/50422648
tags question: http://stackoverflow.com/q/50462916
tags question: http://stackoverflow.com/q/50534954
tags question: http://stackoverflow.com/q/50478535
tags question: http://stackoverflow.com/q/50441365
tags question: http://stackoverflow.com/q/50527251
tags question: http://stackoverflow.com/q/50402812
tags question: http://stackoverflow.com/q/50478807
tags question: http://stackoverflow.com/q/50455722
tags question: http://stackoverflow.com/q/50473552
tags question: http://stackoverflow.com/q/50423675
tags question: http://stackoverflow.com/q/50487981
tags question: http://stackoverflow.com/q/50442889
tags question: http://stackoverflow.com/q/50391617
tags question: http://stackoverflow.com/q/50453254
tags question: http://stackoverflow.com/q/50392949
tags question: http://stackoverflow.com/q/50395812
tags question: http://stackoverflow.com/q/50440937
tags question: http://stackoverflow.com/q/50394183
tags question: http://stackoverflow.com/q/50484686
tags question: http://stackoverflow.com/q/50525872
tags question: http://stackoverflow.com/q/50510320
tags question: http://stackoverflow.com/q/50438529
tags question: http://stackoverflow.com/q/50418775
type: Tag
tags question: http://stackoverflow.com/q/50449807
tags question: http://stackoverflow.com/q/50386955
tags question: http://stackoverflow.com/q/50437331
tags question: http://stackoverflow.com/q/50501524
tags question: http://stackoverflow.com/q/50511839
tags question: http://stackoverflow.com/q/50418903
tags question: http://stackoverflow.com/q/50415389
tags question: http://stackoverflow.com/q/50413479
tags question: http://stackoverflow.com/q/50505418
tags question: http://stackoverflow.com/q/50404101
tags question: http://stackoverflow.com/q/50527732
tags question: http://stackoverflow.com/q/50473215
tags question: http://stackoverflow.com/q/50420906
tags question: http://stackoverflow.com/q/50395475
tags question: http://stackoverflow.com/q/50479804
tags question: http://stackoverflow.com/q/50538088
tags question: http://stackoverflow.com/q/50532929
tags question: http://stackoverflow.com/q/50458200
tags question: http://stackoverflow.com/q/50479788
tags question: http://stackoverflow.com/q/50436311
tags question: http://stackoverflow.com/q/50422593
tags question: http://stackoverflow.com/q/50484845
tags question: http://stackoverflow.com/q/50447652

http://stackoverflow.com/a/54231829
answers question: http://stackoverflow.com/q/50515409
score: 1
type: Answer
has body: You can use ZeroPadding2D padding input image to 32X32, then use Cropping2D cropping decoded image. from keras.layers import ZeroPadding2D, Cropping2D input_img = Input(shape=(28,28,1)) # adapt this if using `channels_first` image data format input_img_padding = ZeroPadding2D((2,2))(input_img) #zero padding image to shape 32X32 x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img_padding) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) encoded = MaxPooling2D((2, 2), padding='same')(x) # at this point the representation is (4, 4, 8) i.e. 128-dimensional x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded) x = UpSampling2D((2, 2))(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) x = UpSampling2D((2, 2))(x) x = Conv2D(16, (3, 3), activation='relu', padding='same')(x) x = UpSampling2D((2, 2))(x) decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x) decoded_cropping = Cropping2D((2,2))(decoded) autoencoder = Model(input_img, decoded_cropping) #cropping image from 32X32 to 28X28 autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') autoencoder.summary()
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50469989
tagged with: python
has answer: http://stackoverflow.com/a/50470083
tagged with: dictionary
upvote count: 6
type: Question
tagged with: python-3.x
has body: Let's say buff is a dictionary. I do del buff[k], but k is not a key in the buff. Is this an error, or you python just passes the line like nothing happened?
has title: What happens if I delete a nonexistent key in Python Dictionary Class?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/138085399
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/138085365
has comment: http://stackoverflow.com/comment/87953357
favorite count: 0
score: 3
has comment: http://stackoverflow.com/comment/138085412
has comment: http://stackoverflow.com/comment/87957546

http://stackoverflow.com/a/50417472
has comment: http://stackoverflow.com/comment/87854301
accepted answer of: http://stackoverflow.com/q/50417376
type: Answer
answers question: http://stackoverflow.com/q/50417376
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: for k,v in lst[0].items(): print(k, ':', len(v))

http://stackoverflow.com/a/50533181
accepted answer of: http://stackoverflow.com/q/50491326
answers question: http://stackoverflow.com/q/50491326
type: AcceptedAnswer
downvote count: 0
has body: I'm going to respond to my own question with my current solution. This is not to say that there doesn't exist an easier or faster method. def kth_root(x,k): if k % 2 != 0: res = np.power(np.abs(x),1./k) return res*np.sign(x) else: return np.power(np.abs(x),1./k) x = np.linspace(-100,100,100) kth_root(x,3) &gt;&gt;&gt; array([-4.64158883, -4.26859722, -3.81571414, -3.21829795, -2.23144317, 2.23144317, 3.21829795, 3.81571414, 4.26859722, 4.64158883])
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/88009865
type: QuestionComment
comment on: http://stackoverflow.com/q/50497922
type: Comment
score: 0
has text: Of course you would need to call `plt.subplots_adjust` for every figure you have, not only the last one.

http://stackoverflow.com/q/50477976
accepted answer: http://stackoverflow.com/a/50478039
score: 5
has answer: http://stackoverflow.com/a/50478039
answer count: 5
has answer: http://stackoverflow.com/a/50478152
upvote count: 5
possible better answer: http://stackoverflow.com/a/50478086
has comment: http://stackoverflow.com/comment/87969654
tagged with: python
has answer: http://stackoverflow.com/a/50478083
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87969591
has title: Location of N max values in a python list?
downvote count: 0
has answer: http://stackoverflow.com/a/50478103
has answer: http://stackoverflow.com/a/50478086
has body: I have a python list(containing integers), and I want to find the indices of N highest values in a list. Where N is less than the length of the list. I can find the N maximum values by sorting the list, but is there good way to find the location of these N maximum values? As an example, my list is a = [10, 16, 29, 1, 4, 5, 7, 9, 13, 15], and I need to find the location of 3 highest values. Expected result is [2, 1, 9]
favorite count: 0
type: Question

http://stackoverflow.com/a/50538326
upvote count: 8
has comment: http://stackoverflow.com/comment/88089246
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/88089297
answers question: http://stackoverflow.com/q/50537967
has body: The process you are describing sounds similar to a breadth-first search, which can be utilized to find the triangles which are neighbors. The output merely gives the indices, however, since it is unclear as to how the empty lists end up in the final output: from collections import deque d = [[[2.0, 1.0, 3.0], [3.0, 1.0, 2.0], [1.2, 2.5, -2.0]], [[3.0, 1.0, 2.0], [1.0, 2.0, 3.0], [1.2, -2.5, -2.0]], [[1.0, 2.0, 3.0], [2.0, 1.0, 3.0], [3.0, 1.0, 2.0]], [[1.0, 2.0, 3.0], [2.0, 1.0, 3.0], [2.2, 2.0, 1.0]], [[1.0, 2.0, 3.0], [2.2, 2.0, 1.0], [4.0, 1.0, 0.0]], [[2.0, 1.0, 3.0], [2.2, 2.0, 1.0], [-4.0, 1.0, 0.0]]] def bfs(d, start): queue = deque([d[start]]) seen = [start] results = [] while queue: _vertices = queue.popleft() exists_at = [i for i, a in enumerate(d) if a == _vertices][0] current = [i for i, a in enumerate(d) if any(c in a for c in _vertices) and i != exists_at and i not in seen] results.extend(current) queue.extend([a for i, a in enumerate(d) if any(c in a for c in _vertices) and i != exists_at and i not in seen]) seen.extend(current) return results print(bfs(d, 2)) Output: [0, 1, 3, 4, 5]
downvote count: 0

http://stackoverflow.com/comment/87887218
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50434784
has text: [Why “Can someone help me?” is not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question)
type: Comment

http://stackoverflow.com/comment/88469557
score: 0
type: AnswerComment
has text: Thank you for your update. It is very interesting how in the end the simplest solution, i.e. hiding the tick lines, and drawing afterwards was the trick. I have upvoted and accepted the answer and awarded to you the bounty. Thanks for your help
comment on: http://stackoverflow.com/a/50632992
type: Comment

http://stackoverflow.com/a/64565019
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/114525244
has comment: http://stackoverflow.com/comment/114525278
answers question: http://stackoverflow.com/q/50463092
downvote count: 0
score: 6
has body: In TF 2, tensor = tf.reshape(tf.convert_to_tensor(()), (0, n)) worked for me.

http://stackoverflow.com/q/50497930
upvote count: 0
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/50498095
favorite count: 0
has body: Am having troubles with replacing a certain value for a key in dictionary. dictionary = {'accesskey': 4567, 'name': u'D:\\PROG'} Am trying to replace the value for 'name' when name has '\' in it, with 'other'. Appreciate any little help. Thanks in advance!!
type: Question
has comment: http://stackoverflow.com/comment/88008801
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has title: Replace a specific value of a key in dictionary using python
score: -3

http://stackoverflow.com/a/50863700
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/50497104
has body: I think the problem is how you create the figure attribute and layout of the Graph component. Try this code, it should solve your problem. import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go app = dash.Dash() trace1 = go.Bar( x=['giraffes', 'orangutans', 'monkeys'], y=[20, 14, 23], name='SF Zoo' ) trace2 = go.Bar( x=['giraffes', 'orangutans', 'monkeys'], y=[12, 18, 29], name='LA Zoo' ) app.layout = html.Div([ dcc.Graph(id='bar_plot', figure=go.Figure(data=[trace1, trace2], layout=go.Layout(barmode='stack')) ) ]) It produces the following result:
type: Answer
upvote count: 6

http://stackoverflow.com/q/50491839
tagged with: python
has answer: http://stackoverflow.com/a/58673719
answer count: 2
tagged with: row
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88069564
tagged with: openpyxl
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I'm a fairly new Python user and I have an excel sheet that contains multiple unformatted tables. I am trying to iterate through column B with Python and openpyxl in order to find the headers of the respective table. When I find the header, I would like to save the row number in a variable. Unfortunately, the code is not running as intended and I am not receiving any error message. Below you can find a screenshot of a sample excel sheet as well as my code. Thank you for your help! start = 1 end = 14 sheet = wb[('Positioning')] for col in sheet.iter_cols(min_col=2,max_col=2, min_row = start, max_row=end): for cell in col: if cell.value == 'Table 1': table1 = cell.row elif cell.value == 'Table 2': table2 = cell.row Screenshot - Excel Example
has answer: http://stackoverflow.com/a/50529235
has title: Python / Openpyxl - Find Strings in column and return row number

http://stackoverflow.com/q/50494000
has body: hello every one I have problem of when I am trying to multiply the food price by quantity of food txtReceipt.insert( END, str(No) + " " + str(my_text) + '\t\t' +\ str(my_quantity) + '\t\t' + int(my_quantity) * int(price) + "\n" ) I have this problem TypeError: must be str, not int
has answer: http://stackoverflow.com/a/50494124
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
score: -1
has title: python fix TypeError: must be str, not int
has answer: http://stackoverflow.com/a/50494030

http://stackoverflow.com/q/50510456
score: 3
possible better answer: http://stackoverflow.com/a/50510579
has answer: http://stackoverflow.com/a/50510616
has comment: http://stackoverflow.com/comment/88033285
tagged with: project
has answer: http://stackoverflow.com/a/50510694
has comment: http://stackoverflow.com/comment/88033262
tagged with: python
has body: I have been looking around to see if I could find something that could help, but nowhere has an answer for what I'm looking for. I have a Hangman game I'm doing for a final project in one of my classes, and all I need is to make it so if a word has a capital letter, you can input a lowercase letter for it. This is the code. import random import urllib.request wp = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&amp;content- type=text/plain" response = urllib.request.urlopen(wp) long_txt = response.read().decode() words = long_txt.splitlines() ########### # Methods # ########### def Run(): dashes1 = "-" * len(word) dashes2 = "-" * len(word2) used_letter = [] dashes = dashes1 + " " + dashes2 #dashes ="-" * len(secretWord) guessesLeft = 6 while guessesLeft &gt; -1 and not dashes == secretWord: print(used_letter) print(dashes) print (str(guessesLeft)) guess = input("Guess:") used_letter.append(guess) if len(guess) != 1: print ("Your guess must have exactly one character!") elif guess in secretWord: print ("That letter is in the secret word!") dashes = updateDashes(secretWord, dashes, guess) else: print ("That letter is not in the secret word!") guessesLeft -= 1 if guessesLeft &lt; 0: print ("You lose. The word was: " + str(secretWord)) print(dashes) else: print ("Congrats! You win! The word was: " + str(secretWord)) print(dashes) def updateDashes(secret, cur_dash, rec_guess): result = "" for i in range(len(secret)): if secret[i] == rec_guess: result = result + rec_guess else: result = result + cur_dash[i] return result ######## # Main # ######## word = random.choice(words) word2 = random.choice(words) #print(word) #print(word2) secretWord = word + " " + word2 # can comment out the + word2 to do one word or add more above to create and combine more words will have to adjust abouve in Run() splitw = ([secretWord[i:i+1] for i in range(0, len(secretWord), 1)]) print (splitw) Run() any bit of help is appreciated. The website I'm using has a bunch of words that are b…
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/50510707
downvote count: 0
accepted answer: http://stackoverflow.com/a/50510707
has answer: http://stackoverflow.com/a/50510579
has title: How do I have a list accept lowercase in place of capitalized letters in Hangman for a randomized list in Python 3?
linked to: http://stackoverflow.com/q/6797984
has comment: http://stackoverflow.com/comment/88033135
favorite count: 0
has comment: http://stackoverflow.com/comment/88033197
has comment: http://stackoverflow.com/comment/88033258
tagged with: python-3.x
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/87897608
has text: I tried to run the same program. I am getting the ids as equal every-time I am printing their ids. >>> print(id(df.loc[0, 'a'])) 4402589368 >>> print(id(df1.loc[0, 'a'])) 4402589368 >>> print(id(df.loc[0, 'a'])) 4402589368 >>> print(id(df1.loc[0, 'a'])) 4402589368 >>> print(id(df.loc[0, 'a'])) 4402589368 >>> print(id(df1.loc[0, 'a'])) 4402589368 >>> print(id(df1.loc[0, 'a'])) 4402589368 I think, you must be redefine the df and df1 again. or Running the program
comment on: http://stackoverflow.com/q/50441576
type: Comment
score: 0
type: QuestionComment

pyspark
tags question: http://stackoverflow.com/q/50523055
tags question: http://stackoverflow.com/q/50517559
tags question: http://stackoverflow.com/q/50467121
tags question: http://stackoverflow.com/q/50482720
tags question: http://stackoverflow.com/q/50418429
tags question: http://stackoverflow.com/q/50482829
tags question: http://stackoverflow.com/q/50386955
tags question: http://stackoverflow.com/q/50390255
tags question: http://stackoverflow.com/q/50387354
tags question: http://stackoverflow.com/q/50527953
tags question: http://stackoverflow.com/q/50530679
tags question: http://stackoverflow.com/q/50425475
tags question: http://stackoverflow.com/q/50496361
tags question: http://stackoverflow.com/q/50393696
tags question: http://stackoverflow.com/q/50535772
tags question: http://stackoverflow.com/q/50496448
tags question: http://stackoverflow.com/q/50406096
tags question: http://stackoverflow.com/q/50435900
tags question: http://stackoverflow.com/q/50456449
tags question: http://stackoverflow.com/q/50526122
tags question: http://stackoverflow.com/q/50454850
tags question: http://stackoverflow.com/q/50441128
tags question: http://stackoverflow.com/q/50419797
tags question: http://stackoverflow.com/q/50425779
tags question: http://stackoverflow.com/q/50533833
tags question: http://stackoverflow.com/q/50523950
tags question: http://stackoverflow.com/q/50533589
tags question: http://stackoverflow.com/q/50458082
tags question: http://stackoverflow.com/q/50508838
tags question: http://stackoverflow.com/q/50414294
tags question: http://stackoverflow.com/q/50499894
tags question: http://stackoverflow.com/q/50499628
tags question: http://stackoverflow.com/q/50444290
tags question: http://stackoverflow.com/q/50410862
tags question: http://stackoverflow.com/q/50388822
tags question: http://stackoverflow.com/q/50473181
tags question: http://stackoverflow.com/q/50465399
tags question: http://stackoverflow.com/q/50493426
type: Tag
tags question: http://stackoverflow.com/q/50414300
tags question: http://stackoverflow.com/q/50453048
tags question: http://stackoverflow.com/q/50515267
tags question: http://stackoverflow.com/q/50530819
tags question: http://stackoverflow.com/q/50502485
tags question: http://stackoverflow.com/q/50431221
tags question: http://stackoverflow.com/q/50436311
tags question: http://stackoverflow.com/q/50450552
tags question: http://stackoverflow.com/q/50465895
tags question: http://stackoverflow.com/q/50393380
tags question: http://stackoverflow.com/q/50467823
tags question: http://stackoverflow.com/q/50466293
tags question: http://stackoverflow.com/q/50514640
tags question: http://stackoverflow.com/q/50428414
tag name: pyspark
tags question: http://stackoverflow.com/q/50398598
tags question: http://stackoverflow.com/q/50455680
tags question: http://stackoverflow.com/q/50426245
tags question: http://stackoverflow.com/q/50417891
tags question: http://stackoverflow.com/q/50424196
tags question: http://stackoverflow.com/q/50442803
tags question: http://stackoverflow.com/q/50480921
tags question: http://stackoverflow.com/q/50457079

http://stackoverflow.com/comment/87951878
score: 0
has text: Since you couldn't confirm my problem I updated my question and wrote full code that you can actually run and see the problem I'm talking about. please look at it again. thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50458394

http://stackoverflow.com/a/50434323
answers question: http://stackoverflow.com/q/50434065
has body: Rather using Selenium to scrape use BeautifulSoup, requests and import the below code import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage from bs4 import BeautifulSoup import requests 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) def Callable(self, html_str): self.html = html_str self.app.quit() and import this code in another python file like this from jssoup import Page (I have named it as 'jssoup') page = Page(url) soup = bs.BeautifulSoup(page.html, 'lxml') js_test = soup.find('p', class_='jstest') print(js_test)
has comment: http://stackoverflow.com/comment/87882832
type: Answer
score: 0

http://stackoverflow.com/comment/88004591
score: 2
comment on: http://stackoverflow.com/a/50495917
type: Comment
has text: You don't need to use `**kwargs`; `if opt is None: bar() else bar(opt)`.
type: AnswerComment

http://stackoverflow.com/a/50478055
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50475932
has body: Your question is broad, but I will try and dispel some myths to get your started. I only have experience with Python, so my examples will only relate to using HDF5 with Python. Pandas or PyTables can access HDF5 files, but they do not allow to store plain NumPy arrays I think. You are correct in that PyTables doesn't let you save a plain NumPy array without any additional overhead. But you don't need to use PyTables. h5py offers a NumPy-like interface to storing and accessing arrays in / from HDF5 files. Store a NumPy array import h5py, numpy as np arr = np.random.randint(0, 10, (1000, 1000)) f = h5py.File('file.h5', 'w', libver='latest') # use 'latest' for performance dset = f.create_dataset('array', shape=(1000, 1000), data=arr, chunks=(100, 100) compression='gzip', compression_opts=9) There are compression and chunking options which you can explore further to optimise read/write performance and compression ratios, according to your requirements. Note, however, that gzip is one of the few compression filters which ship with all HDF5 installations. Store axis labels as attributes Attributes are similar to datasets and allow you to store a wide range of data, including scalars or arrays. dset.attrs['Description'] = 'Some text snippet' dset.attrs['X-Labels'] = np.arange(1000) dset.attrs['Y-Labels'] = np.arange(1000) Internally, data is not stored as NumPy arrays, but in data-type sensitive contiguous memory blocks according to the HDF5 specification. As such, you will be able to read these files from any HDF5 API. It is worth noting that there are specific requirements to ensure strings are transportable, see Strings in HDF5 from the h5py docs for more details.
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50475932
upvote count: 3
type: AcceptedAnswer

seaborn
tags question: http://stackoverflow.com/q/50524857
tags question: http://stackoverflow.com/q/50399802
tags question: http://stackoverflow.com/q/50470220
tags question: http://stackoverflow.com/q/50525473
tags question: http://stackoverflow.com/q/50516094
tag name: seaborn
tags question: http://stackoverflow.com/q/50434784
tags question: http://stackoverflow.com/q/50423426
tags question: http://stackoverflow.com/q/50415567
tags question: http://stackoverflow.com/q/50527658
tags question: http://stackoverflow.com/q/50468874
tags question: http://stackoverflow.com/q/50518825
tags question: http://stackoverflow.com/q/50460673
tags question: http://stackoverflow.com/q/50472448
tags question: http://stackoverflow.com/q/50405248
type: Tag
tags question: http://stackoverflow.com/q/50438077
tags question: http://stackoverflow.com/q/50520096

http://stackoverflow.com/comment/88031605
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50509465
has text: @sharifa as Chris stated you need to check the resolution of your webcam. If you are running ubuntu and have v4l2 installed you can check everything with `v4l2-ctl --all`

http://stackoverflow.com/q/50447549
answer count: 2
has comment: http://stackoverflow.com/comment/87908498
has title: Else statement in python
upvote count: 1
has body: I'm a python beginner. Two quick questions on the code below: Why can't I ever execute the print("printed valueError")? Why does the else statement with print("no error occurred") will print no matters what I put in? The code: def int_checker(a,b): try: if isinstance(a,int) and isinstance(b,int): print('both integers') else: raise ValueError print('printed ValueError') except: print('error occurred') else: print('no error occurred') finally: print('no error occurred') print(int_checker(1,2)) print(int_checker(1,'a')
has answer: http://stackoverflow.com/a/50447603
downvote count: 1
has answer: http://stackoverflow.com/a/50447699
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87908451
linked to: http://stackoverflow.com/q/13957829
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6051934
has comment: http://stackoverflow.com/comment/87908479
tagged with: python
has comment: http://stackoverflow.com/comment/87908674
has comment: http://stackoverflow.com/comment/87908419
has comment: http://stackoverflow.com/comment/87908527
score: 0

http://stackoverflow.com/a/60149686
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/123295412
has comment: http://stackoverflow.com/comment/118548569
score: 5
has comment: http://stackoverflow.com/comment/123621800
answers question: http://stackoverflow.com/q/50454857
downvote count: 0
has body: A complete sentence contains at least one subject, one predicate, one object, and closes with punctuation. Subject and object are almost always nouns, and the predicate is always a verb. Thus you need to check if your sentence contains two nouns, one verb and closes with punctuation: import spacy nlp = spacy.load("en_core_web_sm") doc = nlp("I. Introduction\nAlfred likes apples! A car runs over a red light.") for sent in doc.sents: if sent[0].is_title and sent[-1].is_punct: has_noun = 2 has_verb = 1 for token in sent: if token.pos_ in ["NOUN", "PROPN", "PRON"]: has_noun -= 1 elif token.pos_ == "VERB": has_verb -= 1 if has_noun &lt; 1 and has_verb &lt; 1: print(sent.string.strip()) Update I also would advise to check if the sentence starts with an upper case letter, I added the modification in the code. Furthermore, I would like to point out that what I wrote is true for English and German, I don't know how it is in other languages.
has comment: http://stackoverflow.com/comment/121372377

http://stackoverflow.com/q/50468807
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87952030
has comment: http://stackoverflow.com/comment/87952372
tagged with: pyqt
has comment: http://stackoverflow.com/comment/87960298
has title: How to display different directories on different QTabWidget
answer count: 1
tagged with: pyqt5
type: Question
tagged with: python-3.x
has body: I can't run more than one function to set layout to different tabs. In my code only the last def function runs even if i interchange their position still its only the last def that runs. I tried adding another function to check (def_one) and it works and still only one (the last) tab function runs. here is my code. from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys import os import shutil import DiskCleaner_ui class main(QMainWindow, DiskCleaner_ui.Ui_MainWindow): def __init__(self): QMainWindow.__init__(self) self.setupUi(self) systray_icon = QIcon("s.png") self.systray = QSystemTrayIcon(systray_icon, self) menu = QMenu() restore = QAction("Restore", self) close = QAction("Close", self) menu.addActions([restore, close]) self.systray.setContextMenu(menu) self.systray.show() self.systray.showMessage("DC", "Started...", QSystemTrayIcon.Information) close.triggered.connect(self.close) self.treeView = QTreeView() self.fileSystemModel = QFileSystemModel(self.treeView) self.fileSystemModel.setReadOnly(False) self.root = self.fileSystemModel.setRootPath(r'C:\Users\Black Laptop\Desktop') self.treeView.setModel(self.fileSystemModel) self.treeView.setRootIndex(self.root) self.treeView.setSortingEnabled(True) self.Delete_Button = QPushButton("Clear Files") self.Delete_Button.setFixedSize(90, 30) self.Layout = QVBoxLayout(self) self.Layout.addWidget(self.treeView) self.Layout.addWidget(self.Delete_Button) self.Duplicate() #doesnt run self.Unused() #doesnt run self.Temp() #last position : runs (even if i interchange functions between them self.one()# to check : runs def Temp(self): self.Temp_Tab.setLayout(self.Layout) self.Delete_Button.clicked.connect(self.Clear_Temp_Files) def Duplicate(self): self.Duplicate_Tab.setLayout(self.Layout) def Unused(self): self.UnUsed_Tab.setLayout(self.Layout) def one(self): print('self.one() works...') def closeEvent(self, event): reply = QMessageBox.question(self, 'Exit', "Are you sure you want to exit…
tagged with: qtabwidget
accepted answer: http://stackoverflow.com/a/50472019
has comment: http://stackoverflow.com/comment/87960973
tagged with: python
has answer: http://stackoverflow.com/a/50472019

http://stackoverflow.com/q/50498557
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50498674
has comment: http://stackoverflow.com/comment/88027215
upvote count: 2
has answer: http://stackoverflow.com/a/50498674
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88010061
favorite count: 0
has comment: http://stackoverflow.com/comment/88010051
has comment: http://stackoverflow.com/comment/88009927
type: Question
score: 2
has body: I want to create a program that prompts for input and based on this input provides with a tailored reply. As the code is, it works perfectly, with the exception that it is not looping at all. (After running the script in CMD or Powershell it terminates and dies.) I want the program to return to the input prompt following every run. I think I need the return function but I have no idea what kind of argument to give it. Also, the ValueError argument is kind of pointless, there is an issue there. Name = input ("What is your name ? ").strip().lower() while True: try: if Name in ("A"): print("message for A") break else: if Name in ("N"): print("message for N") break except ValueError: print ("Sorry, my only purpose is to talk to N and A") else: print("dammit") break
type: AnsweredQuestion
tagged with: while-loop
linked to: http://stackoverflow.com/q/23294658
has title: Input prompt within a while-true loop
tagged with: python
duplicate of: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/88027281

http://stackoverflow.com/comment/88002004
comment on: http://stackoverflow.com/q/50494463
type: Comment
type: QuestionComment
score: 0
has text: Interestingly I can't replicate your issue, `df.groupby(['class1','class2']).agg(lambda x: x.tolist()).reset_index()` works fine, as does: `df.groupby(['class1','class2']).agg(list).reset_index()` what version of pandas are you running?

http://stackoverflow.com/q/50410547
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87836538
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50410767
has comment: http://stackoverflow.com/comment/87836422
has title: Calculations with pandas categories
has comment: http://stackoverflow.com/comment/87836480
has answer: http://stackoverflow.com/a/50410767
has comment: http://stackoverflow.com/comment/87836606
has body: Is it still possible to do calculations with categorical dtypes? If not, how can I reduce RAM usage of having categorical ints (very big table of 10m+ entries, with only ~500 unique ints). All calculations must be done as 1 array. df = pd.DataFrame({'a':[1,2,3,2,1,3,4,5,6,7], 'b':[1,2,3,2,1,3,4,5,6,7]}) df['a'] = df['a'].astype('category') df['a'] * df['b'] In pandas 0.20.3: Out[23]: 0 1 1 4 2 9 3 4 4 1 5 9 6 16 7 25 8 36 9 49 dtype: int64 This no longer works in newer pandas versions (e.g. v0.23.0) TypeError: Series cannot perform the operation * I now need to refactor my code for the newer pandas version, but is there a way to maintain the reduced RAM consumption categories provided?
has comment: http://stackoverflow.com/comment/87836470
tagged with: python
has comment: http://stackoverflow.com/comment/87836660

http://stackoverflow.com/comment/87992748
type: AnswerComment
score: 2
type: Comment
has text: Another option is `os.path.join(*user_input.split('\\'))`
comment on: http://stackoverflow.com/a/50489884

http://stackoverflow.com/comment/88019050
has text: Except OP also wants conversion from `%m%Y` to something like `%02d-%02m-%Y`
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50503324

http://stackoverflow.com/comment/87949066
type: Comment
comment on: http://stackoverflow.com/a/50467926
has text: I think he wants: `if num > 0 and N in range(2, 60)`. `num` is just used to check if the number is even, `N` is the input number.
type: AnswerComment
score: 1

http://stackoverflow.com/q/50498525
answer count: 2
has title: python Tensorflow ImportError
type: UnansweredQuestion
downvote count: 0
score: 6
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/51462933
linked to: http://stackoverflow.com/q/60029821
linked to: http://stackoverflow.com/q/42013316
has body: Error in the import statement for Tensorflow: import tensorflow as tf Traceback (most recent call last): File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/home/user/anaconda3/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/home/user/anaconda3/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: libcusolver.so.8.0: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module> from tensorflow.python import * File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in <module> from tensorflow.python import pywrap_tensorflow File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "/home/user/anaconda3/lib/python3.6/site-package…
has comment: http://stackoverflow.com/comment/88010675
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/64788915

http://stackoverflow.com/comment/88046864
score: 2
type: Comment
comment on: http://stackoverflow.com/q/50517089
type: QuestionComment
has text: Then you don't really have `N` random integers. You have `N` - `K` random integers.

http://stackoverflow.com/q/50395773
upvote count: 2
has body: I have no idea why this code does not work properly. This program is for automatically locating respective fields of username, password, and enter some data for the tweet to be sent. I am selecting the elements of the page correctly, but not able to enter data into it and get a NoSuchElement Exception . from selenium import webdriver import time import os import selenium chromedriver = "mypathto/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get('https://twitter.com/login') username = driver.find_element_by_name("session[username_or_email]") password= driver.find_element_by_name("session[password]") username.send_keys("myusername") password.send_keys("password") submit = driver.find_element_by_class_name("submit EdgeButton EdgeButton--primary EdgeButtom--medium") submit.click() autotw1= driver.find_element_by_id('tweet-box-home-timeline') autotw1.send_keys("""Just a testing """) print "Tweet probably sent" driver.save_screenshot("mybotfunc.png")
answer count: 1
has comment: http://stackoverflow.com/comment/87810005
has comment: http://stackoverflow.com/comment/87808792
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87808207
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87808978
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/50396498
has title: Tweet using Selenium Python chrome webdriver
has comment: http://stackoverflow.com/comment/87809325
has answer: http://stackoverflow.com/a/50396498

http://stackoverflow.com/comment/87965852
has text: JSON objects can only have strings as keys. Which can always be alphabetically sorted. (And remember, we're not taking about sorting things for display purposes here, just sorting things to verify that the diff is empty.)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50475966
type: QuestionComment

http://stackoverflow.com/a/50486603
has body: def duplicate_finder(word): word1 = word.lower(); w1 = ''; length = len(word1) for i in range(0, length): w2 = word1[i] if(word1[i] != ")"): word1 = word1.replace(word1[i],"(",1) for v in range(i+1,length): if(word1[v] != ")" and word1[v] != "("): if (word1[v] == w2): word1 = word1.replace(w2,")") return (word1)
type: Answer
has comment: http://stackoverflow.com/comment/87985953
score: 0
answers question: http://stackoverflow.com/q/50485559

http://stackoverflow.com/comment/88067792
comment on: http://stackoverflow.com/a/50527690
has text: In fact I want to create a ddos attack on topology using scapy. I write a .py script for this. The problem is that I have no idea how to call each hosts in my custom topology and run attack.py (ddos attack script).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50390364
answer count: 1
tagged with: duplicates
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/14657241
downvote count: 0
has title: Pandas 'dupout' how to view removed duplicate files
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/50390399
tagged with: pandas
upvote count: 3
has body: In pandas I am using drop_duplicates(subset='Full Name', inplace=True) to remove duplicate records, however I would like to view the removed duplicate records for manual inspection. How can I do this?
has answer: http://stackoverflow.com/a/50390399

python-3.4
tags question: http://stackoverflow.com/q/50419505
tag name: python-3.4
type: Tag

http://stackoverflow.com/q/50396232
tagged with: captcha
has title: python requests captcha form
type: UnansweredQuestion
score: 1
tagged with: python
downvote count: 0
answer count: 0
upvote count: 1
tagged with: recaptcha
tagged with: python-requests
favorite count: 0
has body: I'm filling a form using requests and python but i'm blocked with the recaptcha. I need to send a g-recaptcha-response but I don't know how to get it. Here is the website code: &lt;div class="g-recaptcha" data-callback="checkoutAfterCaptcha" data-sitekey="6LeWwRkUAAAAAOBsau7xxxx-xxxxxxxxxx" data-size="invisible"&gt; &lt;div class="grecaptcha-badge" data-style="bottomright" style="width: 256px; height: 60px; transition: right 0.3s ease; position: fixed; bottom: 14px; right: -186px; box-shadow: gray 0px 0px 5px;"&gt; &lt;div class="grecaptcha-logo"&gt; &lt;iframe src="https://www.google.com/recaptcha/api2/anchor?ar=1&amp;amp;k=6LeWwRkUAAAAAOBsau7KpuC9AV-6J8mhw4AjC3Xz&amp;amp;co=aHR0cHM6Ly93d3cuc3VwcmVtZW5ld3lvcmsuY29tOjQ0Mw..&amp;amp;hl=fr&amp;amp;v=v1525674693836&amp;amp;size=invisible&amp;amp;cb=g8s5582r6zik" width="256" height="60" role="presentation" frameborder="0" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox" kwframeid="3"&gt; &lt;/iframe&gt; &lt;/div&gt; &lt;div class="grecaptcha-error"&gt; &lt;/div&gt; &lt;textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid #c1c1c1; margin: 10px 25px; padding: 0px; resize: none; display: none; "&gt; &lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; here is my code, I manage to get the data-sitekey but I don't understand how to get the g-recaptcha-response: page = c.get(link_checkout) soup = BeautifulSoup(page.text, 'html.parser') find_class = soup.find(class_='g-recaptcha') get_captcha_token = find_class.get('data-sitekey') print (get_captcha_token) # try: # content = requests.post( # 'https://www.google.com/recaptcha/api/siteverify', # data={ # 'secret': RECAPTCHA_SECRET, # 'response': get_captcha_token, # 'remoteip': ip # } # ).content # except: # print ("fail") # print (get_captcha_token) c.post(url, data=payload_FORM, headers={"Refered": …
type: Question

http://stackoverflow.com/a/50510001
has body: --override-ini=testpaths=test_integ solved my problem. I was able to override the options from my setup.cfg file using this.
answers question: http://stackoverflow.com/q/50508746
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50508746
score: 1
upvote count: 1

http://stackoverflow.com/comment/88114726
has text: I THINK I got it. Your answer helped me look in the right place for where to change this setting. I'll report back once I know I've change the units. But for now, this worked for me before reading the step file: Interface_Static_SetIVal("read.step.product.mode",0)
score: 0
comment on: http://stackoverflow.com/a/50535681
type: Comment
type: AnswerComment

refactoring
tags question: http://stackoverflow.com/q/50520268
type: Tag
tag name: refactoring

http://stackoverflow.com/a/50397976
accepted answer of: http://stackoverflow.com/q/50397885
answers question: http://stackoverflow.com/q/50397885
type: Answer
score: 2
upvote count: 2
has body: You can control the date format in pd.to_datetime and pd.Series.dt.date: pd.to_datetime(wind.Date, format="%d/%m/%Y").dt.date.strftime('%Y-%m-%d') for example.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50391209
tagged with: python
tagged with: ubuntu-14.04
has body: I'm trying to install watson_developer_cloud for my python 2.7 in Ubuntu 14. I used following command sudo pip install --upgrade watson-developer-cloud And got following error message autobahn 18.5.1 has requirement six&gt;=1.10.0, but you'll have six 1.5.2 which is incompatible. Cannot uninstall 'pyOpenSSL'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. Can you suggest me how to resolve this issue?
has title: Installation error:autobahn 18.5.1 has requirement six>=1.10.0, but you'll have six 1.5.2 which is incompatible
answer count: 0
downvote count: 0
upvote count: 1
score: 1
tagged with: ibm-watson
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/50520133
tagged with: list
tagged with: for-loop
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/88052865
tagged with: loops
has title: how can i append these entries to a list?
type: Question
has body: number = int(input("Enter the number of parcels you want to input: ")) width = int(input("Enter the width (cm)of the parcel: ")) length = int(input("Enter the length (cm)of the parcel: ")) height = int(input("Enter the height (cm)of the parcel: ")) weight = int(input("Enter the weight (kg) of the parcel: ")) width_list = [] length_list = [] height_list = [] weight_list = [] parcel_number = [] parcel_number.append(number) if width &gt; 80 or width &lt; 1: print("Only widths between 1-80 cm is acceptable") elif height &gt; 80 or height &lt; 1: print("Only heights between 1-80 cm is acceptable") elif length &gt; 80 or length &lt; 1: print("Only lengths between 1-80 cm is acceptable") elif weight &gt; 10 or weight &lt; 1: print("Only allowed weights between 1-10 kg") else: print("Parcel is acceptable") First i asked the user to add the measurements of the parcel. Then i needed to check if each parcel was between the correct size 1-80 cm and the weight between 1-10 kg, and then if the user input a measurement beyond the limit it needs to print the mistake. And if the parcel is acceptable i should append each measurement to the lists below, but i dont know how to do it, with the acception of the parcel_number. And if possible can you help me put the code in a loop so i run it the number of times appended to the parcel_number list? Thanks!
has answer: http://stackoverflow.com/a/50520342
tagged with: while-loop
tagged with: python
score: 0

http://stackoverflow.com/q/50397474
tagged with: web-scraping
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/50410318
favorite count: 0
has title: Python - How to test similarity between strings and only print new strings?
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87810684
has body: I have developed a webscraper with beautiful soup that scrapes news from a website and then sends them to a telegram bot. Every time the program runs it picks up all the news currently on the news web page, and I want it to just pick the new entries on the news and send only those. How can I do this? Should I use a sorting algorithm of some sort? Here is the code: #Lib requests import requests import bs4 fonte = requests.get('https://www.noticiasaominuto.com/') soup = bs4.BeautifulSoup(fonte.text, 'lxml') body = soup.body for paragrafo in body.find_all('p', class_='article-thumb-text'): print(paragrafo.text) conteudo = paragrafo.text id = requests.get('https://api.telegram.org/bot&lt;TOKEN&gt;/getUpdates') chat_id = id.json()['result'][0]['message']['from']['id'] print(chat_id) msg = requests.post('https://api.telegram.org/bot&lt;TOKEN&gt;/sendMessage', data = {'chat_id': chat_id ,'text' : conteudo})
type: UnansweredQuestion
tagged with: python
tagged with: sorting
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50521094
upvote count: 0
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/46257103
downvote count: 1
favorite count: 0
type: Question
has body: I have a data of 500k rows and the formatting of the whole data is kinda inconsistent I'm using Spyder, pandas to do the cleaning of data I will have a column that consists of numbers or string. I would like to delete the entire row if that particular cell is in string As shown below is my code with some adjustment due to confidential info import pandas as pd import csv mydataset = pd.read_csv('test.txt', error_bad_lines=False, engine='python', index_col=False,header = None,quoting=csv.QUOTE_NONE, sep="[\s|,|/]",names=["1","2","3","4","a","b","c", "h","i","j","k","l","m","n","o","p","f","g", "q","r","s","t","u","v","w","x","y","z", "5","6","7","8","9","10","11","12","13","14"]) print (mydataset.shape) columns =['3','4','h','a','b','c','i','j','k','l','m','n','f','g'] mydataset.drop(columns,inplace=True,axis=1) print (mydataset.shape) mydataset = mydataset[(mydataset.q.notnull())&amp;(mydataset.r.notnull())&amp; (mydataset.s.notnull())&amp;(mydataset.2.notnull())&amp;(mydataset.2 != "@")] Pardon the naming convention of the header. example of data: 1 2 3 4 &lt;--header abc 123 123 bcd &lt;--Data 123 123 123 bcd &lt;--Data would like to detect the "abc" and remove the whole row Please advice!
has title: Deleting rows with a cell checking if its string or int
duplicate of: http://stackoverflow.com/q/46257103
tagged with: pandas
has comment: http://stackoverflow.com/comment/88054685
tagged with: python
has answer: http://stackoverflow.com/a/50521139
score: -1

http://stackoverflow.com/q/50399802
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50400060
tagged with: seaborn
linked to: http://stackoverflow.com/q/15840926
has body: I have a 12x17 dataframe and want to create a categorical bubble plot looking like this one: https://i.sstatic.net/IvD58.png (from Categorical bubble plot for mapping studies) My dataframe looks basically like this: # A B C # X 0.3 0.2 0.4 # Y 0.1 0.4 0.1 I can't use matplotlib.scatter because it does not take categorical input and creating fake values doesn't work either because it's not n*n. Or can I? I couldn't figure it out. I found seaborn.stripplot which takes one categorical input but the size of all bubbles is the same so I am stuck. Any ideas how I could create such a plot in python? Thanks a lot.
answer count: 1
has title: Python - Categorical bubble plot
type: Question
has answer: http://stackoverflow.com/a/50400060
tagged with: matplotlib

http://stackoverflow.com/q/50464273
tagged with: python-3.x
has body: I have two nested arrays which can look like this: firstArray=[[1,10],[11,31],[32,40],[41,61],[62,78]] secondArray=[[1,10],[12,32],[33,39],[41,78]] I now want to search the elements of secondArray in firstArray. I want two events to be distinguished: 1: if the element is found directly, I want to print it. 2: If it is not found, I want to print the preceeding and following element, or the elements it spans/the elements that contain it. For example, for second Array's [1,10] I want to print firstArray's[1,10], but for secondArray's [12,32] I want to print firstArrays's [11,31] and [32,40]. For secondArray's [33,39] I want to print firstArray's [32,40] and so on. I know, that I can access the two arrays with a nested for loop and that I can access the elements via indexing. I am having trouble to do the part, if there are no direct hits. for the direct hits, I am doing the following: foundYou=[] for entry in firstArray: for element in secondArray: if(entry[0] == element[0]) and (entry[1] == element[1]): foundYou.append(element) I also did some research about indexing, but could not figure out, how to solve this. I also thought of using &lt;=, >=, &lt; and >, but it would then print all elements with a smaller number than the search at first position, but it would ofc print a lot more than I want. I could "index" using a map and another array with values from 1...length of array, but that seems to be a rather complicated way to achieve what I want. Thanks in advance :)
has answer: http://stackoverflow.com/a/50464723
tagged with: for-loop
tagged with: try-except
upvote count: 2
has answer: http://stackoverflow.com/a/50464791
tagged with: arrays
downvote count: 0
has title: Python 3.x: Print specific array items
has answer: http://stackoverflow.com/a/50465299
tagged with: python
has answer: http://stackoverflow.com/a/50465314
favorite count: 0
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50465299
answer count: 4
possible better answer: http://stackoverflow.com/a/50464723
has comment: http://stackoverflow.com/comment/87942251
type: Question

http://stackoverflow.com/comment/87919311
type: Comment
type: AnswerComment
has text: @AnnaRG No, `nunique()` is to count unique values, `drop_duplicates()` is to give all unique values.
score: 1
comment on: http://stackoverflow.com/a/50452840

firefox
tags question: http://stackoverflow.com/q/50513128
type: Tag
tags question: http://stackoverflow.com/q/50400666
tag name: firefox
tags question: http://stackoverflow.com/q/50467167

http://stackoverflow.com/comment/88091062
comment on: http://stackoverflow.com/a/50535415
type: AnswerComment
has text: You have accidentally put an additional semicolon somewhere into the statement.
score: 0
type: Comment

http://stackoverflow.com/q/50422112
tagged with: config
has body: I have a config file that is made up of multiple nested arrays and dictionaries. I need to have a text command that can edit any variable. This is in Python 3. Here is a sample of the config (json): { "joinMsg":{ "help":[ "I need help", "Type !help or !info" ] } The command syntax can be changed to something else but its as follows: !config write joinMsg;help;1 'Try typing !help' I figured out how to read from the config in this way but the way I setup the recursion means I don't have a way to replace the value. This is what I have, arrays is something like joinMsg;help;1 with ; deliminators: # reads from the config file def configRead(arrays): try: arrays = configSearch(arrays) print(arrays) output = config for r in arrays: output = output[r] except: output = 'No array found' return output # recursive config helper def configSearch(arrays): searchRE = re.match(r'([^;]+);(.+)', arrays, re.I) if searchRE: output = configSearch(searchRE.group(2)) output.insert(0, searchRE.group(1)) return output else: return [arrays] This code probably sucks (I'm not formally trained) and I don't know what to do from here. Any help is appreciated, thanks.
has title: [Python]How to edit nested array config values with recursion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87859142
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87859240
has comment: http://stackoverflow.com/comment/87859167
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87859187
tagged with: recursion
has answer: http://stackoverflow.com/a/50422255
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/87983145
comment on: http://stackoverflow.com/q/50462529
has text: If you're using that exact WSGI glue code, is there a file called `/home/charles125/mysite/mysite/settings.py`? Have you reloaded the site after making your code changes?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88007334
comment on: http://stackoverflow.com/a/50496696
has text: Ok so that did work however I did forget one more, specifically (no stderr), when I tried re.sub('(nostder)', '', string) it works, however, it leaves the () and just removes the nostder.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50538430
score: 0
answers question: http://stackoverflow.com/q/50538367
has comment: http://stackoverflow.com/comment/88089056
has body: You have to exit the loop if you detect the press, but I can't this exit condition in your while loop :-) Also if you detect the "right" press you can take the time with time.time() and substract the the starttime to get the actual time difference time_diff = time.time() - starttime
has comment: http://stackoverflow.com/comment/88088828
type: Answer
has comment: http://stackoverflow.com/comment/88088942

http://stackoverflow.com/comment/87848841
comment on: http://stackoverflow.com/a/50415766
type: AnswerComment
score: 0
type: Comment
has text: That's perfect. Thanks a bunch.

http://stackoverflow.com/q/50428376
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50428631
score: 0
answer count: 2
has body: Write a program that determines where to add periods to a decimal string so that the resulting string is a valid IP address. There may be more than one valid IP address corresponding to a string, in which case you should print all possibilities. For example, "19216811", two of the nine possible IP addresses include 192.169.1.1 and 19.216.81.1. Below is my (incomplete) solution: def valid_ips(string): def is_valid_part(part): return len(part) == 1 or (part[0] != 0 and int(part) &lt;= 255) def build_valid_ips(substring): result = [] for i in range(1, min(4, len(substring))): part = substring[:i] if is_valid_part(part): for sub in build_valid_ips(substring[i:]): result.append(part + '.' + sub) return result return build_valid_ips(string) This is a variant problem in the book I'm working out of, so I don't have a solution to look at. However, I have a couple of questions This solution is incorrect, as it always returns an empty list but I'm not sure why. Seems like I'm handling the inductive step and base case just fine. Could someone point me in the right direction? How can I do this better? I understand each recursive call generates a new list and multiple new strings which adds a ton of overhead, but how to avoid this?
accepted answer: http://stackoverflow.com/a/50428907
possible better answer: http://stackoverflow.com/a/50428631
type: Question
has answer: http://stackoverflow.com/a/50428907
tagged with: recursion
tagged with: python
has title: Building IP addresses from string

http://stackoverflow.com/q/50416424
downvote count: 2
has body: I have installed opencv for example, and when importing in sublimetext or in a terminal I jump "ModuleNotFoundError: No module named". If I do it from the python idle, it does not
tagged with: python
score: -1
has title: ModuleNotFoundError: No module named: openCV
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50416631
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87848856
has comment: http://stackoverflow.com/comment/87849008
favorite count: 0
has comment: http://stackoverflow.com/comment/87849238
type: Question
accepted answer: http://stackoverflow.com/a/50416631

http://stackoverflow.com/comment/88023347
comment on: http://stackoverflow.com/q/50503904
type: QuestionComment
has text: How did you install `cntk`?
score: 1
type: Comment

http://stackoverflow.com/q/50412230
type: Question
answer count: 1
downvote count: 0
upvote count: 1
tagged with: sharepoint
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50429966
has title: Receive keyerror when attempting to authorize myself into sharepoint site
has answer: http://stackoverflow.com/a/50429966
score: 1
has body: I am trying to connect to a SharePoint Online site using Python. I have found the Office365-REST-Python-Client on GitHub and have been using that as a guide. I have used "pip install Office365-REST-Python-Client" and it installed without any issue. In the examples folder, I am following along with the file named "listitems_operations_alt.py". If I paste the code into my python file and do not alter it at all, I receive an error saying, "NameError: name 'urlparse' is not defined". If I attempt to alter the url to match my SharePoint Online site's url, I receive an error "KeyError: 'mysite.sharepoint.com'". I am not exactly sure what is causing this issue. below is my code. from examples.settings import settings from office365.runtime.auth.authentication_context import AuthenticationContext from office365.runtime.client_request import ClientRequest def read_list_items(web_url, ctx_auth, list_title): """Read list items example""" request = ClientRequest(web_url, ctx_auth) request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items".format(web_url, list_title) # Web resource endpoint print("Retrieving list items from List {0}".format(list_title)) data = request.execute_request_direct(request_url=request_url) for item in data['d']['results']: print("Item title: {0}".format(item["Title"])) def create_list_item(web_url, ctx_auth, list_title): """Create list item example""" request = ClientRequest(web_url, ctx_auth) request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items".format(web_url, list_title) # Web resource endpoint print("Creating list item...") item_payload = {'__metadata': {'type': 'SP.Data.TasksListItem'}, 'Title': 'New Task'} data = request.execute_request_direct(request_url=request_url, data=item_payload) print("Task {0} has been successfully [created]".format(data['d']['Title'])) return data['d'] def update_list_item(web_url, ctx_auth, list_title, item_id): """Update list item example""" request = ClientRequest(web_url, ctx_auth) request_url = "{0}/_api/web/li…
tagged with: python
tagged with: keyerror

http://stackoverflow.com/comment/88034754
type: QuestionComment
comment on: http://stackoverflow.com/q/50510722
has text: I have figured this out - by using forms.MultipleChoiceField, with the widget= forms.CheckboxSelectMultiple, it allows me to take a list, and not just a value! thanks!
score: 1
type: Comment

http://stackoverflow.com/q/50533478
favorite count: 0
type: Question
tagged with: ffmpeg
has comment: http://stackoverflow.com/comment/88080458
type: UnansweredQuestion
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/88083238
tagged with: python
has body: I am using the following command ffmpeg command and execute it in Python. It used to work for at least a month finely. However, its two days it stopped working and generates different errors. The most important one is "Output file is empty, nothing was encoded" PS: I checked the connectivity to Camera and is healthy. I am able to see the Camera output on my screen using its software. The Command: ffmpeg -i rtsp://username:pass@ip_add:port/videoMain -b 1920k -f image2 -r fps -strftime 1 %Y-%m-%d_%H-%M-%S.jpg PS: fps is taken from input. I mainly used 1 for that. I would be gratfful if anyone can help with this. Thank you.
has comment: http://stackoverflow.com/comment/88080019
answer count: 0
score: 2
upvote count: 2
has title: FFmpeg error: Output file is empty, nothing was encoded
has comment: http://stackoverflow.com/comment/88079153
downvote count: 0

http://stackoverflow.com/q/50400456
tagged with: scipy
has title: I have a function that process a list of floats, and returns a list of floats - how do I find arguments for it that return a list of 0s?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87816943
answer count: 2
has comment: http://stackoverflow.com/comment/87816857
has answer: http://stackoverflow.com/a/50400778
accepted answer: http://stackoverflow.com/a/50401021
tagged with: python
has comment: http://stackoverflow.com/comment/87816999
has answer: http://stackoverflow.com/a/50401021
has comment: http://stackoverflow.com/comment/87817457
has comment: http://stackoverflow.com/comment/87817042
has comment: http://stackoverflow.com/comment/87816908
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50400778
score: 0
has body: This probably involves calculus, but I don't remember how to do calculus. I do know python, but I don't know how to do math in python either. That's why I'm here. I have a function that does something like this (EDIT: a more representative logic): other_lst = [1.,2.,3.,4.,5.] # A list of 5 floats from elsewhere target_lst = [10,20,30,40,50] # A list of 5 ints from elsewhere def get_result( a_lst, an_other_lst, a_target_lst ): zipped = zip( a_lst, an_other_lst ) # no global(s), a pure call-signature _l = [ (x*y) / sum( [ x*y for x,y in zipped ] ) for x,y in zipped ] return [ i-j for i,j in zip( _l, a_target_lst ) ] I want to find some non-trivial lst, such that get_result( lst, other_lst, target_lst ) == [0,0,0,0,0]. EDIT: or even all values of lst such that get_result(lst) == [0,0,0,0,0]. This isn't necessary, but it'd be nice if this were possible. How do I go about doing that? My original approach was just iterating through some values to approximate an answer, but it's not quite giving me what I want. Ignore the arithmetic inside the function logic - they're just placeholders for other logic.
has comment: http://stackoverflow.com/comment/87817102
has comment: http://stackoverflow.com/comment/87816892
has comment: http://stackoverflow.com/comment/87817093

http://stackoverflow.com/a/50419519
has comment: http://stackoverflow.com/comment/87855442
score: 0
has body: It's possible to do it with F() from django.db.models from django.db.models import F User.objects.filter(pk=pk).update(new_attr=F('username')+str(1)) or all_users = User.objects.filter() for user in all_users: user.username = F('username') + str(1) user.save()
answers question: http://stackoverflow.com/q/50419162
has comment: http://stackoverflow.com/comment/87855313
type: Answer
has comment: http://stackoverflow.com/comment/87855219

http://stackoverflow.com/comment/87939892
score: 0
has text: Rewrite at least your inner loopbody to simple loops (no np.einsums, no multiply and if possible no temporary arrays). This will be much easier to optimise for a compiler like Numba and Cython.
type: QuestionComment
comment on: http://stackoverflow.com/q/50440592
type: Comment

http://stackoverflow.com/q/50514919
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: Using beautifulsoup I'm able to scrape a web page with this code: import requests from bs4 import BeautifulSoup page = requests.get("http://www.acbbroker.it/soci_dettaglio.php?r=3") page soup = BeautifulSoup(page.content, 'html.parser') test = soup.find(id="paginainterna-content") test_items = test.find_all(class_="entry-content") tonight = test_items[0] names = [] for x in tonight.find_all('a', itemprop="url"): names.append(str(x)) print(names) but I'm not able to clean the results and obtain only the content inside the &lt; a > paragraph (removing also the href). Here is a small snap of my result: '&lt;a href="http://www.google.com/maps/place/45.45249938964844,9.210599899291992" itemprop="url" target="_blank"&gt;A&amp;amp;B; Insurance e Reinsurance Brokers Srl&lt;/a&gt;', '&lt;a href="http://www.google.com/maps/place/45.647499084472656,8.774800300598145" itemprop="url" target="_blank"&gt;A.B.A. BROKERS SRL&lt;/a&gt;', '&lt;a href="http://www.google.com/maps/place/45.46730041503906,9.148480415344238" itemprop="url" target="_blank"&gt;ABC SRL BROKER E CONSULENTI DI ASSI.NE&lt;/a&gt;', '&lt;a href="http://www.google.com/maps/place/45.47710037231445,9.269220352172852" itemprop="url" target="_blank"&gt;AEGIS INTERMEDIA SAS&lt;/a&gt;', What is the proper way to handle this kind of data and obtain a clean result? Thank you
score: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/88043519
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/50515001
has title: Remove HTML tag from beautifulsoup results
upvote count: 2
accepted answer: http://stackoverflow.com/a/50514949
has answer: http://stackoverflow.com/a/50515001
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50514949
tagged with: python-requests

http://stackoverflow.com/q/50471676
type: Question
has body: Here's my code import scrapy class PvSpider(scrapy.Spider): name = 'pv' allowed_domains = ['www.piaov.com'] start_urls = ['http://www.piaov.com/'] def start_requests(self): yield scrapy.Request(url='http://www.piaov.com/list/7.html') def parse(self, response): names = response.xpath("//ul[@class='mlist']//li/a/@title").extract() on = response.meta.get("names", []) cmp_names = on + names for p in range(2, 7): yield scrapy.Request(url='http://www.piaov.com/list/7_{}.html'.format(p), meta={"names": cmp_names}, callback=self.parse) yield scrapy.Request("http://www.piaov.com", meta={"names": cmp_names}, callback=self.parse_item) def parse_item(self, response): pass When i debug my code in 'parse_item' function,the 'response.meta["names"]' only include the first page datas(12 titles in this case), how could i get the 6 pages datas list.
accepted answer: http://stackoverflow.com/a/50482231
has answer: http://stackoverflow.com/a/50482231
tagged with: python
type: AnsweredQuestion
score: 0
has title: How do I recurse in scrapy?
answer count: 1
tagged with: scrapy

http://stackoverflow.com/q/50533848
type: Question
score: 3
has title: How to pass plugin options to py.test when using Pycharm's py.test runner?
has comment: http://stackoverflow.com/comment/88083271
type: UnansweredQuestion
tagged with: python
tagged with: pycharm
tagged with: pytest
linked to: http://stackoverflow.com/q/35109718
upvote count: 3
answer count: 1
downvote count: 0
has body: I'm trying to run some tests using the Pycharm py.test test runner and I need to pass a command line option to a py.test plugin (pytest-beds). I've tried adding the option to the additional options field in the test run config, but I get the following error: Testing started at 9:54 AM ... /usr/local/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/_jb_pytest_runner.py -- --sdk-path=/some/other/long/path/google-cloud-sdk/platform/google_appengine tests/test_fixture_handler Launching py.test with arguments --sdk-path=/some/other/long/path/google-cloud-sdk/platform/google_appengine tests/test_fixture_handler in /some/long/path usage: _jb_pytest_runner.py [options] [file_or_dir] [file_or_dir] [...] _jb_pytest_runner.py: error: unrecognized arguments: --sdk-path=/some/other/long/path/google-cloud-sdk/platform/google_appengine inifile: /some/long/path/pytest.ini rootdir: /some/long/path Process finished with exit code 2 Empty test suite. Adding the option to adopts in pytest.ini, but I get the same result.
has answer: http://stackoverflow.com/a/50594035
favorite count: 0

http://stackoverflow.com/a/50446261
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87938187
answers question: http://stackoverflow.com/q/50446105
has body: It would probably be better to remove init2 and only use __init__. Having both is confusing and unnatural. class A: def __init__(self, obj): # I believe that this is what you tried to achieve if isinstance(obj, type(self)): self.a = obj.a else: self.a = obj class B(A): def __init__(self, A, b): super().__init__(A) self.b = b On a side note, there are too many things called A here. The A in def __init__(self, A, b): is most probably not referring to the A that you expect.

http://stackoverflow.com/comment/87958009
has text: The return statement exits the function and returns control to its caller 100% of the time. You could retaliate `calc` as `def calc(number): return number + number` and it would behave identically to what you have now.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50467781
score: 0

http://stackoverflow.com/q/50500210
tagged with: web-crawler
type: Question
tagged with: beautifulsoup
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/50500256
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/50500257
possible better answer: http://stackoverflow.com/a/50500232
accepted answer: http://stackoverflow.com/a/50500256
score: 0
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/50500232
has body: I have some web links in a file, article_links.txt, which I want to open one by one, extract their text, and print them out. My code to do this is: import requests from inscriptis import get_text from bs4 import BeautifulSoup links = open(r'C:\Users\h473\Documents\Crawling\article_links.txt', "r") for a in links: print(a) page = requests.get(a) soup = BeautifulSoup(page.text, 'lxml') html = soup.find(class_='article-wrap') if html==None: html = soup.find(class_='mag-article-wrap') text = get_text(html.text) print(text) But I get an error saying, ---> text = get_text(html.text) AttributeError: 'NoneType' object has no attribute 'text' So, when I printed out the soup variable to see what ts contents are. This is what I find for each link: http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law Bad Request Bad Request - Invalid URL HTTP Error 400. The request URL is invalid. Bad Request Bad Request - Invalid URL HTTP Error 400. The request URL is invalid. So, I tried to extract the text from the links individually, like so: import requests from inscriptis import get_text from bs4 import BeautifulSoup page = requests.get('http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law') soup = BeautifulSoup(page.text, 'lxml') html = soup.find(class_='article-wrap') if html==None: html = soup.find(class_='mag-article-wrap') text = get_text(html.text) print(text) And it works perfectly! So, I tried to give the links in a list/array form, and tried to extract the text from each of them: import requests from inscriptis import get_text from bs4 import BeautifulSoup links = ['http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law', 'http://www3.asiainsurancereview.com//Mock-News-Article/id/42946/T…
has title: Beautiful soup cannot extract HTML from pages when opening links from a file

http://stackoverflow.com/comment/88088894
comment on: http://stackoverflow.com/q/50538447
type: Comment
score: 0
type: QuestionComment
has text: Try running `sudo apt-get install libzbar-dev` then re-running with python3.

http://stackoverflow.com/q/50449602
tagged with: rgb
tagged with: opencv
type: AnsweredQuestion
has body: I have these lists containing blue values in RGB format. low = [ [0, 0, 128], [65, 105, 225], [70, 130, 180], [72, 61, 139], [83, 104, 120] ] What I want to make is this: convert all the values from, for example, first list from RGB to HSV. I made this code: import cv2 import numpy as np for v in low: rgb = np.uint8(v) print("RGB: ", rgb) hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) print("HSV: ", hsv) print("\n") The problem is when I go to check if the colors (RGB-HSV) are the same. Here I discovered that it's not. Let's take the last value from low list. RGB: [[[ 83 104 120]]] HSV: [[[103 79 120]]] RGB is RGB input value and HSV is output. But this last one it's not the same color as RGB. First is a shade of blue and last is green. Why? I used this tool to check values. It also says that the right HSV for this RGB should be 205, 30, 47. Where is my mistake?
possible better answer: http://stackoverflow.com/a/50463711
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50450658
accepted answer: http://stackoverflow.com/a/50450658
has answer: http://stackoverflow.com/a/50463711
linked to: http://stackoverflow.com/q/43307959
has comment: http://stackoverflow.com/comment/87937013
has comment: http://stackoverflow.com/comment/87912445
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87913991
answer count: 2
downvote count: 0
has title: Wrong HSV conversion from RGB
tagged with: python
has comment: http://stackoverflow.com/comment/87913348

http://stackoverflow.com/q/50479335
tagged with: deep-learning
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87972420
upvote count: 1
tagged with: keras
downvote count: 1
has answer: http://stackoverflow.com/a/50495806
has title: Reinforcement learning for predicting rotation between two images
favorite count: 0
type: Question
tagged with: reinforcement-learning
has body: I have pairs of images randomly rotated with respect to each other. I want to predict the rotation angle. I don't know the true rotation angle, but I know that MSE between the two image after applying correct rotation should be minimized. I could generate a training data with known rotations and train network. But can we do this without training data, with MSE between original and rotated images as the loss function? I tried to add a layer that applies predicted rotation to one input image and compares with the second input image. Alternatively, we could use custom loss function that does this, but it needs to take an input image and predicted rotation as input, instead of y_pred and y_true. But I don't know how to do this in Keras. I am just a newbie so would greatly appreciate help.
tagged with: python
score: 0

http://stackoverflow.com/comment/88186863
score: 0
has text: @Heavens93 try `p=[1]`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50535447

http://stackoverflow.com/comment/87808809
type: AnswerComment
has text: Thank you very much
comment on: http://stackoverflow.com/a/50396464
score: 0
type: Comment

http://stackoverflow.com/comment/87789253
comment on: http://stackoverflow.com/q/50386729
has text: You have updated the question, but still `var1` `var2` and `var3` are not valid in python. Your picture is not complete as it is excluding the end of that string.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88060578
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50524328
has text: `print(sorted_dict[:N])`?

http://stackoverflow.com/q/50385200
has comment: http://stackoverflow.com/comment/87786073
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50385298
downvote count: 4
has comment: http://stackoverflow.com/comment/87786943
has comment: http://stackoverflow.com/comment/87785996
has comment: http://stackoverflow.com/comment/87786097
tagged with: datetime
score: -3
upvote count: 1
tagged with: python
tagged with: tweepy
has title: Writing datetime to CSV file in python?
has comment: http://stackoverflow.com/comment/87786034
has answer: http://stackoverflow.com/a/50385298
type: AnsweredQuestion
answer count: 1
tagged with: twitter
has body: I want to write datetime object in a csv file. for that i am doing something like like that: csvWriter.writerow([tweet.created_at.encode('utf-8'), tweet.user.name.encode('utf-8')]) but i am getting error; 'datetime.datetime' object has no attribute 'encode' and if i just simply type "tweet.created_at" with out encode csvWriter.writerow([tweet.created_at, tweet.user.name.encode('utf-8')]) i get this error TypeError: 'datetime.datetime' object is not callable so how can i write datetime in CSV?
has comment: http://stackoverflow.com/comment/87788391

http://stackoverflow.com/comment/87851494
score: 0
has text: Your list is a copy of single element, you are way more productive if you just use numpy for this. I can smell some matlab background of yours :)
comment on: http://stackoverflow.com/q/50417851
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50434460
upvote count: 2
has comment: http://stackoverflow.com/comment/87884091
has comment: http://stackoverflow.com/comment/87884431
downvote count: 0
tagged with: python
tagged with: pygame
has title: Why do I get Pygame KEYUP event without releasing the key?
type: AnsweredQuestion
tagged with: keyevent
has comment: http://stackoverflow.com/comment/87883680
score: 2
tagged with: keyup
has comment: http://stackoverflow.com/comment/87884259
has body: Firstly, I'm a complete beginner, so I do not have any experience, I have however searched all the possible places these last 2 days for a resolve, and could not find it. I'm using this on a Raspberry PI 3 with Raspbian. I'm trying to build a simple code in Python 3.6 that will do the following: When pressing a keyboard key: 1.it should print 'press' if the key was pressed, without repeating. (if the key is being held down, it should print 'press' only once and stop). 2.it should print 'release' if the key was released without repeating. Basically I want to print once the last state of the key, The problem I am having is: while holding down the key, I'm getting consecutive press/release press/release press/release events, even if no key was physically released, instead of getting only 1 'press'. Below is the code that I'm trying to use. #!/usr/bin/env python import pygame from pygame.locals import * from time import sleep import time pygame.init() screen = pygame.display.set_mode((800,800)) keys= [False] last = None pygame.key.set_repeat() while True: if keys[0]==True and last != 'press': print ('press') last = 'press' if keys[0]==False and last != 'release': print('release') last = 'release' for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() exit(0) if event.type == pygame.KEYDOWN: if event.key==K_d: keys[0]=True if event.type == pygame.KEYUP: if event.key==K_d: keys[0]=False
answer count: 1
has comment: http://stackoverflow.com/comment/87884139
has comment: http://stackoverflow.com/comment/87883580
has comment: http://stackoverflow.com/comment/87883567
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50435353
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50435353

modal-dialog
tags question: http://stackoverflow.com/q/50416935
tag name: modal-dialog
tags question: http://stackoverflow.com/q/50399978
type: Tag

http://stackoverflow.com/comment/87871717
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50402801
has text: I guess the it might be a path problem. (The R version and Rscript path is for sure correct?) If yes, then give the full absolute path to `testing.r`, so 'C:/full/absolute/path/to/testing.r' (or is it in 'D:/' even)?
score: 0

http://stackoverflow.com/q/50413021
tagged with: networkx
has answer: http://stackoverflow.com/a/50424511
tagged with: graph
has body: I meet this question when I read about the python script of SCI2(Science of Science)software. Maybe what I want to ask is a simple python question. I will show the SCI2 script first in the picture below. After that,I will write some codes. My question is why the codes in the picture can get list of all nodes by slicing method [:] but I can't. codes from SCI2 python script Maybe the picture can not be shown, I write the important codes here. (the language is python) # make a copy of the list of all nodes nodesbynumworks = g.nodes[:] What I wirte is: import networkx as nx g =nx.Graph() g.add_node(1,size=11) g.add_node(2,size=12) a = g.nodes[:] And this is my result: my result I just want to get the list of all nodes so that I can take some nodes from this list. And maybe I can change some attributes of some nodes.But I can't do that now. What I can think about is the reason that python2 and python3 are different in some place. I know this a a very pale explanation. Hope someone can help me.
has answer: http://stackoverflow.com/a/50415451
has comment: http://stackoverflow.com/comment/87842168
has answer: http://stackoverflow.com/a/50413306
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87841898
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/87842215
has comment: http://stackoverflow.com/comment/87842295
answer count: 3
has title: About the list of all nodes in graph(python)
has comment: http://stackoverflow.com/comment/87845807
has comment: http://stackoverflow.com/comment/87841670
tagged with: nodes
type: Question

http://stackoverflow.com/q/50400306
type: Question
accepted answer: http://stackoverflow.com/a/50409843
tagged with: python
has answer: http://stackoverflow.com/a/50409843
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87816897
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: user-interface
has title: Tkinter Label Text Overlaps in Specific Loop
downvote count: 0
answer count: 1
has body: I'm working on a "simple" search interface using Python and Tkinter. Here is some example code of what I've got: #!/usr/bin/env/python from tkinter import * import os import csv import sys def fetch() word = e1.get() definitions = [] with open(file) as db: dbreader = csv.reader(db, delimiter="\t") for row in dbreader: if word in row[1]: definitions.append(row[4]) if not definitions: output_string = word + " not in database" else: output_string = "Found " + word result_out = Label(master) result_out.config(text=output_string) result_out = result_out.grid(row=3, column = 0) master = Tk() word_entry = Label(master, text = "word") word_entry.grid(row=0, column = 0) e1 = Entry(master) e1.grid(row=0, column=1) Button(master, text='Search', command=fetch).grid(row=2, column=1, sticky=(N, S, W, E), pady=4) mainloop() The code operates as intended if I am searching words that are found in the database. If I search a word that is not in the the database, my next search with a word that is present will overlap the previous output. The opposite is true, if I only search items not found in the database, the label refreshes as expected. When these loops "alternate" I experience issues. What in the world is going on?
favorite count: 0

http://stackoverflow.com/comment/105827612
type: AnswerComment
comment on: http://stackoverflow.com/a/50504635
score: 7
has text: @theggg If I understand your question correctly - escape your backslash, so the string will read `'\\d'`.
type: Comment

http://stackoverflow.com/q/50411340
downvote count: 0
has answer: http://stackoverflow.com/a/50412874
has comment: http://stackoverflow.com/comment/87841491
favorite count: 0
type: Question
tagged with: go
score: 3
tagged with: python
has title: Golang Scrypt Decrypt
tagged with: scrypt
has comment: http://stackoverflow.com/comment/87838618
upvote count: 3
has body: I'm trying to mimic in Go, the functionality that is available in a python library (https://pypi.org/project/scrypt/) for decrypting a scrypt generated digest (given the correct password). It seems the go library only provides one function for encrypting data where as it seems this python library provides not only that but also a way to reverse/decrypt the digest, as well as provide a function for using scrypt for a simpler one-way hash function. I'm not a security expert, nor do I understand maths/numbers so I feel like trying to replicate that python library is beyond my understanding. I presume it's possible to do because the python library appears to have achieved it. Does anyone know where I would even start on approaching this problem. Or be gracious enough with their time to provide some form of example code to help me. Thanks. Update The scrypt function is fundamentally a hash function. It uses a password as a way to derive a digest: meaning, there should be no way for the original message (the message that was hashed) to be retrieved. So with that understanding in place, it makes sense that Golang's interface for scrypt doesn't support any such function such as decrypt. But then how is py-script's decrypt function working? Well, if I look back at https://www.tarsnap.com/scrypt.html it states that the scrypt executable provides an "encryption utility"... A simple password-based encryption utility is available as a demonstration of the scrypt key derivation function. The scrypt utility can be invoked as scrypt enc infile [outfile] to encrypt data (if outfile is not specified, the encrypted data is written to the standard output), or as scrypt dec infile [outfile] to decrypt data (if outfile is not specified, the decrypted data is written to the standard output). ...and upon checking py-script I see it embeds a version of the scrypt executable, meaning py-script is calling the executable's enc and dec functions. So although I don't necessarily know how tarsnap…
type: UnansweredQuestion
answer count: 1
tagged with: encryption

http://stackoverflow.com/a/50458241
answers question: http://stackoverflow.com/q/50458131
has comment: http://stackoverflow.com/comment/87930133
score: 1
downvote count: 0
upvote count: 1
has body: What you are doing may seem sensible, but Python translates your for loop into something like this: i = 0 while i &lt; len(unconfirmed_users): user = unconfirmed_users[i] # ... unconfirmed_users.remove(user) i += 1 So behind the scenes, Python is reading the first element of the list ('anna'), then removing it, then moving to the second element of the modified list ('carmina', because 'anna' was removed and now 'bryce' is the first element). Your code would print 'anna' and 'carmina' only if not for the too-clever-by-half while loop on the outside, which repeats this iteration and picks up the element you skipped the second time through the for loop. As a side note, you probably shouldn't modify a list while you are iterating over it unless you have a really good reason to do so. Check out the definition of the for statement in the documentation, especially the last paragraph at the end describing exactly this situation.
has comment: http://stackoverflow.com/comment/87929984
type: Answer

http://stackoverflow.com/comment/88080058
comment on: http://stackoverflow.com/q/50513219
score: 0
has text: Do check if your orm class is inheriting `db.Model` correctly
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87951850
has text: Please go through the [pandas tutorials](https://pandas.pydata.org/pandas-docs/stable/tutorials.html) and [cookbook](https://pandas.pydata.org/pandas-docs/stable/cookbook.html).
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50469213
type: Comment

http://stackoverflow.com/comment/88052672
type: QuestionComment
comment on: http://stackoverflow.com/q/50519966
has text: Is there a reason why this code `'''INSERT INTO Counts (email, count) VALUES (?, 1)'''` has three single quotes around it, rather than one? I _believe_ (but haven't checked) that this would mean that this would prevent the `INSERT` statement from being interpreted as an `INSERT`.
type: Comment
score: 0

http://stackoverflow.com/comment/87944536
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50465164
has text: i don't know, probably not, why don't you try it out and let me know.
type: Comment

http://stackoverflow.com/comment/87995549
type: Comment
comment on: http://stackoverflow.com/q/50490990
has text: question updated.
score: 0
type: QuestionComment

http://stackoverflow.com/q/50473505
answer count: 1
has body: I have a class in Python that I want to instantiate with kwargs: e.g. a = ClassA(happy=True) I want to override this class with ClassB and set happy to True, I assumed this definition would work: class ClassB(ClassA(happy=True)) However I get: TypeError: 'ClassA' object is not callable The workaround I have currently is to define ClassB as: class ClassB(ClassA) But then every time I instantiate ClassB, I have to do this: b = ClassB(happy=True) Anyone know how to do this?
tagged with: keyword-argument
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Set default kwargs when overrriding in Python 3
has comment: http://stackoverflow.com/comment/87960582
accepted answer: http://stackoverflow.com/a/50473551
tagged with: python
has answer: http://stackoverflow.com/a/50473551
score: -1
linked to: http://stackoverflow.com/q/8333354
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/8333354
upvote count: 0

http://stackoverflow.com/a/50478269
downvote count: 0
has body: One way is to use pd.Series.repeat: res = df.set_index(['id', 'year', 'X', 'Y'])['weight']\ .repeat(df['weight'])\ .reset_index() print(res) id year X Y weight 0 1 2011 54 Medium 2 1 1 2011 54 Medium 2 2 1 2012 57 Medium 1 3 2 2011 8 Micro 1 4 2 2012 10 Micro 2 5 2 2012 10 Micro 2 6 3 2011 10 Micro 3 7 3 2011 10 Micro 3 8 3 2011 10 Micro 3 9 1 2012 9 Micro 1
type: Answer
answers question: http://stackoverflow.com/q/50478221
score: 2
upvote count: 2

http://stackoverflow.com/q/50387437
linked to: http://stackoverflow.com/q/50390985
tagged with: imagemagick-convert
tagged with: python
has body: As per hint from here, I tried to create a gif with 2 dissimilar images as below. It works, but one frame is not disappearing to show another frame. Why would this happen and how to rectify? from wand.image import Image as Image2 with Image2() as wand: # Add new frames into sequance with Image2(blob=d2) as one: wand.sequence.append(one) with Image2(blob=d3) as two: wand.sequence.append(two) # Create progressive delay for each frame for cursor in range(2): with wand.sequence[cursor] as frame: frame.delay = 100 # Set layer type wand.type = 'optimize' wand.save(filename='animated.gif') display(Image('animated.gif')) Current output:
tagged with: image
score: 0
has title: Frames not disappearing in python wand
tagged with: imagemagick
tagged with: wand
has answer: http://stackoverflow.com/a/50389589
accepted answer: http://stackoverflow.com/a/50389589
answer count: 1
linked to: http://stackoverflow.com/q/39939780
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/87906550
comment on: http://stackoverflow.com/a/50440264
type: AnswerComment
has text: Btw, the list comprehension looks neat to me, is there any reason to use the alternate solution?
score: 0
type: Comment

http://stackoverflow.com/comment/88001274
type: AnswerComment
comment on: http://stackoverflow.com/a/50493721
has text: Yes, they will still be functioning. Let me edit the answer and add a button.
type: Comment
score: 0

http://stackoverflow.com/comment/87974393
type: AnswerComment
comment on: http://stackoverflow.com/a/50470431
score: 0
type: Comment
has text: Just do `[x[0] for x in lst]`.

http://stackoverflow.com/q/50388683
has comment: http://stackoverflow.com/comment/87794099
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87793731
has title: Pandas convert datetime string column to datetime without offset applied
tagged with: pandas
has comment: http://stackoverflow.com/comment/87794161
has body: I'm new to Python and Pandas, so dont be hard with me :) I have multiple Columns in the form of "2014-01-01 00:00:00-06:00". Now i want to convert the columns name into a pandas datetime. But i struggle with the format i need to use. I already tried date = pd.to_datetime("2014-01-01 00:00:00-06:00", format='%Y-%m-%d %H:%M:%S%z') But here i get a error with "ValueError: time data '2014-01-01 00:00:00-06:00' does not match format '%Y-%m-%d %H:%M:%S%Z' (match)" I dont want the time to get converted into my timezone. I need it for the Timezone -06:00 For this Input: 2014-01-01 00:00:00-06:00 The Output should be: 2014-01-01 00:00:00 I want to use the date variable of the Output so i can split my data into seasons. Something like this: date &gt; springBegining Thanks for all help
tagged with: datetime
has comment: http://stackoverflow.com/comment/87794059
tagged with: python
has comment: http://stackoverflow.com/comment/87793890
accepted answer: http://stackoverflow.com/a/50388814
has comment: http://stackoverflow.com/comment/87793193
has answer: http://stackoverflow.com/a/50388814
type: Question
has comment: http://stackoverflow.com/comment/87793834
has comment: http://stackoverflow.com/comment/87793868
score: 2
has comment: http://stackoverflow.com/comment/87793941
upvote count: 3
has comment: http://stackoverflow.com/comment/87792951
answer count: 1
has comment: http://stackoverflow.com/comment/87793810
has comment: http://stackoverflow.com/comment/87792915
downvote count: 1
has comment: http://stackoverflow.com/comment/87794170

http://stackoverflow.com/comment/87973860
type: AnswerComment
has text: And there's no need to "from kivy.uix.gridlayout import GridLayout"? how does that work?
type: Comment
comment on: http://stackoverflow.com/a/50469911
score: 0

http://stackoverflow.com/a/50520736
type: Answer
answers question: http://stackoverflow.com/q/50520662
score: 0
has body: queryset aggragate all filters, excludes annotates and somethins like that and when you do something with this queryset, django generate query (from filters etc. do sql query) to database and after that do qyery do database

http://stackoverflow.com/q/50535911
has comment: http://stackoverflow.com/comment/95467984
score: 2
upvote count: 2
has body: (Running Windows 10 Home) Steps to reproduce problem: Install miniconda Install MS Visual Studio 2017 C++ build tools with Windows 8.1 and 10 SDK conda create -n myenv python=3.5 activate myenv pip install spectrum Fails with error error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools deactivate pip install spectrum Build succeeds. What's going on?
answer count: 1
downvote count: 0
tagged with: pip
favorite count: 0
has answer: http://stackoverflow.com/a/73491453
type: Question
has title: pip install fails inside conda environment but works in base
tagged with: anaconda
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88084800
tagged with: python
has comment: http://stackoverflow.com/comment/88083990
tagged with: conda

http://stackoverflow.com/a/50493781
has body: Try out this, from pyspark.sql import functions as F total = event_rates.groupBy().agg(F.sum("mean_encoded"),F.sum("cluster_id")).collect() total Answer will be, [Row(sum(mean_encoded)=31.459970115421946, sum(cluster_id)=6)]
answers question: http://stackoverflow.com/q/50493426
type: Answer
score: 0

http://stackoverflow.com/q/50475199
has answer: http://stackoverflow.com/a/50475483
favorite count: 0
type: Question
tagged with: cosine-similarity
has answer: http://stackoverflow.com/a/50477029
tagged with: dataframe
tagged with: python
has title: Scipy Cosine Similarity is very slow using Pandas Dataframes
tagged with: collaborative-filtering
answer count: 2
tagged with: pandas
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
has body: Few days back i have started learning Python by doing a project. I have two dataframes that i prepared out of my data which are User and Item Dataframes. User DF has the 17k distinct users and Item DF has 1,500 albums. I am using collaborative filtering to get the cosine similarity between two dataframes as below from scipy.spatial.distance import cosine for i in range(0,len(user_normalized.index)-1): for j in range(0,len(item_matrix.index)-1): item_matrix_cpy.at[j, 'cosine'] = 1 -cosine(item_matrix_same_shape.iloc[j], user_normalized.iloc[i]) I observed that my looping logic is performing very slow and running for ever to complete. I tested the logic for few users (&lt;10), observed that cosine computation is taking longer to execute (~12s). But when i tried to run the same cosine logic for all the users(i.e 17K) , the query is taking forever to complete. Can you guys help me here ?

http://stackoverflow.com/q/50540186
tagged with: pyside2
answer count: 1
downvote count: 0
has body: i have small application that i want to minimize to system tray, and i do have code that creates icon and minimizes it to system tray on push of a button, (on purpose i did not want to overwrite default close operation). How ever, i dont know how to get my root object from qml, so i am unable to perform any action, and when i would get it, what type would it be ? app = QApplication(sys.argv) engine = QQmlApplicationEngine() manager = Manager() ctx = engine.rootContext() ctx.setContextProperty("Manager", manager) engine.load('main.qml') if not engine.rootObjects(): sys.exit(-1) app.setWindowIcon(QtGui.QIcon('ico.png')) sys.exit(app.exec_()) class Manager(QObject): def __init__(self): QObject.__init__(self) self.tray_icon = QSystemTrayIcon(self) now the following code i made to "work" on my application, even though is not working properly. self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) show_action = QAction("Show", self) quit_action = QAction("Exit", self) hide_action = QAction("Hide", self) show_action.triggered.connect(self.show) hide_action.triggered.connect(self.hide) quit_action.triggered.connect(qApp.quit) tray_menu = QMenu() tray_menu.addAction(show_action) tray_menu.addAction(hide_action) tray_menu.addAction(quit_action) self.tray_icon.setContextMenu(tray_menu) self.tray_icon.show() def minimize(self): self.hide() print("Test") _translate = QtCore.QCoreApplication.translate #self.hide() self.tray_icon.showMessage( "Tray Program", "Application was minimized to Tray", QSystemTrayIcon.Information, 2000 ) the only thing i did i changed class Manager(QObject): to (QMainWindow) and i could use this code, but instead manipulating my window, i got the completly new window, nonetheless i did get normal system tray icon and all menu items i needed. So bottom line, how can i get reference of my root, and how can i use minimize to tray on it. root of my QML is normal ApplicationWindow. Just a small edit, i saw on some c++ examples they used to use …
favorite count: 0
type: Question
tagged with: qml
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50545847
has title: Get root object from pyside2
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50545847

http://stackoverflow.com/comment/87910467
has text: can u please add a link to a small example of your data so I can debug it offline?
type: Comment
comment on: http://stackoverflow.com/a/50439853
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87963891
has text: " because this is a numpy.ndarray and not a column of a DF anymore " - I realized that after you pointed out. I wanted to have the dates in datetime64[D] type. But as you pointed out thats not possible as long as I am using a data frame.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50474488

http://stackoverflow.com/q/50521914
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50522471
has title: Matplotlib - Possible to make sub plots with parasite axes?
answer count: 1
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50522471
downvote count: 0
tagged with: matplotlib
has body: I'm trying to make a chart with two subplots, each of which has a parasite axis, as shown in the documentation here. However, although I can replicate the example with a single plot, it doesn't seem to work with 2 subplots. Is Matplotlib even capable of doing this? Here is my code: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) plt.subplot(2,1,1) par1 = host.twinx() par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par1.axis["right"].toggle(all=True) par2.axis["right"].toggle(all=True) host.set_xlim(0, 2) host.set_ylim(0, 2) host.set_xlabel("Distance") host.set_ylabel("Density") par1.set_ylabel("Temperature") par2.set_ylabel("Velocity") p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density") p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature") p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity") par1.set_ylim(0, 4) par2.set_ylim(1, 65) host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right"].label.set_color(p3.get_color()) #####2##### plt.subplot(2,1,2) par1 = host.twinx() par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par1.axis["right"].toggle(all=True) par2.axis["right"].toggle(all=True) host.set_xlim(0, 2) host.set_ylim(0, 2) host.set_xlabel("Distance") host.set_ylabel("Density") par1.set_ylabel("Temperature") par2.set_ylabel("Velocity") p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density") p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature") p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity") par1.set_ylim(0, 4) par2.set_ylim(1, 65) host.legend() host.axis["left"].label.set_color(p1.g…
favorite count: 0

http://stackoverflow.com/comment/94869792
type: Comment
comment on: http://stackoverflow.com/a/50422952
type: AnswerComment
has text: @Iiliscent How to give column to these columns instead of count and product?
score: 0

http://stackoverflow.com/comment/87931283
has text: Thank you so much for this. I have decided to implement it this way and expand on it. My question is, how do I get the Revenue for example instead of traffic? Why is it selecting traffic instead of revenue, as revenue comes first in the way you have it declared. Thank you very much!
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50440704
type: AnswerComment

http://stackoverflow.com/comment/87905896
has text: @Karthik did you run handle.exe ?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50405554

http://stackoverflow.com/q/50459452
type: Question
has comment: http://stackoverflow.com/comment/87932204
accepted answer: http://stackoverflow.com/a/50459539
tagged with: python
linked to: http://stackoverflow.com/q/7588511
has comment: http://stackoverflow.com/comment/87932181
tagged with: timestamp
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Generate Time stamp with millisecond frequency in Python
downvote count: 0
has body: Hello I am analyzing vibration data, the output form my sensors just gives my the array values and cannot export the time stamping. Its a 10 Khz data which is 0.0001 ms. Is there a way to generate timestamp values in python with this interval. For example: 2018-05-21 00:00:00:0001, 2018-05-21 00:00:00:0002
answer count: 1
has answer: http://stackoverflow.com/a/50459539
favorite count: 0

http://stackoverflow.com/a/70646488
type: Answer
has body: one option, which offers a modest speed up, is to build an array of 1s and 0s for the days overdue, before grouping: temp = df.assign(d = np.where(df['Days overdue'] == 0, 1, 0)).groupby('Course') count = temp.Trainee.size() in_time = temp.d.sum() completed_in_time = in_time/count pd.DataFrame({'count':count, 'in time' : in_time, '% completed in time' : completed_in_time }) count in time % completed in time Course ABC 2 1 0.500000 DEF 3 2 0.666667 GHI 1 1 1.000000
score: 0
answers question: http://stackoverflow.com/q/50507750

http://stackoverflow.com/a/50468625
has comment: http://stackoverflow.com/comment/87951338
has comment: http://stackoverflow.com/comment/87951088
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87951147
accepted answer of: http://stackoverflow.com/q/50468300
downvote count: 0
has body: Use params to pass a tuple of parameters including machineid to read_sql. pyodbc replaces the ? character in your query with parameters from the tuple, in order. Their values will be safely substituted at runtime. This avoids dangerous string formatting issues which may result in SQL injection. df = pd.read_sql(""" SELECT fld_ATM FROM [003_tbl_ATM_Tables] WHERE (LINK &lt;&gt; 1) AND (fld_ATM = ?) ; """, connection, params=(machineid,))
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50468300

http://stackoverflow.com/q/50513310
has title: Django test will not notice "django.contrib.auth.context_processors.auth"
has comment: http://stackoverflow.com/comment/88039865
has answer: http://stackoverflow.com/a/50514240
has body: I'm writing a basic django test for a forms.Form type page. Here is the form: # This is the form to become a seller class BecomeSellerForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField(min_length=3, max_length=20) phone_number = forms.IntegerField(max_value=19999999999) My test consists of a basic post request and I asser my response status code is 200. However, my I get this error in my test: ValueError: modules context processor require "django.contrib.auth.context_processors.auth"to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file. And it's getting caught in the successful return statement in my views.py code: return render(request, 'accounts/become_seller_success.html', context) What confuses me is that I 100% have met this requirement in my settings file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], }, }, ] So why is my test fussing about it? I have been looking around but have not seen a problem/solution that is similar. Thanks a bunch for the help
has comment: http://stackoverflow.com/comment/88039904
tagged with: python
tagged with: templates
type: Question
score: 0
tagged with: pytest
type: UnansweredQuestion
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/88040229

http://stackoverflow.com/q/50493892
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50494025
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I have an object that looks like this object_1 = [(1,"car"), (1,"stuff"), (2,"things"), (2,"more stuff"), (3,"less thing"), (4,"diff_things")] And I need a pythonic way to loop through it and make it into this [(1,["car","stuff"]), (2,["things","more stuff"]), (3,"less thing"), (4,"diff_things")] Seems simple enough but I cant seem to get it to work correctly.
tagged with: python-3.x
has title: Loop through object to create new object in python
accepted answer: http://stackoverflow.com/a/50494025
has comment: http://stackoverflow.com/comment/88000874

http://stackoverflow.com/a/50545127
has comment: http://stackoverflow.com/comment/88202975
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50539692
score: 1
upvote count: 1
has body: You can use itertools.groupby with recursion: import itertools rows = [{'Year': None, 'Region': None, 'Country': None, 'Manufacturer': None, 'Brand': None, 'Value': 1}, {'Year': 2013, 'Region': None, 'Country': None, 'Manufacturer': None, 'Brand': None, 'Value': 2}, {'Year': 2013, 'Region': 'LTM', 'Country': None, 'Manufacturer': None, 'Brand': None, 'Value': 3}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': None, 'Brand': None, 'Value': 4}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M1', 'Brand': None, 'Value': 5}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M1', 'Brand': 'B1', 'Value': 6}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M2', 'Brand': None, 'Value': 7}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M2', 'Brand': 'B2', 'Value': 8}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M2', 'Brand': 'B3', 'Value': 9}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M3', 'Brand': None, 'Value': 10}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M3', 'Brand': 'B4', 'Value': 11}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M4', 'Brand': None, 'Value': 12}, {'Year': 2013, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M4', 'Brand': 'B5', 'Value': 13}, {'Year': 2014, 'Region': None, 'Country': None, 'Manufacturer': None, 'Brand': None, 'Value': 14}, {'Year': 2014, 'Region': 'LTM', 'Country': None, 'Manufacturer': None, 'Brand': None, 'Value': 15}, {'Year': 2014, 'Region': 'LTM', 'Country': 'Chile', 'Manufacturer': None, 'Brand': None, 'Value': 16}, {'Year': 2014, 'Region': 'LTM', 'Country': 'Chile', 'Manufacturer': 'M1', 'Brand': None, 'Value': 17}, {'Year': 2014, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer': 'M1', 'Brand': None, 'Value': 18}, {'Year': 2014, 'Region': 'LTM', 'Country': 'Colombia', 'Manufacturer'…

http://stackoverflow.com/q/50457421
type: Question
has title: get video resolution from ffpmeg
answer count: 0
tagged with: subprocess
duplicate of: http://stackoverflow.com/q/684015
has comment: http://stackoverflow.com/comment/87928560
tagged with: ffmpeg
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87929632
has body: I try to get resolution of a video file, and hope this code would help thanks to arionik from GitHub from subprocess import Popen, PIPE def getWH(pathvideofile): in_pipe = Popen(["ffmpeg", "-i", "\"%s\"" % (pathvideofile)], stderr=PIPE) lines = in_pipe.stderr.readlines() for line in lines: rx = re.compile('.+Video.+, (\d{2,4})x(\d{2,4}).+') m = rx.match(line) if m is not None: w = int(m.group(1)) h = int(m.group(2)) return w, h But get this error code: m = rx.match(line) TypeError: cannot use a string pattern on a bytes-like object What it could be? Thank you,
linked to: http://stackoverflow.com/q/31019854
score: 1
linked to: http://stackoverflow.com/q/684015
tagged with: python
tagged with: regex
favorite count: 0
duplicate of: http://stackoverflow.com/q/31019854

http://stackoverflow.com/a/50416900
type: AcceptedAnswer
has body: Oh thanks, it was easyer then I expected. import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure() i=0 im = plt.imshow(arr[0], animated=True) def updatefig(*args): global i if (i&lt;99): i += 1 else: i=0 im.set_array(arr[i]) return im, ani = animation.FuncAnimation(fig, updatefig, blit=True) plt.show()
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50413680
answers question: http://stackoverflow.com/q/50413680
type: Answer
upvote count: 6
score: 5

http://stackoverflow.com/q/50426349
tagged with: deep-learning
score: 1
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50426459
downvote count: 0
has answer: http://stackoverflow.com/a/50426459
tagged with: machine-learning
has body: I am building a deep colorization model using the CIFAR dataset. I have converted the rgb images into lab for the same. Now for that, the input X_train needs only the grayscale part of lab while the output labels are the coloured part. X_train dimensions = [50000,32,32] and Y_train = [50000,32,32,2]. I am getting this dimensional error for some reason while training the dataset. model = Sequential() model.add(Conv2D(64, (3, 3), activation='relu', padding='same',input_shape = (50000,32,32,1))) model.add(Conv2D(64, (3, 3), activation='relu', padding='same', strides=2)) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(Conv2D(256, (3, 3), activation='relu', padding='same')) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) #model.add(UpSampling2D((2, 2))) model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) #model.add(UpSampling2D((2, 2))) model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(Conv2D(2, (3, 3), activation='tanh', padding='same')) #model.add(UpSampling2D((2, 2))) model.compile(optimizer='rmsprop', loss='mse') model_info = model.fit(X_train, Y_train, batch_size=128, epochs=200)
upvote count: 1
tagged with: python
tagged with: keras
type: AnsweredQuestion
tagged with: conv-neural-network
has title: Input 0 is incompatible with layer conv2d_121: expected ndim=4, found ndim=5

http://stackoverflow.com/comment/87978167
comment on: http://stackoverflow.com/a/50480243
type: Comment
has text: in that case, you must send JSON response or HTML response saying file does not exist.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50510772
has comment: http://stackoverflow.com/comment/88033876
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50511077
upvote count: 0
has answer: http://stackoverflow.com/a/50511077
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88034043
tagged with: unicode
has comment: http://stackoverflow.com/comment/88037790
type: AnsweredQuestion
has title: Why '\xfc\xa9\xf1\xd2Mb\x80?' == 'ü©ñÒMb\x80?' is True in Python?
linked to: http://stackoverflow.com/q/50502883
has comment: http://stackoverflow.com/comment/88033796
has body: This was an comment from my previous question. but I was so confused, so ask it separatly. in Python 3: '\xfc\xa9\xf1\xd2Mb\x80?'=='ü©ñÒMb\x80?' Out[42]: True because the str in Python 3 is a sequence of unicode, I double checked them in Python 2.7 using u'\xfc\xa9\xf1\xd2Mb\x80?' == u'ü©ñÒMb\x80?' Out[29]: True so these two unicode are the same, but why? they look very different.
answer count: 1

http://stackoverflow.com/comment/88070004
has text: this is just an example where the error is caused by the variable r because its zero, but what if after incrementing r the exception might occur and needs to be incremented again then the divide function must be called
comment on: http://stackoverflow.com/a/50529045
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87879584
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50432645
has text: can you provide a dict that everyone can define without reworking it?

http://stackoverflow.com/comment/87933695
type: QuestionComment
has text: @Elisha it is Python3. See this question to prove it: https://stackoverflow.com/questions/21316968/division-in-python-2-7-and-3-3
score: 0
comment on: http://stackoverflow.com/q/50459313
type: Comment

http://stackoverflow.com/comment/87976657
has text: I modified my code as you said,but the mistake still exists.
score: 0
comment on: http://stackoverflow.com/a/50481706
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50495799
tagged with: tkinter
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0
has title: Trying to move an object and using Tkinter as a GUI, but it is not working when there is more than one instance of the class
has comment: http://stackoverflow.com/comment/88004790
has answer: http://stackoverflow.com/a/50496078
accepted answer: http://stackoverflow.com/a/50496078
has comment: http://stackoverflow.com/comment/88004630
type: Question
has body: Well, I never really worked in Python before this project. I am doing it because it's an assignment from a teacher (even tough we never had a Python class) and, of course, because learning a new language is always good. Anyways this code is working as intended until I add another instance of the AND class. When I add it in my code things are going crazy. I would appreciate if you would check how my code works with and without both test instances of the AND class. While we are at it I would really appreciate if one of you guys/girls could tell me how to make the AND button create a new instance of the class (for example in c++ I would use new AND, I want something similar when I press the button). EDIT: As someone pointed i was not clear enough. What i meant by things go crazy is that when i add more than 1 instance of the class the click and drag function i'm trying to do is not working properly anymore. The click and drag is not working anymore for one square and for the other one it will just follow my mouse whenever i go around it, even tought i'm not clicking. I really belive that this is because i have this int the init function : self.workspace.tag_bind(self.patrat,"&lt;Enter&gt;",self.whileInside) workspace.bind("&lt;ButtonRelease-1&gt;",self.onRelease) I think it doesn't belong there but i really have no ideea how to desing my code and where to put this, if that's the problem Here's my code so far: import tkinter as tk from tkinter import* def doNothing(): print("nothing happens bro") root = Tk() #========= Drop down menu/toolbar menu = Menu(root) root.config(menu=menu) subMenu = Menu(menu) menu.add_cascade(label="file", menu=subMenu) subMenu.add_command(label="New Project...",command=doNothing) subMenu.add_command(label="New",command=doNothing) subMenu.add_separator() subMenu.add_command(label="exit",command=doNothing) editMenu = Menu(menu) menu.add_cascade(label="edit", menu=editMenu) editMenu.add_command(label="redo", command=doNothing) #========Canvas wo…

variables
tags question: http://stackoverflow.com/q/50454861
tag name: variables
tags question: http://stackoverflow.com/q/50474696
tags question: http://stackoverflow.com/q/50530519
tags question: http://stackoverflow.com/q/50516591
tags question: http://stackoverflow.com/q/50421361
tags question: http://stackoverflow.com/q/50499646
tags question: http://stackoverflow.com/q/50402632
tags question: http://stackoverflow.com/q/50511612
tags question: http://stackoverflow.com/q/50488912
tags question: http://stackoverflow.com/q/50475094
type: Tag
tags question: http://stackoverflow.com/q/50387337
tags question: http://stackoverflow.com/q/50405907
tags question: http://stackoverflow.com/q/50492377

http://stackoverflow.com/q/50497999
answer count: 1
type: Question
tagged with: indexing
has body: I have a 1D array that contains some video data: data=np.random.randint(0,high=255,size=(500*500*100),dtype=np.uint8) imgs=np.reshape(data,(100, 500,500)) # 100 frames, 500x500 pixels I want to extract certain regions of interest (roi) along all the frames idx=np.random.randint(0,high=500*500,size=(49, 300)) #300 rois, 49 points each rois=imgs.reshape(100, -1)[:,idx] I flattened each frame and then took rois along 1st dimension. The real imgs array is larger than the shown here and the previous indexing operation can be a bit slow. If I reshape imgs in a different way (se below), rois.size is the same and the indexing is much faster, but this retrieves the wrong data %timeit imgs.reshape(100, -1)[:,idx] # 13 ms %timeit imgs.reshape(-1, 100)[idx, :] # 1.2 ms, much faster but wrong data In my real code the difference is almost 50x. Is there any way to index imgs fast?
has answer: http://stackoverflow.com/a/50498734
type: UnansweredQuestion
tagged with: python
has title: Fast way to extract ROIs in 3D numpy array
tagged with: numpy
score: 0
tagged with: arrays

http://stackoverflow.com/comment/88113790
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50535619
has text: What about counting the number of processed samples? I supposed you considered that option, why wouldn't it work for you?
score: 0

http://stackoverflow.com/a/50511720
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: ex = pd.to_datetime('Dec-2012') str(ex.year) + "-" + str(ex.month) and with a series series = pd.Series(["Dec-2012", "Nov-2013"]) series = pd.to_datetime(series) series.apply(lambda x: str(x.year) + "-" + str(x.month)) you can also use series.dt.to_period('M') Check the pandas docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html
answers question: http://stackoverflow.com/q/50511640
has comment: http://stackoverflow.com/comment/88037668

http://stackoverflow.com/a/50592434
accepted answer of: http://stackoverflow.com/q/50521481
type: Answer
answers question: http://stackoverflow.com/q/50521481
has body: Finally figured it out. Yes, adding the useLabels param was needed, but using the code I supplied above wasn't enough. For some reason JSON wouldn't accept it, I believe it needed a boolean to typecast into JSON not just a string that looks like a boolean. So I made a dictionary and loaded the params and used JSON.dumps() on the dictionary and it worked like a charm. Hope this helps anyone else wanting their data with the labels. useLabels = True dictionaryPayload = {'format': fileFormat, 'surveyId': surveyId, 'useLabels': useLabels} downloadRequestPayload = json.dumps(dictionaryPayload)
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87853623
type: Comment
comment on: http://stackoverflow.com/q/50398154
score: 1
type: QuestionComment
has text: I solved the problem, I forgave the labels the wrong way around... :D thx

http://stackoverflow.com/q/50506076
favorite count: 0
has comment: http://stackoverflow.com/comment/88028492
tagged with: inkscape
has comment: http://stackoverflow.com/comment/88028782
type: Question
has comment: http://stackoverflow.com/comment/88031499
has comment: http://stackoverflow.com/comment/88027662
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/88029672
has title: Is there an efficient way to store 2D plots as a vector graphic in python?
has comment: http://stackoverflow.com/comment/88028971
has body: I'm currently trying to store python plots as vector graphics to improve their appearance in a latex document. For 1D plots this works quite fine: import numpy as np import matplotlib as mpl mpl.use('svg') new_rc_params = { "font.family": 'Times', "font.size": 12, "font.serif": [], "svg.fonttype": 'none'} #to store text as text, not as path mpl.rcParams.update(new_rc_params) import matplotlib.pyplot as plt x = np.linspace(-.5, .5, 1024) plt.figure() plt.plot(x, x) plt.title('\$x = y\$') plt.xlabel('\$x\$ [m]') plt.ylabel('\$y\$ [m]') plt.savefig('test.svg', format = 'svg', bbox_inches = 'tight') This way I can open the svg file in inkscape and convert it to pdf/pdf_tex and every text in the plot will be rendered in latex within the document --> same font and fontsize as everywhere else in the document. 2D plot get increadibly large as svg files. Therefore I want to store the plot as a pdf (again, I want to keep text as text. That's why I can't store the plot as .png): mpl.use('pdf') new_rc_params = { "font.family": 'Times', "font.size": 12, "font.serif": [] } #"svg.fonttype": 'none'} #not needed here since we don't use svg anymore mpl.rcParams.update(new_rc_params) import matplotlib.pyplot as plt x = np.linspace(-.5, .5, 1024) x, y = np.meshgrid(x, x) z = np.exp(-(x**2 + y**2)) plt.figure() plt.title('Gaussian plot: \$z = \exp{-(x^2 + y^2)}\$') plt.pcolormesh(x, y, z) plt.colorbar() plt.savefig('test.pdf', bbox_inches='tight', format='pdf') This stores the 2D plot as a pdf. Anyway, storing the plot takes a while now and it gets quite large (even with only 500 x 500 points in the plot it's about 11 MB). But, the text is stored as text. Unfortunately I can't open the pdf in inkscape now, for it always crashes after a while. Probably the file is already to large. Any suggestions? Further downsampling might work in this case, but probably not in general.
has comment: http://stackoverflow.com/comment/88027505
has comment: http://stackoverflow.com/comment/88029022
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50511521
tagged with: vector-graphics
has answer: http://stackoverflow.com/a/50511521

http://stackoverflow.com/q/50512444
answer count: 1
downvote count: 0
score: 1
upvote count: 1
tagged with: keras
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/53817647
has answer: http://stackoverflow.com/a/53817647
has title: Shape error when using CRF for binary segmentation in keras
tagged with: keras-layer
type: Question
tagged with: python
has body: I am trying to apply a CRF layer to my network for binary segmentation, but it is resulting in an error ValueError: Shapes (?, 1, 1) and (?, 336, 1) are not compatible. I want to output a tensor with the shape (batch_size, 224, 336, 1). Based on the error, the img_height appears to have been lost once the CRF was introduced. Below is some sample code describing the model. Without the CRF at the end it works well. import keras from keras.layers import UpSampling2D, Conv2D, Activation, MaxPooling2D from keras_contrib.layers import CRF img_width, img_height = 336, 224 kernel_size = 7 input=keras.engine.topology.Input(shape=(img_height, img_width, 3)) e=Conv2D(32,(kernel_size,kernel_size),padding='same')(input) e1=Activation('relu')(e) e=MaxPooling2D(pool_size=(2, 2))(e1) e=Conv2D(64,(kernel_size,kernel_size),padding='same')(e) e2=Activation('relu')(e) e=MaxPooling2D(pool_size=(2, 2))(e2) #Decoder layers d=UpSampling2D()(e) d=Conv2D(64,(kernel_size,kernel_size),padding='same')(d) d=Activation('relu')(d) d=UpSampling2D()(d) d=Conv2D(32,(kernel_size,kernel_size),padding='same')(d) d=Activation('relu')(d) d=Conv2D(1,(1,1),padding='valid')(d) d=Activation('sigmoid')(d) out=CRF(1, sparse_target=True)(d) autoencoder = Model(inputs=input, outputs=out) What is the correct way to add the CRF to my segmentation network?
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/50527747
answer count: 1
tagged with: web3py
tagged with: python-3.x
has body: I am able to use the web3.py library and I am able to deploy the contract directly using my node in Ethereum. I created my solidity code in remix and copied the ABI in the Ethereum console to deploy the code. I got the address of the contract as well. My solidity code is as follows. pragma solidity ^0.4.0; contract bidding { struct bid { string bidderName; uint grainId; uint bidAmount; uint bidTime; } mapping (uint => bid) bidInfos; uint[] public bidIds; function addBid( uint _bidId, string _bidderName, uint _grainId, uint _bidAmount ) public { var bid_info = bidInfos[_bidId]; bid_info.bidderName = _bidderName; bid_info.grainId = _grainId; bid_info.bidAmount=_bidAmount; bid_info.bidTime= now; bidIds.push(_bidId) -1; } function getallBids() view public returns(uint[]) { return bidIds; } function getBid(uint _bidId) view public returns (string, uint, uint, uint) { return ( bidInfos[_bidId].bidderName, bidInfos[_bidId].grainId, bidInfos[_bidId].bidAmount, bidInfos[_bidId].bidTime ); } function getbidcount() view public returns (uint) { return bidIds.length; } } I deployed in my Ethereum network and got the address as I am using the web3py library. from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider import json web3 = Web3(IPCProvider()) bid_abi=json.loads('''[{"constant":false,"inputs":[{"name":"_bidId","type":"uint256"},{"name":"_bidderName","type":"string"},{"name":"_grainId","type":"uint256"},{"name":"_bidAmount","type":"uint256"}],"name":"addBid","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getallBids","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_bidId","type":"uint256"}],"name":"getBid","outputs":[{"name":"","type":"string"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":tru…
type: Question
has title: Ethereum Blockchain trying to send transaction using web3.py
tagged with: go-ethereum
has comment: http://stackoverflow.com/comment/88067292
has answer: http://stackoverflow.com/a/51572357
tagged with: python
type: UnansweredQuestion
tagged with: ethereum
score: 0

http://stackoverflow.com/q/50477220
tagged with: multi-index
has title: Join on MultiIndex with different number of levels in pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50477334
score: 5
downvote count: 0
possible better answer: http://stackoverflow.com/a/50477261
has body: How can one join 2 pandas DataFrames on MultiIndex with different number of levels? import pandas as pd t1 = pd.DataFrame(data={'a1':[0,0,1,1,2,2], 'a2':[0,1,0,1,0,1], 'x':[1.,2.,3.,4.,5.,6.]}) t1.set_index(['a1','a2'], inplace=True) t1.sort_index(inplace=True) t2 = pd.DataFrame(data={'b1':[0,1,2], 'y':[20.,40.,60.]}) t2.set_index(['b1'], inplace=True) t2.sort_index(inplace=True) &gt;&gt;&gt; t1 x a1 a2 0 0 1.0 1 2.0 1 0 3.0 1 4.0 2 0 5.0 1 6.0 &gt;&gt;&gt; t2 y b1 0 20.0 1 40.0 2 60.0 Expected result for joining on 'a1' => 'b1': x y a1 a2 0 0 1.0 20.0 1 2.0 20.0 1 0 3.0 40.0 1 4.0 40.0 2 0 5.0 60.0 1 6.0 60.0 Another example: joining on ['a1','a2'] => ['b1','b2']: import pandas as pd, numpy as np t1 = pd.DataFrame(data={'a1':[0,0,0,0,1,1,1,1,2,2,2,2], 'a2':[3,3,4,4,3,3,4,4,3,3,4,4], 'a3':[7,8,7,8,7,8,7,8,7,8,7,8], 'x':[1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.]}) t1.set_index(['a1','a2','a3'], inplace=True) t1.sort_index(inplace=True) t2 = pd.DataFrame(data={'b1':[0,0,1,1,2,2], 'b2':[3,4,3,4,3,4], 'y':[10.,20.,30.,40.,50.,60.]}) t2.set_index(['b1','b2'], inplace=True) t2.sort_index(inplace=True) &gt;&gt;&gt; t1 x a1 a2 a3 0 3 7 1.0 8 2.0 4 7 3.0 8 4.0 1 3 7 5.0 8 6.0 4 7 7.0 8 8.0 2 3 7 9.0 8 10.0 4 7 11.0 8 12.0 &gt;&gt;&gt; t2 y b1 b2 0 3 10.0 4 20.0 1 3 30.0 4 40.0 2 3 50.0 4 60.0 Expected result for joining on ['a1','a2'] => ['b1','b2']: x y a1 a2 a3 0 3 7 1.0 10.0 8 2.0 10.0 4 7 3.0 20.0 8 4.0 20.0 1 3 7 5.0 30.0 8 6.0 30.0 4 7 7.0 40.0 8 8.0 40.0 2 3 7 9.0 50.0 8 10.0 50.0 4 7 11.0 60.0 8 12.0 60.0 The solution should work joining on multiple index levels. Thank you for your help!
has answer: http://stackoverflow.com/a/50477373
has answer: http://stackoverflow.com/a/50477261
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50492504
accepted answer: http://stackoverflow.com/a/56192812
tagged with: pandas
answer count: 5
tagged with: join
upvote count: 5
has answer: http://stackoverflow.com/a/56192812
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/50532929
has body: how to calculate the sum of the values ​​(1) and the sum of the values ​​(0) contained in each date? or how to calculate the sum of the values ​​(1) divided by the sum of the values ​​(0) in each date. sentiment_value = log10(count_of_(1)/count_of_(0)), this is the formula I am using for. date new_sentiment 0 2017-04-28 1.0 1 2017-04-28 1.0 2 2017-04-28 1.0 3 2017-04-27 0.0 4 2017-04-27 1.0 5 2017-04-26 0.0 6 2017-04-26 1.0 7 2017-04-26 1.0 8 2017-04-26 0.0 9 2017-04-26 1.0 result_neg = date_df.appl
has comment: http://stackoverflow.com/comment/88077776
accepted answer: http://stackoverflow.com/a/50533190
type: Question
has answer: http://stackoverflow.com/a/50533190
has title: Get count or sum of values in dataframe of each day
answer count: 1
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: sentiment-analysis
tagged with: pandas

http://stackoverflow.com/q/50496994
accepted answer: http://stackoverflow.com/a/50497175
has body: I am trying to split the contents of a cell from an excel spreadsheet, being new to Python, I can't quite figure out the syntax for it. I am using the xlrd and xlwt libraries. So far I can get the correct columns I need and would like to split out the contents of the cell pvalue similar to the excel function text to columns, is this a practical thing to do in python? Everything I can find on line, already has data neatly formatted with all data points in a seperate column, I was wondering if I could get a point in the right direction. Here is the code I have so far import xlrd import xlwt # open and create workbook workbook = xlrd.open_workbook('myexcelfile.xlsx') workbookwrite = xlwt.Workbook('output.xlsx') # open and create sheets worksheet = workbook.sheet_by_index(0) sheet = workbookwrite.add_sheet('Sheet1') i = 1 # iterate through rows in worksheet, get columns completed_at and name for rows in range(worksheet.nrows): cell1 = worksheet.cell(rows, 3).value cell2 = worksheet.cell(rows, 15).value row = sheet.row(i) # if a completed_at date is empty, don't write data to new workbook if cell1 != '': value = cell2 pvalue = cell2.split(',') row.write(0, cell1) row.write(1, pvalue) i += 1 workbookwrite.save('output.xls') If I could get direction on a different library to use, if there is a better one out there that would be great. Thanks
type: AnsweredQuestion
score: 0
has title: I am trying to split contents of an excel spreadsheet cell
has comment: http://stackoverflow.com/comment/88006988
answer count: 1
has comment: http://stackoverflow.com/comment/88006865
has comment: http://stackoverflow.com/comment/88007088
type: Question
has answer: http://stackoverflow.com/a/50497175
tagged with: python
tagged with: excel

http://stackoverflow.com/a/50489822
upvote count: 3
downvote count: 0
type: Answer
has body: In case anyone is having a similar issue, here is the solution that worked for me: import logging logger = logging.getLogger() logger.setLevel(logging.CRITICAL)
score: 3
answers question: http://stackoverflow.com/q/50488803

http://stackoverflow.com/comment/87871422
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50428318
score: 0
has text: So what's the question? Are there errors? Then please include the full exception of the error. Please include sample input that reproduces the problem. It runs but nothing appears to change? Then give us sample input and the output it produces, as well as the output you expected it to produce instead.

http://stackoverflow.com/comment/88028582
type: Comment
comment on: http://stackoverflow.com/a/50502699
score: 0
type: AnswerComment
has text: I updated variable names to be a little more specific, but do you mean something like that?

http://stackoverflow.com/comment/87808482
score: 0
type: QuestionComment
has text: Maybe `(?i)^[a-z]+_|_[a-z]+_`?
comment on: http://stackoverflow.com/q/50396347
type: Comment

http://stackoverflow.com/q/50445409
downvote count: 1
favorite count: 0
type: Question
has body: def cipherText(): text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = int(input("Enter numerical key--")) word = str(input("Type word to be ciphered--")) i = 0 k = 0 n = len(word) print(n) while n &gt;= 0: letter = word[i] i = i + 1 while k &lt;= 25: textLetter = text[k] if textLetter == letter: givenLetter = letter if k &lt; (25 - key): cipherLength = k + key else: cipherLength = k + key - 25 print(text[cipherLength]) k = k + 1 n = n - 1 cipherText() WHEN I RUN THIS FOLLOWING MESSAGE POPS OUT: Traceback (most recent call last): File "main.py", line 23, in cipherText() File "main.py", line 10, in cipherText letter=word[i] IndexError: string index out of range
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87905034
has answer: http://stackoverflow.com/a/50445471
tagged with: python
has title: my string index is out of range in this cipher code
score: 0
has comment: http://stackoverflow.com/comment/87904635
answer count: 1
upvote count: 1

http://stackoverflow.com/a/50422257
downvote count: 0
upvote count: 1
has body: As answered by kvmahesh, the return type of input() is always str. You need to convert it to int if you want numbers. while True: user_input = input("Enter number or quit: ") if user_input == "quit": break try: final_input.append(int(user_input)) except ValueError: print("Invalid input!") A try...except block is good to check if user gives some invalid input (e.g. asdfg). Also, if you just want to sort the list, you can use sorted(): final_input = sorted(final_input)
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50422101
answers question: http://stackoverflow.com/q/50422101
type: AcceptedAnswer

http://stackoverflow.com/comment/87805004
type: AnswerComment
comment on: http://stackoverflow.com/a/50394568
score: 0
type: Comment
has text: Nice solution Aaron!

http://stackoverflow.com/a/50430574
type: Answer
has body: You don't need to put the code into the __getitem__ method. You can use the __missing__ method: &gt;&gt;&gt; class MyDict(dict): def __missing__(self, index): return 0 &gt;&gt;&gt; md = MyDict({(0,0): 1, (1,1): 5, (1,2): 3, (2,2): 1}) &gt;&gt;&gt; md[0,0] 1 &gt;&gt;&gt; md[1,2] 3 &gt;&gt;&gt; md[2, 1] 0 &gt;&gt;&gt;
upvote count: 4
has comment: http://stackoverflow.com/comment/87879309
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/50430470

http://stackoverflow.com/q/50489943
answer count: 1
has answer: http://stackoverflow.com/a/50505675
tagged with: flask
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
type: Question
has body: I have query in sqlserver and I wanted to write a model corresponding to it using sqlalchemy orm. I need to know how to convert ON [PRIMARY] into sqlalchemy. Here is my query: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[UserModel]( [userid] [nvarchar](255) NULL, [username] [nvarchar](255) NULL, [serialnumber] [nvarchar](255) NULL ) ON [PRIMARY] GO Here is my model: class UserModel(db.Model): __tablename__ = 'UserModel' userid = Column('userid', Unicode(255)) username = Column('username', Unicode(255)) serialnumber = Column('serialnumber', Unicode(255)) Any suggestions, how would I achieve this Currently I m getting the following error as below: sqlalchemy.exc.ArgumentError: Mapper Mapper|UserModel|UserModel could not assemble any primary key columns for mapped table 'UserModel' I know there there is no primary primary key defined in my model but the above query is working fine. So I wanted to translate the above query using sqlalchemy orm.
tagged with: python
score: 0
linked to: http://stackoverflow.com/q/2798213
has title: How to Convert SqlServer ON [PRIMARY] into Sqlalchemy Model?
type: UnansweredQuestion

http://stackoverflow.com/q/50492241
has comment: http://stackoverflow.com/comment/87997533
has comment: http://stackoverflow.com/comment/87997469
tagged with: django
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50492410
type: AnsweredQuestion
tagged with: github-api
has comment: http://stackoverflow.com/comment/87997680
has body: I'm working on a project using Python(3.6) in which I need to implement GitHub API. I have tried by using JSON apis as: from views.py: class GhNavigator(CreateView): def get(self, request, *args, **kwargs): term = request.GET.get('search_term') username = 'arycloud' token = 'API_TOKEN' login = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token)) print(login) return render(request, 'navigator/template.html', {'login': login}) but it simply returns status 200, I want to get a list of repositories for term which is passed by the user. How can I achieve that? Help me, please! Thanks in advance!
has title: Implement Github API in Python
has comment: http://stackoverflow.com/comment/87997721
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50492410
has comment: http://stackoverflow.com/comment/87997444
tagged with: python-requests
has comment: http://stackoverflow.com/comment/87997403
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/q/50539257
has answer: http://stackoverflow.com/a/50539328
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has title: how can I save more than one data in a single out put file separately using numpy
linked to: http://stackoverflow.com/q/47104306
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88090543
tagged with: numpy
has body: How can I save more than one data consecutively in a single output file using numpy? For example, the out put file should contain Matrix A "and below that some text and the another" matrix B
downvote count: 2

http://stackoverflow.com/comment/87875467
has text: The thing is, I doubt there is a library that could take a list of some class `Product` and "know" that it has two members that need to be printed (`name` and `price`) and so you will already have to go through your list and create a new list of names and prices before you can pass them to a library. While you create a list of names you can easily compute longest name while you build the list or do it in a separate pass. I do not see the point of a library here or what would be the benefit here.
comment on: http://stackoverflow.com/q/50430337
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50437484
tagged with: python
has title: SyntaxError on input() supposedly in Python 3
has comment: http://stackoverflow.com/comment/87888892
has comment: http://stackoverflow.com/comment/87888930
linked to: http://stackoverflow.com/q/4915361
linked to: http://stackoverflow.com/q/21122540
has body: I have a script for sending emails using SMTP_SSL. The code is working fine in PyCharm but in the terminal I get an error. This is the code: import smtplib s = smtplib.SMTP_SSL("smtp.googlemail.com:465") mml=input("enter your email address :\n") str(mml) passr=input("enter your pass:\n") str(passr) s.login(mml,passr) em = input("please type the email you want to send :\n") str(em) a = input("please type the message:\n") str(a) s.sendmail(mml,em,a) print("\nEmail Was Sent..:)") When I run this in my terminal its giving this after i enter the email: enter your email address : mahmoud.wizzo@gmail.com Traceback (most recent call last): File "medo.py", line 3, in &lt;module&gt; mml=input("enter your email address :\n") File "&lt;string&gt;", line 1 mahmoud.wizzo@gmail.com ^ SyntaxError: invalid syntax When I am trying to put the email between quotes, e.g. "mahmoud.wizzo@gmail.com" its working fine. How can I run my script in the terminal?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87889073
answer count: 2
possible better answer: http://stackoverflow.com/a/50437606
duplicate of: http://stackoverflow.com/q/21122540
has comment: http://stackoverflow.com/comment/87889013
has answer: http://stackoverflow.com/a/50437606
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50437562
tagged with: linux
has comment: http://stackoverflow.com/comment/87889121
has answer: http://stackoverflow.com/a/50437562

http://stackoverflow.com/q/50477410
type: Question
tagged with: glob
has answer: http://stackoverflow.com/a/50477740
tagged with: python
type: UnansweredQuestion
tagged with: regex
answer count: 1
score: 0
has body: I am trying to use glob.glob() to get a list of files that comes from different directories with two kinds of suffix. For example, the files i am going to read are /ABC/DEF/HIJ/*.{data,index} and /ABC/LMN/HIJ[0-3]/*.{data,index} I was asked to do it with only a single glob.glob() call. How can I do it? Thanks.
has title: python glob.glob() regex multi files in different dir

http://stackoverflow.com/a/50516230
downvote count: 0
has body: Here, not bear_moved means bear_moved is False. Quoting the python doc: The operator not yields True if its argument is false, False otherwise.
upvote count: 1
has comment: http://stackoverflow.com/comment/88047626
has comment: http://stackoverflow.com/comment/88051205
type: Answer
accepted answer of: http://stackoverflow.com/q/50516148
score: 1
answers question: http://stackoverflow.com/q/50516148
type: AcceptedAnswer

http://stackoverflow.com/q/50516350
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88045323
has comment: http://stackoverflow.com/comment/88046822
has comment: http://stackoverflow.com/comment/88045235
type: Question
has comment: http://stackoverflow.com/comment/88046568
tagged with: package
has comment: http://stackoverflow.com/comment/88045415
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88045281
has body: I want to add this package to my project https://django-el-pagination.readthedocs.io/en/latest/start.html. The documentation tells me to place the distribution on the PYTHONPATH. What do they mean and how am I supposed to do that?
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88045189
has title: How to place a package on the PYTHONPATH?

http://stackoverflow.com/comment/87996184
score: 0
has text: @TomDalton added chmod for /home/wger as well. however, now it says forbidden !
comment on: http://stackoverflow.com/q/50491192
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50457828
has comment: http://stackoverflow.com/comment/87929305
possible better answer: http://stackoverflow.com/a/50501123
accepted answer: http://stackoverflow.com/a/50472071
type: Question
has comment: http://stackoverflow.com/comment/87929344
has answer: http://stackoverflow.com/a/50501123
has answer: http://stackoverflow.com/a/50472071
tagged with: python
has title: Scrolling to an element in Selenium
has comment: http://stackoverflow.com/comment/87953244
type: AnsweredQuestion
score: 0
answer count: 2
has body: I am using selenium to scrape a dynamic website. My problem is that I can't scroll down to the items I am looking for. First, I made a list of those items I want to get information from (python_button1). I have to click on each item in this list to see a new window, in which I want to scrape them. Then I made a loop to click on those items. After that, I close the window I opened. Unfortunately, I can't scroll down to each item to click them. I used the following code but it scrolls down to the last item and skips other items. I would really appreciate if you can help me. Thanks! python_button1 = driver.find_elements_by_class_name('simboloEvento') for x in python_button1: x.click() time.sleep(2) driver.find_element_by_class_name('cerrarBoton').click() driver.execute_script("coordinates=arguments[0]. getBoundingClientRect();scrollTo( coordinates.x,coordinates.y);", x) time.sleep(2) innerHTML = driver.execute_script("return document.body.innerHTML") print(innerHTML) the scroll down list is a JavaScript Object. I have to click on each of those objects to activate the javascript function ( a new window). I can activate those objects via my code, but the problem is when at least one of those items are not in the current screen. That's why I should scroll down to that object ( here x) first to be able to click on it. But I don't know how to scroll down to that object. I have used the code I used in this post as well as this one : driver.execute_script("arguments[0].scrollIntoView();", x) but none of them worked for me!
tagged with: selenium

http://stackoverflow.com/comment/87883349
has text: Right. You can certainly derive a 512 bit key, then split it up into two 256 bit halves. How much security there is depends of course on the input. But even if that is 256 bits of security then the two keys should still be at around 256 bits of security, i.e. no decrease from what you already had... Feeling unclear around encryption - or at least feeling defensive - around encryption is exactly what is required. You need to be slightly paranoid, otherwise you'll stumble into problems. Doing a course like Cryptography I from Dan Boneh is a good idea though :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50428759
type: Comment

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/50454584
tags question: http://stackoverflow.com/q/50520232
tags question: http://stackoverflow.com/q/50401685
tags question: http://stackoverflow.com/q/50406898
tags question: http://stackoverflow.com/q/50442068
tags question: http://stackoverflow.com/q/50438869
tags question: http://stackoverflow.com/q/50505191
type: Tag
tags question: http://stackoverflow.com/q/50537452
tags question: http://stackoverflow.com/q/50501005
tags question: http://stackoverflow.com/q/50440664

http://stackoverflow.com/comment/110714160
comment on: http://stackoverflow.com/a/56779598
score: 0
type: Comment
has text: Because maybe you are in a virtual environment so the path of python executable is different than that you actually want to use.
type: AnswerComment

http://stackoverflow.com/q/50463113
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/28836048
score: 8
type: Question
upvote count: 9
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/50463436
has title: Multiple size font in suptitle
has answer: http://stackoverflow.com/a/50463436
type: AnsweredQuestion
has body: I would like to have multiple title in my graph. A picture is better than anyword : I use a title for every graph (D2/E, D3/E and D4/E) and a suptitle for title 1 and 2 but they have the same font size. Is there a solution to have different size for Title 1 and Title 2 ? I've already seen this solution using LaTeX but the thing is when I use plt.rc('text', usetex=True) every font and text are changed. Moreover, I use variable in each title and it looks like I can't do it with LaTeX.
answer count: 1

http://stackoverflow.com/q/50441904
has answer: http://stackoverflow.com/a/50441960
tagged with: web-crawler
tagged with: html-parsing
tagged with: http
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has body: I want to print out the web links of news articles containing a specific keyword (say, "Tesla"). So, I search the word "tesla" in Google news home page, and I wrote the following code to search for the articles with the word "Tesla" in it (which should be all the articles, as its searching for the word in a collection of articles that contain the word for sure): import httplib2 from bs4 import BeautifulSoup, SoupStrainer http = httplib2.Http() status, response = http.request('https://news.google.com/search?q=tesla&amp;hl=en-US&amp;gl=US&amp;ceid=US%3Aen') words_to_search = ['tesla'] for link in BeautifulSoup(response, "lxml", parse_only=SoupStrainer('a')): if 'href' in link: for word in words_to_search: if word in link['href']: print(link['href']) But I get no output (or empty output). Why is the code not able to find articles with the specified word? And how do I fix it?
has title: Python program to print out web links containing specific words does not output anything
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/87897886
answer count: 1

http://stackoverflow.com/a/53237541
has body: The add_fieldsets class variable is used to define the fields that will be displayed on the create user page. Unfortunately it's not well documented, and the closest thing I found to documentation was a comment in the code example on https://docs.djangoproject.com/en/2.1/topics/auth/customizing/ (search page for add_fieldsets). The classes key sets any custom CSS classes we want to apply to the form section. The fields key sets the fields you wish to display in your form. In your example, the create page will allow you to set an email, password1 and password2.
downvote count: 0
score: 23
answers question: http://stackoverflow.com/q/50436596
has comment: http://stackoverflow.com/comment/95311104
type: Answer
upvote count: 23

http://stackoverflow.com/comment/88076056
type: AnswerComment
has text: Add the `from __future__ ...` and it will make the program py2 and py3 compatible. How to make `pycharm` use `python3` is not something I can help - I don't use `pycharm` - but I'm sure a quick google will help you.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50521633

http://stackoverflow.com/comment/87853117
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50418785
score: 1
has text: None of these classes is a metaclass.

http://stackoverflow.com/comment/87862640
comment on: http://stackoverflow.com/q/50423502
type: Comment
has text: Can you post a small sample of the dataframe?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87872599
type: AnswerComment
has text: Here's the full error. https://pastebin.com/qjb9Pnrm It seems I already have python installed there. But I thought Homebrew installs things in a seperate location?
comment on: http://stackoverflow.com/a/50428732
type: Comment
score: 0

http://stackoverflow.com/q/50421623
has body: The aim of this code is to make the button create a label, where it would add or subtract the number provided and display it depending on whether the first attribute for "release_button()" is "add" or "sub". So as an example to explain it better: (lets say "price_release(game_id)" = 19.99) price_overall_release = price_overall_release + price_releases[game_id] "price_overall_release" is equal to 0 at the start. When the button is pressed, it will add "price_release(game_id)" to the 0 and then replace "price_overall_release" with itself. (press once: 0 = 0 + 19.99, press twice: 19.99 = 19.99 + 19.99) For some reason though, it doesn't like that, and it will spit out this error instead: price_overall_release = price_overall_release + price_releases[game_id] NameError: name 'price_overall_release' is not defined I am not sure what the problem is. It doesn't make much sense to me since from what I can tell, it HAS been defined. price_overall_release = 0 # A definition for adding and subtracting to the price at the bottom. def release_button(add_or_sub, game_id): global price_overall_release if add_or_sub == "add": price_releases[game_id] = float(price_releases[game_id]) price_overall_release = price_overall_release + price_releases[game_id] price_releases[game_id] = str(price_releases[game_id]) # Declare and show. price_overall_release = str(price_overall_release) label_overallprice_releases = Label(new_release_window, text="$"+price_overall_release, bg = releases_price_colour, fg = "black", relief = "sunken", borderwidth = 1, font = gui_font_10) amount_ordered_release = Label(new_release_window, text = amount_release, bg = releases_price_colour, fg = "black", borderwidth = 1, font = gui_font_10) label_overallprice_releases.grid(row = 12, column = 3, padx = 7.5, pady = space_between) # + price_overall_release = float(price_overall_release) return price_overall_release else: price_releases[game_id] = float(price_releases[game_id]) price_overall_release = price_overall_re…
type: UnansweredQuestion
has title: Python 3 Tkinter - NameError: name 'price_overall_release' is not defined?
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87858884
downvote count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/87875974
has comment: http://stackoverflow.com/comment/87858823
type: Question
tagged with: python-3.x
answer count: 0

http://stackoverflow.com/q/50510642
has answer: http://stackoverflow.com/a/50549141
answer count: 2
tagged with: python
tagged with: sorting
has body: I need help in properly indexing my dataframe from the web. I'm using the pandas module df1 = pd.read_csv('https://raw.githubusercontent.com/bonsalakot00/Test-Server/master/Data_2012.csv') This is one of my codes for accessing my data repository and reading it as a dataframe frames = [df1, df2, df3, df4, df5, df6] result = df1.append(frames, sort=False) print(result) And this is the code where I'm trying to automatically sort my dataframe from [1 to 258], I tried doing result=pd.concat([df1],[df2],[df3],[df4],[df5],[df6],[df7], axis=1, join='inner').sort_index() to sort the numbers properly but it ends up doubling each count. This is the image of what I'm trying to describe
has title: How do I index a merged CSV file from the web
tagged with: indexing
has comment: http://stackoverflow.com/comment/88033789
type: Question
tagged with: pandas
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88034173
possible better answer: http://stackoverflow.com/a/50515128
has answer: http://stackoverflow.com/a/50515128
has comment: http://stackoverflow.com/comment/88033836
tagged with: preprocessor
has comment: http://stackoverflow.com/comment/88033653
accepted answer: http://stackoverflow.com/a/50549141

http://stackoverflow.com/a/50404125
has body: I think this may works for you: import cv2 import numpy as np import math # mouse callback function def draw_circle(event, x, y, flags, param): global x1, y1, radius, num if event == cv2.EVENT_LBUTTONDOWN: x1, y1 = x, y if event == cv2.EVENT_LBUTTONUP: num += 1 radius = int(math.hypot(x - x1, y - y1)) cv2.circle(img, (x1,y1), radius, (255, 0,), 1) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, f'label: {num}', (x + 30, y + 30), font, 1, (200, 255, 155), 1, cv2.LINE_AA) if __name__ == "__main__": num = 0 # Create a black image and a window windowName = 'Drawing' img = cv2.imread('img.jpg', cv2.IMREAD_COLOR) cv2.namedWindow(windowName) # bind the callback function to window cv2.setMouseCallback(windowName, draw_circle) while (True): cv2.imshow(windowName, img) if cv2.waitKey(20) == 27: break cv2.destroyAllWindows() Result: This is a simple code and you can do a lot of things with mouse events.
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50403176
downvote count: 0

http://stackoverflow.com/q/50426736
tagged with: python
has answer: http://stackoverflow.com/a/50427417
type: AnsweredQuestion
downvote count: 0
tagged with: django-queryset
answer count: 1
score: 6
tagged with: django
accepted answer: http://stackoverflow.com/a/50427417
tagged with: django-filter
has body: I have a model similar to class House: x = IntegerField() y = IntegerField() I want to return the houses that are at a smaller distance that distance from some position using the following calculation: abs(house.x - myPos.x) + abs(house.y - myPos.y) &lt; distance But I don't know how to make that filter since filter() only compares with a model's field. I would like to do something like: House.objects.filter(abs(x - myPos.x) + abs(y - myPos.y) &lt; distance)
favorite count: 0
type: Question
has title: How filter queryset with a calculation?
upvote count: 6

http://stackoverflow.com/comment/87983946
comment on: http://stackoverflow.com/q/50471654
score: 0
type: Comment
type: QuestionComment
has text: `soup = BeautifulSoup(open(os.getcwd()+"/Desktop/Pneus auto _ Michelin FR.html", encoding='utf-8'), 'lxml')` **this works for me**

http://stackoverflow.com/a/50514607
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/88082769
has comment: http://stackoverflow.com/comment/126933198
answers question: http://stackoverflow.com/q/50510569
has body: You will need to create a separate bind parameter for each item in the list, and then pass the list of ids into read_sql(): idlist = ['123456548','546465464'] in_vars = ','.join(':%d' % i for i in range(len(idlist))) query = """ select PEBEMPL_ECLS_CODE from PEBEMPL inner join SPRIDEN on spriden_pidm = pebempl_pidm where SPRIDEN_CHANGE_IND is null and SPRIDEN_ID in (%s) """ % in_vars df = pd.read_sql(query, connection, params=idlist) To avoid any confusion, the above example talks to Oracle using Pandas read_sql() function. For people working with a cursor object directly, then the syntax is: cursor.execute(query, params)
has comment: http://stackoverflow.com/comment/88082439
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50510569
score: 8

http://stackoverflow.com/a/50394239
type: Answer
has comment: http://stackoverflow.com/comment/87804347
has comment: http://stackoverflow.com/comment/87804327
has body: You can do something like this: while True: x = input("Input a 3 digit number: ") if x.isdigit() and 100 &lt;= int(x) &lt;= 999: break isdigit() checks whether the string consists of digits only (won't work for floats). Since Python uses short-circuiting to evaluate boolean expressions using the operator and, the second expression 100 &lt;= int(x) &lt;= 999 will not be evaluated unless the first (x.isdigit()) is true, so this will not throw an error when a string is provided. If isdigit() evaluates to False, the second expression won't be evaluated anyway. Another option is the following: condition = True while condition: x = input("Input a 3 digit number: ") condition = not (x.isdigit() and 100 &lt;= int(x) &lt;= 999)
has comment: http://stackoverflow.com/comment/87804667
downvote count: 0
has comment: http://stackoverflow.com/comment/87862400
score: 5
answers question: http://stackoverflow.com/q/50394119
has comment: http://stackoverflow.com/comment/87804916
upvote count: 5

http://stackoverflow.com/a/50419396
downvote count: 0
upvote count: 1
has body: You should look into multiprocessing. May not be what it was intended to do, but it should be possible to kill off outside of the code thread. https://docs.python.org/3/library/multiprocessing.html
answers question: http://stackoverflow.com/q/50419057
type: Answer
score: 1

http://stackoverflow.com/q/50460894
tagged with: python
has answer: http://stackoverflow.com/a/50460995
possible better answer: http://stackoverflow.com/a/50460995
tagged with: tornado
type: Question
answer count: 2
has body: I've been looking on how to get the Authorization Header from a Tornado GET/POST Request, but there's none. Anyone can help on this? The reason is that I want to implement JWT in my Python application. For example, this tornado API just creates a GET request: class HeaderHandler(tornado.web.RequestHandler): def get(self): headers = tornado.httputil.HTTPHeaders() response = { 'message': str(headers) } self.write(response) I want to access this API via http://localhost:{port} and I will add a header which is Authentication: Bearer {token} But this code doesn't work. It cannot fetch the authorization header passed to the request. Any help is appreciated. Thanks!
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/54948634
favorite count: 0
accepted answer: http://stackoverflow.com/a/54948634
has title: How to get the request's Authentication Header in Tornado
tagged with: jwt
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/50452967
answers question: http://stackoverflow.com/q/50452855
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: You can try with apply df Out[115]: index 0 0 SKDJF SSDILFJKSIDHFKJSHDKUFH 1 FDKSJFSSDF SLIDFSOIUDHFIUSDHF 2 SIDFDS K&lt;NFSKJGHSDUFSDK df.apply(lambda x : x[0][len(x['index'])],axis=1) Out[116]: 0 F 1 H 2 J dtype: object Or just using python [y[len(x)]for x,y in zip(df['index'],df[0])] Out[117]: ['F', 'H', 'J']

http://stackoverflow.com/comment/87956945
score: 2
has text: Well, that string doesn't contain French accented characters. It contains [garbage](https://en.wikipedia.org/wiki/Mojibake). How did that string get like this in the first place?
comment on: http://stackoverflow.com/q/50471654
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87994168
score: 0
comment on: http://stackoverflow.com/q/50490410
type: Comment
type: QuestionComment
has text: export() method is not part of class, I think it's ok without self.

http://stackoverflow.com/q/50504441
tagged with: django-class-based-views
type: Question
tagged with: django-views
has comment: http://stackoverflow.com/comment/88028977
tagged with: python
has title: Django UpdateView generic class
has comment: http://stackoverflow.com/comment/88030347
accepted answer: http://stackoverflow.com/a/50505034
has answer: http://stackoverflow.com/a/50505034
type: AnsweredQuestion
has body: How can I access the object passed by the user inside a generic view class? In template, when the user clicks the link: Edit this goes to urls.py: url(r'^update_peon/(?P<pk>\d+)$', views.UpdatePeon.as_view(), name='update_peon'), and my view: class UpdatePeon(generic.UpdateView): login_required = True template_name = 'appform/Peons/peon_form.html' model = Person form_class = PersonForm success_url = reverse_lazy('view_peons') I would like to access the item.attr1 or at least item.pk inside the class so I could change the model and form accordingly, something like: class UpdatePeon(generic.UpdateView): login_required = True template_name = 'appform/Peons/peon_form.html' if item['attr1'] == "Attribute1": model = model1 form = model1Form else: etc success_url = reverse_lazy('view_peons') I know how to do it in a normal function based class or even if I rewrite a class based view from scratch but I don't want to do that.
downvote count: 0
upvote count: 1
tagged with: django
score: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88022204

http://stackoverflow.com/comment/88059651
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50523074
has text: I didnt understand what you really mean.
score: 0

http://stackoverflow.com/comment/87837724
score: 0
has text: I'm trying to understand the python path your error reports. On my ubuntu 16 laptop, they are all '/usr/lib/...' and '/usr/local/lib/...'. But on my debian server, they have a mix of '/usr/lib/...' and '/usr/local/lib/...' and '/home/mike/.local/lib/...' like yours. I'll edit one more thing into the answer for you to try.
comment on: http://stackoverflow.com/q/50391868
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50452918
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50450994
has body: That is cool i did not know you could use SSM to execute code from github directly. If you weren't married to a pure SSM solution you could incorporate lambda Two options. Use Lambda and CloudWatch Events. Put your code in Lambda, and use Cloud Watch Events to trigger the Lambda function. Use Lambda and CloudWatch Events to call SSM at the pre-determine interval. Essentially a shim that does the remote call.
type: Answer
has comment: http://stackoverflow.com/comment/87919440
accepted answer of: http://stackoverflow.com/q/50450994
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87952875
type: AnswerComment
has text: Thanks. I was actually using `fib` which converted it into a number
comment on: http://stackoverflow.com/a/50468161
type: Comment
score: 0

http://stackoverflow.com/q/50514405
has answer: http://stackoverflow.com/a/50515125
tagged with: python
has body: The below is a working example, you can copy all the variables and run the for loop to check I have two lists, one of length = 13 and one of length = 7. varying_DA = [70,78,86,90,94,98,100,102,106,110,114,122,130] test_array = [1,2,3,4,5,6,7,8,9,10,11,12,13] #DUMMY array varying_Hinv = [60,76,92,100,108,124,140] I would like to loop through the above two lists, i.e. using two for loops like: for vary_DA,test in zip(varying_DA,test_array): for vary_Hinv,min_a,max_a in zip(varying_Hinv,min_aH,max_aH): So in the above for loop, it starts with 70 for vary_DA and loops through the 7 values of vary_Hinv, i.e. 60,76,...,124,140. Then goes to 78 for vary_DA and so on until it finishes with 130 for vary_DA. I have specific values of min_aH and max_aH for each of the vary_DA and vary_Hinv values. min_aH = np.array([[24,30,30,30,30,30,30],[36,42,42,47,47,47,47], [36,42,42,42,42,42,42],[36,42,42,42,42,42,42], [42,47,47,47,53,47,53],[42,53,47,47,53,53,53], [47,47,47,47,47,53,47],[47,47,47,47,47,59,59], [53,53,59,59,59,59,64],[47,65,59,59,47,47,64], [53,47,41,47,53,47,47],[36,41,41,41,53,47,47], [36,36,41,41,53,47,47]]) # As you can see it is a 13x7 matrix, 7 for the 7 different vary_Hinv # values and 13 for the 13 different vary_DA values max_aH = np.array([[54,60,60,60,60,60,60],[60,66,66,66,66,66,66], [66,66,72,72,72,72,72],[66,72,72,72,78,78,78], [72,78,78,78,84,84,84],[78,84,84,89,89,84,84], [78,84,78,89,84,84,78],[84,84,78,84,84,89,89], [84,84,84,89,89,89,89],[84,89,84,89,101,101,101], [89,89,95,101,95,101,101],[96,96,95,107,95,101,101], [96,101,95,107,107,101,101]]) i.e. when vary_DA = 70 and vary_Hinv = 60, min_aH = 24 and max_aH = 54. when vary_DA = 70 and vary_Hinv = 76, min_aH = 30 and max_aH = 60 and so on. Now I would like to use these specific values of min_aH and max_aH for the for loops, but as you can see from the below working example that it fails. ii = 0 for vary_DA,test in zip(varying_DA,test_array): jj = 0 for vary_Hinv,min_a,max_a in zip(varying_Hinv,min_aH…
has comment: http://stackoverflow.com/comment/88042666
has answer: http://stackoverflow.com/a/50515296
accepted answer: http://stackoverflow.com/a/50515296
tagged with: indices
score: 2
upvote count: 2
tagged with: numpy
type: AnsweredQuestion
answer count: 2
tagged with: for-loop
downvote count: 0
has comment: http://stackoverflow.com/comment/88042706
has comment: http://stackoverflow.com/comment/88042572
has title: Python zip on two numpy arrays
possible better answer: http://stackoverflow.com/a/50515125
favorite count: 0
type: Question

http://stackoverflow.com/a/50532360
answers question: http://stackoverflow.com/q/50531995
has body: You need to specify the name of all your features: feature_names = ['viewed','carted','knownpurchases','totlength','avgtime','stdtime','vartime','KMP','Leven','prodnum'] In the tutorial, only 1 feature (explanatory variable) is used.
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50531995
type: Answer

http://stackoverflow.com/comment/87996108
score: 0
type: AnswerComment
has text: what does your `train_labels` look like? There is essentially a shape mismatch between that and the output of the model.
comment on: http://stackoverflow.com/a/50487614
type: Comment

http://stackoverflow.com/comment/88051930
type: QuestionComment
comment on: http://stackoverflow.com/q/50517837
has text: For example, publish the class DataPoint and Weather, the main.py and the .qml
score: 1
type: Comment

http://stackoverflow.com/comment/88051253
type: AnswerComment
comment on: http://stackoverflow.com/a/50518852
type: Comment
has text: I love this answer and the appreciate amount of work that has gone into it. This certainly challenges the limits of performance for operations like this as we know it. A couple of minor remarks, 1) can you explain/document your code so it is a little more clear what certain subroutines are doing? 2) at low values of N the overhead essentially outweighs the performance, and 3) I'd be interested to see how this compares in terms of memory. Overall, awesome job!
score: 2

http://stackoverflow.com/comment/124802900
has text: `tkinter` really isn't the best thing for this. However, Gtk's `TextView` does this automatically. You can type in a RTL language, then switch to English, then back to the RTL language, and it formats perfectly. If you want to write apps that handle languages like this well, I recommend you use Gtk instead of `tkinter`. There are, of course, other options out there, but Gtk is the one I have the most experience with, so that's the one I'm able to help you with if you have any questions :-). And no, I'm not affiliated with Gtk.
score: 0
comment on: http://stackoverflow.com/q/50387231
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50534310
has body: Expanding upon my comment, you'd be able to accomplish being able to distinguish between which link produced which text by re-writing to something like this: dirty_text = {} for url in test_links: r = requests.get(url) soup = BeautifulSoup(r.content, 'lxml') dirty_text[url] = '\n'.join([node.get_text() for node in soup.find_all('p')]) Going further, if all the titles for the articles are formatted similarly (say they're all in the first h1 tag on the page), you could do something like this: dirty_text = {} for url in test_links: r = requests.get(url) soup = BeautifulSoup(r.content, 'lxml') article_title = soup.find('h1').text dirty_text[article_title] = '\n'.join([node.get_text() for node in soup.find_all('p')])
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50534249
type: Answer
accepted answer of: http://stackoverflow.com/q/50534249
score: 0

http://stackoverflow.com/comment/87988019
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50487058
has text: @MartijnPieters, I however strongly agree that the docstrings are pretty useless though... `This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute.`
type: QuestionComment

http://stackoverflow.com/a/50471190
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50470889
has body: Please see this question How does % work in Python? Modulo give you the remainder of a number. So 4 % 10 = 4 and 14 % 10 = 4. So for directly comparing two numbers you will lose information by using modulo. Comparing large numbers is pretty quick in python. Use ipython's %timeit to see. %timeit (99 ** 85)&gt;( 73 ** 62 ) On my system ( an older i7, 14 GB of ram) it took 46.3 nano seconds which is about as fast as any operation in python.
has comment: http://stackoverflow.com/comment/87956194

http://stackoverflow.com/a/50508522
has comment: http://stackoverflow.com/comment/88030399
score: 1
upvote count: 1
has body: The arguably cleaner way would be to add exception handling to your main code and call worker.shutdown() if an exception is caught that you consider severe enough to warrant termination of the program. Another solution is to flag the worker as daemon thread before starting them (see Hannu's answer). Please be aware that this will ungracefully terminate the worker. From the docs: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly.
answers question: http://stackoverflow.com/q/50507898
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88030132

php
tags question: http://stackoverflow.com/q/50493631
tags question: http://stackoverflow.com/q/50496358
tags question: http://stackoverflow.com/q/50398940
tags question: http://stackoverflow.com/q/50487345
tags question: http://stackoverflow.com/q/50386860
tags question: http://stackoverflow.com/q/50493309
tags question: http://stackoverflow.com/q/50431530
tags question: http://stackoverflow.com/q/50520943
tag name: php
tags question: http://stackoverflow.com/q/50536905
type: Tag

http://stackoverflow.com/a/50429217
answers question: http://stackoverflow.com/q/50428668
has body: Here is a solution using cumulative multiplication which scales better than power based approaches, especially if the input array is of float dtype: import numpy as np def f_mult(a, k): m, n = a.shape out = np.empty((m, k, n), dtype=a.dtype) out[:, 0, :] = 1 a = np.broadcast_to(a[:, None], (m, k-1, n)) a.cumprod(axis=1, out=out[:, 1:]) return out.reshape(m, -1) Timings: int up to power 9 divakar: 0.4342731796205044 ms hpaulj: 0.794165057130158 ms pp: 0.20520629966631532 ms float up to power 39 divakar: 29.056487752124667 ms hpaulj: 31.773792404681444 ms pp: 1.0329263447783887 ms Code for timings, thks @Divakar: def f_divakar(a, k): return (a[:,None]**np.arange(k)[:,None]).reshape(a.shape[0],-1) def f_hpaulj(a, k): return np.hstack(a**np.arange(k)[:,None,None]) from timeit import timeit np.random.seed(0) a = np.random.randint(0,9,(100,100)) k = 10 print('int up to power 9') print('divakar:', timeit(lambda: f_divakar(a, k), number=1000), 'ms') print('hpaulj: ', timeit(lambda: f_hpaulj(a, k), number=1000), 'ms') print('pp: ', timeit(lambda: f_mult(a, k), number=1000), 'ms') a = np.random.uniform(0.5,2.0,(100,100)) k = 40 print('float up to power 39') print('divakar:', timeit(lambda: f_divakar(a, k), number=1000), 'ms') print('hpaulj: ', timeit(lambda: f_hpaulj(a, k), number=1000), 'ms') print('pp: ', timeit(lambda: f_mult(a, k), number=1000), 'ms')
has comment: http://stackoverflow.com/comment/87874931
has comment: http://stackoverflow.com/comment/87873827
type: Answer
has comment: http://stackoverflow.com/comment/87874482
upvote count: 6
downvote count: 0
score: 6

http://stackoverflow.com/comment/87868646
has text: With `data` initialized as dtype float, `data[k] = parts[1:]` should work. `numpy` will convert the strings to floats during the assignment.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50426238
type: Comment

http://stackoverflow.com/comment/88010302
type: QuestionComment
has text: A decorator has to return a callable (like a function).
comment on: http://stackoverflow.com/q/50498727
score: 3
type: Comment

http://stackoverflow.com/a/50471214
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87978853
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50470726
answers question: http://stackoverflow.com/q/50470726
type: Answer
score: 2
has body: Creating your own list of visitors, iterating over those and searching the data frame again and again is not ideal. Have a look at groupby, which can be used in your situation, if I understand your question correctly. To have code similar to what you have now, you can start like this: grouped = sortedData.groupby('visitorId') for visitorId, group in grouped: print(vistorId) # your code here custom_url_algorithm(group)

http://stackoverflow.com/q/50423903
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50423997
accepted answer: http://stackoverflow.com/a/50423997
has body: I want to add a new code template/snippet to PyCharm. For example, I want to expand lw to log.write_Line("|here is sould be cursor after code completition from snippet|"). Something like https://www.tutorialspoint.com/eclipse/eclipse_code_templates.htm . But I didn't find such settings in PyCharm. How to make it in PyCharm?
tagged with: python
type: AnsweredQuestion
tagged with: pycharm
has title: Adding code templates in the PyCharm - is it possible?
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50453934
favorite count: 0
type: Question
tagged with: model
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50457635
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: keras
has answer: http://stackoverflow.com/a/50457635
type: AnsweredQuestion
has body: I am quite new to machine learning and I am currently working on a "car value predictor" application. I stuck where I have to feed my data to my model. I have 4 inputs: date: the car's first registration date (int) km: the car's mileage meter (int) consume: the car's consume type (one-hot encoded vector with 10 element e.g. for petrol: [1 0 0 0 0 0 0 0 0 0]) type: the car's type (for example: "BMW-320", stored in one-hot encoded vector with 440 element ) and one output: the price of the car. I would like to do something similar to this: https://i.sstatic.net/MpYRo.jpg I have tried the following code which compiles but the output is not what I wanted: model = Sequential([ Dense(128, input_shape=(1,), activation='relu', name='date'), Dense(128, input_shape=(1,), activation='relu', name='km'), Dense(128, input_shape=(10,), activation='relu', name='consume'), Dense(128, input_shape=(440,), activation='relu', name='type'), Dropout(0.5), Dense(128, activation='relu'), Dropout(0.5), Dense(1, activation='linear') ]) model.compile(loss='mse', optimizer='adam') model.fit( x = {'date' : samples_train['input'][:,0], 'km' : samples_train['input'][:,1], 'consume':samples_train['input'][:,2], 'type':samples_train['input'][:,3]}, y = samples_train['output'], epochs=1000, batch_size=16, verbose=1, validation_data = ({'date' : samples_valid['input'][:,0], 'km' : samples_valid['input'][:,1], 'consume':samples_valid['input'][:,2], 'type':samples_valid['input'][:,3]}, samples_valid['output']), callbacks=callbacks) Can anyone point out what am I doing wrong or how can I implement a model "structure" like on the picture? EDIT: I think this is what I was looking for. Can anyone confirm this? :) input_1 = Input(shape=(1,), name='date') # input layers input_2 = Input(shape=(1,), name='km') input_3 = Input(shape=(10,), name='consume') input_4 = Input(shape=(440,), name='type') dense_1 = Dense(256, activation='relu')(input_1) # hidden layers dense_1 = Dense(256, activation='relu')(input_2) den…
score: 1
has title: Keras Sequential model, more inputs

http://stackoverflow.com/comment/88010407
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50498642
type: Comment
has text: I was just asking how the highlighted code works the way it was written.

http://stackoverflow.com/q/50395618
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76857787
tagged with: python
score: 2
has body: I would like to have an avro schema that has a field called validExtensions. How can I have validExtensions accept a list of enum extensions? I created a list of acceptable extensions in an enum: { "type":"enum", "name":"extensions", "symbols": [".zip",".txt",".csv",".pdf",".xls",".xlsx"] } But I can't seem to figure out a way to have a field that accepts an array of enum values within extensions. For example an json output would be: { "data":{ "validExtensions": [".csv", ".xls"], "fileName": "testing.csv" } } Here's what I already tried but it does not work: { "type":"record", "name":"data", "fields": [ { "name":"validExtensions", "type":"array", "items": { "extensions" } } ] }
has title: How do I create an array of enums in a JSON avro schema?
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50399558
tagged with: avro
answer count: 2

http://stackoverflow.com/comment/87912104
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50449181
has text: @DevanshuMisra maybe this is what you are looking for [link](https://stackoverflow.com/questions/47304991/python-xml-print-particular-child-node-based-on-sub-element-text)
type: Comment

http://stackoverflow.com/q/50431179
has comment: http://stackoverflow.com/comment/87877559
has comment: http://stackoverflow.com/comment/87877538
answer count: 0
downvote count: 0
has body: I'm attempting to log into a MySQL server in python. I'm able to easily access this serve using MySQL Workbench and the same credentials, but I get an error when using the following code: import MySQLdb as db import sshtunnel import pandas as pd sshtunnel.SSH_TIMEOUT = 5.0 sshtunnel.TUNNEL_TIMEOUT = 5.0 with sshtunnel.SSHTunnelForwarder( ('accesspoint.fake.com', 22), ssh_username='Tony', ssh_password='pwtony', remote_bind_address=('180.45.89.0', 3306)) as server: conn = db.connect(host='180.45.89.0', port=server.local_bind_port, user='Tony', password='pwtony', db='all_data') Error message: -------------------------------------------------------- OperationalError Traceback (most recent call last) &lt;ipython-input-16-ca168ce0a4a7&gt; in &lt;module&gt;() 9 user='Tony', 10 password='pwtony', ---&gt; 11 db='all_data') ~/anaconda3/lib/python3.6/site-packages/MySQLdb/__init__.py in Connect(*args, **kwargs) 84 """Factory function for connections.Connection.""" 85 from MySQLdb.connections import Connection ---&gt; 86 return Connection(*args, **kwargs) 87 88 connect = Connection = Connect ~/anaconda3/lib/python3.6/site-packages/MySQLdb/connections.py in __init__(self, *args, **kwargs) 202 self.waiter = kwargs2.pop('waiter', None) 203 --&gt; 204 super(Connection, self).__init__(*args, **kwargs2) 205 self.cursorclass = cursorclass 206 self.encoders = dict([ (k, v) for k, v in conv.items() OperationalError: (2003, "Can't connect to MySQL server on '180.45.89.0' (110)") Would appreciate any help :)
upvote count: 1
score: 1
tagged with: mysql
has title: Trouble connecting to a remote MySQL database, via SSH-tunnel, using Python 3.6?
favorite count: 0
type: Question
tagged with: ssh-tunnel
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87878092

http://stackoverflow.com/comment/87958851
type: Comment
score: 0
type: AnswerComment
has text: Thanks for your help. I added your recommended change to the code by I still receive the following error: `NameError: name 'flight_miles' is not defined`
comment on: http://stackoverflow.com/a/50472275

http://stackoverflow.com/a/50519107
downvote count: 0
has comment: http://stackoverflow.com/comment/88051178
answers question: http://stackoverflow.com/q/50519063
type: Answer
score: 4
upvote count: 4
has body: You can try the following code: list = { "A" : [ "1", "2", "3" ], "B" : [ "2" ], "C" : [ "1", "2" ] } data = [] for key, values in list.items(): for value in values: data.append("{0}.{1}".format(key,value)) print(data) # Output ['A.1', 'A.2', 'A.3', 'B.2', 'C.1', 'C.2']

http://stackoverflow.com/a/50476472
has body: There's no way to fully replace how Python wraps the stdin and stdout pipes in sys.stdin and sys.stdout. (There is some limited control, like the -u option`, but that's it.) However, you're asking for multiple other things, all of which are possible, and some of which might be what you want. First, sys.stdin is just a normal TextIOWrapper, as returned by open (in text mode). This means you can access its underlying binary object, or the raw unbuffered file object underneath that, or the OS file descriptor underneath that, the same as for any other text file: sys.stdin.buffer sys.stdin.buffer.raw sys.stdin.fileno() Often, that's all you need. You wouldn't want to actually replace sys.stdin = sys.stdin.buffer. That would break input, the fileinput module, and who knows what else that's expecting stdin to be a text file. But you can just use sys.stdin.buffer instead of sys.stdin, and it's roughly the equivalent of what I think you were looking for from perl's binmode. And you want a TextIOWrapper with different options wrapped around the same underlying file, you can do that too. For the simplest cases, the easiest way to do that is just to call open the way you wanted to call open, passing the file descriptor: sin = open(sys.stdin.fileno(), &lt;your open arguments here&gt;) For less trivial cases, you may need to read the TextIOWrapper docs (and BufferedReader and other types in the io module) and wrap exactly the part you want in exactly the way you want. But usually, open will be good enough. Either way, you can just use sin in place of sys.stdin. Or, since this now is a perfectly good TextIOWrapper (assuming you opened in text mode), it is safe and reasonable to replace sys.stdin: sys.stdin = sin … and now input, etc., will continue to work—and will work the way you wanted them to.
downvote count: 0
answers question: http://stackoverflow.com/q/50476200
upvote count: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/50476200
score: 7
type: AcceptedAnswer

http://stackoverflow.com/q/50500298
type: Question
has body: I have an understanding that object is an instance of type and type inherits from object. So the following relationships makes sense: isinstance(object, type) # returns True, ok issubclass(type, object) # returns True, ok I also know that isinstance(a,b) checks whether a is an instance of either b or its bases. So, the following makes sense too: isinstance(type, type) # returns True because it is translated to .... isinstance(type, object) # which is True What I cannot follow is why do the following statements return True. isinstance(type, object) # returns True, but why? isinstance(object, object) # returns True, but why? Let me know if you know. Thanks.
answer count: 2
has comment: http://stackoverflow.com/comment/88013310
has comment: http://stackoverflow.com/comment/88013423
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50500481
tagged with: types
duplicate of: http://stackoverflow.com/q/55775218
downvote count: 0
tagged with: python-datamodel
has comment: http://stackoverflow.com/comment/88013820
favorite count: 0
tagged with: object
score: 3
has answer: http://stackoverflow.com/a/50500423
has comment: http://stackoverflow.com/comment/88013373
has title: isinstance(type, object) = True, why?
tagged with: python
has comment: http://stackoverflow.com/comment/88013266
linked to: http://stackoverflow.com/q/55775218

http://stackoverflow.com/a/50533357
downvote count: 0
upvote count: 5
type: Answer
has body: Unfortunately they are not supported right now - you have to load them at runtime instead of in the ini file itself. A common approach in my apps is to define a render-config script which takes a site.ini.in template and renders it out to site.ini using jinja2 with env vars available to it. It's not very satisfying but it does work well. import jinja2 import os def multiline(val): lines = (l.strip() for l in val.strip().split('\n')) return '\n ' + '\n '.join(lines) def main(cli, args): env = jinja2.Environment( loader=jinja2.FileSystemLoader(os.getcwd()), undefined=jinja2.StrictUndefined, ) env.filters['multiline'] = multiline template = env.get_template(args.template) result = template.render({ 'env': os.environ, }) with open(args.config_file, 'w', encoding='utf8') as fp: fp.write(result)
accepted answer of: http://stackoverflow.com/q/50532544
score: 5
answers question: http://stackoverflow.com/q/50532544
has comment: http://stackoverflow.com/comment/88288348
type: AcceptedAnswer

http://stackoverflow.com/comment/87937502
score: 0
has text: Don't know yet for certain, but I suspect it will as R is used in palaeoclimatology.
type: Comment
comment on: http://stackoverflow.com/a/50411668
type: AnswerComment

http://stackoverflow.com/comment/87967858
has text: That is perfect. Thank you!!
comment on: http://stackoverflow.com/a/50477126
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50479337
has title: pynvrtc on Google Colab: libnvrtc.so not found
has answer: http://stackoverflow.com/a/50483234
has body: In a Google Colab notebook, I am installing a python package which uses pynvrtc to compile some CUDA codes. I got the error: OSError: libnvrtc.so: cannot open shared object file: No such file or directory I run !find / -name 'libnvrtc.*' and get /usr/lib/x86_64-linux-gnu/libnvrtc.so.8.0.61 /usr/lib/x86_64-linux-gnu/libnvrtc.so.8.0 My question is: Do I suppose to have libnvrtc.so in my Google Colab system? How can I get around if I just have libnvrtc.so.8.0?
tagged with: python
linked to: http://stackoverflow.com/q/49135065
has comment: http://stackoverflow.com/comment/87979194
score: 2
accepted answer: http://stackoverflow.com/a/50483234
upvote count: 2
has comment: http://stackoverflow.com/comment/87975666
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87972966
tagged with: google-colaboratory
tagged with: cuda
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/50387465
has body: I am trying to write a 3D float list into a TFrecord, so I successfully, write it by flattening it first, I parse it but it raises an error while reshaping it. Error: ValueError: Shapes () and (8,) are not compatible This is how I write the TFrecord file def _floats_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value.flatten())) def write(output_path, data_rgb, data_depth, data_decalib): with tf.python_io.TFRecordWriter(output_path) as writer: feature = {'data_rgb': _floats_feature(data_rgb), 'data_depth': _floats_feature(data_depth), 'data_decalib': _floats_feature(data_decalib)} sample = tf.train.Example(features=tf.train.Features(feature=feature)) writer.write(sample.SerializeToString()) And This is how I read the TFrecord file def get_batches(date, drives, batch_size=1): """ Create a generator that returns batches of tuples rgb, depth and calibration :param date: date of the drive :param drives: array of the drive_numbers within the drive date :return: batch generator """ filenames = get_paths_drives(date, drives) dataset = tf.data.TFRecordDataset(filenames) dataset = dataset.map(input_parser) # Parse the record into tensors. dataset = dataset.repeat() # Repeat the input indefinitely. dataset = dataset.batch(batch_size) return dataset config = configparser.ConfigParser() config.read(path_helpers.get_config_file_path()) IMAGE_WIDTH = int(config['DATA_INFORMATION']['IMAGE_WIDTH']) IMAGE_HEIGHT = int(config['DATA_INFORMATION']['IMAGE_HEIGHT']) INPUT_RGB_SHAPE = [IMAGE_HEIGHT, IMAGE_WIDTH, 3] INPUT_DEPTH_SHAPE = [IMAGE_HEIGHT, IMAGE_WIDTH, 1] LABEL_CALIB_SHAPE = [8] def input_parser(example_proto): features = {'data_rgb': tf.FixedLenFeature([], tf.float32), 'data_depth': tf.FixedLenFeature([], tf.float32), 'data_decalib': tf.FixedLenFeature([], tf.float32)} parsed_features = tf.parse_single_example(example_proto, features) data_rgb = parsed_features['data_rgb'] data_rgb.set_shape(np.prod(INPUT_RGB_SHAPE)) img_rgb = tf.reshape(data_rgb, …
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50390262
has answer: http://stackoverflow.com/a/50390262
answer count: 1
downvote count: 0
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
tagged with: numpy
has title: Tensorflow parsing and reshaping float list in Dataset.map()

http://stackoverflow.com/a/50513251
score: 0
answers question: http://stackoverflow.com/q/50508332
has body: the error has resolved just replace bgr_image to augmented_image predictions = sess.run(prob_tensor, {input_node: [bgr_image] }) to predictions = sess.run(prob_tensor, {input_node: [augmented_image] })
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50508332

http://stackoverflow.com/comment/87802586
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50391047
has text: Thank you so much, it worked

http://stackoverflow.com/a/50468825
score: 0
answers question: http://stackoverflow.com/q/50468597
type: Answer
has body: When you first call the menu function, you set a and b both to 1. When you make a choice, you call the menu function again, and thus reset a and b both to 1. You should either remove the initialization of a and b inside the function, initialize them before the call to menu, and pass them as variables to menu. Alternatively, you can remove the calls to menu at each choice and enclose your input and if/else statements within a while loop that will break when ch is equal to some sentinel value. If you want to do this using recursion, do it like this: def menu(a, b): ch = int(input('Choice:')) if ch is 1: a = 11 menu(a,b) elif ch is 2: b = 22 print(a+b) menu(a,b) elif ch is 0: print('End') else: print('Unknown Choice') a, b = 1, 1 menu(a, b) If you want to do it using a while loop, do it like this: def menu(): ch = -1 a, b = 1, 1 while ch != 0: ch = int(input('Choice:')) if ch is 1: a = 11 elif ch is 2: b = 22 print(a+b) elif ch is 0: print('End') else: print('Unknown Choice') menu() Hope this helped!

http://stackoverflow.com/q/50448342
has comment: http://stackoverflow.com/comment/87955044
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/13156395
has comment: http://stackoverflow.com/comment/87955526
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87955715
has comment: http://stackoverflow.com/comment/87956124
has comment: http://stackoverflow.com/comment/87955158
has body: Link to the .json file -> This is the link to the .json file. I am making a Python based project and what I am trying to do here is to make use of a .json file. However when I tried to import it to use it with the GUI I got the following error. Thank you in advance. Traceback (most recent call last): File "&lt;ipython-input-1-31816de2c4db&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Akshita/pyex/Webmap/Gui.py', wdir='C:/Users/Akshita/pyex/Webmap') File "C:\Users\Akshita\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\Akshita\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Akshita/pyex/Webmap/Gui.py", line 12, in &lt;module&gt; data=json.load(open(r"C:\Users\Akshita\pyex\Webmap\world.json")) File "C:\Users\Akshita\Anaconda3\lib\json\__init__.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "C:\Users\Akshita\Anaconda3\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\Akshita\Anaconda3\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Akshita\Anaconda3\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting value # -*- coding: utf-8 -*- """ Created on Mon May 21 10:15:01 2018 @author: Akshita """ from tkinter import * import json import difflib from difflib import get_close_matches data=json.load(open(r"C:\Users\Akshita\pyex\Webmap\world.json")) window=Tk() window.title("Webmap") l1=Label(window,text="Name_of_place") l1.grid(row=0,column=0) val=StringVar() e=Entry(window,textvariable=val) e.grid(row=0,column=1) be=Button(window,text="Enter",command=entry) be.grid(row=0,column=2) def entry(): w= e_val.get() w=w.title() if w in data: t.insert("Data ma…
accepted answer: http://stackoverflow.com/a/50471164
answer count: 1
has comment: http://stackoverflow.com/comment/87955055
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50471164
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has title: Importing json files on GUI using python. getting JSONDecodeError
tagged with: anaconda

http://stackoverflow.com/comment/88031726
comment on: http://stackoverflow.com/q/50503934
type: Comment
type: QuestionComment
has text: Oh, that might be a problem. Why not assign a column as an index or reset the index `dataframe.reset-index()` on a small dataframe and see how that behaves.
score: 0

http://stackoverflow.com/a/50397703
answers question: http://stackoverflow.com/q/50397126
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: Please refer to the official numpy documentation (https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.cov.html) and check whether you usage of the numpy.cov function is consistent with what you are trying to achieve and you understand what you are trying to do. When looking at the signature numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None) m : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of m represents a variable, and each column a single observation > > of all those variables. Also see rowvar below. y : array_like, optional An additional set of variables and observations. y has the same form as that of m. Note how m and y are combined as shown in the last example on the page &gt;&gt;&gt; x = [-2.1, -1, 4.3] &gt;&gt;&gt; y = [3, 1.1, 0.12] &gt;&gt;&gt; X = np.stack((x, y), axis=0) &gt;&gt;&gt; print(np.cov(X)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] &gt;&gt;&gt; print(np.cov(x, y)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] &gt;&gt;&gt; print(np.cov(x)) 11.71

http://stackoverflow.com/q/50420686
tagged with: rolling-computation
tagged with: python
score: 3
tagged with: pandas
upvote count: 3
favorite count: 0
type: Question
has body: I've been reading documentation on the rolling() funciton and I can't seem to find a way to incorporate both a forward and backward window at the same time. What I want to do is compute the mean absolute deviation (or even standard deviation) of the forward 10 and past 10 events for outlier analysis. I was able to compute mean for forward/past 10 in a hacky way by doing df = pd.DataFrame({ 'date': pd.date_range(start='1/1/2017', end='12/31/2017'), 'value': np.random.rand(365)}) first_10 = df.rolling(window=10, win_type='triang')['value'].mean().shift().reset_index() last_10 = df[::-1].rolling(window=10, win_type='triang')['value'].mean().shift().reset_index() and then pd.merge(first_10, last_10, on = ['level_1']).set_index(['level_1']).mean(axis=1) But because you can't just average two MADs together to get the MAD for that window, I can't do this. Does anyone have a more robust way to use the rolling function for calculations like this? Feels like there has to be away using some sort of shift function. Appreciate the help on this.
has answer: http://stackoverflow.com/a/52470621
has title: Pandas- how to compute a rolling forward 10/backward 10 mean absolute deviation?
type: UnansweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/87861461
type: Comment
score: 0
type: AnswerComment
has text: Hey, I've Updated the Post, please have a look at it and let me know what you think? And Could you please elaborate on what you mean by "l when an object of the model is saved or updated, you should override the save() method of the model and put the code you want to execute" I Started learning Django Just a little while ago, So i dont know much about it..
comment on: http://stackoverflow.com/a/50423002

http://stackoverflow.com/a/50527983
has body: Yes , uploading the file to AWS s3 will definitely work for you and you need nothing else and if you want to do that with python , it's quite easy import boto3 s3 = boto3.client('s3') s3.upload_file('images/4.jpeg', 'mausamrest', 'test/jkl.jpeg',ExtraArgs={'ACL': 'public-read'}) where mausamrest is bucket and test/jkl.jpeg is keyname or you can say filename in s3 and this is how you will have your url https://s3.amazonaws.com/mausamrest/test/jkl.jpeg s3.amazonaws.com/bucketname/keyname this is the format of how your object url will be in my case image is opening in browser as i have done that kind of thing , in your case your csv will get downloaded
score: 0
answers question: http://stackoverflow.com/q/50527604
type: Answer

http://stackoverflow.com/q/50478671
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50498762
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50498762
tagged with: webpack
tagged with: django-webpack-loader
tagged with: django
tagged with: python
has body: I am starting to learn some react, and trying to learn how to combine ReactJS and Django. I am currently following the proposed tutorial here After setting up the django urls, and installing django-webpack-loader, I am stuck with the following error when running the django server: TemplateSyntaxError at / 'webpack_loader' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz My current index.html is as follows: {% load render_bundle from webpack_loader %} Ponynote {% render_bundle 'main' %} I already tried going on, and setting up the rest, but nothing seems to work. The error I am getting is different from the one in the tutorial and both in the github page of django-webpack-loader package and here I can't see any problem like this. The solutions for similar errors I found here did not solve my problems, so I am not sure what or where the error is lying. I tried: Literally copy-pasting the tutorial code remaking the entire project several solutions like creating a custom tag checking if the react(webpack) server is running Info: Django version 2.0.5 django-webpack-loader==0.6.0 Python version 3.6.5 Running on Ubuntu x64 18.04 LTS Thanks for any help, and sorry if this is a stupid, simple to solve mistake.
type: AnsweredQuestion
score: 2
tagged with: reactjs
has title: 'webpack_loader' is not a registered tag library
upvote count: 2

http://stackoverflow.com/a/50525079
has comment: http://stackoverflow.com/comment/88062682
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88063128
has comment: http://stackoverflow.com/comment/88063485
has comment: http://stackoverflow.com/comment/88063001
score: 1
has body: First, i'd change : followers = models.ManyToManyField(User to followers = models.ManyToManyField(Profile Then, if you try to print user1 = Profile.objects.create() #missing args but you don't need it for the example user2 = Profile.objects.create() user1.followers.add(user2) user1.followers.all() You'll get : [user2] But if you do user1.is_following.all() You'll get : [] Finally, if you do : user2.is_following.all() Result will be : [user1] related_name allows you to get your object in another object.
has comment: http://stackoverflow.com/comment/88062943
has comment: http://stackoverflow.com/comment/88063265
has comment: http://stackoverflow.com/comment/88063514
has comment: http://stackoverflow.com/comment/88063639
answers question: http://stackoverflow.com/q/50524720

http://stackoverflow.com/q/50405946
answer count: 5
has body: Even though there were some similar question but none of proposed solution applied to my case. Simply, after tensorflow installationattempting to install packages this message "You are using pip version 9.0.1, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command." like this: But following this python -m pip install --upgrade pip doesn't work even with administrator level, nor this one : python -m pip install -U pip. (I'm using Miniconda, just as an additional information)
has answer: http://stackoverflow.com/a/50406004
has comment: http://stackoverflow.com/comment/87829311
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/51801963
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/87827285
tagged with: miniconda
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/96711185
downvote count: 2
has comment: http://stackoverflow.com/comment/87882105
has title: pip doesn't upgrade in windows
linked to: http://stackoverflow.com/q/46528671
has comment: http://stackoverflow.com/comment/87827470
possible better answer: http://stackoverflow.com/a/50406169
has answer: http://stackoverflow.com/a/50407028
upvote count: 4
has answer: http://stackoverflow.com/a/50407060
accepted answer: http://stackoverflow.com/a/50407060
has answer: http://stackoverflow.com/a/50406169
has comment: http://stackoverflow.com/comment/87827400
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/q/50498913
type: AnsweredQuestion
has body: So previously, I was using django-1.8 version &amp; I am in the process of upgrading to django-1.11. When I load my /admin page, I get Exception Type: TemplateDoesNotExist Exception Value: admin/index.html I have tried multiple options and dont know why django is not loading admin templates for django-1.11. Few more details: - I use django-jet for the admin interface - My TEMPLATES in settings looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'custom_dir_1'), os.path.join(BASE_DIR, 'custom_dir_2'), os.path.join(BASE_DIR, 'custom_dir_3') ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'context_processors.base_context', ], } } ] Let me know if I can provide any other information to debug better. Any guidance in this issue is super appreciated, Have been at this issue for 3rd consecutive day :-(
score: 1
downvote count: 0
answer count: 1
tagged with: django-1.11
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50499096
has title: Error loading admin page after upgrading to django-1.11
accepted answer: http://stackoverflow.com/a/50499096
tagged with: django
tagged with: python

http://stackoverflow.com/a/50412569
score: 0
has comment: http://stackoverflow.com/comment/87841488
accepted answer of: http://stackoverflow.com/q/50412290
type: AcceptedAnswer
has body: What about this instead? fileLista = glob.glob('*.xls') Company = pd.DataFrame() for arquivo in fileLista: df = pd.read_excel(arquivo) Company= pd.concat([Company,df]) Company.columns = Company.columns.str.strip()
has comment: http://stackoverflow.com/comment/87842092
answers question: http://stackoverflow.com/q/50412290
type: Answer
has comment: http://stackoverflow.com/comment/87841897

http://stackoverflow.com/comment/87976627
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50481366
has text: @ZaphoOxx as you can see the encryption and decryption methods are pre-defined so i am sure the output is correct. the problem is that the input has to look like those bytes in order for the functions to work, so naturally the output looks like that too.
score: 0

http://stackoverflow.com/q/50479752
score: 4
upvote count: 4
has title: Apyori relevance measure
type: AnsweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51236590
accepted answer: http://stackoverflow.com/a/51236590
favorite count: 0
type: Question
has body: I'm using Apyori library as an implementation of the Apriori algorithm. rules = apriori(trs, min_support = 0.02, min_confidence = 0.1, min_lift = 3) rules is a generator and can be converted to a list with res=list(rules). For a large dataset, list(rules) seem to take long time. Can you help me understand if the rules are sorted in some criterion so that I can retrieve only the top-n most relevant rules? Or, what is the most efficient way to sort the rules by the lift for example. This is what the typical output looks like (i.e. element in the list): RelationRecord(items=frozenset({'chicken', 'light cream'}), &gt; support=0.004532728969470737, &gt; ordered_statistics=[OrderedStatistic(items_base=frozenset({'light cream'}), &gt; items_add=frozenset({'chicken'}), &gt; confidence=0.29059829059829057, lift=4.84395061728395)])
tagged with: apriori
tagged with: python

http://stackoverflow.com/comment/88076980
type: Comment
score: 0
has text: and what have you tried?
comment on: http://stackoverflow.com/q/50532520
type: QuestionComment

http://stackoverflow.com/q/50505440
tagged with: python
accepted answer: http://stackoverflow.com/a/50506078
type: Question
has answer: http://stackoverflow.com/a/50506078
upvote count: 3
score: 3
has body: I am receiving an array with a few files. My request.data looks like this: &lt;QueryDict: {'image': [&lt;TemporaryUploadedFile: image_1.png (image/png)&gt;, &lt;TemporaryUploadedFile: image_2.png (image/png)&gt;] However, if I try to parse images like this: request.data['image'] I only can see the last image, and django rest framework recognize it as a file object, not a list. If I try to iterate over it all I can see is bytes. I am using a ModelViewset and added this parsers parser_classes = (MultiPartParser, FormParser)
answer count: 1
tagged with: multipartform-data
downvote count: 0
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: AnsweredQuestion
has title: How to parse multiple files in multipart form-data with django rest framework?

http://stackoverflow.com/comment/87874037
has text: Yep, you are right. Thank you for the correction, I'll edit my post accordingly.
score: 0
comment on: http://stackoverflow.com/q/50429685
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50490849
has title: Division with a 0. value and force digits in result
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/50494460
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88000103
has answer: http://stackoverflow.com/a/50494460
type: Question
tagged with: math
tagged with: python
score: -1
has body: I'm in need off assistance with some ZeroDivision. In my example I got an optionMenu, that returns a value to a label, whitch is divided with an entry, then the result is shown in a new label in column 3. I allways want to type an entry, that starts with an zero, like 0.250 etc. then this float is divided with the labels value from the optionMenu and then the result should be shown in a new label with digits. It works fine with int, but thats not how it should work :) and now I'm a bit lost. My following code looks like this and I would really appreciate a bit off help :) Thx in advance. from tkinter import * class App(Frame): def __init__(self, root=None): Frame.__init__(self, root) self.materialPrice = {'Brick': 70, 'Rockwool': 50, 'Concrete': 20} materialvariable1 = StringVar(self, root) materialvariable1.set("Choose material") materialvariable2 = StringVar(self, root) materialvariable2.set("Choose materiale") self.w1 = OptionMenu(root, materialvariable1, *self.materialPrice, command=self.displayPrice) self.w1.grid(row=2, column=0, columnspan=1, sticky='WE') self.w2 = OptionMenu(root, materialvariable2, *self.materialPrice, command=self.displayPrice2) self.w2.grid(row=3, column=0, columnspan=1, sticky='WE') self.var = IntVar() self.var.set(float(0.00)) self.var2 = IntVar() self.var2.set(float(0.00)) self.entry1 = Entry(root, textvariable=self.var) self.entry1.grid(row=2, column=1) self.entry2 = Entry(root, textvariable=self.var2) self.entry2.grid(row=3, column=1) self.priceVarLabel1 = IntVar() self.priceVarLabel1.set(float(0.00)) self.priceVarLabel2 = IntVar() self.priceVarLabel2.set(float(0.00)) self.priceVarValue1 = Label(root, textvariable=self.priceVarLabel1, relief='sunken') self.priceVarValue1.grid(row=2, column=2, columnspan=1, sticky='WE') self.priceVarValue2 = Label(root, textvariable=self.priceVarLabel2, relief='sunken') self.priceVarValue2.grid(row=3, column=2, columnspan=1, sticky='WE') self.resultlabel1 = IntVar() self.resultlabel1.set(float(0.00)) s…
has comment: http://stackoverflow.com/comment/87994712
tagged with: tkinter

http://stackoverflow.com/comment/87927646
comment on: http://stackoverflow.com/a/50456525
has text: @cdlane `for result in child.find()` unpacks the list and then adds each item to `rtn`. I did not test it (i tested only `find_leaves`), but I think it should work...
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87915947
has text: Regex is pretty bad at telling what is and isn't within quotes, parens etc. when there may be multiple such instances around.
type: QuestionComment
comment on: http://stackoverflow.com/q/50450985
score: 0
type: Comment

http://stackoverflow.com/a/50455034
has comment: http://stackoverflow.com/comment/87923638
score: 0
has body: One way is to use collections.defaultdict. You can create a set of words and then increment your dictionary counter for each file, for each word. from collections import defaultdict d = defaultdict(int) for root, dirs, files in os.walk(currentdir): for name in files: with open(root+'/'+name,'r') as outfile2: words = {line.split()[0] for line in outfile2} for word in words: d[words[0]] += 1
answers question: http://stackoverflow.com/q/50454906
has comment: http://stackoverflow.com/comment/87924804
type: Answer

http://stackoverflow.com/a/50386382
has comment: http://stackoverflow.com/comment/87788507
has comment: http://stackoverflow.com/comment/87797247
upvote count: 1
has comment: http://stackoverflow.com/comment/87796692
has comment: http://stackoverflow.com/comment/87788438
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87797443
answers question: http://stackoverflow.com/q/50386332
has comment: http://stackoverflow.com/comment/87790548
has body: You can't put the key b in position 1, or any position. Dictionaries are unordered in principle. There is usually not much reason to care about the order. But if you do care about the order then you have to maintain it yourself outside of the dict that holds your data. You can't insist on the dict maintaining the order itself, because dicts don't work that way. For example: orderby = ["b", "a", "d", "c"] for key in orderby: do_something_with(key, Dict[key]) To change the order, for example to exchange the positions of "a" and "b": orderby[0],orderby[1] = orderby[1],orderby[0] There is also an OrderedDict in collections, but that is mainly to remember the order that things were added to it, which doesn't seem to be what you want. To change the value associated with 'a' just assign it: Dict['a'] = [19]
has comment: http://stackoverflow.com/comment/87788766
downvote count: 0

http://stackoverflow.com/comment/91665347
type: AnswerComment
comment on: http://stackoverflow.com/a/50500803
has text: I modified radians(360.0) to math.radians(360.0), what's the effect of above codes? Shall I expect a couple of pictures? Or just camera rotate objects without shooting pictures? What about if I want camera shooting some pictures saved as jped or png?
score: 0
type: Comment

http://stackoverflow.com/a/50834432
has body: I fixed that using boucle while while True: if not driver.find_elements_by_xpath("//*[contains(text(), 'Suivant')]"): break link=WebDriverWait(driver, 1530).until(expected_conditions.element_to_be_clickable((By.LINK_TEXT, "Suivant"))) link.click() next_page = driver.find_element_by_css_selector('#pnnext') next_page.click() time.sleep(5)"""
score: 0
answers question: http://stackoverflow.com/q/50505169
type: Answer

http://stackoverflow.com/comment/88078203
type: AnswerComment
comment on: http://stackoverflow.com/a/50533066
score: 1
type: Comment
has text: or you can do the following to keep the structure `[[j*i for j in range(1, i+1)] for i in range(1,10)]`

http://stackoverflow.com/comment/87886072
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50435936
has text: For the record, I think @user2285236 has a better pandas solution.
type: Comment

http://stackoverflow.com/a/50406169
has body: I think it manybe PIP command before installing TensorFlow can be normal use, only after installation problems, probably because the new version of Python compatible with TensorFlow might be a little less, so update PIP and conda command, can fix. by command conda install pip
has comment: http://stackoverflow.com/comment/87829503
has comment: http://stackoverflow.com/comment/87827791
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87828353
has comment: http://stackoverflow.com/comment/87828576
answers question: http://stackoverflow.com/q/50405946
upvote count: 2
has comment: http://stackoverflow.com/comment/87829673
downvote count: 0

http://stackoverflow.com/q/50483836
type: UnansweredQuestion
has title: scrapy recursive scrape website
answer count: 1
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/50484035
tagged with: python
has body: I want to write a scraper that visits all subpages of the initial page. The example website is: pydro.com So it should for example also extract pydro.com/impressum and save it as an html file on my hard drive. The code I wrote: import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.exporters import CsvItemExporter from scrapy.loader import ItemLoader from finalproject.items import FinalprojectItem class ExampleSpider(CrawlSpider): name = "projects" # Spider name allowed_domains = ["pydro.com"] # Which (sub-)domains shall be scraped? start_urls = ["https://pydro.com/"] # Start with this one rules = [Rule(LinkExtractor(), callback='parse_item', follow=True)] # Follow any link scrapy finds (that is allowed). def parse_item(self, response): print('Got a response from %s.' % response.url) self.logger.info('Hi this is an item page! %s', response.url) page = response.url.split('.com/')[-1] filename = 'pydro.html' with open(filename, 'wb') as f: f.write(response.body) self.log('Saved file %s' % filename) When I run my spider the output is only pydro.html. I think I need to adjust my filename, that i get the subpage. Or do I need a for loop? EDIT1: I edited the code to get all html pages. But when I want to run the script on another website I get an error called: FileNotFoundError: [Errno 2] No such file or directory: 'otego-https://www.otego.de/de/jobs.php' Thats the script I run: import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.exporters import CsvItemExporter from scrapy.loader import ItemLoader class ExampleSpider(CrawlSpider): name = "otego" #Spider name allowed_domains = ["otego.de"] # Which (sub-)domains shall be scraped? start_urls = ["https://www.otego.de/en/index.php"] # Start with this one rules = [Rule(LinkExtractor(), callback='parse_item', follow=True)] # Follow any link scrapy finds (that is allowed). def parse_item(self, respon…
tagged with: web-crawler
linked to: http://stackoverflow.com/q/44293662
score: 0

http://stackoverflow.com/comment/87855295
comment on: http://stackoverflow.com/a/50419924
score: 0
has text: Since they only want the last result, may want to consider `fname.rsplit('_', 1)[1]` as I believe it will be slightly faster
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87897457
comment on: http://stackoverflow.com/q/50441365
score: 0
type: Comment
has text: Have you tried to use a debugger? Have you tried to run the program with more arguments?
type: QuestionComment

http://stackoverflow.com/comment/87852891
type: QuestionComment
has text: @roganjosh Oh God I didn't spend an hour and a half on a typo did I? Let me give that a try. Sorry about that.
score: 0
comment on: http://stackoverflow.com/q/50418511
type: Comment

http://stackoverflow.com/comment/88092025
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50540215
has text: You're opening the file correctly. The error is unrelated to that
type: Comment

http://stackoverflow.com/a/50474726
accepted answer of: http://stackoverflow.com/q/50474524
has comment: http://stackoverflow.com/comment/87979432
has body: You will need to find an encoding that will convert your data into a format neural network would understand. A common approach is one-hot encoding: suppose you have 7 notes (A,B,C...) 3 octaves (2,3,4) and sharp flat neutral. With one-hot this becomes 3 vectors (7,) ; (3,) ; (3;) and let's take [A,2,#] -&gt; [1,0,0,0,0,0,0,1,0,0,1,0,0] in which the indices for the categories are set to 1. This is only one way of doing it, for the notes you have you would create a matrix (4, 13) which says 4 notes encoded as one-hot per category. Another way would be make every note unique, so you would have a vector (88,) which tells the network what note it would be, [A,2,#] -&gt; [...0,0,1,0,0...] only 1 where the note is set. This would increase the size of the vector obviously but should make it more obvious for the network. But still 88 is not a large number for computers these days. This is how magenta encodes notes, they encode more stuff like time etc as well for more dynamics of music generation. Finally you can create a network: model = Sequential() model.add(LSTM(some_hidden_number_units, input_shape=(4, 88)) # 4 past notes model.add(Dense(88, activation='softmax')) # predict one of 88 notes model.compile(loss='categorical_crossentropy', ...)
has comment: http://stackoverflow.com/comment/87965389
type: Answer
has comment: http://stackoverflow.com/comment/87968298
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87964580
answers question: http://stackoverflow.com/q/50474524

http://stackoverflow.com/q/50473113
tagged with: asynchronous
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50473955
tagged with: python-asyncio
has body: How do I use asyncio and run the function forever. I know that there's run_until_complete(function_name) but how do I use run_forever how do I call the async function? async def someFunction(): async with something as some_variable: # do something I'm not sure how to start the function.
tagged with: python
has comment: http://stackoverflow.com/comment/88255741
accepted answer: http://stackoverflow.com/a/50473955
type: AnsweredQuestion
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/87961534
downvote count: 0
has answer: http://stackoverflow.com/a/50473557
possible better answer: http://stackoverflow.com/a/50473557
has title: How to run async function forever (Python)
upvote count: 1

http://stackoverflow.com/q/50519670
tagged with: cythonize
tagged with: python
tagged with: cython
has answer: http://stackoverflow.com/a/50525790
type: Question
upvote count: 2
score: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/48387310
favorite count: 0
has body: I've seen this question and the answer don't seems to be working. Following is my directory structure. . ├── my_package │ ├── a.pyx │ ├── b.pyx │ ├── b.pxd │ ├── test.py │ └── __init__.py └── setup.py a.pyx file cimport my_package.b as b class a: def __init__(self): self.b = b.b() self.b.run() b.pyx file cdef class b: def __init__(self): pass cpdef run(self): print "b is running" b.pxd file cdef class b: cpdef run(self) test.py import a c = a.a() setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy extensions = [ Extension("my_package.a", ["my_package/a.pyx"] ), Extension("my_package.b", ["my_package/b.pyx"] ) ] for e in extensions: e.cython_directives = {"embedsignature": True} setup( name = "preprocess", ext_modules = cythonize(extensions), ) after running python setup.py build_ext --inplace there is no compile error. But if I try to run test.py it gives ImportError: No module named my_package.b. Any input will be appreciated. BTW if we change the first line of a.pyx from cimport my_package.b as b to import b it will work.
has title: cython import error in same package

http://stackoverflow.com/comment/87931727
score: 0
has text: @Sebastian I am expecting to write 2D matrices in each row of the CSV. I checked the answer to the question you pointed and the requirement is a bit different here.
comment on: http://stackoverflow.com/q/50459119
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87843286
comment on: http://stackoverflow.com/q/50409408
type: QuestionComment
score: 0
has text: @Jeronimo, yep this code works just fine if the time format is dd/mm/yy. But if I change it to dd/mm/yy hh:mm:ss this error pops out..
type: Comment

http://stackoverflow.com/a/50393121
answers question: http://stackoverflow.com/q/50392646
has body: Looks like you have a higher version of requests than needed for awsebcli. Try installing the lower version if that works for you: pip install requests==2.9.1
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87803321
has comment: http://stackoverflow.com/comment/87804581
type: Answer

http://stackoverflow.com/comment/87949045
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50464140
has text: Yeah, but I don't what should be changed in current() function to get a single array. I used for loop to vary Vpv and get corresponding values for Ipv. Then I want to make an array of those Ipv values. To do this I wrote this current function. Can anyone suggest a different way to do this?

http://stackoverflow.com/a/50459066
accepted answer of: http://stackoverflow.com/q/50439037
has comment: http://stackoverflow.com/comment/87962533
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87950944
downvote count: 0
type: AcceptedAnswer
has body: evalf(subs=...) tries to avoid loss of significance that can happen from naive substitution. For example &gt;&gt;&gt; (x + y - z).subs({x: 1e100, y: 1, z: 1e100}) 0 &gt;&gt;&gt; (x + y - z).evalf(subs={x: 1e100, y: 1, z: 1e100}) 1.00000000000000 Naive substitution evaluates 1e100 + 1 - 1e100, which loses the 1 because the default precision, 15 digits, is not enough to keep that information. With evalf(subs=...) the expression is run through the evalf algorithm, which is careful about issues like this where significance can be lost. The subs dictionary tells the evalf algorithms which symbols should be replaced with numbers when they are encountered. You can see the source of evalf.py if you are interested in the nitty-gritty details.
answers question: http://stackoverflow.com/q/50439037
type: Answer

http://stackoverflow.com/a/50500004
type: Answer
has comment: http://stackoverflow.com/comment/88041600
answers question: http://stackoverflow.com/q/50499340
downvote count: 0
score: 21
upvote count: 21
has comment: http://stackoverflow.com/comment/117237849
has body: This can be done by building a custom decorator that calls the click.option decorator multiple times after translating the given data structure into click equivalents. Code: import click def options_from_db(options): map_to_types = dict( array=str, number=float, string=str, ) def decorator(f): for opt_params in reversed(options): param_decls = ( '-' + opt_params['short'], '--' + opt_params['long'], opt_params['name']) attrs = dict( required=opt_params['required'], type=map_to_types.get( opt_params['type'], opt_params['type']) ) if opt_params['type'] == 'array': attrs['cls'] = OptionEatAll attrs['nargs'] = -1 click.option(*param_decls, **attrs)(f) return f return decorator Using the options_from_db decorator: To use the new decorator, decorate the command, and pass the option data from the db like: @options_from_db(run_options) def command(*args, **kwargs): .... How does this work? The @click.option() decorator is, like all decorators, a function. In this case it annotates the decorated function, and returns the same function. So we can simply call it multiple times to annotate our decorated function. Note: your array parameter violates the click requirement to not allow nargs &lt; 0 on options. But there is another answer that enables this, and this answer uses the code from there. Code from other answer: class OptionEatAll(click.Option): def __init__(self, *args, **kwargs): self.save_other_options = kwargs.pop('save_other_options', True) nargs = kwargs.pop('nargs', -1) assert nargs == -1, 'nargs, if set, must be -1 not {}'.format(nargs) super(OptionEatAll, self).__init__(*args, **kwargs) self._previous_parser_process = None self._eat_all_parser = None def add_to_parser(self, parser, ctx): def parser_process(value, state): # method to hook to the parser.process done = False value = [value] if self.save_other_options: # grab everything up to the next option while state.rargs and not done: for prefix in self._eat_all_parser.prefixes: if state.rargs[0].startswith(prefi…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50499340

http://stackoverflow.com/comment/87890352
comment on: http://stackoverflow.com/a/50437452
type: AnswerComment
has text: @StevenChan, Stack Overflow works best with one question per post. Your new error appears to be quite different from the first one. Please search for that error message—it appears to be common when using TensorFlow on Windows with your GPU. If you are unable to find a solution, please post a new question.
score: 0
type: Comment

http://stackoverflow.com/q/50516074
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: cmd
favorite count: 0
type: Question
tagged with: octoprint
has comment: http://stackoverflow.com/comment/88044936
has comment: http://stackoverflow.com/comment/88047960
has title: Python command is not recognized anymore
tagged with: python
has body: I have installed Python 2.7 on my pc. I have checked the PATH and it is there. The python command in the command prompter was working fine. I have updated the pip through cmd, then installed virtualenv, and then worked a while through cmd. I was working on the octoprint plugin tutorial, but after I run the octoprint serve once, the next time it stops recognizing everything, including python and pip commands. The environmental path is still there, untouched. I have no idea on why it is happening. Someone got anything like that? OS Windows 10 Tried cmd and powershell
has comment: http://stackoverflow.com/comment/88045051

http://stackoverflow.com/comment/87980715
type: Comment
comment on: http://stackoverflow.com/a/50469331
has text: Thanks @4ur0r4 for your tip. How would I incorporate this expression into an expression that removes the dates have been discovered?
type: AnswerComment
score: 0

http://stackoverflow.com/a/50525926
answers question: http://stackoverflow.com/q/50525866
type: AcceptedAnswer
downvote count: 0
score: 6
type: Answer
has body: res = tf.count_nonzero(tf.greater_equal(x, 0.)) # or using tf.greater() if you want to exclude 0. Example: import tensorflow as tf x = tf.random_uniform((10,), -2, 2) res = res = tf.count_nonzero(tf.greater_equal(x, 0.)) with tf.Session() as sess: x_val, res_val = sess.run([x, res]) print(x_val) # [-1.5928602 - 0.95617723 1.0444398 0.65296173 1.2118826 - 0.69604445 - 1.3821526 1.3174543 - 1.2171302 - 1.5908141] print(res_val) # 4
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50525866

http://stackoverflow.com/q/50444987
has title: Applying autocorr on a bunch of series
upvote count: 1
tagged with: python
has body: I have a dataframe that contains several time series: df.head() 0 1 2 time 0.0 0.365035 0.365035 0.365035 1.0 0.349999 0.349999 0.349999 2.0 0.340998 0.340998 0.340998 3.0 0.333877 0.333877 0.333877 4.0 0.326411 0.326411 0.326411 Now I would like to compute for each of these the std and autocorr. I know that I can do it individually: df[0].aggregate(['std', 'autocorr']) Out[10]: std 0.081165 autocorr 0.995285 For std, it works: df.unstack().groupby(level=0).aggregate(['std']) Out[11]: std 0 0.081165 1 0.081165 2 0.081165 But when I try to do the same thing for autocorr, I get df.unstack().groupby(level=0).aggregate(['autocorr']) AttributeError: Cannot access callable attribute 'autocorr' of 'SeriesGroupBy' objects, try using the 'apply' method Why is this happening? What's the correct way/workaround?
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50445040
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50445040

http://stackoverflow.com/comment/87838361
has text: Is it what you want that you extend `update_attributes_list` with each iteration of the loop and then update the whole list, including the items already updated with the previous iteration of the loop?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50409408
type: Comment

http://stackoverflow.com/a/50453759
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50451884
upvote count: 3
answers question: http://stackoverflow.com/q/50451884
type: Answer
score: 2
has body: You might consider using lmfit (https://lmfit.github.io/lmfit-py) for this. Lmfit provides a higher-level interface to curve fitting and makes fitting parameters first class python objects. Among other things, this easily allows fixing some parameters, and setting bounds on parameters in a more pythonic manner than what scipy.optimize.curve_fit uses. In particular for your question, lmfit parameters also support using mathematical expressions as constraint expressions for all parameters. To turn your model function piecewise_linear() into an Model for curve-fitting with lmfit you would do something like from lmfit import Model # make a model mymodel = Model(piecewise_linear) # create parameters and set initial values # note that parameters are *named* from the # names of arguments of your model function params = mymodel.make_params(t0=0, t1=1, b=3, m1=2, m2=2) # now, you can place bounds on parameters, maybe like params['b'].min = 0 params['m1'].min = 0 # but what you want is an inequality constraint, so # 1. add a new parameter 'tdiff' # 2. constrain t1 = t0 + tdiff # 3. set a minimum value of 0 for tdiff params.add('tdiff', value=1, min=0) params['t1'].expr = 't0 + tdiff' # now perform the fit result = mymodel.fit(yy, params, t=t) # print out results print(result.fit_report()) You can read in the lmfit docs or on other SO questions how to extract other information from the fit result.
has comment: http://stackoverflow.com/comment/87926405
type: AcceptedAnswer

http://stackoverflow.com/comment/88008349
type: QuestionComment
has text: Names have many different formats, so this is likely to be complicated and produce errors for cases you don't handle properly. This is why forms usually have separate input fields for first name, last name, title, etc.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50497642

http://stackoverflow.com/comment/88050177
comment on: http://stackoverflow.com/a/50518767
score: 0
type: Comment
type: AnswerComment
has text: Works great! Thank you.

http://stackoverflow.com/a/50510075
type: Answer
has comment: http://stackoverflow.com/comment/88061708
has comment: http://stackoverflow.com/comment/88032700
has body: Actually, I don't know the reason for this, but I face the same problem and I know how to pass it. I solve the problem by replacing the "data" in the last line with new numpy array. I mean instead of this line data= data[np.argsort(data[:,0])] replace this two lines code data1 = np.zeros(data.shape) data1 = data[np.argsort(data[:,0])] and finally return the data1.
score: 1
answers question: http://stackoverflow.com/q/50509399
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50509399

http://stackoverflow.com/a/50532588
score: 0
has body: I am not sure, but if I were you I would either use python from windows command line or if launched from git bash I will try winpty python It may be related to this issue
has comment: http://stackoverflow.com/comment/88077609
type: Answer
answers question: http://stackoverflow.com/q/50532332

http://stackoverflow.com/q/50387735
tagged with: image-processing
has comment: http://stackoverflow.com/comment/88434600
favorite count: 0
tagged with: aws-lambda
type: Question
has answer: http://stackoverflow.com/a/50392007
accepted answer: http://stackoverflow.com/a/50392007
upvote count: 2
has comment: http://stackoverflow.com/comment/87791855
has comment: http://stackoverflow.com/comment/87791828
tagged with: python
tagged with: amazon-web-services
has title: Classify images on basics of similarity
has body: I have 30 ,40 pictures of humans , Which I want to get in Python code . And make group of similar pics . Like 5 pic of john and 10 of peter . like this . I am new in Image processing thing. So my question is which algo is best for this . And I want to do this on AWS lambda function . Any help would be highly appreciated. P.S (Its my first ever task in this field. Kindly ignore mistakes of tell me to improve them Thanks)
type: AnsweredQuestion
score: 0
tagged with: classification
downvote count: 2
answer count: 1

http://stackoverflow.com/q/50523055
tagged with: hadoop
has comment: http://stackoverflow.com/comment/88073649
score: 0
has comment: http://stackoverflow.com/comment/88064986
has comment: http://stackoverflow.com/comment/88065791
answer count: 0
tagged with: apache-spark
has title: Why my simple Spark application works so slow?
has body: I am trying to count the frequent item sets generated by FP growth of mllib using Spark API. My Spark is version 1.5.1. The following is my code: #!/usr/bin/python from pyspark.mllib.fpm import FPGrowth from pyspark import SparkContext,SparkConf from pyspark import HiveContext import os os.environ['PYSPARK_PYTHON']='/usr/bin/python' appName = "FP_growth" sc = SparkContext() sql_context = HiveContext(sc) def read_spu(prod):#prod_code): sql = """ select t.orderno_nosplit, t.prod_code, t.item_code, sum(t.item_qty) as item_qty from ioc_fdm.fdm_dwr_ioc_fcs_pk_spu_item_f_chain t where t.prod_code='%s' group by t.prod_code, t.orderno_nosplit, t.item_code """%prod spu_result = sql_context.sql(sql) return spu_result.cache() if __name__ == '__main__': spu=read_spu('6727780') conf=0.7 trans=spu.rdd.repartition(100).map(lambda x: (x[0],x[2])).groupByKey().mapValues(list).values().cache() model = FPGrowth.train(trans, 0.01, 100) freq_count = model.freqItemsets().count() print 'freq_count:',freq_count sc.stop() The input data are read from Hadoop, and the data is not very large, only about 20000 rows. However, the script works very very slow in the stage of .count. I don't know why. From the performance, it seems it is because of data skew. But the output data is not large(only about 100KB per task ). The cluster has 8 nodes of 320 cores and 1.56 T total memory (not only one user). My spark-submit script is spark-submit --master yarn-cluster --executor-memory 30g --num-executors 20 --executor-cores 5 FP_growth.py The attachments are the screen prints of performance when running: Resource used Active Stages Tasks
has comment: http://stackoverflow.com/comment/88085309
type: Question
has comment: http://stackoverflow.com/comment/88061219
has comment: http://stackoverflow.com/comment/88076995
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88081625
tagged with: pyspark
has comment: http://stackoverflow.com/comment/88072737
tagged with: python
has comment: http://stackoverflow.com/comment/88161395

http://stackoverflow.com/comment/87902387
score: 0
has text: Can you write a math library too?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50444202

http://stackoverflow.com/comment/88047760
comment on: http://stackoverflow.com/q/50517467
type: Comment
type: QuestionComment
score: 0
has text: I don't think I can do that. The program may crash, and it would be cool to recover the robot without calling another python script that cleans up and stops the motors.

http://stackoverflow.com/comment/87894406
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50436848
has text: I tried it it caused another typeerror. I only formatted the idfs as Out[14]: [(u'1,800', 7.245417283738939)] and your solution works smoothly :) Thank you again, hope this thread is useful for others too.

http://stackoverflow.com/comment/87982604
comment on: http://stackoverflow.com/q/50484686
score: 0
has text: the problem (I think) is that you are keeping a copy of the original file in variable data, and you aren't updating that when you call the deposit function, so when you call the save function the content of variable data is written out and therefore the deposits are lost.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87872778
type: QuestionComment
has text: Possible duplicate of [error: Unable to find vcvarsall.bat](https://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat)
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50429056

http://stackoverflow.com/comment/88147661
has text: there is no such thing :(
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50508431

http://stackoverflow.com/q/50460325
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87934486
has comment: http://stackoverflow.com/comment/87933929
has title: Sorting the alphanumeric values of a dictionary in python
has answer: http://stackoverflow.com/a/50460703
tagged with: sorting
has answer: http://stackoverflow.com/a/50472839
type: Question
score: 0
answer count: 3
has body: I am trying to sort a dictionary in python which is like below: In this scenario my dictionary has 'ESPN' and 'AAA' are the keys and values are below 'ESPN': [ 'ESPN 90 TO 100_1050', 'ESPN 60 TO 70_1150', 'ESPN 80 TO 90_1250', 'ESPN 90 TO 100_1750', 'ESPN 90 TO 100_900' 'ESPN 90 TO 100_1650', 'ESPN 70 TO 80_1350', 'ESPN 20 TO 30_1450' ] 'AAA': [ 'AAA 90 TO 100_1050', 'AAA 60 TO 70_1150', 'AAA 80 TO 90_1250', 'AAA 90 TO 100_1750', 'AAA 90 TO 100_1650', 'AAA 70 TO 80_1350', 'AAA 20 TO 30_1450' ] I am trying to sort this dictionary in such a way that i want the number after the ESPN and AAA in ascending way and also the number after the underscore. For example like below 'ESPN': [ 'ESPN 20 TO 30_1450', 'ESPN 60 TO 70_1150', 'ESPN 70 TO 80_1350', 'ESPN 80 TO 90_1250', 'ESPN 90 TO 100_900', 'ESPN 90 TO 100_1650', 'ESPN 90 TO 100_1750', ] I am trying regex and sort but i am not able to get it. Would really appreciate if someone could help. I also tried various sorting techniques but i always end up sorting the keys and not the values. Also in most scenarios its not working as expected as when i am having a value as AAA 20 to 30_900 it is not coming in order before AAA 20 TO 30_1450 but after it. TIA
tagged with: python
has comment: http://stackoverflow.com/comment/87934791
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50472839
has answer: http://stackoverflow.com/a/50472777
possible better answer: http://stackoverflow.com/a/50472777

http://stackoverflow.com/q/50387226
has title: 3D Slicer - save content of vtkMRMLImageMetaListNode to textfile with python
has comment: http://stackoverflow.com/comment/87790311
tagged with: python
type: Question
has body: For a python script I need the specific imageID's from a server using openIGTLink. With the Remote Module you can query a List of imageID's, patientnames, modality, etc. which is stored in a vtkMRMLImageMetaListNode. Is there a way to get this List from the ImageMetaListNode and save it in a textfile using python?
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50390771
score: 0

http://stackoverflow.com/q/50510919
type: AnsweredQuestion
has body: If I create a list with an empty dictionary in it, then multiply that list by a number, it seems that instead of adding more dictionaries to the list, python just populates the list with more references to the same dictionary. &gt;&gt;&gt; d = [{}]*3 &gt;&gt;&gt; d[0]["x"] = 43 &gt;&gt;&gt; d [{'x': 43}, {'x': 43}, {'x': 43}] As you can see, adding an element in one of the dictionaries leads to insertion into all of them, which means that there is in fact only one dictionary, with three pointers in d to it. Why is this? What is the best way to add a number of empty dicts to a list in Python?
has comment: http://stackoverflow.com/comment/88034389
score: 1
possible better answer: http://stackoverflow.com/a/50510949
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/88034193
has comment: http://stackoverflow.com/comment/88034211
downvote count: 4
has answer: http://stackoverflow.com/a/50510950
accepted answer: http://stackoverflow.com/a/50510950
type: Question
linked to: http://stackoverflow.com/q/32511394
has comment: http://stackoverflow.com/comment/88034197
answer count: 2
upvote count: 5
duplicate of: http://stackoverflow.com/q/32511394
has answer: http://stackoverflow.com/a/50510949
tagged with: python
favorite count: 0
has title: How to add fixed amount of empty dicts to Python list?

python-mss
type: Tag
tag name: python-mss
tags question: http://stackoverflow.com/q/50511457

http://stackoverflow.com/q/50486422
favorite count: 0
type: Question
has title: Is there a way to use variable from outer function in the inner function body, in Python?
upvote count: 2
has body: The pattern of the code that I try to build is: def OuterFunction(): theVariable = 0 def InnerFunction(): # use theVariable from OuterFunction somehow # the solution is not to use InnerFunction(theVariable) due to the reasons given in the text InnerFunction() My hopes were there is some keyword (like global) or a way to tell the interpreter to use theVariable from the outer method's scope. Why I need it this way: A Python script that we run before has to become module now (the collection of methods). OuterFunction did not exist before and InnerFunction is just an example for a big number of very complex methods that bear an already existing logic. theVariable is just an example for multiple global variables that were used in the script in all of methods that InnerFunction represents. I do not want to change signatures of all methods, that are, by the way, nested. EDIT: Here is the code that crashes for me in every interpreter, with "local variable 'theVariable' referenced before assignment" error (so I could not just reference the variable): def OuterFunction(): theVariable = 5 def InnerFunction(): theVariable = theVariable + 1 print(theVariable) InnerFunction() OuterFunction() EDIT2: Seems trying to change the variable leads to the exception, which gives a wrong description. If InnerFunction() is changed to contain only print(theVariable) statement it works.
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50486507
score: 2
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/50487037
has comment: http://stackoverflow.com/comment/87985686
accepted answer: http://stackoverflow.com/a/50486537
has answer: http://stackoverflow.com/a/50487037
tagged with: ironpython
has answer: http://stackoverflow.com/a/50486537

http://stackoverflow.com/q/50439951
upvote count: 1
has body: Im working recycle django polls app tutorial I've created Question model which contains authorized field, where i store id of users who are authorized to see questions class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') users = User.objects.values_list('id','username') authorized = MultiSelectField(choices=users,null=True) def __str__(self): return "{question_text}".format(question_text=self.question_text) I'm having a problem with writing my view, because idk how to use flask import request to get user id to show only those questions which are designed for logged in user class VotesView(generic.ListView): template_name = 'polls/votes.html' model = Question def get_queryset(request): return Question.objects.filter(authorized__icontains=request.user.id) Keep getting error: return Question.objects.filter(authorized__icontains=request.user) AttributeError: 'VotesView' object has no attribute 'user' or This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. Thanks for any help, i stucked for 2 days
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50440035
accepted answer: http://stackoverflow.com/a/50440035
tagged with: django
tagged with: python
score: -1
has title: How to use request inside of ViewClass
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87894164
tagged with: django-templates
downvote count: 2

http://stackoverflow.com/a/50489932
has comment: http://stackoverflow.com/comment/87993908
has body: You can use if same number of columns: #create index with df1 = df1.set_index('TargetIndex') df2 = df2.set_index('TargetIndex') #set same columns names for align data df2.columns = df1.columns #replace 0 with NaNs and replace NaNs by df2 df = df1.mask(df1 == 0).combine_first(df2) print (df) Current1 Current2 Current3 TargetIndex 0 'D' 'D' 'G' 0 'A' 'E' 'F' 0 'A' NaN 'A' 1 'A' 'A' 'A' 2 'B' 'E' 'F' 2 'F' 'E' 'B' 3 'G' 'C' 'C' 4 'A' 'B' 'C' If order is important add reset_index for sorting: df1 = df1.reset_index().set_index('TargetIndex') df2 = df2.set_index('TargetIndex') df2.columns = df1.columns[1:] df = (df1.mask(df1 == 0) .combine_first(df2) .sort_values('index') .drop('index', 1) .reset_index() .fillna(0)) print (df) TargetIndex Current1 Current2 Current3 0 0 'D' 'D' 'G' 1 2 'B' 'E' 'F' 2 0 'A' 'E' 'F' 3 1 'A' 'A' 'A' 4 0 'A' 0 'A' 5 3 'G' 'C' 'C' 6 2 'F' 'E' 'B' 7 4 'A' 'B' 'C'
accepted answer of: http://stackoverflow.com/q/50489754
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/50489754
type: Answer

http://stackoverflow.com/comment/89475213
has text: Hey nice I used this right away - wonder if you are considering rewriting this as question and answer separately. I think it would make it clearer for the reader (normally, the code in the question is the one that does NOT work)
comment on: http://stackoverflow.com/q/50536250
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/87802226
score: 0
comment on: http://stackoverflow.com/q/50388325
type: QuestionComment
has text: Looks a lot like a zooming problem to me. If you _zoom horizontally_, what do you see?
type: Comment

http://stackoverflow.com/comment/87975684
has text: Your question is impossible to answer without knowing what `slack_util` and `project` and `story` and `task` are. Please see [mcve].
comment on: http://stackoverflow.com/q/50481242
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/a/50471995
has comment: http://stackoverflow.com/comment/87957835
has comment: http://stackoverflow.com/comment/87958218
has body: You could try this approach : n = 3 sorted_dict_list = sorted(category.items(), key = lambda x:x[1], reverse = True) last_value = sorted_dict_list[0][1] for key, value in sorted_dict_list: if (value == last_value - n): break print("{},{}".format(value, key))
has comment: http://stackoverflow.com/comment/87958024
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87958555
answers question: http://stackoverflow.com/q/50471957
has comment: http://stackoverflow.com/comment/87958123
has comment: http://stackoverflow.com/comment/87957920

newrelic
tag name: newrelic
type: Tag
tags question: http://stackoverflow.com/q/50386865

http://stackoverflow.com/a/50480553
answers question: http://stackoverflow.com/q/50477206
has comment: http://stackoverflow.com/comment/88007186
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90224606
has body: You should use tf.get_variable('MyVariableName') (as you did in your example that works), not tf.get_variable('MyVariableName:0') which is the output of the variable operator, i.e its value (and the name of the tensor you will get back by calling get_variable).

http://stackoverflow.com/comment/87944405
comment on: http://stackoverflow.com/a/50465216
score: 0
type: Comment
has text: what if I want to make them in the same order as df1 ?
type: AnswerComment

http://stackoverflow.com/q/50430328
has answer: http://stackoverflow.com/a/50430553
accepted answer: http://stackoverflow.com/a/50430553
score: 1
has title: Python's sh module - is it at all possible for a script to request input?
has comment: http://stackoverflow.com/comment/87875710
type: Question
has comment: http://stackoverflow.com/comment/87875547
answer count: 2
has comment: http://stackoverflow.com/comment/87875479
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50430419
possible better answer: http://stackoverflow.com/a/50430419
has comment: http://stackoverflow.com/comment/87875297
tagged with: python
has comment: http://stackoverflow.com/comment/87875234
has body: Using Python's sh, I am running 3rd party shell script that requests my input (not that it matters much, but to be precise, I'm running an Ansible2 playbook with the --step option) As an oversimplification of what is happening, I built a simple bash script that requests an input. I believe that if make this simple example work I can make the original case work too. So please consider this bash script hello.sh: #!/bin/bash echo "Please input your name and press Enter:" read name echo "Hello $name" I can run it from python using sh module, but it fails to receive my input... import errno import sh cmd = sh.Command('./hello.sh') for line in cmd(_iter=True, _iter_noblock=True): if line == errno.EWOULDBLOCK: pass else: print(line) How could I make this work?
tagged with: sh
favorite count: 0
has comment: http://stackoverflow.com/comment/87875656
type: AnsweredQuestion

http://stackoverflow.com/comment/88060168
score: 0
comment on: http://stackoverflow.com/a/50523928
type: Comment
has text: Thank you. I tried to solve it myself with map, but couldn't figure out that it doesn't work due to python3
type: AnswerComment

http://stackoverflow.com/q/50461985
has answer: http://stackoverflow.com/a/50462028
linked to: http://stackoverflow.com/q/41369408
tagged with: loops
possible better answer: http://stackoverflow.com/a/50462031
has answer: http://stackoverflow.com/a/50462070
downvote count: 1
accepted answer: http://stackoverflow.com/a/50462070
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/423379
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50462031
has title: Reassigning value to a variable inside a function in python
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/19158339
has body: I want to run an infinite loop and at every 100th loop i want to print. If I do this : it works perfectly, delay=0 while 1: delay=delay+1 print(delay) if delay&gt;100: delay=0 print('100th time') However if I put my if statement in a function it gives error: delay=0 def foo(): if delay&gt;100: delay=0 print('100th time') while 1: delay=delay+1 print(delay) foo() The error is : UnboundLocalError: local variable 'delay' referenced before assignment. Is there anyway I can do the reassignment in a function? Putting the entire thing in my while loop would be problematic for me.
answer count: 3

http://stackoverflow.com/q/50494617
score: -1
linked to: http://stackoverflow.com/q/24768455
has comment: http://stackoverflow.com/comment/88002142
downvote count: 2
has comment: http://stackoverflow.com/comment/88002191
has comment: http://stackoverflow.com/comment/88020204
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88002189
has answer: http://stackoverflow.com/a/50495153
favorite count: 0
has comment: http://stackoverflow.com/comment/88044870
type: Question
has body: I am trying to complete an ATM program using GUI in Python. Problem: At the start, my program generates a window of Tkinter that takes PIN as input from entry widgets using 0-9 buttons.Entry button takes Entry (root, textvariable=text_Input) while text_input=StringVar() program compares the entered PIN with the data available in the files. If PIN matches, my program goes to another function through Enter button, destroys the previous root and opens a new one. Here I need to enter some amount to withdraw or deposit. I am using Entry widget here again by doing inp= StringVar() Entry (root1, textvarible=inp) I used withdraw button which sends this (inp) to withdraw function. When I print that (inp), it gives PY_Var16, PY_Var22.
tagged with: tkinter
type: UnansweredQuestion
has title: Double entry widgets in tkinter
tagged with: python

http://stackoverflow.com/a/50469763
has body: You need to transpose the feature matrix. The reason of this is that all scikit-learn functions are expecting a matrix X as input where the rows are the subjects(samples) and the columns are the `features(variables)?. From the documentation: So, transpose the data using numpy as a fast way: import numpy as np features = np.array(features) X = features.T clf.fit(X,....)
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/50460115
type: Answer
answers question: http://stackoverflow.com/q/50460115

http://stackoverflow.com/comment/87842118
type: AnswerComment
has text: @user3446905 yes it gets the data. Then: the line means the tuple-of-tuple `(target, (span, text))` is converted to tuple `(target, text)`.
type: Comment
comment on: http://stackoverflow.com/a/50410218
score: 0

http://stackoverflow.com/q/50461832
score: 1
tagged with: python
has title: how to input string in console and display in tkinter
favorite count: 0
type: Question
tagged with: tkinter
has body: How to input a string in console and display it in a window using tkinter in python? i want to store a string input from the console,not the entry widget and want to display it in the window created using tkinter thank you in advance :)
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50461924
accepted answer: http://stackoverflow.com/a/50461924
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/q/50518671
has answer: http://stackoverflow.com/a/50519447
tagged with: python
accepted answer: http://stackoverflow.com/a/50518961
answer count: 4
has body: I have a list of values (the order of the list matters): lst = [7, 5, 3, 4, 6, 4, 7] My goal is to find the most important loss. For example, in the list above the most important loss is 4, because 7 - 3 = 4. How can I iterate a list, so that if lst[x] &gt; lst[x + 1] I go on to the next one? In other words, I am looking for the largest difference between a larger element and a smaller element that comes later in the list.
upvote count: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50518961
has answer: http://stackoverflow.com/a/50518897
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50518853
has title: Iteration and comparison in python list
downvote count: 5
tagged with: algorithm
has answer: http://stackoverflow.com/a/50518853
score: -3

http://stackoverflow.com/q/50518008
has body: I am trying to data scrape from a certain website. I am using Selenium so that I can log myself in, and then start parsing through data. I have 3 main errors: Last page # not loading properly. here I am loading "1" when it should be "197" and I believe this is happening because of the load associated with the website element 'test' xpath not being found properly. I commented out in last for loop. selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[1]/div[@class='col-lg-3 col-sm-3 result-info' and 2]/span[@class='brand-name' and 1]"} finally, I am trying to click last page to test if that works, but I am getting an error that Element is not found. selenium.common.exceptions.ElementNotVisibleException: Message: element not visible This is my code import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException url = "https://marketplace.refersion.com/" username = "jupoxar@b2bx.net" password = "testpass123" driver = webdriver.Chrome("/Users/xxx/Downloads/chromedriver") if __name__ == "__main__": driver.get(url) driver.find_element_by_xpath("/html/body/div[@class='wrapper']/div[@class='top-block']/header[@class='header clearfix']/div[@class='login-button']/a[@class='login-link']").click() driver.find_element_by_id("email").send_keys(username) # enters the username in textbox driver.find_element_by_xpath("/html/body/div[@id='app']/div[@class='top-block']/div[@class='row']/div[@class='col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3 main-section']/div[@class='main-section-content']/div/form[@class='form-horizontal']/div[@class='form-group ']/div[@class='col-xs-12 col-sm-10 col-sm-offset-1 input-group inp…
accepted answer: http://stackoverflow.com/a/50521627
has title: Selenium load time errors - looking for possible workaround
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/50521627
type: Question

http://stackoverflow.com/a/50433274
has comment: http://stackoverflow.com/comment/95050649
downvote count: 5
has comment: http://stackoverflow.com/comment/95010936
upvote count: 3
has body: This is controlled by you as the user. Is you use the native training API, then this is controlled by num_boost_round (default is 10) see the docs here: num_boost_round (int) – Number of boosting iterations. If you use the sklearn API, then this is controlled by n_estimators (default is 100) see the doc here: n_estimators : int Number of boosted trees to fit. The only caveat is that this is the maximum number of trees to fit the fitting can stop if you set up early stopping criterion. I'm not sure if you use that.
type: Answer
answers question: http://stackoverflow.com/q/50426248
has comment: http://stackoverflow.com/comment/92567906
has comment: http://stackoverflow.com/comment/95020417
score: -2

http://stackoverflow.com/comment/87886498
has text: Try to run your code on my example. With your code I get `{'bob': 6, 'zac': 5}`. That is, the counter does not reset for each user. While @Dave did not explain what he is counting, I would imagine this is not what OP would want.
score: 0
comment on: http://stackoverflow.com/a/50435813
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87808783
type: AnswerComment
has text: @CyrilleMODIANO Probably yes, although it's possible you're missing a `.loc` in the middle (you didn't provide sample data, so it's hard to check it). In any case, you should use the other answer - loops should be avoided when using Pandas.
comment on: http://stackoverflow.com/a/50396464
type: Comment
score: 0

http://stackoverflow.com/a/50509434
answers question: http://stackoverflow.com/q/50509017
score: 21
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50509017
upvote count: 21
downvote count: 0
type: Answer
has body: Big byte-order is like the usual decimal notation, but in base 256: 230 * 256**3 + 4 * 256**2 + 0 * 256**1 + 0 * 256**0 = 3859021824 just like 1234 = 1 * 10**3 + 2 * 10**2 + 3 * 10**1 + 4 * 10**0 For little byte-order, the order is reversed: 0 * 256**3 + 0 * 256**2 + 4 * 256**1 + 230 = 1254

http://stackoverflow.com/a/50402920
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50402816
has comment: http://stackoverflow.com/comment/87821657
has comment: http://stackoverflow.com/comment/87821872
type: Answer
has body: The tricky part for you is to make sure you run your other thread smoothly. I suggest doing it in two steps Change the threads around so that the other stuff is started in a background thread. Then switch to gunicorn, you can start the background thread using post_worker_init server hook. Your thread is not really needed here. You can just immediately switch to gunicorn. Just install pip install gunicorn and move out the app to e.g. server.py. This is very important. from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'hello' Now you can run it without threads like so FLASK_APP=server.py flask run. Once you have it at this point you can switch to a production WSGI such as gunicorn. Just launch it like this instead. gunicorn server:app Once you can run using gunicorn, you can configure it to use multiple threads, and even processes. If your work is IO-bound I recommend using gevent instead.
score: 1

http://stackoverflow.com/q/50417842
type: Question
has comment: http://stackoverflow.com/comment/87851567
accepted answer: http://stackoverflow.com/a/50421735
tagged with: python
tagged with: web-crawler
has answer: http://stackoverflow.com/a/50421735
type: AnsweredQuestion
has body: Having the following spider: import scrapy from final.items import FinalItem class ScrapeMovies(scrapy.Spider): name='final' start_urls = [ 'https://www.trekearth.com/members/page1.htm?sort_by=md' ] def parse(self, response): for row in response.xpath('//table[@class="member-table"]//tr[position() &gt; 1]'): item = FinalItem() item['name'] = row.xpath('./td[2]//a/text()').extract_first() website = row.xpath('./td[2]//a/@href/text()').extract_first() request = scrapy.Request(website, callback=self.parse_page2) yield request def parse_page2(self, response): request.meta['item'] = item item['travelog'] = response.xpath('string(//div[@class="statistics-btm"]/ul//li[position()=4]/a)').extract_first() yield item # next_page=response.xpath('//div[@class="page-nav-btm"]/ul/li[last()]/a/@href').extract_first() # if next_page is not None: # next_page=response.urljoin(next_page) # yield scrapy.Request(next_page, callback=self.parse) I have a table i want to scrape name (and other informations as well) from this table and then follow the link to each of the users profile and then gather some data from those profiles and then merge it into a single item. Then i want to return to the main table and go to a next page of it till the end (final part of the code is responsible for that, it was commented out for convenience). Code i wrote does not work properly. Error i have is: TypeError: Request url must be str or unicode, got NoneType: How to fix this? How to make it to properly crawl all of the data?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87851501
has title: Following crawled links
tagged with: web-scraping
tagged with: scrapy

ladon
tags question: http://stackoverflow.com/q/50419987
tag name: ladon
type: Tag

deconvolution
type: Tag
tags question: http://stackoverflow.com/q/50425044
tags question: http://stackoverflow.com/q/50412204
tags question: http://stackoverflow.com/q/50426661
tag name: deconvolution

http://stackoverflow.com/a/50509985
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50507474
accepted answer of: http://stackoverflow.com/q/50507474
type: Answer
has body: In your make_label function you use y for both the label text and the row number, so when the label is 5 it's going to be on the fifth row. In contradiction, in your matrix variable the first row actually does contain the labels with the highest number. You can see this by changing one of the labels: matrix[1][1].config(text='test') which, unintuitively, produces this: To get the grid of the GUI in line with the matrix you can make a small change in creating the widgets: # Helper function to create a label def make_label(x, y, t): label_box = 'box' + str(t) l = Label(frame1, width=5, relief='solid', text=label_box) l.grid(column=x, row=y) return l # Using list comprehension to create 2d list matrix = [[make_label(x, y, t) for x in range(width)] for (y, t) in enumerate(height)] Which produces this:

http://stackoverflow.com/comment/87867823
has text: Try checking the logs.They could provide you with insights into the problem.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50426462

http://stackoverflow.com/a/50537849
downvote count: 0
type: Answer
has body: The variable x is an object of the class, not the class itself. You need to do: x = MyClass x.myMethod = ClassFun2 Notice that I didn't put () after MyClass. That returns the class itself, it doesn't return an instance of the class. Then you need to create an instance to execute the method: y = MyClass() y.myMethod(2)
answers question: http://stackoverflow.com/q/50537781
score: 2
accepted answer of: http://stackoverflow.com/q/50537781
upvote count: 2
has comment: http://stackoverflow.com/comment/88087725
type: AcceptedAnswer

http://stackoverflow.com/a/50386810
has body: df.columns is of type pandas.indexes.base.Index which is why you are getting the TypeError. If you convert it to a list, then you can update (rename) using the slice, and set df.columns to that updated list. This works for me: lst = list(df.columns) lst[1::3] = ['someName']*len(lst[1::3]) df.columns = lst or to have unique new column names (as @jezrael pointed out it might not be recommended to use the same name): lst = list(df.columns) lst[1::3] = ['someName{}'.format(x) for x in range(len(lst[1::3]))] df.columns = lst
score: 1
answers question: http://stackoverflow.com/q/50386509
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/a/50540584
has body: I don't think there is a strict limit to only two incoming arguments, in metrics.py the function is just three incoming arguments, but k selects the default value of 5. def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5): return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k), axis=-1)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50539213

http://stackoverflow.com/q/50410037
upvote count: 13
score: 13
tagged with: constraints
has title: Multiple Linear Regression with specific constraint on each coefficients on Python
has comment: http://stackoverflow.com/comment/87835687
tagged with: linear-regression
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/68715162
has body: I am currently running multiple linear regression on a dataset. At first, I didn't realize I needed to put constraints over my weights; as a matter of fact, I need to have specific positive &amp; negative weights. To be more precise, I am doing a scoring system and this is why some of my variables should have a positive or negative impact on the note. Yet, when running my model, the results do not fit what I am expecting, some of my 'positive' variables get negative coefficients and vice versa. As an example, let's suppose my model is : y = W0*x0 + W1*x1 + W2*x2 Where x2 is a 'positive' variable, I would like to put a constraint over W2 to be positive ! I have been looking around a lot about this issue but I've not found anything about constraints on specific weights/coefficients, all that I've found is about setting all coefficients positive or summing them to one. I am working on Python using the ScikitLearn packages. This is how I get my best model : def ridge(Xtrain, Xtest, Ytrain, Ytest, position): param_grid={'alpha':[0.01 , 0.1, 1, 10, 50, 100, 1000]} gs = grid_search.GridSearchCV(Ridge(), param_grid=param_grid, n_jobs=-1, cv=3) gs.fit(Xtrain, Ytrain) hatytrain = gs.predict(Xtrain) hatytest = gs.predict(Xtest) Any idea of how I could assign a constraint on the coefficient of a specific variable ? Probably going to be burdensome to define each constraint but I have no idea how to do otherwise.
tagged with: machine-learning
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50451354
favorite count: 0
has comment: http://stackoverflow.com/comment/87839430
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50463037
has body: replace: myfun = lambda x:2*x with: def myfun(x): """doubles the input parameter""" return 2 * x
type: Answer
answers question: http://stackoverflow.com/q/50462908
has comment: http://stackoverflow.com/comment/87939556
accepted answer of: http://stackoverflow.com/q/50462908
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87939636

http://stackoverflow.com/a/50473548
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87961356
has comment: http://stackoverflow.com/comment/87962077
has comment: http://stackoverflow.com/comment/87961313
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50473499
has body: You can use zip L= [[[4.0, 4.0], [1.0, 2.0, 3.0]], [[4.0, 5.0], [1.0]]] new_l = [max(c for b in i for c in b) for i in zip(*L)] Output: [5.0, 3.0]
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50473499
has comment: http://stackoverflow.com/comment/87962052

http://stackoverflow.com/a/59372259
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/108378710
upvote count: 3
answers question: http://stackoverflow.com/q/50524915
has body: I think you need this import nltk from nltk.tokenize import word_tokenize
downvote count: 1

http://stackoverflow.com/q/50415184
has body: I am using Flask/SQLAlchemy to create a web app with a map in it, so naturally I'm using a PostGIS database. The geom column requires an ST_Transform and somehow I need to turn this column and all others into JSON. The general structure of the database is: from app import login, db from datetime import datetime from geoalchemy2 import Geometry from time import time from flask import current_app from sqlalchemy import func class Streets(db.Model): id = db.Column(db.Integer, primary_key=True) street = db.Column(db.String(50)) geom = db.Column(Geometry(geometry_type='LINESTRING')) def to_dict(self): data = { 'id': self.id, 'street': self.street, '_geom': func.ST_AsGeoJSON(func.ST_Transform(self.geom, 4326)) } return data My api route turns this result into an api: return jsonify(Streets.query.get_or_404(id).to_dict()) But I keep getting this error: NameError: name 'ST_AsGeoJSON' is not defined I also tried to create my _geom value like this: data['_geom'] = db.session.query(func.ST_AsGeoJSON(func.ST_Transform(self.geom, 4326))) The error message is: TypeError: Object of type 'BaseQuery' is not JSON serializable Finally, I tried an api route like this: data = Streets.to_dict( db.session.query( func.ST_AsGeoJSON( func.ST_Transform( Streets.geom, 4326 ) ) ) .filter(Streets.id==id)) return jsonify(data) And I get a different error: AttributeError: 'BaseQuery' object has no attribute 'id' If I run this in flask shell it works: streets = db.session.query( Streets.id, Streets.street, func.ST_AsGeoJSON(func.ST_Transform(Streets.geom, 4326))) How can I perform ST_Transform and get JSON to my api route? UPDATE I found this in the SQLALchemy documentation that got me some progress: "orm.column_property() can be used to map a SQL expression". So I tried adding this to my class Streets(db.Model): coords = db.column_property(func.ST_AsGeoJSON(func.ST_Transform(geom, 4326))) Then I add it to data like this: def to_dict(self): data = { 'id': self.id, 'street': self.street, 'coords': s…
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/77546878
tagged with: python
score: 4
tagged with: sqlalchemy
upvote count: 4
answer count: 2
possible better answer: http://stackoverflow.com/a/77546878
accepted answer: http://stackoverflow.com/a/50445083
downvote count: 0
has answer: http://stackoverflow.com/a/50445083
tagged with: flask
favorite count: 0
type: Question
tagged with: postgresql
has title: Flask-SQLAlchemy ORM/GeoAlchemy2 results to a dictionary and ultimately JSON
type: AnsweredQuestion

http://stackoverflow.com/a/50449903
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: @decorator.oauth_aware def get_google_client_credential_tasks(self): if decorator_google_client.has_credentials(): http = decorator.http() service_tasks = build('tasks', 'v1', http=http) temp_str = '' tasklists = service_tasks.tasklists().list().execute(http=http) for tasklist in tasklists[0]['items']: temp_str += tasklist['title'] self.response.write(temp_str) else: url = decorator_google_client.authorize_url() self.redirect(url)
accepted answer of: http://stackoverflow.com/q/50427026
type: Answer
answers question: http://stackoverflow.com/q/50427026

http://stackoverflow.com/q/50422929
has body: I updated python (from 3.5 to 3.6) and notice that all modules i installed for 3.5 are now no more available for importing in 3.6. When i try to import PIL in 3.6 for example there is: &gt;&gt;&gt; import PIL Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import PIL ModuleNotFoundError: No module named 'PIL' &gt;&gt;&gt; How can i use modules in 3.5 which i imported while in version 3.5? Do i have to change some path after updating python or install the modules again every time i update?
score: 2
tagged with: importerror
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/90041676
has comment: http://stackoverflow.com/comment/87860650
has comment: http://stackoverflow.com/comment/87860687
has comment: http://stackoverflow.com/comment/87862861
has comment: http://stackoverflow.com/comment/87860707
favorite count: 0
type: Question
has title: After updating python, do i have to install modules again?
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87861056
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/23832722

http://stackoverflow.com/comment/88073617
score: 0
has text: See something like this answer: https://stackoverflow.com/questions/34914324/use-colormaps-along-with-matplotlib-cycler basically, change the color cycler to the colors in a colormap with as many colors as you want. You might look at the `tab20` colormap as one option
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50530617

apply
tags question: http://stackoverflow.com/q/50410625
tags question: http://stackoverflow.com/q/50471703
tags question: http://stackoverflow.com/q/50421196
tag name: apply
tags question: http://stackoverflow.com/q/50478331
type: Tag
tags question: http://stackoverflow.com/q/50502150
tags question: http://stackoverflow.com/q/50449417
tags question: http://stackoverflow.com/q/50500415

http://stackoverflow.com/comment/87890096
score: 1
comment on: http://stackoverflow.com/q/50426390
type: QuestionComment
type: Comment
has text: Hi, sorry to get you confused. the idea was simply to have some code which worked for Gtk2 and ask how do I get it working with Gtk3? … there is no falling back to 2.x.

http://stackoverflow.com/a/50484284
type: Answer
score: 12
upvote count: 12
answers question: http://stackoverflow.com/q/50483235
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50483235
has body: Ok, here is a working solution (at least on windows 10 &amp; python3.7): Go here: https://www.lfd.uci.edu/~gohlke/pythonlibs/#spacy Search SpaCy and download the correct wheels for your platform :- preshed cymem murmurhash thinc spacy Then you need to install them with pip install [wheel] in the above order. If this doesn't work, try installing scipy and maybe even numpy from the same site.
has comment: http://stackoverflow.com/comment/113343383

http://stackoverflow.com/q/50472226
has body: Hey I'm searching for a pandas solution of getting result from groups of a DataFrame, and then applying these results to the complete dataframe. Here is a minimal example of what I'm doing right now, but I dont find it very good. import pandas as np data = [[0.0, 2.4285714285714286, '0', 'mica02', 'd2o'], [10.0, 1.4285714285714286, '225', 'mica02', 'd2o'], [13.0, 1.0833333333333333, '225', 'mica02', 'd2o'], [954.0, 5.420454545454546, '225', 'mica02', 'air'], [937.0, 5.162534435261708, '225', 'mica02', 'air'], [75.0, 0.4966887417218543, '225', 'mica02', 'h2o'], [78.0, 0.49523809523809526, '225', 'mica02', 'h2o'], [80.0, 0.49323809523809526, '225', 'mica01', 'h2o'], ] df0 = pd.DataFrame(data, columns=['basesubed', 'normalized', 'rot', 'm0', 'm1']) df0 gives and this is a cut down version of what I'm working with: basesubed normalized rot m0 m1 0 0.0 2.428571 0 mica02 d2o 1 10.0 1.428571 225 mica02 d2o 2 13.0 1.083333 225 mica02 d2o 3 954.0 5.420455 225 mica02 air 4 937.0 5.162534 225 mica02 air 5 75.0 0.496689 225 mica02 h2o 6 78.0 0.495238 225 mica02 h2o 7 80.0 0.493238 225 mica01 h2o Now, group the DataFrame by m0 and rot metadata and calculate something from the group. Lets say median for now: mask = (df0.m1 == 'h2o') gdf = df0[mask].groupby(['m0', 'rot']).median() gdf basesubed normalized basesubed_n normalized_n m0 rot mica01 225 80.0 0.493238 1.0 1.0 mica02 225 76.5 0.495963 1.0 1.0 Now I want to subtract the result from my original DataFrame, but only when the multiindex of the gdf matches the metadata in df0 so I do: for i in range(len(gdf.index.values)): mask = ((df0.m0 == gdf.index.values[i][0]) &amp; (df0.rot == gdf.index.values[i][1])) df0.loc[mask, 'basesubed_n'] = df0[mask]['basesubed'] / gdf.loc[gdf.index.values[i]].basesubed df0.loc[mask, 'normalized_n'] = df0[mask]['normalized'] / gdf.loc[gdf.index.values[i]].normalized df0 and I get: basesubed normalized rot m0 m1 basesubed_n normalized_n 0 0.0 2.428571 0 mica02 d2o NaN NaN 1 10.0 1.428571 225 mica02…
has title: Transform pandas DataFrame with group results
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50473487
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50473487
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/50462200
type: Question
linked to: http://stackoverflow.com/q/50483687
tagged with: python
tagged with: kivy
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
has body: So I have two files: returnStation.py returnStationLayout.kv What i am trying to achieve: There are two screens. One is a number pad. Once you keyed in your number and hit enter, it brings you to the next screen. And I hope the other screen shows the number you just keyed in. Issue i am facing: I tried to access the id of the label i am trying to change to show the number but it is not working :/ I am not getting any error in the terminal. Could i be accessing the values in the wrong way? If so, please advise how best to go about it in a two screen. Appreciate any help! This is the file - returnStation.py: How i attempted to change the label is through getPoints() import kivy from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.gridlayout import GridLayout class ScreenOne(Screen): pass class ScreenTwo(Screen): pass class PhoneGridLayout(GridLayout): def backspace(self, textString): newTextString = textString[0:-1] self.display.text = newTextString def getPoints(self, phoneNumber): st = ScreenTwo() st.ids.memberStatus.text = phoneNumber #THIS IS HOW I ATTEMPTED TO CHANGE THE LABEL class ReturnStationLayoutApp(App): pass mainscreen = ScreenOne() mainlayout = PhoneGridLayout() mainscreen.add_widget(mainlayout) if __name__ == '__main__': ReturnStationLayoutApp().run() this is the file - returnStationLayout.kv: The label i am trying to change is all the way at the bottom of this file ScreenManager: id: screen_manager ScreenOne: id: screen_one name: 'menu' manager: 'screen_manager' ScreenTwo: id: screen_two name: 'settings' manager: 'screen_manager' &lt;CustButton@Button&gt;: font_size: 32 &lt;ScreenOne&gt;: PhoneGridLayout: id: numberPad display: entry rows: 5 padding: [300,200] spacing: 10 # Where input is displayed BoxLayout: Label: text: "+65" font_size: 50 size_hint: 0.2, 1 TextInput: id: entry font_size: 50 multiline: False padding: [20, ( self.height - self.line_height ) / 2] BoxLayout: spacin…
possible better answer: http://stackoverflow.com/a/50465941
has title: Label not updating Kivy
accepted answer: http://stackoverflow.com/a/50469911
has answer: http://stackoverflow.com/a/50465941
has answer: http://stackoverflow.com/a/50469911

http://stackoverflow.com/q/50530349
linked to: http://stackoverflow.com/q/28097222
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88072593
duplicate of: http://stackoverflow.com/q/28097222
favorite count: 0
type: Question
tagged with: python-3.x
has title: Pandas, merge 2 dataframes
tagged with: python
tagged with: merge
type: AnsweredQuestion
tagged with: pandas
upvote count: 1
score: 1
has body: I actualy have 2 dataframes one is like: seq1_id seq2_id dN dS Dist1 Dist_brute kingdom seq1 seq2 45 56 23 455 eucaryota seq6 seq9 34 43 34 453 procaryota seq3 seq98 32 34 21 90 Virus seq21 seq87 32 12 35 211 Virus and the other like: seq1_id seq2_id dN dS Dist1 Dist_brute seq1 seq2 45 56 23 455 seq4 seq12 78 45 32 789 seq3 seq98 32 34 21 90 seq21 seq87 32 12 35 211 seq45 seq90 21 23 12 123 seq6 seq9 34 43 34 453 and what I would like to do is to get a new dataframe such: seq1_id seq2_id dN dS Dist1 Dist_brute kingdom seq1 seq2 45 56 23 455 eucaryota seq4 seq12 78 45 32 789 NaN seq3 seq98 32 34 21 90 Virus seq21 seq87 32 12 35 211 Virus seq45 seq90 21 23 12 123 NaN seq6 seq9 34 43 34 453 procaryota Does someone have an idea? Thanks :)
has answer: http://stackoverflow.com/a/50530394
accepted answer: http://stackoverflow.com/a/50530394

http://stackoverflow.com/a/50472071
upvote count: 1
has comment: http://stackoverflow.com/comment/87963723
has comment: http://stackoverflow.com/comment/88010123
has comment: http://stackoverflow.com/comment/88010279
has comment: http://stackoverflow.com/comment/88010219
answers question: http://stackoverflow.com/q/50457828
type: Answer
has comment: http://stackoverflow.com/comment/87965200
accepted answer of: http://stackoverflow.com/q/50457828
score: 1
type: AcceptedAnswer
downvote count: 0
has body: For this you need two things. In first place know where the element is, and you can do it with python-js like this: script = 'return arguments[0].getBoundingClientRect().top + document.documentElement.scrollTop;' posY = driver.execute_script(script, element).split('.')[0] The above combo will return a string that represent the relative position of a element to the top of the document(website) Then you can scroll to the position you want driver.execute_script('window.scrollTo(0, '+ posY +');') This one will move the screen where the element is, some element needs to be waited for, so I would suggest some waiter function of this nature: def waiter(token): # token is whatever you spect to be in the element like str("/") in a date field max_time = 60 #segs driver.switch_to.default_content() while token not in driver.find_element_by_xpath('//*[@Class="important"]'): time.sleep(1) max_time += -1 if max_time == 0: raise Exception('Waited too long') Made myself a small modules with js navigation, because even though selenium is powerfull sometimes it doesn't want to do it's thing on some websites. EDIT: For completeness this snippet makes the element visible: driver.execute_script(“arguments[0].style.visibility = 'visible';”, element) This works because arguments[0] represents the element argument in execute_script

http://stackoverflow.com/comment/88003627
comment on: http://stackoverflow.com/a/50494700
score: 0
type: Comment
has text: @ojunk, Are you sure your dataframes are exactly the minimal example of what you are dealing with? If you do not `reset_index()`, you are ought to get this error. The code works for me. Also, see [this](https://github.com/pandas-dev/pandas/issues/6963)
type: AnswerComment

http://stackoverflow.com/a/50518933
answers question: http://stackoverflow.com/q/50518761
type: Answer
has body: I swear I saw a comment on here asking for the expected output that was posted as soon as I asked the question but I don't see it here anymore. Writing the output made me realize I was thinking of the items in conditions wrong. I wrapped it in a list and now I have a list of dictionaries and it works. {item['label']: {'requiredLevel': item['requiredLevel'], 'preferableLevel': item['preferableLevel'], 'conditions': [{'label': LABEL_REPLACEMENT[condition['label']], 'function': condition['function'], 'valueList': condition.get('valueList',condition.get('value',None))} for condition in item['conditions']]} for item in tempItems}
score: 0

http://stackoverflow.com/comment/100521587
score: 0
comment on: http://stackoverflow.com/q/50484397
type: Comment
type: QuestionComment
has text: In my case both are under D:/Anaconda3/Scripts

http://stackoverflow.com/comment/88059107
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50510090
type: Comment
has text: You don't really need just moving in a curve then, what you need is a path finding algorithm and that can be anywhere from very simple to very complicated. Have a google search for the pac-man path finding algorithm for example.

http://stackoverflow.com/comment/87841794
type: Comment
has text: actually, it is a huge overkill to use many packages for a small project, written by one man. While project grows, it is split in such packages, and every package is developed independently, and has its own vcs repository
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50412823

http://stackoverflow.com/q/50493901
tagged with: arraylist
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50494060
tagged with: list
answer count: 3
score: 1
accepted answer: http://stackoverflow.com/a/50494041
has answer: http://stackoverflow.com/a/50494041
type: Question
has answer: http://stackoverflow.com/a/50494076
has title: Finding calculation value in python list
has body: I have a python list like this. [100, 150, 30, 50, 10, 20, 40] Then I want to find 90 in list above (yes of course not in there), but my expected result are: [50, 40] or [50, 30, 10] How can I achieve that in python or other programming language?
tagged with: arrays
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88001515
has comment: http://stackoverflow.com/comment/88014197
possible better answer: http://stackoverflow.com/a/50494060
favorite count: 0

http://stackoverflow.com/comment/87986093
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50478578
has text: Is there a reference paper for an lstm encoder decoder without the RepeatVector part ? I found only : Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation as a reference Paper for the RepeatVector case

http://stackoverflow.com/a/50425863
downvote count: 0
score: 18
type: Answer
has body: You could do the broadcasting manually (using Tensor.expand()) before the concatenation (using torch.cat()): import torch a = torch.randn(15, 200, 2048) b = torch.randn(1, 200, 2048) repeat_vals = [a.shape[0] // b.shape[0]] + [-1] * (len(b.shape) - 1) # or directly repeat_vals = (15, -1, -1) or (15, 200, 2048) if shapes are known and fixed... res = torch.cat((a, b.expand(*repeat_vals)), dim=-1) print(res.shape) # torch.Size([15, 200, 4096])
upvote count: 18
accepted answer of: http://stackoverflow.com/q/50424167
has comment: http://stackoverflow.com/comment/120047717
answers question: http://stackoverflow.com/q/50424167
type: AcceptedAnswer

http://stackoverflow.com/a/50539043
accepted answer of: http://stackoverflow.com/q/50539010
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50539010
has comment: http://stackoverflow.com/comment/88089989
has comment: http://stackoverflow.com/comment/88089982
has body: I would just change all instances; from a design standpoint this will probably make your life easier in the long run, and won't confuse people who read the code, unlike the alternatives. But to avoid making the same mistake again, you can have a list of acceptable symbols: accept = [iff, jiff] ... if b in accept: ... Now you just need to modify your symbols in one place. If you really want to avoid changing all instances of that if-statement, you can make iff be a special object that overrides __eq__ to return true if the symbol is either iff or jiff: class Sym: def __eq__(self, s): return s in (chr(8801), chr(10231)) iff = Sym() (But this will break if iff is used elsewhere if an actual string is expected.)
score: 0

http://stackoverflow.com/q/50480354
tagged with: python-3.x
type: AnsweredQuestion
has title: How to group same Dictionary values together in Python and Count the Value?
has comment: http://stackoverflow.com/comment/87974094
accepted answer: http://stackoverflow.com/a/50480389
tagged with: python
score: -1
has body: How do you print a dictionary in Python where if the value matches another value in the dictionary, they are printed on the same line? Code: result = {'light':4,'plane':4, 'vehicle':5} print(result) Current Output: {'light': 4, 'plane': 4, 'vehicle': 5} Expected Output: 4 light, plane 5 vehicle How would you also count the frequency of the words as in the expected output? For example, light + plane is 2.
duplicate of: http://stackoverflow.com/q/483666
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50480389
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/483666
type: Question

http://stackoverflow.com/a/50406605
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50405248
has comment: http://stackoverflow.com/comment/87829974
has body: You can try this library(tidyverse) library(ggbeeswarm) d %&gt;% as.tibble() %&gt;% gather(k, v, -Catagory) %&gt;% ggplot(aes(k, v)) + geom_boxplot() + geom_beeswarm() + facet_grid(~Catagory) + theme(axis.text = element_text(angle=45, hjust = 1))
answers question: http://stackoverflow.com/q/50405248
type: AcceptedAnswer

http://stackoverflow.com/comment/88045338
comment on: http://stackoverflow.com/a/50516213
score: 0
type: Comment
type: AnswerComment
has text: you code works but the output result have a blank line after each printed line.

http://stackoverflow.com/comment/88090392
has text: Even though your example involves a DML statement I can't help but wonder if the statement in the [docs](https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions) about DDL statements no longer being auto-committed starting with python 3.6 might be relevant. Check that the `isolation_level` of the connection is the same in the two versions.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50526997
type: QuestionComment

http://stackoverflow.com/comment/87803061
has text: The problem statement is vast, saving to file is just for building Proof of Concept. I changed the code and got it corrected.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50392821
type: Comment

http://stackoverflow.com/comment/87892599
comment on: http://stackoverflow.com/q/50439165
score: 0
type: Comment
type: QuestionComment
has text: Anyway, the problem seems to be related to the `pythoncom` module from the `pywin32` package. Not sure why a web framework would import that, but… Anyway, can you try running something that does an `import pythoncom` twice, and see if that has the same problem? If so, it would probably narrow things down to a much smaller traceback, and also involve a much more popular library (there are lots of `pywin32` experts around to help you, but probably only a handful of people using `dash`).

http://stackoverflow.com/q/50428916
has body: To give a little background, I am coding a genetic algorithm to solve the Traveling Salesman Problem (TSP). In my population, I have an ordered list of paths from shortest to longest (fittest to least fit), and their respective distances, like this: population = [ [[a, b, c, d], [10.12]], [[b, c, a, d], [11.33]], [[d, a, c, b], [11.5]], [[b, a, d, c], [12.07]] ...] After the population is ordered by their fitness, I need to kill half of them randomly, but in such a fashion that the fitter the member, the better their chance of surviving. I've tried using random.choices() and passing a list with chances of probability (bias) into the weights parameter, and my desired size of half the original population as k like this: # returns something like [0.99, 0.75, 0.65, 0.22...] bias_weights = [x / len(population) for x in range(len(population))] random.choices(population, weights=bias_weights, k=len(population) / 2) The problem with the code above is that it produces duplicates in my list, and it's very messy to get rid of them and keep the population size at 50%. I've also tried using the np.random.choices() from the numpy library, but it requires the list that I am passing to be 1D, and the list of weights and biases to add up to 1. Is there any other way to do this?
possible better answer: http://stackoverflow.com/a/50428939
tagged with: traveling-salesman
answer count: 4
favorite count: 0
type: Question
tagged with: numpy
tagged with: python
has answer: http://stackoverflow.com/a/50428939
has answer: http://stackoverflow.com/a/50429089
has answer: http://stackoverflow.com/a/50434957
type: AnsweredQuestion
tagged with: random
linked to: http://stackoverflow.com/q/50221136
downvote count: 0
has title: Choose a random sample from a list with bias in Python
score: 1
tagged with: genetic-algorithm
has answer: http://stackoverflow.com/a/50437920
upvote count: 1
accepted answer: http://stackoverflow.com/a/50437920

http://stackoverflow.com/a/50399491
answers question: http://stackoverflow.com/q/50399374
type: Answer
score: 0
has body: Pretty sure there is no algorithm to convert zip codes to City / State. There is however a database: federalgovernmentzipcodes.us Click on "Free ZipCode Database" and it should download a .csv file to your downloads folder. Then in PowerShell: $all_zip_codes = Import-CSV "C:\path\to\database.csv" $my_excel_sheet = Import-CSV "C:\path\to\my\file.csv" function getCityAndState($zip_code) { // loop through $all_zip_codes and find the data } $output_csv = "C:\path\to\my\output.csv" $obj = new-object psobject $arr = @() foreach($my_row in $my_excel_sheet) { $obj = $my_row; $cityState = getCityAndState($my_row.zipCode) $obj | Add-Member -Name 'City' -Value = $cityState.City $obj | Add-Member -Name 'State' -Value = $cityState.State $arr += $obj } $arr | Export-Csv -NoTypeInformation "$output_csv" I stopped writing the code because you should be able to figure it out based on what I gave you. Import-CSV is going to be your friend here.

http://stackoverflow.com/comment/88019656
type: AnswerComment
has text: Multiplying the norm of two vectors is equivalent to taking the square root of the product of the sum of squares of the vectors. To edit the display, you just need to edit the print statement, other_dicts is the name of the dictionaries you are comparing against.
type: Comment
comment on: http://stackoverflow.com/a/50502261
score: 0

http://stackoverflow.com/comment/87914934
comment on: http://stackoverflow.com/a/50450827
type: AnswerComment
score: 0
type: Comment
has text: This works, thank you!

http://stackoverflow.com/a/50518869
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: At a guess, the import is likely intended from stdlib operator module. But the code is missing the necessary Q objects to use the operator functions in such a fashion. This looks more to me like code written by someone who doesn't know how to use Django ORM very well. Rewrite it like this, no Q nor operator functions are necessary for such a simple query: friends = Friends.objects.filter(user=user.username, friends=view) friends |= Friends.objects.filter(user=view.username, friends=user)
accepted answer of: http://stackoverflow.com/q/50518814
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50518814

http://stackoverflow.com/q/50520608
has answer: http://stackoverflow.com/a/50520825
accepted answer: http://stackoverflow.com/a/50520825
type: AnsweredQuestion
score: 0
has body: I have several tasks for my course regarding Python. I am stuck where to begin. Essentially, they boil down to writing various programs that print the username with the highest count of followers, with ties printing all usernames with the same count in alphanumerical order. The dummy-file in question is named follows.txt and contains the following: andrew fred fred judy andrew fred george judy andrew john george Each line begins with the username and then each name after is the name of who they follow. The main file, however is a lot larger and contains nonalphanumeric characters. EDIT: What would I need to write to bring back the username with the highest count that can also be used on usernames containing characters such as #? I attempted several methods, but met several errors when it came to finding the right way to code what I was attempting to write. user = list() count = () maxCount = () follows = ['andrew fred', 'fred', 'judy andrew fred', 'george judy andrew', 'john george'] along with: with open('follows.txt', 'r') as follows: for line in follows: for word in line: count += 1 word += 1 if count &gt; maxCount: maxCount == count count == 0 user.append(line(0)) elif count == maxCount: user.append(line(0)) With the above code, the program I was using wasn't able to open the text file and so I turned it into something that the program would be able to read, but the code turned into a comment is what I thought should work. This is where I was able to get to.
has answer: http://stackoverflow.com/a/50521864
has comment: http://stackoverflow.com/comment/88053662
has title: Trouble writing a program that counts strings in a line in a file
has comment: http://stackoverflow.com/comment/88053589
has comment: http://stackoverflow.com/comment/88053615
has comment: http://stackoverflow.com/comment/88053732
type: Question
has answer: http://stackoverflow.com/a/50520692
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50520913
has comment: http://stackoverflow.com/comment/88053672
has comment: http://stackoverflow.com/comment/88053638
has answer: http://stackoverflow.com/a/50520687
possible better answer: http://stackoverflow.com/a/50520687

http://stackoverflow.com/q/50534838
has title: Field translation in function GROUP_BY in OPENERP 6.1
tagged with: odoo
has body: I have the following problem, when I do a group_by by date in a view, the months of the year are not translated. How can I show these values in the language I have selected? regards in the view: &lt;filter string="Date" icon="terp-go-year" name="Date" context="{'group_by':'create_date'}"/&gt; in the .py: 'create_date': fields.datetime('Date') OUTPUT: translate group_by error
tagged with: python
has answer: http://stackoverflow.com/a/50570543
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/50570543
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87914066
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50428596
has text: Editing files in place is more than possible - check [this answer](https://stackoverflow.com/a/49734119/7553525) for a couple of ways to do it - but I already gave a link to the OP to see how its done. His main issue is in how he approaches the whole thing.
type: Comment

http://stackoverflow.com/a/50525322
has body: An alternative solution is to work with dictionaries instead of dataframes: v = {'size': 1, 'color': 'red'} match_count = {} fields = df.columns[1:] for k, value in df.to_dict(orient='index').items(): match_count[value['item']] = sum(value[i] == v[i] for i in fields &amp; v.keys()) Result print(match_count) # {2: 1, 3: 2} res = max(match_count.items(), key=lambda x: x[1]) print(res) # (3, 2)
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50521987
type: Answer

http://stackoverflow.com/comment/87976166
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50481481
type: AnswerComment
has text: As I have mentioned in question that I do not have information on data as this error is from log file. The only thing I know about data is that data stored in database is in unicode format.

http://stackoverflow.com/a/63982077
downvote count: 1
has comment: http://stackoverflow.com/comment/129412824
score: 8
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/129858275
has body: do pip install Pillow==0.1.13 since Image is module from PIL
answers question: http://stackoverflow.com/q/50398622
has comment: http://stackoverflow.com/comment/129858798

http://stackoverflow.com/a/50495666
type: Answer
has body: AppEngine standard can not run TensorFlow but AppEngine flexible can. See example here How to run TensorFlow in Google App Engine Flexible Enviroment?
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50483577

http://stackoverflow.com/a/50520100
has comment: http://stackoverflow.com/comment/88061564
accepted answer of: http://stackoverflow.com/q/50519831
has body: I've been working on sockets a lot lately. I don't have a server right now to test your code so I thought I would quickly comment on what I see. You seem to be shutting down the socket (for writing) at the beginning, so your receive statement worked, but your sendall statement fails. def netcat(hostname, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((hostname, port)) s.shutdown(socket.SHUT_WR) &lt;-- WHY IS THIS HERE?
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50519831
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88052798
type: Answer

http://stackoverflow.com/a/50459416
has body: Your error mainly happened here: countnumber=countnumber/10 Note that you are intending to do integer division. Single-slash division in Python 3 is always "float" or "real" division, which yields a float value and a decimal part if necessary. Replace it with double-slash division, which is integer division: countnumber = countnumber // 10. Each time integer division is performed in this case, the rightmost digit is cut. You also have to watch out if your input is 0. The number 0 is considered to be one digit, not zero.
has comment: http://stackoverflow.com/comment/87932117
downvote count: 0
answers question: http://stackoverflow.com/q/50459313
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/87932664
type: Answer
has comment: http://stackoverflow.com/comment/87932134

http://stackoverflow.com/a/50590177
score: 9
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50471802
has body: So the only way I managed to sort this issue was Configure the SSH WITH NO PASSPHRASE. Following steps here. In serverless.yml, I added the following: custom: wsgi: app: app.app packRequirements: false pythonRequirements: dockerizePip: true dockerSsh: true dockerSshSymlink: ~/.ssh Notice I added dockerSshSymlink to report the location of the ssh files on my local machine; ~/.ssh. In requirements.txt, I added my private dependency like this: git+ssh://git@github.com/my_comp/my_repo.git#egg=MyRepo All works.
upvote count: 9
has comment: http://stackoverflow.com/comment/113827952
type: Answer
accepted answer of: http://stackoverflow.com/q/50471802

http://stackoverflow.com/comment/119876557
type: Comment
has text: @jezrael i have this error but i don't understand this, how can i fix this please?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50501889

http://stackoverflow.com/comment/87910014
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50447987
has text: But outside the instance functions, is `class` land. And the point of classes is that it is one meta-level higher than instances. So as a result, they do can not take the `self` into account.

http://stackoverflow.com/a/50455077
accepted answer of: http://stackoverflow.com/q/50448986
type: Answer
answers question: http://stackoverflow.com/q/50448986
has body: I don't see where you're creating a PdfFileMerger object. I don't think you can just import it as merger. What happens if you modify your code to: from PyPDF2 import PdfFileMerger ... for subfolder in os.listdir(parent_folder): merger = PdfFileMerger() if os.path.isdir(parent_folder + subfolder): for file in os.listdir(parent_folder + subfolder): if file.endswith('.pdf'): merger.append(file) merger.write(subfolder +'.pdf') merger.close()
has comment: http://stackoverflow.com/comment/87943432
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87954878
score: 0

http://stackoverflow.com/comment/88002753
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50472580
has text: Was able to solve this using the workfrontapi-plus module for Python. Thanks Craig

http://stackoverflow.com/q/50538415
has comment: http://stackoverflow.com/comment/88088838
tagged with: graph
has comment: http://stackoverflow.com/comment/88183557
answer count: 0
has comment: http://stackoverflow.com/comment/88192035
has body: I am trying to draw a graph like attached in the image Sample Graph here import matplotlib.pyplot as plt import pandas as pd data_set= [ {'date':'2018-05-20','server':'server1','api':'api1','count':4}, {'date':'2018-05-21','server':'server1','api':'api1','count':6}, {'date':'2018-05-22','server':'server1','api':'api1','count':10}, {'date':'2018-05-23','server':'server1','api':'api1','count':10}, {'date':'2018-05-24','server':'server1','api':'api1','count':14}, {'date':'2018-05-20','server':'server1','api':'api2','count':20}, {'date':'2018-05-21','server':'server1','api':'api2','count':22}, {'date':'2018-05-22','server':'server1','api':'api2','count':20}, {'date':'2018-05-23','server':'server1','api':'api2','count':23}, {'date':'2018-05-24','server':'server1','api':'api2','count':20}, {'date':'2018-05-24','server':'server2','api':'api1','count':30}, {'date':'2018-05-21','server':'server2','api':'api2','count':20}] f, (axs) = plt.subplots(3, sharex=True, sharey=True) df = pd.DataFrame(data_set) df['date'] = pd.to_datetime(df['date'],format='%Y/%m/%d %H:%M:%S') df = df.set_index('date') grouped = df.groupby(['api']) for (name, df1), ax in zip(grouped, axs.flat): df1.plot(y='count', ax=ax) plt.legend(bbox_to_anchor=(1, 1, 0.25, -0.2), bbox_transform=plt.gcf().transFigure) f.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) I am not getting the results I want, Can some one please guide me? This is the graph I am getting now. Currently getting this Image Image from group by Server
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88194601
has comment: http://stackoverflow.com/comment/88098568
type: Question
has comment: http://stackoverflow.com/comment/88183839
score: 0
has comment: http://stackoverflow.com/comment/88089492
has comment: http://stackoverflow.com/comment/88185029
tagged with: pandas
tagged with: matplotlib
has title: Multiple graphs sharing same X-axis, and group of yaxis
tagged with: python
has comment: http://stackoverflow.com/comment/88193824

http://stackoverflow.com/comment/87850476
type: Comment
type: QuestionComment
has text: The real question is why? What are you actually trying to do? Because I can guarantee with near certainty that if you even have to ask this question (it's not a bad question, just a bit beginner-y) then this probably isn't the right approach to what you are actually trying to accomplish. Note by the way that variable name spaces in Python are (roughly speaking) just dictionaries themselves so probably all you want is a dict with your hashes as keys.
comment on: http://stackoverflow.com/q/50417265
score: 3

http://stackoverflow.com/comment/87895182
score: 1
comment on: http://stackoverflow.com/q/50440430
has text: You may want to start with a way of [getting data from a web page](http://docs.python-requests.org/en/master/).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50418506
type: Question
has answer: http://stackoverflow.com/a/50418802
has body: Okay so I have a list with following structure: List1=[[a,b,c,data1,e], [a,b,c,data2,e], [a,b,c,data3,e], [a,b,c,data1,e], [a,b,c,data2,e], [a,b,c,data3,e], [a,b,c,data1,e], [a,b,c,data1,e], [a,b,c,data2,e], [a,b,c,data3,e]] Now I have sorted the list using: List1.sort(key=lambda elem: elem[3]) Output generated is: List1=[[a,b,c,data1,e], [a,b,c,data1,e], [a,b,c,data1,e], [a,b,c,data1,e], [a,b,c,data2,e], [a,b,c,data2,e], [a,b,c,data2,e], [a,b,c,data3,e], [a,b,c,data3,e], [a,b,c,data3,e]] what I want to achieve is have only 2 elements for each distinct value of data i.e: List1=[[a,b,c,data1,e], [a,b,c,data1,e], [a,b,c,data2,e], [a,b,c,data2,e], [a,b,c,data3,e], [a,b,c,data3,e]]
type: UnansweredQuestion
has title: How to keep only specific numbers of elements in a list based on columns used for sorting?
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/50418887
has answer: http://stackoverflow.com/a/50419078
score: 0
tagged with: list
answer count: 3

http://stackoverflow.com/q/50495074
accepted answer: http://stackoverflow.com/a/50495443
has comment: http://stackoverflow.com/comment/88003979
type: Question
tagged with: python
has title: Python - Execute Java - Could not find or load main class
type: AnsweredQuestion
score: 0
has body: I followed the SO Answer to execute a java program from python import os.path, subprocess from subprocess import STDOUT, PIPE def compile_java(java_file): subprocess.check_call(['javac', java_file]) def execute_java(java_file, stdin): java_class, ext = os.path.splitext(java_file) cmd = ['java', java_class] process = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, universal_newlines=True) stdout, stderr = process.communicate(stdin) print(stdout) compile_java(os.path.join('model', 'classification', 'Model.java')) execute_java('Model', '5 6 7 8') The python code compiles the /model/classification/Model.java without problems. But when the python code executes the java program, Java can not find or load the main class Model. Executing java Model in the command line in the same directory (with the compiled version, which was triggered by the python snippet above) works.
linked to: http://stackoverflow.com/q/9333637
tagged with: java
duplicate of: http://stackoverflow.com/q/18093928
answer count: 1
linked to: http://stackoverflow.com/q/18093928
has answer: http://stackoverflow.com/a/50495443

http://stackoverflow.com/comment/87799247
type: QuestionComment
has text: cheers for that
comment on: http://stackoverflow.com/q/50391249
score: 0
type: Comment

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/50494262

http://stackoverflow.com/q/50474302
linked to: http://stackoverflow.com/q/39308030
tagged with: python
tagged with: contrast
has comment: http://stackoverflow.com/comment/87967825
answer count: 4
tagged with: brightness
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52313802
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/87967768
has comment: http://stackoverflow.com/comment/87964369
has answer: http://stackoverflow.com/a/63004421
has title: How do I adjust brightness, contrast and vibrance with opencv python?
has body: I am new to image processing. I program in Python3 and uses the OpenCV image processing library.I want to adjust the following attributes. Brightness Contrast Vibrance Hue Saturation Lightness For 4, 5, 6. I am using the following code to convert to HSV space. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(hsv) h += value # 4 s += value # 5 v += value # 6 final_hsv = cv2.merge((h, s, v)) img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR) The only tutorial I found for 1 and 2 is here. The tutorial uses C++, but I program in Python. Also, I do not know how to adjust 3. vibrance. I would very much appreciate the help, thanks!.
favorite count: 0
type: Question
tagged with: opencv
upvote count: 5
has answer: http://stackoverflow.com/a/50477151
has answer: http://stackoverflow.com/a/71744334
accepted answer: http://stackoverflow.com/a/50477151
possible better answer: http://stackoverflow.com/a/71744334

http://stackoverflow.com/comment/87810841
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50396873
has text: I have the correct imports and they are: import math from sympy import binomial import numpy
type: QuestionComment

http://stackoverflow.com/comment/87956442
score: 3
type: Comment
type: QuestionComment
has text: You can use [`.values`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html) instead of [`.items()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.items.html): `for i in ageNew.values:`
comment on: http://stackoverflow.com/q/50471457

http://stackoverflow.com/comment/87960522
comment on: http://stackoverflow.com/a/50473253
type: Comment
type: AnswerComment
has text: Yeah so if you are blocking individually and need a cidr then /32 should do.
score: 0

http://stackoverflow.com/q/50395651
downvote count: 4
tagged with: pandas
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/87807433
has comment: http://stackoverflow.com/comment/87807535
has answer: http://stackoverflow.com/a/50395725
has title: Why accessing values in dataframe and list are different?
favorite count: 0
type: Question
has body: Suppose I have a list a defined as: a =[[1,2,3,4],[5,6,7,8]]; then a[0] returns the first element in the list: [1,2,3,4]. df = pd.DataFrame([[1,2,3,4],[5,6,7,8]]) df is represented as 0 | 1 2 3 4 1 | 5 6 7 8 If I use df[0] the following value is printed: 0 | 1 1 | 5 I would have expected the first row ie 0| 1 2 3 4 to be printed like in a list. Is it because dataframe is represented by dataframe[cols][rows] rather than dataframe[rows][cols]?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87808053
tagged with: dataframe
tagged with: python
score: -1

http://stackoverflow.com/q/50400852
tagged with: python
has comment: http://stackoverflow.com/comment/87821017
linked to: http://stackoverflow.com/q/45753777
tagged with: type-inference
accepted answer: http://stackoverflow.com/a/50401679
has comment: http://stackoverflow.com/comment/87821082
has answer: http://stackoverflow.com/a/50401679
score: 2
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/87817980
has title: Specify the data type of each column in read_csv from each column of an HTTP header
tagged with: types
tagged with: http-headers
has comment: http://stackoverflow.com/comment/87818179
has comment: http://stackoverflow.com/comment/87817692
has body: project_id = request.data['project'] list_fields = request.POST.getlist('headers') type_fields = request.POST.getlist('type') dataframe = pandas.read_csv(file_path, header=0) for field in list_fields: for tipo in type_fields: dataframe[field] = dataframe[field].astype(type) how can I assign each type of data to a column according to the past in the request?
has comment: http://stackoverflow.com/comment/87817578
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50401581
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50401581

http://stackoverflow.com/comment/87906202
score: 0
has text: @user9810829, you would not give performance metrics with unlabeled data for a model trained and validated using a labeled set. You can always collect another labeled set of data and use it to benchmark your model anew.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50408325

http://stackoverflow.com/comment/87850844
has text: Do you get a traceback leading up to the `PermissionError`? And if so could you post it? Either way, a not entirely uncommon problem on Windows is that the permissions on some directory, aka the Access Control Lists (ACL) were corrupted somehow, breaking write access (even for Administrators). I doubt it's anything particular to `tensorflow`. Can you `pip install` any other packages?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50417129
score: 1

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/50515170
tags question: http://stackoverflow.com/q/50532385
tags question: http://stackoverflow.com/q/50532583
type: Tag
tags question: http://stackoverflow.com/q/50525525
tags question: http://stackoverflow.com/q/50526033
tags question: http://stackoverflow.com/q/50453626
tags question: http://stackoverflow.com/q/50458837

http://stackoverflow.com/a/50468883
answers question: http://stackoverflow.com/q/50468792
downvote count: 0
type: Answer
has body: You can use zip, In [5]: A = [[0.45, 0.89, 0.91], [0.5, 0.78, 0.55], [0.134, 0.571, 0.142]] In [6]: [a*b*c for a,b,c in zip(*A)] Out[6]: [0.030150000000000003, 0.39638819999999997, 0.071071]
score: 3
upvote count: 3

http://stackoverflow.com/a/50492061
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50491499
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50491499
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/88018831
has body: This could be a workaround: myCsv = df.astype(str).apply(lambda x: ' '.join(x), axis=1) myCsv.rename(' '.join(df.columns)).to_csv(file, header=True, index=False)
has comment: http://stackoverflow.com/comment/88015772
upvote count: 2

http://stackoverflow.com/comment/88026935
type: AnswerComment
has text: Forgot to add, it's on Mac OSX, sorry. Have changed the original post.
comment on: http://stackoverflow.com/a/50507392
type: Comment
score: 0

http://stackoverflow.com/comment/87893523
score: 0
has text: Ok, I am not going to pretend I'd know what was going on here :D
comment on: http://stackoverflow.com/q/50439358
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87809624
has text: Why would you want to store dictionaries in a dataframe in the first place?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50396877

http://stackoverflow.com/comment/87992760
score: 0
comment on: http://stackoverflow.com/q/50489604
has text: Of course an iterator is not indexible and does not have random access, but that's a tradeoff you gonna have to agree to if you want to avoid putting everything in memory
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50441180
tagged with: image
type: AnsweredQuestion
score: 0
answer count: 1
has body: with not using php , after getting image path from client part , i want to save it into mysql ... how to write mysql query .... i do not know what kind of type i have to use when i save file path where the image saved in my computer memory. i just need to load my image and store image path to my computer(C://) not using web condition , php . i think it is very easy so that could not find google or this site. CREATE TABLE tablename ( number INT(11) unsigned NOT NULL, name VARCHAR(32) NOT NULL, imagepath (whattype)(size) NOT NULL );
accepted answer: http://stackoverflow.com/a/50441197
has title: how to save image path by using mysql and python language
has answer: http://stackoverflow.com/a/50441197
type: Question
tagged with: python
tagged with: mysql

events
tags question: http://stackoverflow.com/q/50532240
tag name: events
tags question: http://stackoverflow.com/q/50476732
type: Tag
tags question: http://stackoverflow.com/q/50522888

http://stackoverflow.com/q/50476889
tagged with: scientific-computing
score: 3
favorite count: 0
upvote count: 4
has body: How can I make sympy.solve not return negative solutions? This seems to be a different task than adding a constraint like positive=True to the symbol I'm solving for. While import sympy x = sympy.symbols("x") print(sympy.solve(x**2-4, x)) x = sympy.symbols("x", positive=True) print(sympy.solve(x**2-4, x)) prints [-2, 2] [2] as expected - I still get a negative solve result for omega with import sympy omega, omega_0, gamma = sympy.symbols("omega, omega_0, gamma", real=True, positive=True) zeta = 1/((omega_0**2 - omega**2)**2 + gamma**2*omega**2) omega_R = sympy.solve(sympy.diff(zeta, omega), omega) print(omega_R) which returns [-sqrt(2)*sqrt(-gamma**2 + 2*omega_0**2)/2, sqrt(2)*sqrt(-gamma**2 + 2*omega_0**2)/2] even though -sqrt(2)*sqrt(-gamma**2 + 2*omega_0**2)/2 will never be positive for real and positive symbols omega_0 and gamma. Alternatively, whats's the best way to eliminate the negative solutions afterwards?
tagged with: sympy
type: Question
tagged with: python
type: UnansweredQuestion
answer count: 1
downvote count: 1
has title: How to eliminate negative solutions from `sympy.solve` result?
has answer: http://stackoverflow.com/a/50959639

http://stackoverflow.com/q/50520682
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
has answer: http://stackoverflow.com/a/50520880
type: Question
score: 0
answer count: 1
has body: I am trying to go back to March 29th 2018 and run through each day till today. Also save each day individually to .csv and change the name BOOKS_thedate.csv. I have been meaning to apply datetime another way and any help understanding this would be much appreciated. import csv import requests import datetime from pprint import pprint outfile = open("BOOKS.csv","w",newline='') writer = csv.writer(outfile) writer.writerow(["book_ids","status","away_team_id","away_rot","ml_away","spread_away","spread_away_line","home_team_id", "home_rot","ml_home","spread_home","spread_home_line","over","under","total","type_odds","insert","time", "one_tm_id","one_tm","one_team","two_tm_id","two_tm","two_team"]) req2 = requests.get('https://api-prod.sprtactn.co/web/v1/scoreboard/mlb?bookIds=21,1,55&amp;date=' + datetime.datetime.now().strftime('%Y%m%d') + '') odd = req2.json()['games'] for info in odd: time = info['start_time'] status = info['status'] away_rot = info['away_rotation_number'] home_rot = info['home_rotation_number'] away_team_id = info['away_team_id'] home_team_id = info['home_team_id'] teams = info['teams'] vegas = info['odds'] one_team = teams[0]['full_name'] one_tm = teams[0]['abbr'] one_tm_id = teams[0]['id'] two_team = teams[1]['full_name'] two_tm = teams[1]['abbr'] two_tm_id = teams[1]['id'] for odds in vegas: ml_away = odds['ml_away'] ml_home = odds['ml_home'] type_odds = odds['type'] insert = odds['inserted'] book_ids = odds['book_id'] spread_away = odds['spread_away'] spread_home = odds['spread_home'] spread_away_line = odds['spread_away_line'] spread_home_line = odds['spread_home_line'] over = odds['over'] under = odds['under'] total = odds['total'] print(book_ids, status, away_team_id, away_rot, ml_away, spread_away, spread_away_line, home_team_id, home_rot, ml_home, spread_home, spread_home_line, over, under, total, type_odds, insert, time, one_tm_id, one_tm, one_team, two_tm_id, two_tm, two_team) writer.writerow([book_ids, status, away_team_id, away_rot, ml_a…
tagged with: python
type: AnsweredQuestion
has title: Run through multiple dates Python
accepted answer: http://stackoverflow.com/a/50520880

http://stackoverflow.com/q/50422124
has comment: http://stackoverflow.com/comment/87859291
has title: Can't find element by xpath with title as a variable
has body: selenium can't locate the element, Time Out Exception. name="karam" This works. WebDriverWait(browser,10).until( EC.presence_of_element_located((By.XPATH,'//*[@title="karam"]')) ) This won't work. WebDriverWait(browser,10).until( EC.presence_of_element_located((By.XPATH,'//*[@title=str(name)]')) ) nor this. WebDriverWait(browser,10).until( EC.presence_of_element_located((By.XPATH,'//*[@title="{}".format(name))) )
answer count: 1
tagged with: selenium
downvote count: 1
favorite count: 0
type: Question
tagged with: xpath
has answer: http://stackoverflow.com/a/50422254
has comment: http://stackoverflow.com/comment/87859339
upvote count: 0
has comment: http://stackoverflow.com/comment/87863207
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/50422254
has comment: http://stackoverflow.com/comment/87859312
has comment: http://stackoverflow.com/comment/87859645
type: AnsweredQuestion

http://stackoverflow.com/comment/87852598
has text: Your DataFrame doesn't contain a column called `'tags'`. You actively called/referenced the column `'tag'` in `data_frame = pd.read_csv(num_file_path, dtype={'adsh': str, 'tag': str, 'version coreg': str, 'ddate': int, 'qtrs': int, 'uom': str, 'value': float, 'footnote': str}`. It looks like a typo
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50418511
type: QuestionComment

http://stackoverflow.com/q/50401236
has answer: http://stackoverflow.com/a/50401376
accepted answer: http://stackoverflow.com/a/50401363
score: 4
has comment: http://stackoverflow.com/comment/87818493
has title: How to use an integer variable as a parameter for a function?
has answer: http://stackoverflow.com/a/50401402
tagged with: function
tagged with: parameter-passing
tagged with: global-variables
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87818334
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50401363
has body: I'm trying to make a piece of code that will count up votes for three different candidates, and I'm using a function that uses the variable name (either A, B or C) as a parameter. I'm trying to have it so that whenever a vote is counted for that candidate, it will call the function to increase the variable for that candidate by 1. However, with every way I've tried all 3 candidates will always have 0 votes counted, unless I completely remove the function. I've tried several different ways of making the variables global variables but they all gave the same results. A = 0 B = 0 C = 0 def after_vote(letter): letter = letter + 1 print("Thank you for your vote.") def winner(winner_letter, winner_votes): print("The winner was", winner_letter, "with", str(winner_votes), "votes.") while True: vote = input("Please vote for either Candidate A, B or C. ").upper() if vote == "A": after_vote(A) elif vote == "B": after_vote(B) elif vote == "C": after_vote(C) elif vote == "END": print("Cadidate A got", str(A), "votes, Candidate B got", str(B), "votes, and Candidate C got", str(C), "votes.") if A &gt; B and A &gt; C: winner("A", A) break elif B &gt; A and B &gt; C: winner("B", B) break elif C &gt; A and C &gt; B: winner("C", C) break else: print("There was no clear winner.") break else: print("Please input a valid option.")
has answer: http://stackoverflow.com/a/50401354
upvote count: 5
possible better answer: http://stackoverflow.com/a/50401376
tagged with: python
answer count: 4

http://stackoverflow.com/comment/88081946
type: Comment
has text: `StringVar()` uses `set()` to change the value.
type: QuestionComment
comment on: http://stackoverflow.com/q/50533460
score: 1

http://stackoverflow.com/comment/87935409
score: 0
type: AnswerComment
has text: Ok, I tried with some sample data and found out, that a heatmap doesn't have axes ranges like labeled and/or with respect to the data. They are just indexed. I'll edit my answer in this direction...
type: Comment
comment on: http://stackoverflow.com/a/50460918

http://stackoverflow.com/a/50511813
accepted answer of: http://stackoverflow.com/q/50510430
score: 0
answers question: http://stackoverflow.com/q/50510430
has body: The image must undergo a so-called homographic transform, X = (a x + b y + c) / (g x + h y + 1) Y = (d x + e y + f) / (g x + h y + 1) This transform will map for instance the four corners of the screen in the input stream to four points in the destination image that form a rectangle with the correct aspect ratio. Knowing the four correspondences between the corners, you establish a system of 8 equations in 8 unknowns, which can be written in a linear form. Equipped with this transformation, you scan the destination image and for every pixel find the corresponding one in the source image, and copy the RGB values. This is good enough for a low quality transform. To avoid jaggies, you can use a bilinear interpolation between the four neighboring pixels in the source. Have a look here: https://docs.opencv.org/3.4.1/d9/dab/tutorial_homography.html If you want to find the screen corners automatically, this is a whole other story.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/115779249
score: 0
type: AnswerComment
has text: @Aseem yes, this the only way, otherwise your server would not have new code changes
comment on: http://stackoverflow.com/a/50487396
type: Comment

http://stackoverflow.com/q/50511730
tagged with: django
tagged with: python
has body: So I need to deny a websocket connection with a specific code so the client can handle the rejection properly. Currently when you reject a connection with: message.reply_channel({'accept': False}) the client simple gets a 403 error. I can close a connection with a code by using: message.reply_channel({'close':3000}) but that requires for the connection to have been accepted in the first place. If that's the only way to do it then so be it but I feel like there should be a way to reject with a code that I simply can't find. I'm using Django Channels 1.1.8 so the 2.x release changes don't benefit me unfortunately.
score: 14
upvote count: 14
answer count: 1
has title: Django Channels deny websocket connection with a custom code
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: django-channels
has answer: http://stackoverflow.com/a/78393789

http://stackoverflow.com/comment/87927076
has text: Be aware that your parser will probably never handle everything and will only work on *relatively simple* c++ code (e.g. an `#include` which includes a file with `#define int {` will probably break everything), so consider using an existing solution (at least if you care for such weird cases;) )
type: QuestionComment
comment on: http://stackoverflow.com/q/50456445
score: 0
type: Comment

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/50391642
type: Tag

http://stackoverflow.com/q/50458305
linked to: http://stackoverflow.com/q/46892261
tagged with: python
has body: What is the reason that raising a KeyError does not format the string whereas other errors do? (notice the embedded \n vs a new line in the examples below) In [1]: raise KeyError("Does not \n format") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-1-2a34667e842b&gt; in &lt;module&gt;() ----&gt; 1 raise KeyError("Does not \n format") KeyError: 'Does not \n format' Whereas for a ValueError In [2]: raise ValueError("Does \n format") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-2-3f8ba28869e2&gt; in &lt;module&gt;() ----&gt; 1 raise ValueError("Does \n format") ValueError: Does format Or an IndexError In [3]: raise IndexError("Does \n format") --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-4-2db4e87594fd&gt; in &lt;module&gt;() ----&gt; 1 raise IndexError("Does \n format") IndexError: Does format
duplicate of: http://stackoverflow.com/q/46892261
answer count: 0
has comment: http://stackoverflow.com/comment/87971492
score: 3
has comment: http://stackoverflow.com/comment/87969860
has comment: http://stackoverflow.com/comment/87996370
has title: KeyError does not format error message
has comment: http://stackoverflow.com/comment/87971422
downvote count: 1
has comment: http://stackoverflow.com/comment/87969892
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87970464

http://stackoverflow.com/comment/87984900
score: 1
type: Comment
has text: Yes, it seems this is what you need, thank you very much!)
type: AnswerComment
comment on: http://stackoverflow.com/a/50485427

http://stackoverflow.com/comment/87985805
has text: What happens when you press `Dismiss this error`? Are you redirected back to the page with the button with text as **Skapa Konto**?
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50486403

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/50502581
tags question: http://stackoverflow.com/q/50448986
tags question: http://stackoverflow.com/q/50481346
tags question: http://stackoverflow.com/q/50512948
tags question: http://stackoverflow.com/q/50488524
tags question: http://stackoverflow.com/q/50532126
tags question: http://stackoverflow.com/q/50420702
type: Tag
tags question: http://stackoverflow.com/q/50475752
tag name: pdf
tags question: http://stackoverflow.com/q/50438941
tags question: http://stackoverflow.com/q/50496411
tags question: http://stackoverflow.com/q/50398940
tags question: http://stackoverflow.com/q/50520029

http://stackoverflow.com/comment/88113215
score: 0
type: QuestionComment
type: Comment
has text: big thanks ! @RThomP
comment on: http://stackoverflow.com/q/50540547

apache-spark
tags question: http://stackoverflow.com/q/50535703
tags question: http://stackoverflow.com/q/50480921
tags question: http://stackoverflow.com/q/50523055
tags question: http://stackoverflow.com/q/50482720
tags question: http://stackoverflow.com/q/50386955
tags question: http://stackoverflow.com/q/50390255
tags question: http://stackoverflow.com/q/50414300
tags question: http://stackoverflow.com/q/50387354
tags question: http://stackoverflow.com/q/50527953
tags question: http://stackoverflow.com/q/50530679
tags question: http://stackoverflow.com/q/50425475
tags question: http://stackoverflow.com/q/50496361
tags question: http://stackoverflow.com/q/50393696
tags question: http://stackoverflow.com/q/50496448
tags question: http://stackoverflow.com/q/50406096
tags question: http://stackoverflow.com/q/50435900
tags question: http://stackoverflow.com/q/50435286
tags question: http://stackoverflow.com/q/50526122
tags question: http://stackoverflow.com/q/50454850
tags question: http://stackoverflow.com/q/50441128
tags question: http://stackoverflow.com/q/50419797
tags question: http://stackoverflow.com/q/50425779
tags question: http://stackoverflow.com/q/50533833
tags question: http://stackoverflow.com/q/50523950
tags question: http://stackoverflow.com/q/50458082
tags question: http://stackoverflow.com/q/50414294
tags question: http://stackoverflow.com/q/50521738
tags question: http://stackoverflow.com/q/50499894
tags question: http://stackoverflow.com/q/50499628
tags question: http://stackoverflow.com/q/50444290
tags question: http://stackoverflow.com/q/50399751
tags question: http://stackoverflow.com/q/50456673
tags question: http://stackoverflow.com/q/50410862
tags question: http://stackoverflow.com/q/50473181
tags question: http://stackoverflow.com/q/50482829
tags question: http://stackoverflow.com/q/50465399
tags question: http://stackoverflow.com/q/50493426
type: Tag
tags question: http://stackoverflow.com/q/50530819
tags question: http://stackoverflow.com/q/50431221
tags question: http://stackoverflow.com/q/50450552
tags question: http://stackoverflow.com/q/50465895
tags question: http://stackoverflow.com/q/50393380
tag name: apache-spark
tags question: http://stackoverflow.com/q/50467823
tags question: http://stackoverflow.com/q/50428414
tags question: http://stackoverflow.com/q/50498260
tags question: http://stackoverflow.com/q/50417891
tags question: http://stackoverflow.com/q/50424196

http://stackoverflow.com/q/50525301
linked to: http://stackoverflow.com/q/7526088
favorite count: 0
has answer: http://stackoverflow.com/a/50527822
type: AnsweredQuestion
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88064695
has title: Django inheritance and polymorphism with proxy models
accepted answer: http://stackoverflow.com/a/50531303
tagged with: django-models
linked to: http://stackoverflow.com/q/4162456
tagged with: django-inheritance
tagged with: proxy-classes
score: 8
upvote count: 8
type: Question
has body: I'm working on a Django project that I did not start and I am facing a problem of inheritance. I have a big model (simplified in the example) called MyModel that is supposed to represents different kind of items. All the instance objects of MyModel should have the same fields but the methods behaviours varies a lot depending on the item type. Up to this moment this has been designed using a single MyModel field called item_type. Then methods defined in MyModel check for this field and perform different logic using multiple if: def example_method(self): if self.item_type == TYPE_A: do_this() if self.item_type == TYPE_B1: do_that() Even more, some of the sub-types have many things in common, so let's say the subtypes B and C represents a 1st level of inheritance. Then these types have sub-types being for example B1, B2, C1, C2 (better explained in the example code below). I would say that's not the best approach to perform polymorphism. Now I want to change these models to use real inheritance. Since all submodels have the same fields I think multi-table inheritance is not necessary. I was thinking to use proxy models because only their behaviour should change depending on their types. This a pseudo-solution I came up to: ITEM_TYPE_CHOICES = ( (TYPE_A, _('Type A')), (TYPE_B1, _('Type B1')), (TYPE_B2, _('Type B2')), (TYPE_C1, _('Type C1')), (TYPE_C2, _('Type C2'))) class MyModel(models.Model): item_type = models.CharField(max_length=12, choices=ITEM_TYPE_CHOICES) def common_thing(self): pass def do_something(self): pass class ModelA(MyModel): class Meta: proxy = True def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.item_type = TYPE_A def do_something(self): return 'Hola' class ModelB(MyModel): class Meta: proxy = True def common_thing(self): pass class ModelB1(ModelB): class Meta: proxy = True def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.item_type = TYPE_B1 def do_something(self): pass class ModelB2(…
has answer: http://stackoverflow.com/a/51989594
linked to: http://stackoverflow.com/q/1397537
possible better answer: http://stackoverflow.com/a/51989594
has comment: http://stackoverflow.com/comment/88064445
has answer: http://stackoverflow.com/a/50531303
tagged with: django
linked to: http://stackoverflow.com/q/18473850
tagged with: python
has comment: http://stackoverflow.com/comment/137926427

http://stackoverflow.com/q/50388325
upvote count: 1
has comment: http://stackoverflow.com/comment/87802226
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87801936
has comment: http://stackoverflow.com/comment/87802360
has body: I'm trying to plot a demand profile for heating energy for a specific building with Python and matplotlib. But instead of being a single line it looks like this: Did anyone ever had plotting results like this? Or does anyone have an idea whats going on here? The corresponding code fragment is: for b in list_of_buildings: print(b.label, b.Q_Heiz_a, b.Q_Heiz_TT, len(b.lp.heating_list)) heating_datalist=[] for d in range(timesteps): b.lp.heating_list[d] = b.lp.heating_list[d]*b.Q_Heiz_TT heating_datalist.append((d, b.lp.heating_list[d])) xs_heat = [x[0] for x in heating_datalist] ys_heat = [x[1] for x in heating_datalist] pyplot.plot(xs_heat, ys_heat, lw=0.5) pyplot.title(TT) #get legend entries from list_of_buildings list_of_entries = [] for b in list_of_buildings: list_of_entries.append(b.label) pyplot.legend(list_of_entries) pyplot.xlabel("[min]") pyplot.ylabel("[kWh]") Additional info: timesteps is a list like [0.00, 0.01, 0.02, ... , 23.59] - the minutes of the day (24*60 values) b.lp.heating_list is a list containing some float values b.Q_Heiz_TT is a constant
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87795816
linked to: http://stackoverflow.com/q/19339
has comment: http://stackoverflow.com/comment/87792624
tagged with: python
has comment: http://stackoverflow.com/comment/87796409
has answer: http://stackoverflow.com/a/50392645
tagged with: plot
answer count: 2
has title: Weird plot with matplotlib
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50393415
downvote count: 0

http://stackoverflow.com/comment/88085014
type: QuestionComment
comment on: http://stackoverflow.com/q/50536420
has text: Not updating the linked list at all, my apologies I should have mentioned that in the question
score: 0
type: Comment

http://stackoverflow.com/q/50404490
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1
tagged with: html-table
answer count: 2
downvote count: 2
upvote count: 1
has body: I am looking to write certain columns of data from an excel sheet to a HTML table. Not looking to write specific/fixed cells into the table always, need to do this based on conditions. For example, if I have a table with columns Name/Age/Occupation, I would like to make an HTML table using just columns Name and Occupation. Also, within Name, I would only like to write the names starting with 'N' onto the table and corresponding Occupation. The Excel sheet dynamically changes with new data everytime. Essentially, I would not want to write specific cells or range of cells into the table but only the data based on conditions I set. Any suggestions using python/html/jquery or other methods are welcome.
has answer: http://stackoverflow.com/a/50405013
tagged with: jquery
has answer: http://stackoverflow.com/a/50404792
tagged with: excel
favorite count: 0
type: Question
has title: Writing from Excel sheet to a table

http://stackoverflow.com/a/54840213
upvote count: 1
downvote count: 0
score: 1
has body: Thank you for the code, @Steve ! I was looking everywhere on the github repo and couldn't find a way to check the tfrecord. Just wanted to point out that an import line seems missing: from google.protobuf import text_format It ran ok for me after adding this
answers question: http://stackoverflow.com/q/50391967
type: Answer

http://stackoverflow.com/q/50428901
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50428976
answer count: 1
downvote count: 0
tagged with: floating-point
favorite count: 0
has body: Here is my code: I have tried all day to solve the mistake but I still have the error: TypeError: unsupported operand type(s) for /: 'Decimal' and 'float'. from math import sqrt, acos, pi from decimal import Decimal, getcontext getcontext().prec = 30 class Vector(object): CANNOT_NORMALIZE_ZERO_VECTOR_MSG = 'Cannot compute an angle with the zero vector' def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(Decimal(x) for x in coordinates) self.dimension = len(self.coordinates) except ValueError: raise ValueError('The coordinates must be nonempty') except TypeError: raise TypeError('The coordinates must be an iterable') #orthogonal or parallel def is_zero(self, tolerance=1e-10): return self.magnitude() &lt; tolerance def is_orthogonal_to(self, v, tolerance=1e-10): return abs(self.dot(v)) &lt; tolerance def is_parallel_to(self, v): return ( self.is_zero() or v.is_zero() or self.angle_with(v) == 0 or self.angle_with(v) == pi ) #dot product &amp;angle def dot(self, v): return sum([x*y for x,y in zip(self.coordinates,v.coordinates)]) def angle_with(self,v,in_degrees=False): try: u1 = self.normalized() u2 = v.normalized() angle_in_radians = acos(u1.dot(u2)) if in_degrees: degrees_per_radian = 180./pi return angle_in_radians * degrees_per_radian else: return angle_in_radians except Exception as e: if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG: raise Exception('Cannot compute an angle with the zero vector') else: raise e #magnitude&amp; Direction def magnitude(self): coordinates_squared = [x**2 for x in self.coordinates] return sqrt(sum(coordinates_squared)) def normalized(self): try: magnitude = self.magnitude() return self.times_scalar(Decimal('1.0')/magnitude) except ZeroDivisionError: raise Exception(self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG) #Plus,minus, scalar multiply def plus(self, v): new_coordinates = [x+y for x,y in zip(self.coordinates,v.coordinates)] return Vector(new_coordinates) def minus(self, v): new_coordinates…
type: Question
type: UnansweredQuestion
has title: Typeerror: unsupported operand type(s) for /: 'Decimal' and 'float'

http://stackoverflow.com/comment/87985467
type: QuestionComment
score: 0
has text: If these are custom classes, maybe give them a member function that builds and returns a list of the info. So you could: `index_error_lst = play.get_error_list()`.
comment on: http://stackoverflow.com/q/50486229
type: Comment

http://stackoverflow.com/a/50428554
downvote count: 0
has comment: http://stackoverflow.com/comment/87878734
upvote count: 2
type: Answer
has body: A more general and Pythonic approach that works for any number of variables is to use an any() or all() function that check the Truth value of the condition for all the arguments. If you want the index to belongs to an item that is divisible buy all the arguments you need all() other wise you can use any() that returns True right after it encounters a match. def indexes(lst, *args): return [i for i, j in enumerate(lst) if any(j % arg == 0 for arg in args)] Demo: &gt;&gt;&gt; lst = [1, 2, 3, 4, 5, 6, 15, 99, 200, 13, 17, 400] &gt;&gt;&gt; indexes(lst, 99, 5, 2, 100) [1, 3, 4, 5, 6, 7, 8, 11] &gt;&gt;&gt; And with all(): &gt;&gt;&gt; indexes(lst, 5, 2, 100) [8, 11]
answers question: http://stackoverflow.com/q/50428346
score: 2

http://stackoverflow.com/q/50515885
duplicate of: http://stackoverflow.com/q/28805028
has comment: http://stackoverflow.com/comment/88050946
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88044431
has comment: http://stackoverflow.com/comment/88045218
has comment: http://stackoverflow.com/comment/88050710
has comment: http://stackoverflow.com/comment/88052181
type: Question
linked to: http://stackoverflow.com/q/28805028
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88050888
has comment: http://stackoverflow.com/comment/88050654
tagged with: python
has comment: http://stackoverflow.com/comment/88045424
has title: NameError when method is clearly defined
has body: I have a very simple program in python to check if a list has a zero value in it class ZeroList(object): def __init__(self,coordinates): self.coordinates = coordinates def is_zero(value): return math.isclose(value,0) def test(self): for coord in self.coordinate: if not is_zero(coord): print(coord) a = ZeroList([1,2,0,8,5,0,3,7,0,3]) a.test() Yet running this results in the error Traceback (most recent call last): File "line2.py", line 2, in &lt;module&gt; class Test(object): File "line2.py", line 12, in Test test([1,2,3]) File "line2.py", line 8, in test if not is_zero(i): NameError: name 'is_zero' is not defined The method is_zero is clearly defined so why is this error showing up?

http://stackoverflow.com/comment/87949620
type: AnswerComment
comment on: http://stackoverflow.com/a/50467786
type: Comment
has text: With same data?
score: 0

http://stackoverflow.com/a/50412914
upvote count: 1
type: Answer
score: 1
has body: To match words connected with periods, you could use: \b\w+(?:\.\w+)+\s* Updated with comment from @Jan Details \b Word boundary \w+ Match one or more word characters (?: Non capturing group \.\w+ Match a dot and one or more times a word character )+ Close non capturing group and repeat one or more times to match a.b or a.b.c etc \s* Match zero or more times a whitespace character. For example: import re str = 'random random 123.4445.764 random goo.34.hi random' print(re.sub("\\b\w+(?:\.\w+)+\s*", "", str)) That would give you: random random random random Demo Python
has comment: http://stackoverflow.com/comment/87842171
answers question: http://stackoverflow.com/q/50409701
downvote count: 0

http://stackoverflow.com/q/50404156
has title: How to access a variable in a method in a class from another method in the same class
answer count: 1
accepted answer: http://stackoverflow.com/a/50404872
has comment: http://stackoverflow.com/comment/87823718
has comment: http://stackoverflow.com/comment/87824052
type: Question
has body: There are no errors or problems with the below code I want to "connect" this script to an external file or database so that that "my_dict" dictionary can have its contents stored and used after the script is executed. I am looking for ideas on how to make this happen. I am not asking for the code to be fixed as it is functional. It is merely there to provide context. my_dict = {} class password(object): def __init__(self): pass def username_input(self): self.user = str(input("Please enter the username you would like to use: ")) return self.user #gets the input for a username def password_input(self): self.passw = str(input("Please enter the password you would like to use: ")) return self.passw #gets the input for a password def username_creator(self): password.username_input(self) return self.user def password_creator(self): password.password_input(self) return self.passw def swap_username(self, new_pass, old_pass): my_dict[new_pass] = my_dict.pop(old_pass) def swap_password(self, new_pas, old_pas): my_dict[old_pas] = new_pas def username_change(self): self.d = input("please enter your username: ") for key in my_dict: if key == self.d: self.x = input("enter a new username: ") password().swap_username(self.x, self.d) print("your username has been updated!") break else: print("the username you entered does not exist in our records") password().username_change() def password_change(self): self.e = input("please enter your username: ") self.q = input("please enter your password: ") for key, value in my_dict.items(): if key == self.e and value == self.q: self.z = input("enter a new password: ") password().swap_password(self.z, self.e) break else: print ('the combination entered does not exist in our records') password().password_change() make_a_username = password() my_dict.update({(make_a_username.username_creator()): (make_a_username.password_creator())})
has comment: http://stackoverflow.com/comment/87823776
tagged with: python
has answer: http://stackoverflow.com/a/50404872
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50443132
has comment: http://stackoverflow.com/comment/87902114
tagged with: series
has comment: http://stackoverflow.com/comment/87900071
score: 0
tagged with: pandas
tagged with: python
has body: Find value in pd.DataFrame and get the column name or index of that value. list of values are : '25362438,25383532 Mobile : 8691017781,8691017798',nan,nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 'Mobile : 0', nan, nan, nan, nan, nan, nan, nan, nan, nan suppose I have converted this list to pandas df. and now I want to know the column index of "Mobile : 0" then how can I know. I used iloc but it is not working.
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50444763
has title: Get column index based on value in pandas
answer count: 1

http://stackoverflow.com/q/50507456
tagged with: input
tagged with: python
type: UnansweredQuestion
has body: I am using CountVectorizer from sklearn python lib to vectorize a corpus from files with input='filename' option to init CountVectorizer from sklearn.feature_extraction.text import CountVectorizer corpus1=['file_name1','file_name2',...] count_vectorizer = CountVectorizer(input='filename') MAT1 = count_vectorizer.fit_transform(corpus1) Then I need to use the model to transform a new corpus but in numpy.array(['str1','str2']) corpus2 = numpy.array(['str1','str2']) # ideally MAT2 = count_vectorizer(input='content').transform(corpus2) this can be ususaly done when CountVectorizer is initialized with input='content' but I don't know how I can specify a new type of input. Any idea to do that or workaround solution ? Thanks !
score: -1
has answer: http://stackoverflow.com/a/50507824
has answer: http://stackoverflow.com/a/50507904
tagged with: corpus
tagged with: scikit-learn
tagged with: countvectorizer
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88027754
type: Question
has title: sklearn / CountVectorizer : fit then transform with different input corpus
upvote count: 0
answer count: 2

http://stackoverflow.com/q/50493132
has comment: http://stackoverflow.com/comment/88005849
type: UnansweredQuestion
has title: Run Celery in production with Supervisor
downvote count: 0
has body: I am trying to launch Celery v3.1.25 in production. As I have found in docs there are 4 ways to run it, 1 of them is to use Supervisor. I have used it before - my Django project is running using it. I made following steps: 1. Created /etc/supervisor/conf.d/mycelery.conf on the basics of official git repo. [program:mycelery] command=celery worker -A cosmetics_crawler_project --loglevel=INFO directory=/home/chiefir/polo/Cosmo user=chiefir numprocs=1 stdout_logfile=/home/chiefir/logs/celery/celery.log stderr_logfile=/home/chiefir/logs/celery/celery.log autostart=true autorestart=true startsecs=10 stopasgroup=true priority=1000 2. Created /etc/supervisor/conf.d/mycelerybeat.conf: [program:mycelerybeat] command=celery beat -A cosmetics_crawler_project --schedule /var/lib/celery/beat.db --loglevel=INFO directory=/home/chiefir/polo/Cosmo user=chiefir numprocs=1 stdout_logfile=/home/chiefir/logs/celery/celerybeat.log stderr_logfile=/home/chiefir/logs/celery/celerybeat.log autostart=true autorestart=true startsecs=10 stopasgroup=true priority=999 3. And my /etc/supervisord.conf is set to: [unix_http_server] file=/var/run/supervisor.sock ; (the path to the socket file) chmod=0700 ; sockef file mode (default 0700) [supervisord] logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) childlogdir=/var/log/supervisor ; ('AUTO' child log dir, default $TEMP) [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL for a unix socket [include] files = /etc/supervisor/conf.d/*.conf I have found in this question that I have to run supervisord to fire the Celery, but it throws error: Traceback (most recent call last): File "/usr/bin/supervisord", line 9, in &lt;module&gt; load_entry_point('supervisor==3.2.0', 'console_scripts', 'supervisord')() Fi…
tagged with: django
upvote count: 1
linked to: http://stackoverflow.com/q/31656717
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/88002497
tagged with: celery
favorite count: 0
has comment: http://stackoverflow.com/comment/88006767
has comment: http://stackoverflow.com/comment/88002750
type: Question
has comment: http://stackoverflow.com/comment/88005947
has comment: http://stackoverflow.com/comment/88036514
has comment: http://stackoverflow.com/comment/87999754
score: 1
has comment: http://stackoverflow.com/comment/88002881
tagged with: supervisord
tagged with: python
has comment: http://stackoverflow.com/comment/88006180
has comment: http://stackoverflow.com/comment/87999850
has comment: http://stackoverflow.com/comment/88040750
answer count: 0

http://stackoverflow.com/a/50437417
answers question: http://stackoverflow.com/q/50437251
score: 2
has body: The site-packages directory for a particular python installation is automatically added to sys.path when you run the binary for the installation. When that binary executes import modname, it looks in the directories on sys.path. So when you run pip install with a particular python binary, pip, by default, puts the package in the site-packages for that binary so that binary can import the package. Advanced used can do more complicated things.
type: Answer
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87814525
has text: Glad I could help :) !
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50399218

http://stackoverflow.com/a/52226468
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91402502
answers question: http://stackoverflow.com/q/50483601
has body: DBSCAN clustering algorithm with the maximum distance of points inside each group extension You can use the DBSCAN algorithm recursively. def DBSCAN_with_max_size(myData, eps = E, max_size = S): clusters = DBSCAN(myData, eps = E) Big_Clusters = find_big_clusters(clusters) for big_cluster in Big_Clusters: DBSCAN_with_max_size(big_cluster ,eps = E/2 ,max_size = S) //eps is something lower than E (e.g. E/2)

http://stackoverflow.com/a/50406616
downvote count: 0
upvote count: 1
score: 1
has body: You can use a list comprehension. result = [item + [a[item[0]]] for item in b] Output [['Volvo', 'VO', 657898], ['Volkswagen', 'VW', 387564]]
type: Answer
answers question: http://stackoverflow.com/q/50406571

http://stackoverflow.com/comment/87891357
comment on: http://stackoverflow.com/a/50436848
score: 0
type: Comment
has text: Oh yes I know now where the error `map_values_fn = lambda kv: (kv[0], f(kv[1])) KeyError: 0 ` occurs!! it's triggered in this line `.leftOuterJoin(idfs)\`. I added the format of idfs :)
type: AnswerComment

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/50453756
tags question: http://stackoverflow.com/q/50431585
tags question: http://stackoverflow.com/q/50475635
tags question: http://stackoverflow.com/q/50428640
tags question: http://stackoverflow.com/q/50415184
tags question: http://stackoverflow.com/q/50487995
tags question: http://stackoverflow.com/q/50422404
tags question: http://stackoverflow.com/q/50492713
tags question: http://stackoverflow.com/q/50440430
tags question: http://stackoverflow.com/q/50534779
tags question: http://stackoverflow.com/q/50457464
tags question: http://stackoverflow.com/q/50424196
tags question: http://stackoverflow.com/q/50428651
tags question: http://stackoverflow.com/q/50437116
tags question: http://stackoverflow.com/q/50503248
tags question: http://stackoverflow.com/q/50403717
tags question: http://stackoverflow.com/q/50408842
tags question: http://stackoverflow.com/q/50458201
tags question: http://stackoverflow.com/q/50486917
tags question: http://stackoverflow.com/q/50425008
tags question: http://stackoverflow.com/q/50494550
tags question: http://stackoverflow.com/q/50521716
tags question: http://stackoverflow.com/q/50534269
tags question: http://stackoverflow.com/q/50434101
tags question: http://stackoverflow.com/q/50537522
tags question: http://stackoverflow.com/q/50395618
tags question: http://stackoverflow.com/q/50456182
tags question: http://stackoverflow.com/q/50418725
tags question: http://stackoverflow.com/q/50438099
tag name: json
tags question: http://stackoverflow.com/q/50448342
tags question: http://stackoverflow.com/q/50515169
tags question: http://stackoverflow.com/q/50515609
tags question: http://stackoverflow.com/q/50503246
tags question: http://stackoverflow.com/q/50525633
tags question: http://stackoverflow.com/q/50451087
tags question: http://stackoverflow.com/q/50416841
tags question: http://stackoverflow.com/q/50497642
tags question: http://stackoverflow.com/q/50495330
tags question: http://stackoverflow.com/q/50397154
tags question: http://stackoverflow.com/q/50460037
tags question: http://stackoverflow.com/q/50527608
tags question: http://stackoverflow.com/q/50399071
tags question: http://stackoverflow.com/q/50516060
tags question: http://stackoverflow.com/q/50467244
tags question: http://stackoverflow.com/q/50392770
tags question: http://stackoverflow.com/q/50461620
tags question: http://stackoverflow.com/q/50457569
tags question: http://stackoverflow.com/q/50533016
tags question: http://stackoverflow.com/q/50491360
tags question: http://stackoverflow.com/q/50485037
tags question: http://stackoverflow.com/q/50539399
tags question: http://stackoverflow.com/q/50486643
tags question: http://stackoverflow.com/q/50420451
tags question: http://stackoverflow.com/q/50427992
tags question: http://stackoverflow.com/q/50418250
tags question: http://stackoverflow.com/q/50522042
tags question: http://stackoverflow.com/q/50494135
tags question: http://stackoverflow.com/q/50458339
tags question: http://stackoverflow.com/q/50472520
tags question: http://stackoverflow.com/q/50425402
tags question: http://stackoverflow.com/q/50489970
tags question: http://stackoverflow.com/q/50434189
tags question: http://stackoverflow.com/q/50501595
tags question: http://stackoverflow.com/q/50483425
tags question: http://stackoverflow.com/q/50426533
tags question: http://stackoverflow.com/q/50505345
tags question: http://stackoverflow.com/q/50438288
tags question: http://stackoverflow.com/q/50518120
tags question: http://stackoverflow.com/q/50500135
tags question: http://stackoverflow.com/q/50518484
tags question: http://stackoverflow.com/q/50404559
tags question: http://stackoverflow.com/q/50519818
tags question: http://stackoverflow.com/q/50393834
type: Tag
tags question: http://stackoverflow.com/q/50427125
tags question: http://stackoverflow.com/q/50541662
tags question: http://stackoverflow.com/q/50455945
tags question: http://stackoverflow.com/q/50428931
tags question: http://stackoverflow.com/q/50540370

http://stackoverflow.com/q/50533775
downvote count: 0
has comment: http://stackoverflow.com/comment/88096221
has comment: http://stackoverflow.com/comment/88089023
favorite count: 0
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/72337941
tagged with: zooming
score: 5
linked to: http://stackoverflow.com/q/46637050
has comment: http://stackoverflow.com/comment/88082444
has answer: http://stackoverflow.com/a/72436281
has comment: http://stackoverflow.com/comment/100261996
tagged with: windows
upvote count: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/65751931
linked to: http://stackoverflow.com/q/15072736
has answer: http://stackoverflow.com/a/65751931
answer count: 4
has comment: http://stackoverflow.com/comment/88096210
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52353316
has answer: http://stackoverflow.com/a/52353316
has title: Zooming functionality in OpenCV imshow in Windows
linked to: http://stackoverflow.com/q/28595958
has body: In Ubuntu, OpenCV's imshow function has a window where different options such as zoom in, zoom out, pan window, etc, are available, like this: However, in Windows, these features are absent. I have a particular case where I need to deploy my OpenCV code on Windows, where the user needs to zoom into parts of the image. Is there any way to access/add these functionalities in Windows also?

http://stackoverflow.com/comment/87850447
type: Comment
comment on: http://stackoverflow.com/a/50417191
score: 0
type: AnswerComment
has text: I don't have a windows machine handy at the moment so this is all just from recall... but its the buffering that is the problem. The example code sleeps to simulate delayed output. I don't think this will show output in real time.

http://stackoverflow.com/q/50459203
tagged with: beautifulsoup
type: Question
upvote count: 4
has body: I am looking for a solution using Python and BeautifulSoup to find an element based on the inside text. For example: Ignore this textFind based on this text How can I find this div? Thanks for you helps!
tagged with: python-3.x
answer count: 2
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/8936030
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50461772
has answer: http://stackoverflow.com/a/50461772
has title: How to find element based on text ignore child tags in beautifulsoup
downvote count: 0
possible better answer: http://stackoverflow.com/a/50459821
favorite count: 0
has answer: http://stackoverflow.com/a/50459821

http://stackoverflow.com/comment/87908441
comment on: http://stackoverflow.com/q/50447533
type: QuestionComment
score: 0
type: Comment
has text: But it's getting the Runtime Error in the website, not my computer

http://stackoverflow.com/comment/88005089
has text: for `s = 'MTD loan slip dated 8-10-14 the Issued'` this does not work for me
type: Comment
comment on: http://stackoverflow.com/a/50495580
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87879655
type: Comment
type: QuestionComment
has text: this is 'utf-8'
comment on: http://stackoverflow.com/q/50432533
score: 0

http://stackoverflow.com/comment/87878146
score: 6
comment on: http://stackoverflow.com/q/50431921
type: Comment
type: QuestionComment
has text: Because at that point you're just creating member variables and not necessary adding to the dictionary (in the second example)

http://stackoverflow.com/q/50499340
type: Question
accepted answer: http://stackoverflow.com/a/50500004
has comment: http://stackoverflow.com/comment/88011532
has answer: http://stackoverflow.com/a/50500004
linked to: http://stackoverflow.com/q/48391777
tagged with: python
has title: Specify options and arguments dynamically
score: 10
tagged with: command-line-interface
type: AnsweredQuestion
tagged with: python-click
has body: I'd like to load arguments and options from a database. I am allowing users to define their own options and arguments. Users can call a remote api on the command line. They specify the URL and parameters to the end point. Here is what the data from database looks like [ { "name": "thename1", "short": "a", "long": "ace" "type": "string", "required": false }, { "name": "thename2", "short": "b", "long": "bravo" "type": "number", "required": true }, { "name": "thename3", "short": "c", "long": "candy" "type": "array", "required": true } ] These parameters align with what the remote end point needs. Each API endpoint has different parameters hence the reason they need to be dynamic. Here is how the command line will look. command run www.mysite.com/api/get -a testparam --bravo testpara2 -c item1 item2 The param and value will be mapped in a URL. Is there a way to setup dynamic parameters in click?
downvote count: 0
answer count: 1
upvote count: 10
has comment: http://stackoverflow.com/comment/88011594
favorite count: 0

http://stackoverflow.com/a/59347041
has comment: http://stackoverflow.com/comment/112270605
answers question: http://stackoverflow.com/q/50389852
type: Answer
upvote count: 3
downvote count: 0
has body: "If you find IntelliSense has stopped working, the language service may not be running. Try restarting VS Code and this should solve the issue." From https://code.visualstudio.com/docs/editor/intellisense and helped to me
score: 3

http://stackoverflow.com/q/50503960
score: 21
favorite count: 0
has body: I need to increase the dpi of my image before reading with ocr in opencv. The problems are : I do not know the dpi of my image right now I do not know how to increase the dpi of an image I searched in Google, and almost every answer suggests using cv2.resize image = cv2.imread("source.png") resized_image = cv2.resize(image, (100, 50)) #I need to change it to 300 DPI resize only changes the size of image, but after all does not increase the dpi. I tried to use it, and then checked in Photoshop, the dpi was not changed. How to do it with opencv? I need to change dpi to 300, why do I need to know current dpi? Because if it is already dpi > 300, I do not need to convert it. I do it with python.
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/78119700
has answer: http://stackoverflow.com/a/50504361
upvote count: 23
type: Question
tagged with: opencv
answer count: 3
has title: how to increase dpi with opencv?
has comment: http://stackoverflow.com/comment/88020902
linked to: http://stackoverflow.com/q/10860969
has answer: http://stackoverflow.com/a/57572801
tagged with: python

http://stackoverflow.com/comment/87792303
has text: `arr = [int(x, 16) for x in s.split(',')]`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50387760
type: Comment

http://stackoverflow.com/comment/132037192
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/53070679
score: 0
has text: My problem was solved by option 2. IntelliSense was working for me, but not for methods of inherited classes. Googling that specific issue turns up many results that lead in the wrong direction. I hope someone with the same problem with Inherited classes not being available in IntelliSense can find your answer.

http://stackoverflow.com/q/50471802
favorite count: 0
score: 12
type: Question
has comment: http://stackoverflow.com/comment/88237979
answer count: 2
has answer: http://stackoverflow.com/a/50590177
upvote count: 12
tagged with: serverless
has comment: http://stackoverflow.com/comment/88237839
downvote count: 0
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/88156188
has answer: http://stackoverflow.com/a/50559260
tagged with: serverless-framework
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50559260
accepted answer: http://stackoverflow.com/a/50590177
has comment: http://stackoverflow.com/comment/88187226
has body: I have a Python Serverless project that uses a private Git (on Github) repo. Requirements.txt file looks like this: itsdangerous==0.24 boto3&gt;=1.7 git+ssh://git@github.com/company/repo.git#egg=my_alias Configurations of the project mainly looks like this plugins: - serverless-python-requirements - serverless-wsgi custom: wsgi: app: app.app packRequirements: false pythonRequirements: dockerizePip: true dockerSsh: true When I deploy using this command: sls deploy --aws-profile my_id --stage dev --region eu-west-1 I get this error: Command "git clone -q ssh://git@github.com/company/repo.git /tmp/pip-install-a0_8bh5a/my_alias" failed with error code 128 in None What am I doing wrong? I'm suspecting either the way I configured my SSH key for Github access or the configurations of the serverless package.
has title: Serverless: Using a private Python package as a dependency

http://stackoverflow.com/q/50496637
has body: I am using MacOS High Sierra and recently got this issue while any python related installations. I am trying to update setup tools pip install --upgrade setuptools &gt;&gt;&gt;spacy 2.0.11 has requirement regex==2017.4.5, but you'll have regex 2017.11.9 which is incompatible. Please suggest how to fix this issue
tagged with: python
accepted answer: http://stackoverflow.com/a/50496789
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50496789
upvote count: 3
downvote count: 0
tagged with: pip
possible better answer: http://stackoverflow.com/a/51645293
tagged with: macos
favorite count: 0
has answer: http://stackoverflow.com/a/51645293
type: Question
score: 3
has title: Spacy 2.0.11 has requirement regex==2017.4.5, but you'll have regex 2017.11.9 which is incompatible

http://stackoverflow.com/a/50718770
upvote count: 12
accepted answer of: http://stackoverflow.com/q/50459326
type: Answer
answers question: http://stackoverflow.com/q/50459326
score: 12
downvote count: 0
has body: I can't fix your lexer code, but I can give you a working example for the same import sys from PyQt5.Qt import * from PyQt5.Qsci import QsciScintilla, QsciLexerCPP from PyQt5.Qsci import QsciLexerCustom if sys.hexversion &lt; 0x020600F0: print('python 2.6 or greater is required by this program') sys.exit(1) _sample = """ # Sample config file this is a junk line [FirstItem] Width=100 Height=200 Colour=orange Info=this is some multiline text [SecondItem] Width=200 Height=300 Colour=green Info= this is some multiline text """ class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setWindowTitle('Custom Lexer For Config Files') self.setGeometry(50, 200, 400, 400) self.editor = QsciScintilla(self) self.editor.setUtf8(True) self.editor.setMarginWidth(2, 15) self.editor.setFolding(True) self.setCentralWidget(self.editor) self.lexer = ConfigLexer(self.editor) self.editor.setLexer(self.lexer) self.editor.setText(_sample) class ConfigLexer(QsciLexerCustom): def __init__(self, parent): QsciLexerCustom.__init__(self, parent) self._styles = { 0: 'Default', 1: 'Comment', 2: 'Section', 3: 'Key', 4: 'Assignment', 5: 'Value', } for key,value in self._styles.items(): setattr(self, value, key) self._foldcompact = True def foldCompact(self): return self._foldcompact def setFoldCompact(self, enable): self._foldcompact = bool(enable) def language(self): return 'Config Files' def description(self, style): return self._styles.get(style, '') def defaultColor(self, style): if style == self.Default: return QColor('#000000') elif style == self.Comment: return QColor('#A0A0A0') elif style == self.Section: return QColor('#CC6600') elif style == self.Key: return QColor('#0000CC') elif style == self.Assignment: return QColor('#CC0000') elif style == self.Value: return QColor('#00CC00') return QsciLexerCustom.defaultColor(self, style) def defaultPaper(self, style): if style == self.Section: return QColor('#FFEECC') return QsciLexerCustom.defaultPaper(self, style) def def…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88694326

http://stackoverflow.com/a/50466721
downvote count: 0
has comment: http://stackoverflow.com/comment/87948233
type: Answer
accepted answer of: http://stackoverflow.com/q/50465865
upvote count: 2
has comment: http://stackoverflow.com/comment/87977749
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87948494
has body: IMHO, regexp is overkill and error prone for this task. I would do something like: result ="""interface xe-1/2/0.0; interface ge-1/2/1.0; interface lo0.0 { """ for l in result.split("\n"): l = l.split(" ") if l[0] == "interface": # cause grep on "int" iface = l[1] if iface[0:3] == "xe-": arg=iface.split(".")[0] # do something with arg print(arg) produces : xe-1/2/0
answers question: http://stackoverflow.com/q/50465865
has comment: http://stackoverflow.com/comment/87954727
score: 2
has comment: http://stackoverflow.com/comment/87948924
has comment: http://stackoverflow.com/comment/87949275

http://stackoverflow.com/q/50513728
has comment: http://stackoverflow.com/comment/88040978
has comment: http://stackoverflow.com/comment/88040959
tagged with: python
has answer: http://stackoverflow.com/a/50534246
tagged with: forms
has comment: http://stackoverflow.com/comment/88040087
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88041135
accepted answer: http://stackoverflow.com/a/50534246
has body: I have a custom user model that I need to add an extra field to. The problem I have is that the information needed is user input from the registration page. This is the code from the form: team = forms.ChoiceField(choices=teamChoices) This is my user model: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I need to add something like this: groups = 'team' But I don't know how I would get that information to my model. My user model is in models.py and my registration form is in forms.py. This is is my current Register Form but I haven't tested to see if it works yet: class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder':'First Name', 'class': 'form-input'})) last_name = forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder':'Last Name', 'class': 'form-input'})) email = forms.EmailField(max_length=254, widget=forms.TextInput(attrs={'placeholder':'Email', 'class': 'form-input'})) teamChoices = (('red','red'),('green','green'),('blue','blue'),('orange','orange')) team = forms.ChoiceField(choices=teamChoices) class Meta: model = User fields = ('first_name','last_name','email','team','password1','password2')
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/88041025
has comment: http://stackoverflow.com/comment/88041728
has title: How to pass in user input into Custom User Model in Django
type: Question
tagged with: model
has comment: http://stackoverflow.com/comment/88041055

http://stackoverflow.com/q/50451087
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87915392
has comment: http://stackoverflow.com/comment/87915355
accepted answer: http://stackoverflow.com/a/50451288
has comment: http://stackoverflow.com/comment/87915425
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50451288
answer count: 1
downvote count: 0
has body: Can someone help me access the "pagination" field in the following API response? I have tried the code below but get an error 'pagination'. It works for 'title' so I'm not sure what's different. Full error below. Traceback (most recent call last): File "myscript.py", line 172, in &lt;module&gt; pag_object = (data['pagination']) KeyError: 'pagination' My code: response = requests.get("https://api.weather.gov/alerts?limit=1", timeout=5) data = response.json() pag_object = (data['pagination']) I have verified that the JSON is valid. Snippet below. { "@context": [ "https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld", { "wx": "https://api.weather.gov/ontology#", "@vocab": "https://api.weather.gov/ontology#" } ], "type": "FeatureCollection", "features": [{ "id": "http://api.weather.gov/alerts/NWS-IDP-PROD-KEEPALIVE-22613", "type": "Feature", "properties": { "@type": "wx:Alert", "id": "NWS-IDP-PROD-KEEPALIVE-22613", "areaDesc": "Montgomery", "geocode": { "UGC": [ "MDC031" ], "SAME": [ "024031" ] }, "affectedZones": [ "http://api.weather.gov/zones/county/MDC031" ], "references": [], "sent": "2018-05-21T14:05:51+00:00", "event": "Test Message", "senderName": "NWS", "description": "Monitoring message only. Please disregard.", "parameters": { "PIL": [ "NWSKEPWBC" ], "BLOCKCHANNEL": [ "CMAS", "NWEM" ] } } }], "title": "Watches, warnings, and advisories", "pagination": { "next": "http://api.weather.gov/alerts?limit=1&amp;cursor=eyJ0IjoxNTI2OTExNTUxLCJpIjoiTldTLUlEUC1QUk9ELUtFRVBBTElWRS0yMjYxMyJ9" } }
has comment: http://stackoverflow.com/comment/87915335
has comment: http://stackoverflow.com/comment/87915284
favorite count: 0
type: Question
tagged with: python-2.6
has comment: http://stackoverflow.com/comment/87915325
tagged with: pagination
tagged with: python
has comment: http://stackoverflow.com/comment/87915509
has title: KeyError accessing field in JSON
score: 2

http://stackoverflow.com/comment/88028419
score: 1
type: Comment
type: QuestionComment
has text: How does 17 give you the range 35-50? What's the logic? What happens for other values? What codes did you try? Where did you get stuck? See [How to Ask](https://stackoverflow.com/help/how-to-ask) for more details.
comment on: http://stackoverflow.com/q/50508262

http://stackoverflow.com/comment/88025846
type: AnswerComment
score: 0
has text: Admittedly, I am not an expert in parallel processing so I don't fully understand the warning. But I did try setting `threading.current_thread().name == 'MainThread'` as suggested in the post you referenced, and it didn't help.
type: Comment
comment on: http://stackoverflow.com/a/50506584

http://stackoverflow.com/q/50506247
score: 0
tagged with: list
downvote count: 2
has comment: http://stackoverflow.com/comment/88025200
answer count: 3
has body: I'm having some problems in selecting the first element of a line with python. I have a txt file where the data are organized in this way: 0 3 546 1 2 435 2 4 900 22 3 384 I would like to print the lines whose first member matches with that of a list: myList = [1, 22] I've tried to do in this way: for i in externalFile: if i[0] in myList: print (i) but it return to me: 1 2 435 2 4 900 22 3 384 because it finds, I suppose, a match between the "22" of myList and the "2" of the external file. Does someone know how to fix this problem?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50506276
has answer: http://stackoverflow.com/a/50506569
type: UnansweredQuestion
has title: Select the first element of a line with python
has answer: http://stackoverflow.com/a/50506337
tagged with: python
upvote count: 2

http://stackoverflow.com/q/50494550
linked to: http://stackoverflow.com/q/35969611
linked to: http://stackoverflow.com/q/41843550
has answer: http://stackoverflow.com/a/50496642
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: Creating Nested Json from CSV with incomplete rows
has body: I've cobbled together a few disparate excel/csv files with pandas for a database I am trying to build. I've seen a few examples here of creating nested Jsons from csvs, and while those have helped to partially replicate what I need, they ultimately have fallen short. Rather that being flat, my data is stepwise like this where data is 'joined' by a subject id #, but information on individual visits and samples are on separate rows with 'NaN' for unrelated columns. in csv format: subject_id,name,dob,gender,visit_date,date_entered,entered_by,sample_id,collected_by,collection_date 1,Bob,1/1/00,M,,,,,, 1,,,,1/1/18,1/2/18,Sally,,, 1,,,,1/2/18,1/2/18,Tim,,, 1,,,,,,,XXX123,Sally,1/3/18 2,Mary,1/2/00,F,,,,,, 2,,,,1/3/18,1/4/18,Sally,,, 2,,,,,,,YYY456,Sally,1/5/18 2,,,,,,,ZZZ789,Tim,1/6/18 I'm trying to get an output like this: { 'subject_id': '1' 'name': 'Bob', 'dob': '1/1/00', 'gender': 'M', 'visits': { '1/1/18': { 'date_entered': '1/2/18', 'entered_by': 'Sally', } '1/2/18': { 'date_entered': '1/2/18', 'entered_by': 'Tim', } } 'samples': { 'XXX123': { 'collected_by': 'Sally', 'collection_date': '1/3/18', } } } { 'subject_id': '2' 'name': 'Mary', 'dob': '1/2/00', 'gender': 'F', 'visits': { '1/3/18': { 'date_entered': '1/4/18', 'entered_by': 'Sally', } } 'samples': { 'YYY456': { 'collected_by': 'Sally', 'collection_date': '1/5/18', } 'ZZZ789': { 'collected_by': 'Tim', 'collection_date': '1/6/18', } } } Where information on visits and samples are nested under the more general information. This is obviously a simplified dataset of what I am trying to accomplish, but any advice would be greatly appreciated. Thanks. EDIT: More accurate reflection of csv data. Not as streamlined or complete as original example. 'subid,firstvisit,name,contact,dob,gender,visitdate1,age,visitcategory,samplenumber,label_on_sample,completed_by 1,12/31/11,Bob,,12/31/00,Male,,,,,, 1,,,,,,12/31/15,17,Baseline Visit,,, 1,,,,,,12/31/16,18,Follow Up Visit,,, 1,,,,,,12/31/17,18,Follow Up Visit,,, 1,,,,12/31/0…
tagged with: http://stackoverflow.com/tag/json
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50496642
tagged with: mongodb
tagged with: python

http://stackoverflow.com/a/50533613
answers question: http://stackoverflow.com/q/50517000
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50517000
score: 2
has body: I've just had the same issue. You can add verify: false to your request yaml.
has comment: http://stackoverflow.com/comment/88181077
type: Answer
upvote count: 2

http://stackoverflow.com/comment/87849281
type: Comment
type: QuestionComment
has text: Discord is getting the right output with subprocess.check_output() but its showing tabs and newlines as \t and \n respectively.
comment on: http://stackoverflow.com/q/50408331
score: 0

http://stackoverflow.com/q/50490856
score: 9
has body: Currently I am using json to save a dict to a config file. I load this to turn it into a dict then turn it into a SimpleNamespace because I prefer dot notation to access the settings. To do this, I load it as in this example: import json from types import SimpleNamespace SETTINGS = json.load(open("config.json", 'r')) SETTINGS = SimpleNamespace(**SETTINGS) However, as I am currently loading the dict into a SimpleNamespace it is not loading the sub dicts within the config file. So for example if I do: SETTINGS.server_info.port I get the error: AttributeError: 'dict' object has no attribute 'port' I was wondering how I load all dicts into the namespace as name spaces so that I am able to use dot notation all the way down the dictionary.
answer count: 2
downvote count: 0
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50491346
linked to: http://stackoverflow.com/q/24601722
has answer: http://stackoverflow.com/a/50491346
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50491016
has title: Creating a namespace with a dict of dicts
has answer: http://stackoverflow.com/a/50491016
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 9

http://stackoverflow.com/comment/87812680
type: Comment
score: 0
type: AnswerComment
has text: I don't think it's necessary to slice and perform the aggregations separately requiring you to concat at the end.
comment on: http://stackoverflow.com/a/50398274

http://stackoverflow.com/comment/88047043
comment on: http://stackoverflow.com/a/50496136
score: 0
type: Comment
has text: My path includes `/usr/lib/`. Doesn't that mean BLAS is also visible since it is a subdirectory? Also, I did `echo $PATH` then `/etc/profile.d/lapack0.sh` then `echo $PATH`. The `$PATH$` is the same even after running the shell script.
type: AnswerComment

http://stackoverflow.com/comment/87826919
type: Comment
type: QuestionComment
has text: Try upgrading to newer version of python
comment on: http://stackoverflow.com/q/50405072
score: 0

http://stackoverflow.com/q/50493974
score: 1
answer count: 1
downvote count: 0
has body: Just wondering if there is a more elegant way to retrieve a value from a specific object in a list based on if the object contains a particular value or if I have to write something to traverse the list and look at each of the objects. For example: class C(object): def __init__(self, url, value): self.url=url self.value=value obj1 = C("http://1", 1) obj2 = C("http://2", 2) mylist = [obj1, obj2] # I want to search mylist and retrieve the "value" element if there is # an object with a "url" value of "http://2"...basically retrieve the # value 2 if an element exists in the list with a url value of "http://2" Of course if I knew it existed in the 1st element of the list I could retrieve it by: mylist[1].value However, in my case I don't know if that object exists in the list or not nor do I know in what position in the list it exists.
accepted answer: http://stackoverflow.com/a/50495689
favorite count: 0
type: Question
has title: Retrieve element of object from list based on object key in Python
has comment: http://stackoverflow.com/comment/88002136
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50495689

http://stackoverflow.com/comment/87906770
has text: For helping others :)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50445697
type: QuestionComment

http://stackoverflow.com/q/50419394
possible better answer: http://stackoverflow.com/a/50419581
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50419611
has body: i have a sample data set: import pandas as pd import numpy as np d = { 'ID': ['A','B','C','D','E'], 'index_1':[2,0,2,-2,0], 'index_2':[-2,-2,0,0,0], 'index_3':[2,2,2,2,0], 'index_4':[2,2,0,-2,0], 'index_total':[2,2,2,2,2] } df = pd.DataFrame(d) it looks like: ID index_1 index_2 index_3 index_4 index_total 0 A 2 -2 2 2 2 1 B 0 -2 2 2 2 2 C 2 0 2 0 2 3 D -2 0 2 -2 2 4 E 0 0 0 0 2 i want to create a column named 'flag' based on following conditions for each row: if any of the columns 'index_1', 'index_2', 'index_3', 'index_4' contains the value -2 AND 'index_total' = 2 then flag = 1 if columns 'index_1', 'index_2', 'index_3', 'index_4' only contain the value 0 AND 'index_total' = 2 then flag = 1 else: flag = 0 desired output: ID index_1 index_2 index_3 index_4 index_total flag 0 A 2 -2 2 2 2 1 1 B 0 -2 2 2 2 1 2 C 2 0 2 0 2 0 3 D -2 0 2 -2 2 1 4 E 0 0 0 0 2 1 my attempts (note i use loops for the index_1, index_2, index_3 and index_4 column names instead of writing them out because in my actual data set there are more than 70 index_ columns) 1st attempt: for colname in df.columns: if "index_" in colname: df[colname] = df[colname].astype(int) #making sure the numbers are all integer for comparison if ((df[colname] == -2).any() and df['index_total']==2): df['flag'] = 1 #this doesn't work , it's going by columns not rows 2nd attempt: for index, row in df.iterrows(): for colname in df.columns: if "index_" in colname: if( (df[colname][index] == -2).any() and df['index_total']==2 ): df['flag'] = 1 # i stopped writing the other conditions because this one doesn't work
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50419611
upvote count: 2
has title: new column based on row and column conditions pandas python
score: 1
has answer: http://stackoverflow.com/a/50419581
has answer: http://stackoverflow.com/a/50419584
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87855096

http://stackoverflow.com/q/50509163
tagged with: python
accepted answer: http://stackoverflow.com/a/50511571
has answer: http://stackoverflow.com/a/50511571
type: AnsweredQuestion
score: 0
tagged with: type-hinting
answer count: 1
has body: I have the following code with python type hints It has a bunch of errors. All erros in code are found by mypy but not the errors in constructor of S. Why? I cannot find out what is happening thanks code: import typing class T(object): def __init__(self, a: int, b: str = None) -&gt; None: self.a = a self.b: typing.Union[str, None] = b self._callback_map: typing.Dict[str, str] = {} class S(T): def __init__(self): super().__init__(self, 1, 2) self._callback_map[1] = "TOTO" s = T(1, 1) t = T(1, b=2) t._callback_map[2] = "jj" s = T(1, 2) t = T(1, b=2) t._callback_map[2] = "jj" output of mypy: t.py:22: error: Argument 2 to "T" has incompatible type "int"; expected "Optional[str]" t.py:24: error: Argument "b" to "T" has incompatible type "int"; expected "Optional[str]" rt.py:25: error: Invalid index type "int" for "Dict[str, str]"; expected type "str" This is fine, but the same errors (same lines) in 'init' at line 16, 17, 18 are not found at all...
has title: Python: All type hints errors in subclass constructure seems ignored
type: Question
tagged with: mypy
has comment: http://stackoverflow.com/comment/88030332

http://stackoverflow.com/comment/87802075
has text: It worked perfectly in python shell mode, but when I included in my code, it occurred the error : "(-2147221008, 'CoInitialize não foi chamado.', None, None)"
comment on: http://stackoverflow.com/a/50392695
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50520820
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/88054228
type: UnansweredQuestion
downvote count: 0
has body: I am trying to get tkinter to clear an entry box each time a button is pressed How I want my program to work is this. Whenever a user selects a statistical distribution, a row of varriable entry boxes appears to the right (the number of variable entry boxes vary by statisical distribution. I would like the user to be able to change the values of the entry boxes multiple times. The variables then feed into a calculation later in the script. Currently, the entry box only stores and returns the first value entered by the user. Therefore, I want to clear the entrybox each time before the final calculation is called. I know that I need to use the variablename.delete(0,END) command, but I am having trouble with its implementation. I can succsefully get the entrybox to clear, but for some reason, whenever I insert this syntax into the code, my labeling syntax ceases working. Below is my current code. I have included 2 separate blocks of the code. The first shows my current attempt on fixing the problem using the variablename.delete(0,END) method. The deleting method works fine, but for some reason import tkinter as tk from tkinter.ttk import * from scipy.stats import * import numpy as np import pandas as pd master = tk.Tk() master.title("Gas Calculator") v = tk.IntVar() combo = Combobox(master) #possible entry boxes depending on the statistic distribution chosen f1 = tk.Entry(master) f2 = tk.Entry(master) f3 = tk.Entry(master) f4 = tk.Entry(master) f5 = tk.Entry(master) f6 = tk.Entry(master) f7 = tk.Entry(master) f8 = tk.Entry(master) f1.grid(row=3, column=5) f2.grid(row=3, column=6) f3.grid(row=3, column=7) f4.grid(row=3, column=8) f5.grid(row=3, column=9) f6.grid(row=3, column=10) #calls the users distribution selection and then is supposed to format the boxes accordinly def callbackARS(eventObject): ARDist=(comboARS.get()) try: if ARDist == "Truncated Normal": f1.delete(0,tk.END) f1 = tk.Entry(master) f2 = tk.Entry(master) f3 = tk.Entry(master) f4 = tk.Entry(master) f5 …
upvote count: 1
has comment: http://stackoverflow.com/comment/88068724
has title: Clearing entry box values in tkinter error
score: 1
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88054432

http://stackoverflow.com/a/50397913
has body: you could use list comprehension syntax. I show the derived array result and a final if conditional statement example. ColorsA = ['red', 'yellow', 'green'] ColorsB = ['red', 'white', 'blue'] ColorsC = ['white', 'blue', 'green'] print print [x for x in ColorsA if x not in ColorsB] print [x for x in ColorsA if x not in ColorsC] print [x for x in ColorsA if ((x not in ColorsC) and (x not in ColorsB))] if (len([x for x in ColorsA if ((x not in ColorsC) and (x not in ColorsB))])==0): print "some elements in ColorsA are not found in ColorsB or ColorsC" else: print "All elements in ColorsA are found in either ColorsB or ColorsC" which gives you the output ['yellow', 'green'] ['red', 'yellow'] ['yellow'] some elements in ColorsA are not found in ColorsB or ColorsC
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50395811

http://stackoverflow.com/q/50462309
type: Question
has comment: http://stackoverflow.com/comment/87940117
has comment: http://stackoverflow.com/comment/87939637
downvote count: 0
type: UnansweredQuestion
tagged with: datetime
answer count: 1
tagged with: python
has body: I am trying to filter dataframe by 2 months window. I have a dataframe of 4 months. Sample dataframe: Index val Datetime 2017-11-01 14:30:00 536.04 2017-11-01 14:30:00 2017-11-01 15:00:00 533.04 2017-11-01 15:00:00 ... ... ... 2017-12-31 10:00:00 145.02 2017-12-31 10:00:00 2017-12-31 10:30:00 145.92 2017-12-31 10:30:00 I tried this: df2[df2['Datetime'] &lt; df2['Datetime'].min() + dateutil.relativedelta.relativedelta(months = 2) + Timedelta('%sD' %x)] output: 2017-11-01 14:30:00 536.04 2017-11-01 14:30:00 2017-11-01 15:00:00 533.04 2017-11-01 15:00:00 ... ... ... 2017-12-31 10:00:00 145.02 2017-12-31 10:00:00 2017-12-31 10:30:00 145.92 2017-12-31 10:30:00 2017-11-01 14:30:00 536.04 2017-11-01 14:30:00 2017-11-01 15:00:00 533.04 2017-11-01 15:00:00 ... ... ... 2018-01-01 10:00:00 145.62 2018-01-01 10:00:00 2018-01-01 10:30:00 151.50 2018-01-01 10:30:00 The datafame is increasing by 1 day but but the start day is fixed. I want to shift dataframe by 2 months with each increasing day. expected output: 2017-11-01 14:30:00 536.04 2017-11-01 14:30:00 2017-11-01 15:00:00 533.04 2017-11-01 15:00:00 ... ... ... 2017-12-31 10:00:00 145.02 2017-12-31 10:00:00 2017-12-31 10:30:00 145.92 2017-12-31 10:30:00 2017-11-02 14:30:00 536.04 2017-11-02 14:30:00 2017-11-02 15:00:00 533.04 2017-11-02 15:00:00 ... ... ... 2018-01-01 10:00:00 145.62 2018-01-01 10:00:00 2018-01-01 10:30:00 151.50 2018-01-01 10:30:00
has comment: http://stackoverflow.com/comment/87938150
has comment: http://stackoverflow.com/comment/87939015
tagged with: timestamp
has comment: http://stackoverflow.com/comment/88971843
has title: filter dataframe in a for loop for a period of two months with 1 day increasing
has comment: http://stackoverflow.com/comment/87937671
has answer: http://stackoverflow.com/a/50465544
has comment: http://stackoverflow.com/comment/88965405
tagged with: pandas
upvote count: 1
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87937723
favorite count: 0

http://stackoverflow.com/q/50435988
tagged with: datetime-format
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50436038
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50436038
has title: Trouble producing list of dates in a customized manner
has body: I've written a script to produce list of dates. The script I've tried with can do it. However, the way I need the list of dates is very different from what I'm getting at this moment. The script I've tried with: import datetime start = datetime.datetime(2017,1,1) end = datetime.datetime(2017,6,20) daterange = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)] for idate in daterange: print(idate) Current results are like: 2017-01-01 00:00:00 2017-01-02 00:00:00 2017-01-03 00:00:00 2017-01-04 00:00:00 2017-01-05 00:00:00 2017-01-06 00:00:00 The way I expect to get the dates like: 01-01-2017 01-02-2017 01-03-2017 01-04-2017 01-05-2017 01-06-2017 How can I modify my script to achieve the same? Thanks in advance.
tagged with: python
tagged with: date

http://stackoverflow.com/comment/87952759
type: Comment
has text: I can't code for you. Obviously your last error doesn't related to your original question
type: AnswerComment
comment on: http://stackoverflow.com/a/50468231
score: 0

datagridview
tag name: datagridview
tags question: http://stackoverflow.com/q/50487227
type: Tag

http://stackoverflow.com/a/50534201
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50406898
has body: As it turns out, the ios_user module is not compatible with Cisco IOS version 12.2(55)SE because it is using an output filter ("section") which is not available for this device's version. To fix this, I just had to substitute the word "section" with "include" in the ansible/modules/network/ios/ios_user.py file (the complete file path depends on your ansible instalation, because you might be using a virtual environment). Here is the module code. So that part of the the code then looked like this: def map_config_to_obj(module): data = get_config(module, flags=['| include username']) match = re.findall(r'^username (\S+)', data, re.M) if not match: return list() The module now works as intendeed. As for the ios_ping, I've been trying to reverse engineer it's code and, in my opinion, has more then one bug. I think it is working only when the success rate is above 0%.
type: Answer
answers question: http://stackoverflow.com/q/50406898
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50412224
answer count: 2
type: UnansweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I am trying to plot a boxplot which box is filled. I would also like it to have a custom-colour border (different than the whiskers are). I have found an answer how to enable filled boxplots. Unfortunately the 'edgecolor' boxprops property does not work as expected: plt.boxplot(np.random.normal(size=1000), patch_artist=True, boxprops={'facecolor': '#AAAAAA', 'edgecolor': '#FFCC00'}) results with: How can I change the border colour of the box alone? Preferably in call to the plt.boxplot().
has title: Border colour of matplotlib filled boxplots
tagged with: matplotlib
tagged with: boxplot
linked to: http://stackoverflow.com/q/20289091
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/69603714
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50412586

xml-namespaces
type: Tag
tags question: http://stackoverflow.com/q/50453543
tag name: xml-namespaces
tags question: http://stackoverflow.com/q/50387482

http://stackoverflow.com/comment/87991812
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50488628
has text: Do you want to be able to access that PanedWindow outside the drawBoard method? If so, you should make it an attribute, not a local variable, that is, `self.pane_1 = ttk.PanedWindow(master, orient='horizontal')`
score: 0

http://stackoverflow.com/comment/88044204
has text: `shlex.split` splits a string like a shell. By default the `-h` Action displays the help and does a `sys.exit`. If you don't want the exit, you need to either catch it in a `if/except` block, or omit it with `add_help=False` parameter. You could then add your own `-h` as a `store_true`.
score: 3
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50515694

http://stackoverflow.com/a/50503052
answers question: http://stackoverflow.com/q/50503033
type: AcceptedAnswer
score: 19
has body: If not datetime column need to_datetime with dt.date: print (df.dtypes) Date object Price int64 dtype: object df['Date'] = pd.to_datetime(df['Date']).dt.date print (df.dtypes) Date object Price int64 dtype: object print (df['Date'].head().apply(type)) 0 &lt;class 'datetime.date'&gt; 1 &lt;class 'datetime.date'&gt; 2 &lt;class 'datetime.date'&gt; Name: Date, dtype: object Or if need datetimes without hours, minutes and seconds use dt.floor: df['Date'] = pd.to_datetime(df['Date']).dt.floor('d') print (df.dtypes) Date datetime64[ns] Price int64 dtype: object print (df['Date'].head().apply(type)) 0 &lt;class 'pandas._libs.tslibs.timestamps.Timesta... 1 &lt;class 'pandas._libs.tslibs.timestamps.Timesta... 2 &lt;class 'pandas._libs.tslibs.timestamps.Timesta... Name: Date, dtype: object If datetime column: print (df.dtypes) Date datetime64[ns] Price int64 dtype: object df['Date'] = df['Date'].dt.date df['Date'] = df['Date'].dt.floor('d')
type: Answer
upvote count: 19
accepted answer of: http://stackoverflow.com/q/50503033
downvote count: 0

http://stackoverflow.com/comment/87977927
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50482088
has text: Can you post the xml string in the question? and not the image

http://stackoverflow.com/q/50437704
has answer: http://stackoverflow.com/a/50439061
tagged with: python
has comment: http://stackoverflow.com/comment/87893515
score: -1
has body: I have this piece of code def get_vector (vx,vy): lst = [[[] for _ in range (len(vx[0]))]for _ in range (len(vx))] print (lst[1]) for x in range (len(lst)): for y in range (len(lst[x])): print (vx[x,y]) c = math.sqrt(pow(vx[x,y],2)+pow(vy[x,y],2)) print (c) cos_angle_y= ((pow(vx[x,y],2)) + (pow(c,2)) - (pow(vy[x,y],2))) / 2*vx[x,y]*c uhol=math.cos(math.radians(cos_angle_y)) lst[x][y].append([c,uhol]) return lst my question is how can i acces or save those values so i can access them later from nested list. i tried this but it kinda work but not really. I get the right values but i'm not sure how to access them. lst = get_vector(vx,vy) print (lst[0][10]) this is the result I get from print lst[0][10] : [[1.0, 0.9998476951563913]] I need to get value 0.999... to another variable outside of the list within the structure similar to lst[0][10][2] or some different approach if possible, any advice ?
type: AnsweredQuestion
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/50439926
has title: Inserting and reading multiple values within nested list
possible better answer: http://stackoverflow.com/a/50439061
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50439926
type: Question

http://stackoverflow.com/a/50533439
upvote count: 1
has comment: http://stackoverflow.com/comment/88078901
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88078991
has comment: http://stackoverflow.com/comment/88078942
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50533070
has body: words.words() returns a list, which takes O(n) time for checking whether a word is present in the list or not. To optimize the time complexity, you can take create the set out of this list which offers the constant time search. Second optimization is that remove() method on list takes O(n) time. You can maintain a separate list to remove that overhead. To know more about the complexity of various operations, you can refer to https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt set_of_words = set(words.words()) def check_for_word(sentence): s = sentence.split(' ') return ' '.join(w for word in s if word in set_of_words)
downvote count: 0
answers question: http://stackoverflow.com/q/50533070

http://stackoverflow.com/comment/87801515
has text: You are right. I uninstalled the python3-32bit pyinstaller and then the pyinstaller is searching within Anaconda's scripts folder. Does this means that if I want to pack another .py file provided by python3-32bit, I must unistall Anaconda's pyinstaller and install python3-32's pyinstaller again?
comment on: http://stackoverflow.com/a/50389330
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50492748
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88012257
tagged with: boto3
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/52430630
has answer: http://stackoverflow.com/a/50603903
score: 3
has comment: http://stackoverflow.com/comment/88013920
has comment: http://stackoverflow.com/comment/88011919
answer count: 3
upvote count: 3
has title: boto3 and AWS Athena permission
has body: I am trying to use boto3, v. 1.7.4, to interact with AWS Athena through the following script: import boto3 import botocore # Test access to the input bucket bucket = boto3.resource('s3').Bucket('s3_input') print(list(bucket.objects.all()) client = boto3.client('athena', region_name='us-east-1') # Create a new database db_query = 'CREATE DATABASE IF NOT EXISTS france;' response = client.start_query_execution( QueryString=db_query, ResultConfiguration={'OutputLocation': 's3_output'}) # Create a new table table_query = ''' CREATE EXTERNAL TABLE IF NOT EXISTS france.by_script (`content` string ) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' WITH SERDEPROPERTIES ('separatorChar' = ',') LOCATION 's3_input';''' response = client.start_query_execution( QueryString=table_query, ResultConfiguration={'s3_output'}, QueryExecutionContext={'Database': 'france'}) With the current permissions of my account, the test to read the content of s3_input works well. I can also create the database through the db_query but the table creation fails with the following error message: Your query has the following errors:FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:Got exception: java.io.IOException com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.model.AmazonS Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: [...]), S3 Extended Request ID: [...]) If I run the table_query command from the console, console.aws.amazon.com/athena/home, using the same account, there is no problem and the table is properly created. The permissions are { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "s3:GetObject", "Resource": "s3_input" }, { "Sid": "VisualEditor1", "Effect": "Allow", "Action": [ "s3:ListAllMyBuckets", "s3:HeadBucket" ], "Resource": "*" } ] } I would be happy to understand what I am missing here. Thanks in advance…
downvote count: 0
has answer: http://stackoverflow.com/a/50500685
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88008992

http://stackoverflow.com/a/50458993
has body: to_numeric to convert non-numeric type to NaN dropna to drop NaN astype to convert type pd.to_numeric(df['A'], errors='coerce').dropna().astype(int)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50458856

http://stackoverflow.com/comment/88050443
score: 0
comment on: http://stackoverflow.com/q/50518913
type: Comment
type: QuestionComment
has text: Please can you fix the indentation? I can't see why you'd get that error. Also, we can use a full traceback here.

http://stackoverflow.com/a/50503101
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50502999
type: Answer
answers question: http://stackoverflow.com/q/50502999
upvote count: 3
score: 3
has body: You're right, token_pattern requires a custom regex pattern, pass a regex that treats any one or more characters that don't contain whitespace characters as a single token. tfidf = TfidfVectorizer(lowercase=False, token_pattern=r'\S+') tf_idf_matrix = pd.DataFrame( tfidf.fit_transform(dataset['des']).toarray(), columns=tfidf.get_feature_names() ) print(tf_idf_matrix) 1-1/4 1/8 4 brush tube wire 0 0.000000 0.707107 0.000000 0.000000 0.000000 0.707107 1 0.000000 0.000000 0.707107 0.000000 0.707107 0.000000 2 0.707107 0.000000 0.000000 0.707107 0.000000 0.000000
type: AcceptedAnswer

http://stackoverflow.com/comment/87793474
type: Comment
has text: `[tuple(range(1,10))]`
type: QuestionComment
comment on: http://stackoverflow.com/q/50388974
score: 3

http://stackoverflow.com/comment/89093131
has text: Your answer looks like Ctrl-C + Ctrl-V from comments
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51050733
score: 0

http://stackoverflow.com/comment/87922012
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50454353
score: 0
has text: Have the program print out the images you're feeding in. Determine the size of each. If you're cutting up the images to train, make sure the cuts are generating equally-sized images.

http://stackoverflow.com/q/50534517
has title: What is the difference between having parameters within super and the init parentheses .... super().__init__()
tagged with: python
tagged with: class
has comment: http://stackoverflow.com/comment/88081186
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50536551
downvote count: 0
tagged with: super
has comment: http://stackoverflow.com/comment/88081107
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88081173
answer count: 1
has body: I understand that the concept of super().__init__() is to do with inheritance and I have seen code with parameters within init. However, I came across a code sample that had this: class Maze(tk.Tk, object): def __init__(self): super(Maze, self).__init__() the parameters are now within the super parenthesis. What is the difference and why may one be used over the other? Thank you
favorite count: 0
has comment: http://stackoverflow.com/comment/88081161
type: Question
accepted answer: http://stackoverflow.com/a/50536551
tagged with: oop
tagged with: init
has comment: http://stackoverflow.com/comment/88081039
has comment: http://stackoverflow.com/comment/88081226
has comment: http://stackoverflow.com/comment/88081178

http://stackoverflow.com/q/50403711
tagged with: selenium-chromedriver
score: 3
upvote count: 3
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/8385281
has title: ResponseNotReady error when making concurrent selenium/chromedriver requests
linked to: http://stackoverflow.com/q/3231543
tagged with: selenium
has comment: http://stackoverflow.com/comment/87822939
tagged with: concurrent.futures
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: httpresponse
has body: I have a script that is making requests using multiple headless browsers (selenium + Chrome drivers), each of which makes HTTP requests over a different SOCKS proxy. All of the requests are made inside of a concurrent.futures.ThreadPoolExecutor(). For some reason, I am periodically getting the error ResponseNotReady: Idle, and I can't understand why. My question is: 1) What is causing this ResponseNotReady error? Is it something I'm doing wrong, or a normal exception that I just need to catch and respond to? 2) How can I properly handle the ResponseNotReady exception? What is the best way to recover from this? Here is the function where I am making the requests: def _fetch_selenium(self, url, session, port): domain = self.domainFromURL(url) with self.locks[port][domain]: try: start_time = datetime.now() session.get(url) sleep(self.delay) return {'url': url, 'html': session.page_source, 'time': datetime.now() - start_time, 'proxy_port': port} except selenium_exceptions.WebDriverException as e: print("Request of URL " + url + " failed with exception: " + str(e)) sleep(self.delay) return {'url': url, 'html': None, 'time': datetime.now() - start_time, 'proxy_port': port} And here is the code where I am dispatching requests to different selenium sessions (the fetch() function basically just ends up calling _fetch_selenium(): def fetchConcurrent(self, urls): results = [] timeouts = defaultdict(int) with ThreadPoolExecutor(max_workers=self.num_threads) as executor: futures = [] for url in urls: session = self.sessions.popleft() futures.append(executor.submit(self.fetch, url, session)) self.sessions.append(session) for future in as_completed(futures): result, session = future.result() results.append(result) if not result['html']: socks_port = result['proxy_port'] print(f"Got no HTML for url {result['url']}, using port {socks_port}.") timeouts[socks_port] += 1 if timeouts[socks_port] &gt; MAX_TIMEOUTS_PER_CLIENT: tor_client_pool.replaceClient(socks_port) self.killSeleniumSes…
has comment: http://stackoverflow.com/comment/87822904

http://stackoverflow.com/comment/87889741
type: Comment
has text: @AaronBrandhagen if I remove delimiter, the whole sentence is split into alphabets and each column holds only one alphabet
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50427865

http://stackoverflow.com/comment/88084094
type: AnswerComment
has text: OP made a good MCVE. Will it still be the most readable when generalised to more than 2 keys?
type: Comment
comment on: http://stackoverflow.com/a/50535763
score: 0

http://stackoverflow.com/a/50389999
has body: This isn't working because parameter converters expects a dict of functions for converting values in certain columns. Keys can either be integers or column labels. None of ['Struct','{','}'] is a column label. In order to read this text file, you would need to preprocess it getting rid of 'Struct', '{', '}'. I.e. you will need to convert it to a proper CSV file.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50389618
type: AcceptedAnswer
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50389618
score: 1

http://stackoverflow.com/q/50411570
type: AnsweredQuestion
upvote count: 3
tagged with: pytest
has title: Pytest: mock/patch sys.stdin in program using threading with python
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50422414
favorite count: 0
tagged with: unit-testing
type: Question
tagged with: mocking
has answer: http://stackoverflow.com/a/50422414
tagged with: python
tagged with: monkeypatching
has body: I've acquired some code that I need to test before refactoring. It uses deep recursion so sets new limits and then runs itself in a fresh thread: sys.setrecursionlimit(10**6) threading.stack_size(2**27) ... threading.Thread(target=main).start() The code relies heavily on sys.stdin and sys.stdout e.g. class SpamClass: def read(self): self.n = int(sys.stdin.readline()) ... for i in range(self.n): [a, b, c] = map(int, sys.stdin.readline().split()) ... def write(self) print(" ".join(str(x) for x in spam())) To test the code, I need to pass in the contents of a series of input files and compare the results to the contents of some corresponding sample output files. So far, I've tried three or four different types of mocking and patching without success. My other tests are all written for pytest, so it would be a real nuisance to have to use something else. I've tried patching module.sys.stdin with StringIO, which doesn't seem to work because pytest's capsys sets sys.stdin to null and hence throws an error despite the patch. I've also tried using pytest's monkeypatch fixture to replace the module.SpamClss.read method with a function defined in the test, but that produces a segmentation error due, I think, to the thread exiting before the test (or …?). 'pytest test_spam.py' terminated by signal SIGBUS (Misaligned address error) Any suggestions for how to do this right? Many thanks.
score: 2

http://stackoverflow.com/comment/87927417
type: AnswerComment
score: 0
has text: The package and module name are 2 different things. The first one is defined in setup.py's name and it is what you install with pip. The module name (Python standard module) is determined by the directory name.
comment on: http://stackoverflow.com/a/50456752
type: Comment

http://stackoverflow.com/comment/87917334
type: Comment
has text: @codebase5000, this library perhaps https://github.com/fancycode/pylzma ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50424946

http://stackoverflow.com/comment/87857403
type: Comment
comment on: http://stackoverflow.com/a/50421033
type: AnswerComment
score: 0
has text: I don't think this will work in my case because I think your solution is doing the opposite (checking 'a' against 'check_against'). This means that when check_against is {'e': str, 'b': {'c': int, 'd': int}} it results in a key error. Still trying to understand the code though.

http://stackoverflow.com/comment/87835785
score: 0
type: QuestionComment
has text: @Relequestual I have been using this documentation: http://python-jsonschema.readthedocs.io/en/latest/errors/#errortrees But I can't seem to manipulate the error tree (as you can see in my code) to get it to give me all of the invalid keys.
type: Comment
comment on: http://stackoverflow.com/q/50401837

http://stackoverflow.com/q/50416680
has body: I have created an XML file to publish a question to MTurk and the HIT is visible in the worker sandbox. A couple of my friends even submitted responses to the HIT, but I'm unable to view the results of this HIT. Here's the code I used to publish the HIT: import boto3 MTURK_SANDBOX = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com' MTURK_PROD = 'https://mturk-requester.us-east-1.amazonaws.com' mturk = boto3.client('mturk', aws_access_key_id = "blah", aws_secret_access_key = "blah", region_name='us-east-1', endpoint_url = MTURK_SANDBOX ) # Read in the questions.xml file saved in the same directory question = open(file='E:\\QuestionsXML\\5235319d5aa41337122b28bc.xml',mode='r', encoding='utf-8').read() new_hit = mturk.create_hit( Title = 'Map the following question to the paragraph/content where the answer to the question may lie.', Description = 'Please review the following content to figure out where the answer to the posted question may reside', Keywords = 'images, quick, labeling', Reward = '0.00', MaxAssignments = 1, LifetimeInSeconds = 1728, AssignmentDurationInSeconds = 600, AutoApprovalDelayInSeconds = 14400, Question = question, AssignmentReviewPolicy={ 'PolicyName':'ScoreMyKnownAnswers/2011-09-01', 'Parameters':[ {'Key':'AnswerKey', 'MapEntries':[{'Key': 'question_1', 'Values':['yes']}]}, {'Key': 'ApproveIfKnownAnswerScoreIsAtLeast', 'Values':['1']}, {'Key': 'RejectIfKnownAnswerScoreIsLessThan', 'Values':['1']},{'Key': 'RejectReason', 'Values':['Sorry, we could not approve your submission as you did not correctly identify the image containing the Flamingo.']}, {'Key': 'ExtendIfKnownAnswerScoreIsLessThan','Values':['1']} ] }) print("A new HIT has been created. You can preview it here:") print(new_hit['HIT']['HITGroupId']) print("https://workersandbox.mturk.com/mturk/preview?groupId=" + str(new_hit['HIT']['HITGroupId'])) This code gave the the following: A new HIT has been created. You can preview it here: 3X1QANT5IR1WSSCGJ0Y38AZG1ZW2RB https://workersa…
favorite count: 0
type: Question
tagged with: python
tagged with: mechanicalturk
tagged with: boto3
score: 4
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50613388
accepted answer: http://stackoverflow.com/a/50613388
downvote count: 0
answer count: 1
has title: How to get results from a HIT on sandbox via Mturk API

http://stackoverflow.com/a/50401871
has body: If you want all the elements in l that are not in m you may do a comprehension (as @PatrickHaugh suggested) or a set operation. The comprehension: &gt;&gt;&gt; l = [1, 2, 3] &gt;&gt;&gt; m = [4, 5, 6] &gt;&gt;&gt; [o for o in l if o not in m] [1, 2, 3] If you prefer to use a set operation: &gt;&gt;&gt; l = {1, 2, 3} &gt;&gt;&gt; m = {4, 5, 6} &gt;&gt;&gt; l - m {1, 2, 3} &gt;&gt;&gt; l = {1, 2, 3, 4} &gt;&gt;&gt; l - m {1, 2, 3} Note that l and m here are sets.
accepted answer of: http://stackoverflow.com/q/50401794
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50401794
type: Answer
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/88000314
comment on: http://stackoverflow.com/a/50426380
score: 0
type: Comment
type: AnswerComment
has text: One of my classes does that arguments. But also the patching wasn't working when you do factory=OtherClass. I believe this is due to creating an instance of the factory and then patching can't be applied while with the lambda it is called every time.

http://stackoverflow.com/a/50470404
type: Answer
has body: Add the jquery file in the static/js directory.
has comment: http://stackoverflow.com/comment/87957008
accepted answer of: http://stackoverflow.com/q/50469579
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87955901
answers question: http://stackoverflow.com/q/50469579
score: 0

http://stackoverflow.com/q/50434101
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: twitter
type: Question
accepted answer: http://stackoverflow.com/a/50434157
has title: I'm unable to write tweets to a json file with _json due to AttributeError
has body: This is my code: searched_tweets = [] new_tweets = api.search(q=query, count=remaining_tweets, since_id=str(since_id), max_id=str(max_id)) searched_tweets.append(new_tweets) def write_tweets(tweets, filename): with open(filename + ".json", "w") as f: for tweet in tweets: json.dump(tweet, f) f.write('\n') write_tweets(searched_tweets, "testfile") And I get this error when I try to write tweets to a new json file. AttributeError: 'SearchResults' object has no attribute '_json' I'm using Python 3x.
has answer: http://stackoverflow.com/a/50434157
tagged with: python

http://stackoverflow.com/comment/88110037
comment on: http://stackoverflow.com/q/50521383
score: 0
has text: @ToddBurus No sir, quotes around author don't matter.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50471596
has comment: http://stackoverflow.com/comment/87956873
has body: You can use .values instead of .items() to get just the value: for v in dct.values: if v &lt;= 100: ...
answers question: http://stackoverflow.com/q/50471457
has comment: http://stackoverflow.com/comment/87956781
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87956925

http://stackoverflow.com/comment/87806059
score: 0
type: QuestionComment
has text: Very well spotted! This is indeed an assumption I silently made, and it's true in my application. I added the statement to the question.
type: Comment
comment on: http://stackoverflow.com/q/50389518

http://stackoverflow.com/q/50447743
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50447858
tagged with: dataframe
tagged with: python
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50448008
downvote count: 0
upvote count: 1
tagged with: string
has body: I want to replace some strings in a column from a data frame which is like this df["column"] ------------------ 1. Ne Road 2. Rosemarys street se 3. Plunkett pkwy 4. like that so on..... like these there are thousands of values Here i want to replace Ne to NE, se to SE, pkwy to Parkway like that So here is my code: def replace_all(text, dic): for i, j in dic.items(): text = text.replace(i, j) return text my_text = df.iloc[:,2] -----### '2' is the Column number here in my Dataframe ### reps = { 'se' : 'SE' 'Ne' : 'NE' 'pkwy' :'"Parkway' } df["column"] = replace_all(my_text,reps) I want to know where I went wrong and please help me regarding this. Thanks in advance!!
has title: How to replace a value/string from a column in a data frame?
tagged with: excel
favorite count: 0
type: Question

http://stackoverflow.com/comment/88114844
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50541561
type: AnswerComment
has text: `for l in response.css('div.ev-teaser-content'):` `yield {'area': l.css('ul.card-property__features > li:nth-child(3) > span.label__property::text').extract()}`

reactjs
tags question: http://stackoverflow.com/q/50478671
tag name: reactjs
type: Tag
tags question: http://stackoverflow.com/q/50494064

http://stackoverflow.com/q/50397740
has title: How to make an adjacency matrix out of a list?
has comment: http://stackoverflow.com/comment/87811585
type: Question
linked to: http://stackoverflow.com/q/29146892
tagged with: list
has body: I have a list like: [['10', '20', 2], ['10', '21', 2], ['10', '1', 2], ['10', '0', 3], ['10', '3', 2], ['10', '2', 2], ['10', '5', 3], ['10', '4', 3], ['10', '7', 2], ['10', '6', 2], ['10', '9', 2], ['10', '8', 2], ['10', '11', 2], ['10', '10', 2], ['10', '13', 2], ['10', '12', 2], ['10', '15', 2], ['10', '14', 2], ['10', '17', 0], ['10', '16', 3], ['10', '19', 2], ['10', '18', 2], ['1', '20', 3], ['1', '21', 3], ['1', '1', 3], ['1', '0', 0], ['1', '3', 3], ['1', '2', 3], ['1', '5', 4], ['1', '4', 4], ['1', '7', 3], ['1', '6', 3], ['1', '9', 3], ['1', '8', 3], ['1', '11', 3], ['1', '10', 3], ['1', '13', 3], ['1', '12', 3], ['1', '15', 3]] (it's a lot bigger than this) which the first and second item are actually node names and the third one is the edge weight between them (I didn't make a graph though, it's a list). I'd like to make an adjacency matrix out of this list.
answer count: 3
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: adjacency-matrix
has answer: http://stackoverflow.com/a/50398222
has answer: http://stackoverflow.com/a/50398043
tagged with: python
has answer: http://stackoverflow.com/a/50398256

http://stackoverflow.com/a/50526476
answers question: http://stackoverflow.com/q/50526408
type: Answer
score: 0
has body: As you are using python3: pip3 install pycrypto

http://stackoverflow.com/q/50403649
has comment: http://stackoverflow.com/comment/87823097
has title: Typerror : 'list' object is not callable which the input is from .txt Python 3
type: Question
has comment: http://stackoverflow.com/comment/87823113
type: UnansweredQuestion
tagged with: python
tagged with: text-processing
has body: I am trying to create a function that would remove stop-words inside a document. But instead, I got an error like this : TypeError: 'list' object is not callable Here is the code: import re def stopwords(text): reg = re.compile(r"\n") return reg.split(text) file = open("stopwords.txt","r"); st = file.read() stopwordz = stopwords(st) #this is the error line for word in stopwordz: raw1=raw1.replace(" "+word+" "," ") raw2=raw2.replace(" "+word+" "," ") raw3=raw3.replace(" "+word+" "," ") raw4=raw4.replace(" "+word+" "," ") raw5=raw5.replace(" "+word+" "," ") The error occurred on stopwordz variable line. I was trying to use [] instead of () but still can't solve the issue. Can anyone tell me what I am doing wrong here? Thanks before.~
tagged with: stop-words
has comment: http://stackoverflow.com/comment/87822889
score: 0
has comment: http://stackoverflow.com/comment/87822893
answer count: 0

http://stackoverflow.com/q/50434046
has body: Using the HTTPretty library for Python, I can create mock HTTP responses for my unit tests. When the code I am testing runs, instead of my request reaching the third party, the request is intercepted and my code receives the response I configured. I then use last_request() and can check the url my code requested, any parameters, etc. What I would like is to know how can I access not just the last request but also any other requests my code sent before the last one. This seems to be possible. In the documentation it uses a list called latest_requests. For example here But that doesn't seem to work for me. I get an AttributeError AttributeError: module 'httpretty' has no attribute 'latest_requests' Here is some code that illustrates what I am trying to do and where I get AttributeError import httpretty import requests httpretty.enable() httpretty.register_uri( method=httpretty.GET, uri='http://www.firsturl.com', status=200, body='First Body' ) httpretty.enable() httpretty.register_uri( method=httpretty.GET, uri='http://www.secondurl.com', status=200, body='secondBody' ) firstresponse = requests.get('http://www.firsturl.com') secondresponse = requests.get('http://www.secondurl.com') print(httpretty.latest_requests[-1].url) # clean up httpretty.disable() httpretty.reset() Thanks!!
tagged with: python-requests
favorite count: 0
tagged with: unit-testing
type: Question
score: 3
has answer: http://stackoverflow.com/a/50435011
accepted answer: http://stackoverflow.com/a/50435011
has title: How to get a request that is not the last in HttPretty?
tagged with: python
type: AnsweredQuestion
upvote count: 3
downvote count: 0
tagged with: httpretty
answer count: 1

http://stackoverflow.com/comment/88032346
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50498672
has text: If I remember correctly, `pip` expects the package name in `install_requires` to match the egg name and link in `dependency_links`, so it must be smth like `install_requires=['python-api']` and the dep link `github.com/shotgunsoftware/python-api.git@v3.0.36#egg=python-api`. It will still install package named `shotgun-api3` because the real name will be taken from the setup script.

http://stackoverflow.com/q/50404195
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50409505
has body: I have 2 separate files, each having its own class defined in it. File 1: class AndorCameraSDK: def __init__(self): self.count = 0 def LiveAcquisition(self,nframes,np.ndarray[np.unit16_t,ndim = 3,mode = 'c']image: cdef unsigned char * pBuf #This has the data #.......Initialisation of parameters..............# for i in range(nframes): pBuf = &lt;unsigned char *&gt;calloc(sizeinBytes,sizeof(unsigned char) #-----Storing the data in pBuf into a 3-D array image....# pus_image = &lt;unsigned short*&gt; pBuf for j in range(self.width): pus_image = &lt;unsigned short*&gt; pBuf for k in range(self.height): image[i][j][k] = pus_image[0] pus_image += 1 _puc_image += self.stride def function1(self): #Something else to be done with another function In File 2 import AndorCameraSDK as andorcamera class AndorCameraGUI: def __init__(self): #Making use of Tkinter couple of widgets has been created, which includes a button named LiveImage which calls the function LiveImageGUI. def LiveImageGUI (self): self.camera = andorcamera() #define a 3D array I self.camera.LiveAcquisition(nframes,I) #called from File 1 def LivePlot(self) # A function using FigurecanvasTkAgg to display the image processed from LiveAcquisition in the display area defined in the GUI panel What I want to achieve: The for loop to store the pBuf into a 3D-array has to be a function called by thread inside the same. This function should call LivePlot function from file 2 such that the stored image frame should be displayed in GUI. Both these should happen such that while processing (i+1)st frame, display the ith frame so that there is not time lag. Could anyone please help me regarding this? Any help is highly appreciated.
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
has title: How to call a tkinter Class file from another class file?
score: 1
tagged with: multithreading
answer count: 1

generator
type: Tag
tags question: http://stackoverflow.com/q/50530460
tags question: http://stackoverflow.com/q/50439634
tags question: http://stackoverflow.com/q/50493572
tag name: generator
tags question: http://stackoverflow.com/q/50474398
tags question: http://stackoverflow.com/q/50496229

http://stackoverflow.com/a/50520410
upvote count: 1
answers question: http://stackoverflow.com/q/50520215
score: 1
has body: Create an bool array, and then fill it: import numpy as np a = np.array([1, 2, 3, 0, 3, 2, 1]) b = np.zeros((len(a), a.max() + 1), bool) b[np.arange(len(a)), a] = 1
has comment: http://stackoverflow.com/comment/88055222
accepted answer of: http://stackoverflow.com/q/50520215
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88094376
score: 0
comment on: http://stackoverflow.com/a/50540993
type: Comment
type: AnswerComment
has text: I don't think I am fully understanding what you are trying to say, do you mean to say that total is the total number of times the program played the game? because in the program, total is the total number of times both players got the same output for 10 consecutive terms.

http://stackoverflow.com/a/50418146
has body: remove from sm.OLS(Y,X) -> fit , this works, you dont put fit method where it needed import statsmodels.api as sm Y = [1,3,4,5,2,3,4] X = range(1,8) X = sm.add_constant(X) model = sm.OLS(Y,X) results = model.fit()
type: AcceptedAnswer
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/50418006
has comment: http://stackoverflow.com/comment/87853742
type: Answer
accepted answer of: http://stackoverflow.com/q/50418006
has comment: http://stackoverflow.com/comment/87853895
score: 2

http://stackoverflow.com/comment/87816586
score: 0
comment on: http://stackoverflow.com/q/50393696
type: Comment
type: QuestionComment
has text: I figured the issue. The data returned from the source has all columns as strings. After changing the datatype in the source, it worked perfect. Thank you @user2722968

http://stackoverflow.com/q/50397250
favorite count: 0
type: Question
tagged with: python-3.x
has body: I want to remove outliers based on percentile 99 values by group wise. import pandas as pd df = pd.DataFrame({'Group': ['A','A','A','B','B','B','B'], 'count': [1.1,11.2,1.1,3.3,3.40,3.3,100.0]}) in output i want to remove 11.2 from group A and 100 from group b. so in final dataset there will only be 5 observations. wantdf = pd.DataFrame({'Group': ['A','A','B','B','B'], 'count': [1.1,1.1,3.3,3.40,3.3]}) I have tried this one but I'm not getting the desired results df[df.groupby("Group")['count'].transform(lambda x : (x&lt;x.quantile(0.99))&amp;(x&gt;(x.quantile(0.01)))).eq(1)]
answer count: 2
possible better answer: http://stackoverflow.com/a/54356494
has comment: http://stackoverflow.com/comment/87810307
downvote count: 0
tagged with: python
upvote count: 6
score: 6
has title: pandas group by remove outliers
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50400461
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/50400461
tagged with: pandas
has answer: http://stackoverflow.com/a/54356494

http://stackoverflow.com/comment/87828561
type: Comment
score: 0
type: AnswerComment
has text: I can see what you mean. It is the first time I have seen `wsse` to increase. I'll see if the results move in expected directions on changing the max_iter and tolerance values. Thanks for the help.
comment on: http://stackoverflow.com/a/50406499

http://stackoverflow.com/a/74080947
has body: To @s3n0 &amp; @DanielYu's point they can be handled two different ways. I had to list these out to better understand the overlap: Connection Objects backup close commit create_aggregate create_collation create_function cursor enable_load_extension execute executemany executescript in_transaction interrupt isolation_level iterdump load_extension rollback row_factory set_authorizer set_progress_handler set_trace_callback text_factory total_changes Cursor objects arraysize close connection description execute executemany executescript fetchall fetchmany fetchone lastrowid rowcount setinputsizes setoutputsize
answers question: http://stackoverflow.com/q/50429589
downvote count: 0
upvote count: 1
type: Answer
score: 1

http://stackoverflow.com/comment/87990219
score: 1
has text: I'm not sure what you mean by "adding the `self` to the widget instances". Could you show an example?
comment on: http://stackoverflow.com/q/50488628
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50471846
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50472187
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50472100
tagged with: pandas
has answer: http://stackoverflow.com/a/50472100
tagged with: dataframe
tagged with: python
tagged with: loops
has title: Python looping two different dataFrames to create a new column
type: Question
answer count: 2
has body: I want to add a new column to a dataframe by referencing another dataframe. I want to run an if statement using startswith method to match df1['BSI'] column to df2['initial'] to assign the corresponding df2['marker'], and give df1 a new column that consists of markers, which I will use for cartopy marker style. I am having trouble looping df2 inside a df1 loop. I basically can't figure out how to call df1 item onto df2 loop to compare to df2 items. df1 looks like this: BSI Shelter_Number Location Latitude Longitude 0 AA-010 1085 SUSSEX (N SIDE) &amp; RIDEAU FALLS 45.439571 -75.695694 1 AA-030 3690 SUSSEX (E SIDE) &amp; ALEXANDER NS 45.442795 -75.692322 2 AA-180 279 CRICHTON (E SIDE) &amp; BEECHWOOD FS 45.439556 -75.676849 3 AA-200 2018 BEECHWOOD (S SIDE) &amp; CHARLEVOIX NS 45.441154 -75.673622 4 AA-220 3301 BEECHWOOD (S SIDE) &amp; MAISONNEUVE NS 45.442188 -75.671356 df2 looks like this: initial marker 0 AA bo 1 AB bv 2 AC b^ 3 AD b&lt; 4 AE b&gt; desired output is: BSI, Shelter_Number, Location, Latitude, Longitude, marker 0 AA-010 1085 SUSSEX (N SIDE) &amp; RIDEAU FALLS 45.439571 -75.695694 bo 1 AA-030 3690 SUSSEX (E SIDE) &amp; ALEXANDER NS 45.442795 -75.692322 bo 2 AA-180 279 CRICHTON (E SIDE) &amp; BEECHWOOD FS 45.439556 -75.676849 bo 3 AA-200 2018 BEECHWOOD (S SIDE) &amp; CHARLEVOIX NS 45.441154 -75.673622 bo 4 AA-220 3301 BEECHWOOD (S SIDE) &amp; MAISONNEUVE NS 45.442188 -75.671356 bo
has comment: http://stackoverflow.com/comment/87957520
score: 1
possible better answer: http://stackoverflow.com/a/50472187

http://stackoverflow.com/a/50413132
has comment: http://stackoverflow.com/comment/87841906
has body: You can use a multiprocessing.pool.ThreadPool to manage both the starting of new threads and limiting the maximum number of them executing concurrently. from multiprocessing.pool import ThreadPool from random import randint import threading import time MAX_THREADS = 5 # Number of threads that can run concurrently. print_lock = threading.Lock() # Prevent overlapped printing from threads. def myFunc(): time.sleep(random.uniform(0, 1)) # Pause a variable amount of time. with print_lock: print('myFunc') def test(): pool = ThreadPool(processes=MAX_THREADS) for _ in range(100): # Submit as many tasks as desired. pool.apply_async(myFunc, args=()) pool.close() # Done adding tasks. pool.join() # Wait for all tasks to complete. print('done') if __name__ == '__main__': test()
answers question: http://stackoverflow.com/q/50411854
downvote count: 0
has comment: http://stackoverflow.com/comment/87842157
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/50437865
tagged with: arrays
has answer: http://stackoverflow.com/a/50438225
tagged with: python
has title: finding the interpolated intersection between two arrays in Python/Numpy/Scipy
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50438225
score: 0
accepted answer: http://stackoverflow.com/a/50438293
has answer: http://stackoverflow.com/a/50438293
tagged with: scipy
tagged with: linear-interpolation
linked to: http://stackoverflow.com/q/15112964
tagged with: numpy
type: Question
has body: I am looking for a simple approach to finding the interpolated intersection between two Numpy arrays. I know that this is simply achieved if we have two function handles, rather than two arrays, as shown in this link using Scipy or using Sympy. I want to do the same, but given two arrays, specifically between the linear spline that results from connecting array entries by lines. For example, suppose we have two arrays, y_1 and y_2, both thyought of as being evaluated at xSupport. import numpy as np xSupport = np.array([0,1]) y_1 = np.array([0,2]) y_2 = np.array([1,0]) I am looking for the function that returns 1/3, which is the x value at the intersections between these two lines. In my application the support is larger than two, so I am looking for an approach that is independent of the arrays' length.
answer count: 2

http://stackoverflow.com/a/50533077
score: 2
has body: If you are going to use numpy later, then it's best to avoid the list comprehension. Also it's always good practice to automate things as much as possible, so instead of manually selecting the singleton dimension just let numpy take care of: b=numpy.array(a).squeeze() Unless there are other singleton dimensions that you need to keep.
has comment: http://stackoverflow.com/comment/88078328
upvote count: 2
answers question: http://stackoverflow.com/q/50532583
downvote count: 0
type: Answer

http://stackoverflow.com/comment/124111061
score: 0
comment on: http://stackoverflow.com/a/69082491
type: Comment
has text: Another question: How can I select a few files to zip? All my files are on the main dir and I only need to zip 4 of them. How can I specifically zip just those?
type: AnswerComment

http://stackoverflow.com/q/50532544
type: Question
has answer: http://stackoverflow.com/a/50533357
upvote count: 5
has body: For example, now I have this .ini file: [DEFAULT] db_user = user_test db_password = psw_test db_host = localhost db_name = db_test ... I want to do: export ENV_DB_USER=user_test export ENV_DB_PSW=psw_test export ENV_DB_HOST=localhost export ENV_DB_NAME=db_test Then I want to do somethings like this in .ini file: [DEFAULT] db_user = ${ENV_DB_USER} db_password = ${ENV_DB_PSW} db_host = ${ENV_DB_HOST} db_name = ${ENV_DB_NAME} ... I have try to use %()s syntax but unfortunately not working. Where I'm doing wrong? Thanks :)
tagged with: python
tagged with: pyramid
type: AnsweredQuestion
score: 5
downvote count: 0
answer count: 1
has title: How i can use environment variables on .ini file in Pyramid?
favorite count: 0
accepted answer: http://stackoverflow.com/a/50533357

http://stackoverflow.com/a/50460873
type: Answer
has body: x = something If you have something assigned to x, e.g. x = object1, then if you write x = object2, that does not influence object1* (or any other data, for that matter) in any way. It just means that variable x now refers to a different object (object2 rather than object1). x.y = something On the other hand x.y = something does influence data (in general case). It modifies data in x. It still does not modify data which was previously in x.y* - that old data is just no longer referenced by x.y. x['y'] = something This has very similar semantics as x.y = something. The original example for item in data: if item['hostname'] == 'c.example.com': item = update After item = update, variable item no longer references an item from data, it references a different variable: update. If you print(item) you will see that. The line that is execute after that is for item in data, which again changes what item references, thus effectively cancelling the previous line. What you actually want is to modify data, so you should do so, e.g. for i in range(len(data)): ... data[i] = update (*) Although the original data is not modified by this, it may be "deleted" i.e. it's memory may be freed if it is no longer referenced by any variable, because it is no longer needed.
answers question: http://stackoverflow.com/q/50460523
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/50770611
score: 5
has comment: http://stackoverflow.com/comment/106583069
has comment: http://stackoverflow.com/comment/106571393
accepted answer of: http://stackoverflow.com/q/50502781
has body: My question was answered on the GitHub issue (https://github.com/graphql-python/graphene-sqlalchemy/issues/134). The idea is to identify the requested fields out of the info argument (of type graphql.execution.base.ResolveInfo) that gets passed to the resolver function through a get_field_names function such as the one below: def get_field_names(info): """ Parses a query info into a list of composite field names. For example the following query: { carts { edges { node { id name ...cartInfo } } } } fragment cartInfo on CartType { whatever } Will result in an array: [ 'carts', 'carts.edges', 'carts.edges.node', 'carts.edges.node.id', 'carts.edges.node.name', 'carts.edges.node.whatever' ] """ fragments = info.fragments def iterate_field_names(prefix, field): name = field.name.value if isinstance(field, FragmentSpread): _results = [] new_prefix = prefix sub_selection = fragments[field.name.value].selection_set.selections else: _results = [prefix + name] new_prefix = prefix + name + "." if field.selection_set: sub_selection = field.selection_set.selections else: sub_selection = [] for sub_field in sub_selection: _results += iterate_field_names(new_prefix, sub_field) return _results results = iterate_field_names('', info.field_asts[0]) return results The above function was taken from https://github.com/graphql-python/graphene/issues/348#issuecomment-267717809. That issue contains other versions of this function but I felt this was the most complete. and using the identified fields to limit the retrieved fields in the SQLAlchemy query as such: fields = get_field_names(info=info) query = TypeAuthor.get_query(info=info).options(load_only(*relation_fields)) When applied to the above example query: query GetAuthor{ author(authorId: 1) { nameFirst } } The get_field_names function would return ['author', 'author.nameFirst']. However, as the 'original' SQLAlchemy ORM fields are snake-cased the get_field_names query needs to be updated to remove the author prefix and convert the f…
type: Answer
has comment: http://stackoverflow.com/comment/125407027
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/106567879
answers question: http://stackoverflow.com/q/50502781
upvote count: 5

macos
tags question: http://stackoverflow.com/q/50425739
tags question: http://stackoverflow.com/q/50437855
tags question: http://stackoverflow.com/q/50510139
tags question: http://stackoverflow.com/q/50522345
tags question: http://stackoverflow.com/q/50439358
tags question: http://stackoverflow.com/q/50503977
tags question: http://stackoverflow.com/q/50496637
tags question: http://stackoverflow.com/q/50420306
tags question: http://stackoverflow.com/q/50432450
tags question: http://stackoverflow.com/q/50510320
type: Tag
tags question: http://stackoverflow.com/q/50395216
tags question: http://stackoverflow.com/q/50397477
tags question: http://stackoverflow.com/q/50469796
tags question: http://stackoverflow.com/q/50511274
tags question: http://stackoverflow.com/q/50497479
tags question: http://stackoverflow.com/q/50399522
tags question: http://stackoverflow.com/q/50524762
tags question: http://stackoverflow.com/q/50440799
tags question: http://stackoverflow.com/q/50454280
tag name: macos
tags question: http://stackoverflow.com/q/50490569
tags question: http://stackoverflow.com/q/50421933
tags question: http://stackoverflow.com/q/50404212

http://stackoverflow.com/comment/88002052
comment on: http://stackoverflow.com/q/50458910
has text: it is definitely possible, but you will still have a problem - you would have to switch between running main program loop and checking between-the-two-programs communication channel for new data. Solving this problem efficiently is non trivial and requires some skills in concurrent programming
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87856074
comment on: http://stackoverflow.com/a/50420331
score: 0
type: Comment
type: AnswerComment
has text: @AntonvBR Not exactly. I think it is important to retain the OP's original `evenorodd` structure. For instance, What if the input is`[1,3,6,7]`, `['a','b','c','d']`, `['A','B','C','D']`?

http://stackoverflow.com/comment/87831497
comment on: http://stackoverflow.com/a/50407949
score: 0
type: AnswerComment
has text: No, you don't, you need **4** distances, you are missing the last distance of 4.
type: Comment

http://stackoverflow.com/q/50493572
tagged with: generator
has body: I am trying to write code in python using the Box-Muller equations, but I do not know how to start! This is the example I am trying to solve: A peak observed at 900 keV shows a FWHM of 2 keV. Using a Gaussian sampling method listed below, generate 15,000 counts corresponding to the 900 keV peak and save the sampled energies. Create and plot a histogram with a bin width of 0.2 keV and compare with the Gaussian function with the same peak area. Using a data analysis software, try a Gaussian fit to the Monte Carlo data and see the result is close enough to the peak model. Box-Muller Gaussian sampling method: [ Note, the two sampled variable y1, y2 below are for the unit Gaussian distribution (i.e. mu=0,segma=1). y1 = (-2 ln r1)^1/2 * cos(2pi*r2) y2 = (-2 ln r1)^1/2 * sin(2pi*r2) (r1, r2: random numbers)} Any suggestions? * Update * I am getting an error msg: g1 = BoxMuller(v) NameError: name 'v' is not defined The code used is: import random import matplotlib.pyplot as plt import numpy as np def BoxMuller(): r1 = np.random.randn(15000)*10 r2 = np.random.randn(15000) a = 2.0 * np.pi * r2 v = np.sqrt( -2.0*np.log(1.0 - r1)) * np.sin(a) u = np.sqrt( -2.0*np.log(1.0 - r1)) * np.cos(a) g1 = BoxMuller(v) g2 = BoxMuller(u) q = 900.0 + g1*2.0 k = 900.0 + g2*2.0 plt.hist(q, k) plt.show()
score: 0
tagged with: random
upvote count: 1
has title: Box-muller Gaussian random number generator & plot his
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88002138
has answer: http://stackoverflow.com/a/50494001
type: UnansweredQuestion
tagged with: physics
tagged with: python
has comment: http://stackoverflow.com/comment/88000884

http://stackoverflow.com/q/50525213
has comment: http://stackoverflow.com/comment/88064156
has comment: http://stackoverflow.com/comment/88071103
score: 1
answer count: 1
downvote count: 0
has body: I have an infinite script written in Python which connects to Postgresql and inserts there a record when the person appears in front of the camera connected to my computer. I would like to know what is the best way to connect (and store connection) to the database, if it is necessary to connect and close every time when the person appears or if I can somehow store connection. Because when I create a connection before the infinite loop and there is no activity in front of the camera, the connection stays idle and when the script wants to insert a new row after some time, the connection is closed. When I connect every time I want to insert a new row, there is no problem, but this is slower. Thank you for any suggestions.
upvote count: 1
has answer: http://stackoverflow.com/a/50546973
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/19963954
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
tagged with: psycopg2
has title: psycopg2 and infinite python script
has comment: http://stackoverflow.com/comment/88072190

http://stackoverflow.com/q/50537482
tagged with: python
score: -1
tagged with: dictionary
has title: Remove item from nested dictionaries if specified key contains None values
type: AnsweredQuestion
answer count: 2
has body: I have a list of dictionaries in which I am trying to remove any dictionary should the value of a certain key is None, it will be removed. item_dict = [ {'code': 'aaa0000', 'id': 415294, 'index_range': '10-33', 'location': 'A010', 'type': 'True'}, {'code': 'bbb1458', 'id': 415575, 'index_range': '30-62', 'location': None, 'type': 'True'}, {'code': 'ccc3013', 'id': 415575, 'index_range': '14-59', 'location': 'C041', 'type': 'True'} ] for item in item_dict: filtered = dict((k,v) for k,v in item.iteritems() if v is not None) # Output Results # Item - aaa0000 is missing # {'index_range': '14-59', 'code': 'ccc3013', 'type': 'True', 'id': 415575, 'location': 'C041'} In my example, the output result is missing one of the dictionary and if I tried to create a new list to append filtered, item bbb1458 will be included in the list as well. How can I rectify this?
accepted answer: http://stackoverflow.com/a/50537511
upvote count: 0
has answer: http://stackoverflow.com/a/50537511
has comment: http://stackoverflow.com/comment/88087040
has comment: http://stackoverflow.com/comment/88087061
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88087075
possible better answer: http://stackoverflow.com/a/50537519
has comment: http://stackoverflow.com/comment/88087298
has answer: http://stackoverflow.com/a/50537519

http://stackoverflow.com/q/50448026
has comment: http://stackoverflow.com/comment/88303585
has comment: http://stackoverflow.com/comment/87925107
has comment: http://stackoverflow.com/comment/88174171
tagged with: setup.py
has body: I have a setup.py file that is very similar to the one shown here: https://stackoverflow.com/a/49866324/4080129. It looks like this: from distutils.core import setup, Extension from Cython.Build import cythonize import numpy sources = ["hs/subfolder/detect.pyx", "hs/subfolder/Donline.cpp", "hs/subfolder/Handler.cpp", "hs/subfolder/Process.cpp", "hs/subfolder/Filter.cpp", "hs/subfolder/Localize.cpp"] exts = [Extension(name='hs.detect', sources=sources, extra_compile_args=['-std=c++11', '-O3'], include_dirs=[numpy.get_include()])] setup( ext_modules=cythonize(exts), include_dirs=[numpy.get_include()] ) There's a package with some pure-Python, and a submodule that contains Cython files. The setup.py is in the parent folder, not in the Cython one: setup.py hs/ some_python.py subfolder/ detect.pyx Donline.cpp ...etc Now, setup.py correctly compiles all the files module/submodule/file1.cpp etc. and saves the build to build/temp.linux-x86_64-3.6/module/submodule/file1.o . However, just after that, it tries to compile a file called file1.cpp, which doesn't exist (the correct one is module/submodule/file1.cpp, and has already been compiled). gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Ihs/subfolder -I/[...]/python3.6/site-packages/numpy/core/include -I/[...]/python3.6/site-packages/numpy/core/include -I/[...]/include -I/disk/scratch/miniconda/envs/my_default/include/python3.6m -c Donline.cpp -o build/temp.linux-x86_64-3.6/Donline.o -std=c++11 -O3 gcc: error: Donline.cpp: No such file or directory gcc: fatal error: no input files compilation terminated. error: command 'gcc' failed with exit status 4 I'm very confused, this completely prevents my code from compiling...
answer count: 1
has comment: http://stackoverflow.com/comment/87922169
downvote count: 0
has comment: http://stackoverflow.com/comment/87914916
has comment: http://stackoverflow.com/comment/88038923
tagged with: compilation
has comment: http://stackoverflow.com/comment/88040541
score: 11
has answer: http://stackoverflow.com/a/50666970
has comment: http://stackoverflow.com/comment/88029963
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87921766
has comment: http://stackoverflow.com/comment/88033983
has title: Cython attemps to compile twice, and fails
has comment: http://stackoverflow.com/comment/88343868
has comment: http://stackoverflow.com/comment/87920436
tagged with: python
linked to: http://stackoverflow.com/q/49861124
tagged with: cython
accepted answer: http://stackoverflow.com/a/50666970
has comment: http://stackoverflow.com/comment/87921085
upvote count: 11
favorite count: 0
has comment: http://stackoverflow.com/comment/87921000
type: Question
has comment: http://stackoverflow.com/comment/87915149

http://stackoverflow.com/comment/88055533
has text: Your representation doesn't make sense. Either you want `{[...], [...]}`, or {...}\n{...}... so which is it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50521716
score: 0

http://stackoverflow.com/q/50387754
has comment: http://stackoverflow.com/comment/87791121
answer count: 3
upvote count: 0
score: -6
favorite count: 0
type: Question
has title: How do I access similar key, value pairs in a list with multiple dictionaries
has comment: http://stackoverflow.com/comment/87791189
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50387801
has body: Suppose I have the following list [{ "user_id": 1, "firstname": "James", "lastname": "Katarikawe", "email": "jpkatarikawe@gmail.com", "password": "$3cur!ty1" }, { "user_id": 2, "firstname": "Paul", "lastname": "Kayongo", "email": "nserekopaul@gmail.com", "password": "rasengan" }] How do I print out only the email and password values of all items in the list
tagged with: python
has answer: http://stackoverflow.com/a/50387835
has answer: http://stackoverflow.com/a/50387821
downvote count: 6

http://stackoverflow.com/a/50419652
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50419523
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50419523
has body: Use QPalette: import sys from PyQt5 import QtWidgets, QtGui, QtCore class Program(QtWidgets.QWidget): def __init__(self): super().__init__() """expierment""" test = QtWidgets.QLabel(self) pal = test.palette() pal.setColor(QtGui.QPalette.WindowText, QtGui.QColor("red")) test.setPalette(pal) test.setText("I am trying to make this red?") self.resize(test.sizeHint()) self.show() app = QtWidgets.QApplication(sys.argv) tradingApp = Program() sys.exit(app.exec_())
type: Answer

class
tags question: http://stackoverflow.com/q/50438379
tags question: http://stackoverflow.com/q/50534517
tags question: http://stackoverflow.com/q/50513589
tags question: http://stackoverflow.com/q/50433883
type: Tag
tags question: http://stackoverflow.com/q/50437243
tags question: http://stackoverflow.com/q/50397741
tags question: http://stackoverflow.com/q/50422593
tags question: http://stackoverflow.com/q/50527974
tags question: http://stackoverflow.com/q/50528067
tags question: http://stackoverflow.com/q/50537781
tags question: http://stackoverflow.com/q/50463520
tag name: class
tags question: http://stackoverflow.com/q/50537673
tags question: http://stackoverflow.com/q/50402861
tags question: http://stackoverflow.com/q/50496545
tags question: http://stackoverflow.com/q/50402492
tags question: http://stackoverflow.com/q/50410272
tags question: http://stackoverflow.com/q/50391429
tags question: http://stackoverflow.com/q/50395789
tags question: http://stackoverflow.com/q/50393811
tags question: http://stackoverflow.com/q/50392787
tags question: http://stackoverflow.com/q/50385593
tags question: http://stackoverflow.com/q/50425038
tags question: http://stackoverflow.com/q/50460402
tags question: http://stackoverflow.com/q/50460267
tags question: http://stackoverflow.com/q/50386104

http://stackoverflow.com/comment/87841018
comment on: http://stackoverflow.com/q/50411346
score: 0
type: Comment
type: QuestionComment
has text: @BalázsKovacsics But I wont be able save anything if I open it as read-only. I have tried that and still gives the same 'Permission denied' error.

http://stackoverflow.com/comment/91050789
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50474709
score: 0
has text: I solved this case by set proxy, https://kb.k12usa.com/knowledgebase/proxy-settings-on-a-mac-os-x

http://stackoverflow.com/comment/87989200
type: QuestionComment
comment on: http://stackoverflow.com/q/50487712
score: 0
type: Comment
has text: Python has a csv module.

http://stackoverflow.com/a/50488693
type: Answer
has comment: http://stackoverflow.com/comment/87990347
has comment: http://stackoverflow.com/comment/87990844
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50488251
has comment: http://stackoverflow.com/comment/87990462
has comment: http://stackoverflow.com/comment/87991027
accepted answer of: http://stackoverflow.com/q/50488251
has comment: http://stackoverflow.com/comment/87990962
has comment: http://stackoverflow.com/comment/87990750
has body: Two things. You need to convert the Abortions per Year column to a numeric type for plotting, at least for the data you provided which is in str format; second, you can plot Affiliation with Religious Institutions as a line by dropping the nan values before plotting. ax1.plot(newdf['Abortions per Year'].astype(int)) ... ax1b.plot(newdf['Affiliation with Religious Institutions'].dropna())
type: AcceptedAnswer

http://stackoverflow.com/comment/87937323
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50411668
has text: Still working on one: Pandas is being a bit of a pain here. I may try putting the dataset into a numpy array and plot from there. Or maybe try using R for this plot (possibly via rpy2 or whatever it is called.

http://stackoverflow.com/q/50449181
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50452441
has comment: http://stackoverflow.com/comment/87934560
has answer: http://stackoverflow.com/a/50452441
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
has title: Unable to locate element based on absolute path in XML using Python
tagged with: python
has comment: http://stackoverflow.com/comment/87912104
has comment: http://stackoverflow.com/comment/87911917
linked to: http://stackoverflow.com/q/47304991
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87911720
score: 1
has body: My XML file looks something like this: <SCAN_LIST_OUTPUT> 2018-05-21T11:29:05Z <SCAN_LIST> scan/1526727908.25005 <TITLE> ACRS_Scan <LAUNCH_DATETIME>2018-05-19T11:05:08Z</LAUNCH_DATETIME> scan/1526549903.07613 <TITLE> testScan <LAUNCH_DATETIME>2018-05-17T09:38:23Z</LAUNCH_DATETIME> </SCAN_LIST> </SCAN_LIST_OUTPUT> Now when I try to find the REF element of the first element using an absolute path where I know the LAUNCH_DATETIME it gives me an error saying invalid predicate. Here is my code: import xml.etree.ElementTree as ET tree = ET.ElementTree(ET.fromstring(response)) groot = tree.getroot() path = './/REF[../LAUNCH_DATETIME="2018-05-19T11:05:08Z"]' scan_id = tree.find(path) Here is the following traceback call: KeyError: ('.//REF[../LAUNCH_DATETIME="2018-05-19T11:05:08Z"]', None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/doomsday/PycharmProjects/untitled/venv/ScanList.py", line 44, in <module> scan_id = tree.find(path) File "/usr/lib/python3.5/xml/etree/ElementTree.py", line 651, in find return self._root.find(path, namespaces) File "/usr/lib/python3.5/xml/etree/ElementPath.py", line 298, in find return next(iterfind(elem, path, namespaces), None) File "/usr/lib/python3.5/xml/etree/ElementPath.py", line 277, in iterfind selector.append(ops[token[0]](next, token)) File "/usr/lib/python3.5/xml/etree/ElementPath.py", line 233, in prepare_predicate raise SyntaxError("invalid predicate") SyntaxError: invalid predicate When I use the same absolute path on an online xpath evaluator, it gives me the desired output. But when I try the same in my code, it fails. If anyone could tell what the problem is and how it can be resolved, would be great. Thanks in advance.
has comment: http://stackoverflow.com/comment/87912020

http://stackoverflow.com/a/50534023
answers question: http://stackoverflow.com/q/50533812
has comment: http://stackoverflow.com/comment/88080632
score: 32
has comment: http://stackoverflow.com/comment/88080073
type: Answer
has comment: http://stackoverflow.com/comment/88080669
has comment: http://stackoverflow.com/comment/88080535
has body: Python does not allow constant declarations like C or C++. Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant. Ex. MY_CONSTANT = "Whatever" Another valid way of doing it which I don't use but heard of, is using a method: def MY_CONSTANT(): return "Whatever" Now in theory, calling MY_CONSTANT() acts just like a constant. EDIT Like the comments says, someone can go and change the value by calling MY_CONSTANT = lambda: 'Something else' but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.
has comment: http://stackoverflow.com/comment/88080479
downvote count: 0
upvote count: 32

http://stackoverflow.com/q/50493828
downvote count: 0
has answer: http://stackoverflow.com/a/54600860
answer count: 1
has body: I am trying to convert a Scrapy script to an EXE file. The main.py file looks like this: from scrapy.crawler import CrawlerProcess from amazon.spiders.amazon_scraper import Spider spider = Spider() process = CrawlerProcess({ 'FEED_FORMAT': 'csv', 'FEED_URI': 'data.csv', 'DOWNLOAD_DELAY': 3, 'RANDOMIZE_DOWNLOAD_DELAY': True, 'ROTATING_PROXY_LIST_PATH': 'proxies.txt', 'USER_AGENT_LIST': 'useragents.txt', 'DOWNLOADER_MIDDLEWARES' : { 'rotating_proxies.middlewares.RotatingProxyMiddleware': 610, 'rotating_proxies.middlewares.BanDetectionMiddleware': 620, 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, 'random_useragent.RandomUserAgentMiddleware': 400 } }) process.crawl(spider) process.start() # The script will block here until the crawling is finished The Scrapy script looks like any other. I am using pyinstaller.exe --onefile main.py to convert it to an EXE file. When I try to open the main.exe file inside the dist folder it starts outputting errors: FileNotFoundError: [Errno 2] No such file or directory: '...\\scrapy\\VERSION' I can fix it by creating a scrapy folder inside the dist folder and uploading a VERSION file from lib/site-packages/scrapy. After that, many other errors occur but I can fix them by uploading some scrapy libraries. In the end, it starts outputting an error: ModuleNotFoundError: No module named 'email.mime' I don’t even know what it means. I have never seen it. I am using: Python 3.6.5 Scrapy 1.5.0 PyInstaller 3.3.1
tagged with: scrapy
has comment: http://stackoverflow.com/comment/90928634
favorite count: 0
type: Question
tagged with: pyinstaller
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25557693
tagged with: python
score: 4
upvote count: 4
has title: Python Scrapy conversion to EXE file using PyInstaller

http://stackoverflow.com/comment/87920238
type: Comment
comment on: http://stackoverflow.com/q/50409623
score: 0
type: QuestionComment
has text: @Umair that helped a bit - answer changed, i saw `200 response`, but got another error (probably not connected with Scrapy) - I have posted another question about that. But here I have one more question - can you see please my update?

http://stackoverflow.com/comment/87850038
type: Comment
comment on: http://stackoverflow.com/q/50417089
score: 0
type: QuestionComment
has text: Does `python manage.py migrate` work?

http://stackoverflow.com/a/50456662
type: Answer
has comment: http://stackoverflow.com/comment/129676484
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/129675742
type: AcceptedAnswer
downvote count: 0
has body: There is an id associated with your input field! You can use the id to find the element element = driver.find_element_by_id('ContentPlaceHolder1_wucSignInStep2_chkTC').click() That should do it. If you are getting an element not visible error then you can try the following: from selenium.webdriver.common.action_chains import ActionChains element = driver.find_element_by_id("ContentPlaceHolder1_wucSignInStep2_chkTC") actions = ActionChains(driver) actions.move_to_element(element).perform() driver.execute_script("arguments[0].click();", element) The above code will make the element visible and also, put the mouse cursor over the checkbox.
accepted answer of: http://stackoverflow.com/q/50456362
answers question: http://stackoverflow.com/q/50456362
has comment: http://stackoverflow.com/comment/87958763
has comment: http://stackoverflow.com/comment/87964825

http://stackoverflow.com/q/50526408
type: Question
upvote count: 2
score: 2
answer count: 2
has title: pycrypto works on python2.7 not python3.6
downvote count: 0
type: UnansweredQuestion
tagged with: python
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/88064509
tagged with: python-2.7
has body: I am using Ubuntu 16 machine. I want to use python 3. I isntalled it. However, I have to use the command python3 otherwise it runs python2.7. I installed pycrypto library using pip install pycrypto but when I try to import from pycrypto using python3 I get this error: &gt;&gt;&gt; from Crypto.Cipher import AES Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'Crypto' While I do not face the same problem in python 2.7 (the import works fine). What is the problem? how to solve it? UPDATE: I tried pip3 and this is the result: x@x-VirtualBox:~$ sudo -H pip3 install pycrypto Requirement already satisfied: pycrypto in /usr/local/lib/python3.6/dist-packages (2.6.1) x@x-VirtualBox:~$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from Crypto.Cipher import AES Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'Crypto' &gt;&gt;&gt;
tagged with: pycrypto
has answer: http://stackoverflow.com/a/50526476
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50527288
has comment: http://stackoverflow.com/comment/88065342

http://stackoverflow.com/q/50488057
has title: Django handle requests with theading
has body: I have a Django project which make predictions on a VM with 2 CPU cores and 8 RAM. When my Django app starts it loads a large file (2.5GB, time to load:10 sec.) with information that the app needs. My app can handle a large amount of concurrent requests till I get error but it only use the 50% of my CPU (1 core), in order to use the 100% of my machines power I need to activate the second core through threading. How can I set the my app so can handle users requests through different threads ? Is there a recommended way to do that or an example ?
score: 0
has comment: http://stackoverflow.com/comment/87988920
answer count: 0
has comment: http://stackoverflow.com/comment/87992764
tagged with: multithreading
has comment: http://stackoverflow.com/comment/87988930
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/88013781
score: 0
has text: Ahh! That is the intended behavior of `'first'` and `'last'` in an `agg` context. This is very similar to a question of mine https://stackoverflow.com/q/45744800/2336654
comment on: http://stackoverflow.com/a/50500484
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87968688
type: Comment
type: QuestionComment
has text: @wim My linked dup is only right if the OP's real question is "how do I get a set to preserve insertion order?" (Which is why I asked instead of voting to close/dup-hammering…)
comment on: http://stackoverflow.com/q/50477509
score: 0

http://stackoverflow.com/comment/109664806
has text: There is a difference between `code running` and `task running`.
type: Comment
comment on: http://stackoverflow.com/q/50385276
type: QuestionComment
score: 0

http://stackoverflow.com/a/50463918
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50404197
upvote count: 1
has body: If you do not want to convert std::vector to boost::python::list. Then it can be possible if you pass the size of vector to python side and iterate the function with argument as index to get the element of vector to python side. in cpp: class vc { private: vector &lt;int&gt; vec ; public: vc(){}; void set_vector(); int vector_size(); int vector_iterator(int index); ~vc(){}; } void vc::set_vector() { for(int i=0;i&lt;10;i++) this-&gt;vec.push_back(i); } int vc::vector_size() { return this-&gt;vec.size(); } int vc::vector_iterator(int index) { if(this-&gt;vec.size()&gt; index) return this-&gt;vec[index]; return 0; } BOOST_PYTHON_MODULE(vector_imp) { class_&lt;vc&gt;("vc", init&lt;&gt;()) .def("set_vector",&amp;vc::set_vector) .def("vector_size",&amp;vc::vector_size) .def("vector_iterator",&amp;vc::vector_iterator) ; } in python: import vector_imp as vect vc_obj = vect.vc() vc_obj.set_vector() v_size = vc_obj.vector_size() for i in range(0,v_size): element = vc_obj.vector_iterator(i) print element

http://stackoverflow.com/q/50519818
has comment: http://stackoverflow.com/comment/88052194
has comment: http://stackoverflow.com/comment/88052121
type: Question
has comment: http://stackoverflow.com/comment/88052139
has answer: http://stackoverflow.com/a/50520116
answer count: 2
accepted answer: http://stackoverflow.com/a/50520280
score: 1
downvote count: 0
upvote count: 1
has body: I have three lists like below and I want to create a JSON file from them: devices = ['iphone', 'ipad', 'ipod', 'watch'], cities = ['NY', 'SFO', 'LA', 'NJ'], companies = ['Apple', 'Samsung', 'Walmart'] I have done like below. First manually create a dictionary: data = { 'devices': ['iphone', 'ipad', 'ipod', 'watch'], 'cities': ['NY', 'SFO', 'LA', 'NJ'], 'companies': ['Apple', 'Samsung', 'Walmart'] } Then convert it to JSON format like this: import json with open('abc.json', 'w') as outfile: json.dump(data, outfile, indent=4) Is there a better way of doing this when we have more number of lists. Ideally if I have N number of lists, I want to create a JSON formatted file a minimal amount of manual work.
favorite count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50520116
has answer: http://stackoverflow.com/a/50520280
has title: Better way to create json file from multiple lists?
tagged with: http://stackoverflow.com/tag/json
tagged with: python

http://stackoverflow.com/q/50393536
type: Question
tagged with: graph
tagged with: if-statement
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/35833011
has title: tf.reduce_max inconsistent on comparison
has answer: http://stackoverflow.com/a/50393878
tagged with: tensor
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
has body: Given a list/tensor of items, I want to check whether the max item of the whole list is the same as the max item in specific part of list: import tensorflow as tf a = tf.get_variable('a', (10,100)) b = tf.unstack(a,axis=1) c = tf.reduce_max(b[0]) d = tf.reduce_max(b[0]) if c == d: c = tf.ones((1,100)) sess = tf.Session() sess.run(tf.global_variables_initializer()) sess.run([c,d]) In the above example, c and d should be the same, however, when you run the model, it doesn't satisfy the condition to re-make variable c as a one vector. This is just an example to show that these types of comparison seem to be wrong. Any idea what would be the correct way to do it?
favorite count: 0

countvectorizer
type: Tag
tag name: countvectorizer
tags question: http://stackoverflow.com/q/50507456

http://stackoverflow.com/a/50513447
accepted answer of: http://stackoverflow.com/q/50512797
has body: I think you're overly complicating things. You can just groupby and rank to the vals columns. This returns a pandas.Series of the same length of your original df so you can just set the column to this. df['vals'] = df.groupby(['date', 'category']).vals.rank() category date info1 info2 vals 0 A 2015-01-01 BJWYE 990 2.0 1 A 2015-01-01 ISQES 475 1.0 2 A 2015-01-01 KDEKE 214 3.0 3 B 2015-01-01 TFOXR 203 2.0 4 B 2015-01-01 HKTNF 992 1.0
upvote count: 2
answers question: http://stackoverflow.com/q/50512797
has comment: http://stackoverflow.com/comment/88039743
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50516248
has body: I've been trying to get this to work, and have searched everywhere and read page up and page down, but doesn't seem to find an answer. I have Apache with mod_wsgi and a simple test Flask application. I got it working using this: https://www.jakowicz.com/flask-apache-wsgi/ Then I somehow found that Apache mod_wsgi used the system python and I want to use venv (https://docs.python.org/3/library/venv.html). My application is in a directory with the normal directory structure of the venv, but how do I get my application to use that? I found this: http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html But if I put in python-home my application fails. A couple of questions: How do I find the Python version that my app is using? How do I find my mod_wsgi version? How do I get my app to use my venv? I'm new to Python and WSGI, I have mostly worked with PHP. Hope someone can explain to me what to do... -- Ronni
has comment: http://stackoverflow.com/comment/88059261
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50526840
favorite count: 0
type: Question
tagged with: python-venv
has title: Python Flask using mod_wsgi in Apache; how to get venv to work?
tagged with: wsgi
has answer: http://stackoverflow.com/a/70175091
tagged with: python
tagged with: flask
possible better answer: http://stackoverflow.com/a/50528211
has comment: http://stackoverflow.com/comment/88045078
has answer: http://stackoverflow.com/a/50528211
has comment: http://stackoverflow.com/comment/88065218
type: AnsweredQuestion
answer count: 3
tagged with: mod-wsgi
accepted answer: http://stackoverflow.com/a/50526840

http://stackoverflow.com/comment/87874993
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50429861
has text: I created a user without staff permissions and i tested with it. In the admin appears the item but when i click on the django admin site reject me, it means, i haven't permissions.

http://stackoverflow.com/q/50514936
score: 0
has answer: http://stackoverflow.com/a/50515294
type: UnansweredQuestion
has title: Delayed Compute with Method Chaining in Python
has answer: http://stackoverflow.com/a/50515187
has answer: http://stackoverflow.com/a/50514976
has answer: http://stackoverflow.com/a/50515096
has body: Let say I have a class: class MATH(object): def __init__(self): self.results = [0, 1, 2] def add(self, value): # Add amount 'value' to every element in the results list def minus(self, value): # Subtract amount 'value' from every element in the results list def compute(self): # Perform computation Is there a way to do something like: m = MATH() m.add(5).minus(2).add(7) # This would be a lazy and not actually compute m.compute() # This would actually run the computations in order How do I do something like this in python?
tagged with: python
answer count: 4
type: Question

http://stackoverflow.com/comment/87893866
type: Comment
type: QuestionComment
score: 1
has text: so what's the code in `cascadenet.network.layers`?!
comment on: http://stackoverflow.com/q/50439879

http://stackoverflow.com/comment/88028782
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50506076
type: QuestionComment
has text: No, the usage of imshow has nothing to do with the backend used for storing the plot. It works perfectly fine with PDF backend, for example. Try `extent` option to imshow for custom axis range.

http://stackoverflow.com/q/50400765
score: 6
tagged with: tensorflow
favorite count: 0
tagged with: sequential
has body: I am trying to implement a slightly modified binary crossentropy loss function for a model in Keras. From Keras, binary_crossentropy is defined as: def binary_crossentropy(y_true, y_pred): return K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1) The data I have is grouped (i.e there is a column indicating group1, group2, etc.) but there is a varying number of rows for each group (i.e group1 has 52 observations, group2 has 101 observations, etc.). IDEALLY, I would like to find the mean binary crossentropy for each of these groups, and return the maximum mean binary crossentropy (largest average binary crossentropy, by group). There doesn't seem to be any out-of-the-box solutions for using groups, and I wasn't able to come up with a solution. The information about which group an observation belongs to gets lost and isn't passed into y_true and y_pred, and I'm not sure how k-fold cv would exactly change what/how many observations are passed as y_true and y_pred. If there was a way to retain the group information through the Sequential model, that would probably be the solution. Code would accomplish something like: def custom_loss(y_true, y_pred): max_bc = [] for group in groups: max_bc += [K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)] return max_bc If the above isn't possible, an alternative measure could be something like the 75th percentile value of the tensor. Something like: def custom_loss(y_true, y_pred): return K.binary_crossentropy(y_true, y_pred)[len(y_true)*0.75] But I know for sure that is wrong-- I'm just not familiar enough with Keras and Tensorflow to get the right code. EDIT: I might've just found a way to do the percentiles, but the outcome isn't as desired... Would still be great to get insight on the first part. def custom_loss(y_true, y_pred): e = K.binary_crossentropy(y_true,y_pred) return distributions.percentile(e, q=75.)
linked to: http://stackoverflow.com/q/46858016
tagged with: loss-function
tagged with: python
has comment: http://stackoverflow.com/comment/87819633
upvote count: 6
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/101655367
type: UnansweredQuestion
downvote count: 0
has title: Keras - custom loss function / access 75th percentile element of a tensor
has comment: http://stackoverflow.com/comment/87893548
tagged with: keras

http://stackoverflow.com/comment/87967233
type: QuestionComment
comment on: http://stackoverflow.com/q/50476771
has text: Meanwhile, do you by any chance have a file named `random.py`, `random.pyc`, `random.pyd`, `random.dll`, etc. in your working directory or site-packages (or any other directory you've added to `sys.path`)?
score: 0
type: Comment

http://stackoverflow.com/q/50486647
has title: Cannot import neo4j in python
tagged with: neo4j
has comment: http://stackoverflow.com/comment/87988684
tagged with: import
has comment: http://stackoverflow.com/comment/87989350
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: cypher
downvote count: 0
tagged with: python
has body: Neo4j driver v1.5.3 has been installed, Neo4j is running. After that I've tried to run example: from neo4j.v1 import GraphDatabase uri = "bolt://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "password")) def print_friends_of(tx, name): for record in tx.run("MATCH (a:Person)-[:KNOWS]-&gt;(f) " "WHERE a.name = {name} " "RETURN f.name", name=name): print(record["f.name"]) with driver.session() as session: session.read_transaction(print_friends_of, "Alice") But I'm getting: Traceback (most recent call last): File "C:/experiment/Cypher.py", line 1, in from neo4j.v1 import GraphDatabase ModuleNotFoundError: No module named 'neo4j' Process finished with exit code 1 Additional info using: (venv) >pip freeze aiohttp==3.1.2 appdirs==1.4.3 async-timeout==2.0.1 attrs==17.4.0 beautifulsoup4==4.6.0 certifi==2018.1.18 chardet==3.0.4 idna==2.6 idna-ssl==1.0.1 lxml==4.2.1 multidict==4.1.0 neo4j-driver==1.5.3 packaging==17.1 py2neo==3.1.2 pyparsing==2.2.0 PyQt5==5.10.1 pyqt5-tools==5.9.0.1.2 python-dateutil==2.7.2 requests==2.18.4 selenium==3.11.0 sip==4.19.8 six==1.11.0 urllib3==1.22 yarl==1.1.1 So, what I do wrong? UPDATE I'm using PyCharm 2018.1.3 (pro) and python 3.6.1. All modules were installed using pip. The strange thing is that I just successfully ran this script directly using Windows PowerShell command string "python c:\experiment.cypher.py". So, the problem is in PyCharm, or I have something to do to make this work inside PyCharm?
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/50416409
answers question: http://stackoverflow.com/q/50416254
has comment: http://stackoverflow.com/comment/87849563
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50416254
type: Answer
has body: The most scalable solution would be to standardize the signature of functions in commands. Do so by making all functions take any number of arguments with *args and let them handle the argument parsing. The advantage of this approach is that it will easily generalize when you will need to add a function that takes, say, 2 arguments to your dict and allow your API to gracefully display custom error messages. This even extends to functions that need keyword arguments using **kwargs. def create_droplet(*args): print(args) def droplets(*args): # Here you can warn the user if arguments are given if args: print('command droplets takes no argument') return print("test") commands = { 'create_droplet': create_droplet, 'droplets': droplets } # Here is a one-line way to extract command and arguments command, *args = input('enter a command: ').split() if command in commands: commands[command](*args) else: print('command does not exist') Example of outputs: enter a command: create_droplet 1 2 ('1', '2') enter a command: droplets test enter a command: droplets 1 command droplets takes no argument
has comment: http://stackoverflow.com/comment/87849627
score: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/88000540
type: AnswerComment
has text: Could you explain how? related_name is for the reverse relation from A back to B, no? So I can do a.b_set (or whatever I define related_name to be) but how does that help me here?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50493679

http://stackoverflow.com/q/50532695
score: 1
has answer: http://stackoverflow.com/a/50534067
has title: Embed filename using python-gnupg
tagged with: gnupg
favorite count: 0
type: Question
has body: I'm able to embed the original filename using python-gnupg when encrypting a file using below: filename = 'test.tim' with open(filename, 'rb) as fh: status = gpg.encrypt_file(fh, recipients='somerecipient', output='test.tim.gpg',\ sign='somesignature', extra_args=['--set-filename', os.path.basename(filename)]) This can be verified by using gpg from the command line: $ gpg2 --list-packets test.tim.gpg | grep name I am however unable to preserve the original filename when decrypting the file: with open(filename, 'rb') as fh: status = gpg.decrypt_file(fh, extra_args['--use-embedded-filename']) I am aware about the output parameter (which specifies the filename to save contents to) in the decrypt_file function, but i want to preserve the original filename (which i won't always know) It seems the decrypt_file function always passes the --decrypt flag to gpg which always ouputs the contents to stdout (unless used in conjunction with output parameter) as in: $ gpg --decrypt --use-embedded-filename test.tim.gpg Below command will decrypt and save output to original filename: $ gpg --use-embedded-filename test.tim.gpg Any ideas? Tim
linked to: http://stackoverflow.com/q/325463
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88048002
has text: added a more accurate reflection of the data. Apologies for the inconvenience.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50496642
type: AnswerComment

redis
tags question: http://stackoverflow.com/q/50470949
type: Tag
tags question: http://stackoverflow.com/q/50511910
tags question: http://stackoverflow.com/q/50452025
tags question: http://stackoverflow.com/q/50518116
tags question: http://stackoverflow.com/q/50398484
tags question: http://stackoverflow.com/q/50486563
tag name: redis
tags question: http://stackoverflow.com/q/50399438

http://stackoverflow.com/comment/88010443
has text: @CharlesDuffy If I remove "shell=True", then I always get "FileNotFoundError: [WinError 2] The system cannot find the file specified." I understand it is bad but it seems like it runs at least.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50497327
score: 0

http://stackoverflow.com/a/50486770
score: 1
has body: The matching should be done row wise In that case you have to add some form of indices and join from pyspark.sql.types import * def index(df): schema = StructType(df.schema.fields + [(StructField("_idx", LongType()))]) rdd = df.rdd.zipWithIndex().map(lambda x: x[0] +(x[1], )) return rdd.toDF(schema) brand_name = spark.createDataFrame(["TOASTMASTERS", "USBORNE"], "string").toDF("brand_stop") poi_name = spark.createDataFrame(["TOASTMASTERS DISTRICT 48", "USBORNE BOOKS AND MORE"], "string").toDF("poi_name") index(brand_name).join(index(poi_name), ["_idx"]).selectExpr("*", "poi_name rlike brand_stop").show() # +----+------------+--------------------+-------------------------+ # |_idx| brand_stop| poi_name|poi_name RLIKE brand_stop| # +----+------------+--------------------+-------------------------+ # | 0|TOASTMASTERS|TOASTMASTERS DIST...| true| # | 1| USBORNE|USBORNE BOOKS AND...| true| # +----+------------+--------------------+-------------------------+
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50482720
answers question: http://stackoverflow.com/q/50482720
type: Answer

http://stackoverflow.com/comment/87853963
comment on: http://stackoverflow.com/a/50418949
score: 0
has text: @Megalng I just did. Both of the codes within my question and the your solution are not desired. What's desired is for a user to be unable to initialize `A()`. If I do `B()` and `B.C()` then `A()` is initializable. Now I can do things like doing a sys.settrace within A and jump back and forth within B, for `A()` to still be uninitializable but I'm trying to see if there's a better way.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50393155
downvote count: 0
tagged with: file
answer count: 0
has body: I have a computer with Windows10 and Ubuntu virtual machine. There is a file with the name log in a shared folder that contains precisely one Unix EOL character. It was created by the virtual machine. In the virtual machine, the following happens: Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.path.isdir('/media/path/to/log') True Hence, python mistakenly thinks that log is a directory (for example, the call list(os.listdir('/media/path/to/log')) raises the NotADirectoryError). The same happens when I insert the relative path. If I call isdir in Windows command line, it always returns False as expected.
favorite count: 0
has comment: http://stackoverflow.com/comment/87803240
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87803123
type: Question
has comment: http://stackoverflow.com/comment/87806449
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/87802745
has comment: http://stackoverflow.com/comment/87806797
tagged with: python
has comment: http://stackoverflow.com/comment/87828831
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87802314
has comment: http://stackoverflow.com/comment/87802757
has comment: http://stackoverflow.com/comment/87803501
has title: Python3: os.path.isdir(path) is True for a file
has comment: http://stackoverflow.com/comment/87802854
has comment: http://stackoverflow.com/comment/87802434
has comment: http://stackoverflow.com/comment/87802936
has comment: http://stackoverflow.com/comment/87807465
has comment: http://stackoverflow.com/comment/87803927

http://stackoverflow.com/q/50452686
type: UnansweredQuestion
answer count: 1
has title: Is there a way to interpolate values while maintaining a ratio?
type: Question
tagged with: pandas
score: 0
has body: I have a dataframe of percentages, and I want to interpolate the intermediate values 0 5 10 15 20 25 30 35 A 0.50 0.50 0.50 0.49 0.47 0.41 0.35 0.29 0.22 B 0.31 0.31 0.31 0.29 0.28 0.24 0.22 0.18 0.13 C 0.09 0.09 0.09 0.09 0.08 0.07 0.06 0.05 0.04 D 0.08 0.08 0.08 0.08 0.06 0.06 0.05 0.04 0.03 E 0.01 0.01 0.01 0.01 0.01 0.02 0.02 0.03 0.04 F 0.01 0.01 0.01 0.04 0.10 0.20 0.30 0.41 0.54 So far, I've been using scipy's interp1d and iterating row by row, but it doesn't always maintain the ratios perfectly down the column. Is there a way to do this all together in one function?
has answer: http://stackoverflow.com/a/50452800
tagged with: scipy
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/50498770
linked to: http://stackoverflow.com/q/48736670
has body: If I have a class A: def foo(self): pass this evaluates to True: getattr(A, 'foo') is A.foo but this evaluates to False: a = A() getattr(a, 'foo') is a.foo as does a.foo is a.foo Why? I found that getattr(a, 'foo') and a.foo both are represented by &lt;bound method A.foo of &lt;__main__.A object at 0x7a2c4de10d50&gt;&gt;) So no hint there....
has comment: http://stackoverflow.com/comment/88010424
possible better answer: http://stackoverflow.com/a/50498855
duplicate of: http://stackoverflow.com/q/48736670
favorite count: 0
has answer: http://stackoverflow.com/a/50498855
type: Question
has comment: http://stackoverflow.com/comment/88010515
linked to: http://stackoverflow.com/q/41900639
upvote count: 5
has answer: http://stackoverflow.com/a/50498830
accepted answer: http://stackoverflow.com/a/50498830
tagged with: python
type: AnsweredQuestion
has title: Why does `instance_of_object.foo is instance_of_object.foo` evaluate False?
has answer: http://stackoverflow.com/a/50498979
has comment: http://stackoverflow.com/comment/88010389
tagged with: introspection
score: 5
answer count: 3
has comment: http://stackoverflow.com/comment/88010349
has comment: http://stackoverflow.com/comment/88010713
downvote count: 0

http://stackoverflow.com/q/50533629
has answer: http://stackoverflow.com/a/50534060
accepted answer: http://stackoverflow.com/a/50534060
has comment: http://stackoverflow.com/comment/88079192
tagged with: regex
has answer: http://stackoverflow.com/a/50533684
has comment: http://stackoverflow.com/comment/88079308
has title: Searching for a substring match in a string list with 2 lists
tagged with: substring
has body: I have 2 lists that I'm trying to work with. The first is a nameList that corresponds to names that I want to find a match within and the second list is a status of that named list. I want to be able to look through the 1st list and look for a match within the string and if there is a match grab the element in the first list into a new list and also grab the corresponding element in the second list to get a name and status pair. I've tried several approaches at this and have not been able to get it right and have looked at various list comprehension questions on the board and haven't been able to find a solution that works for my case. For example in the code below, I would like to grab the 'abc-1' and 'abc-2' entries as well as the 'ok' and 'ok' status for both of those entries and output those as the finalNameList and finalStatusList. I'd be grateful for any help anyone could provide. In my current implementation I am getting a type error : 'expected string or buffer' import re import os import sys import getopt import pdb nameList = ['abc-1', 'abc-2', 'def-1', 'def-2'] statusList = ['ok', 'ok', 'bad', 'bad'] scac = 'abc' def scacFilter (scac, nameList, statusList): if not scac: newNameList = nameList newStatusList = statusList else: for i in nameList: if re.search(scac, i): name = nameList[i] status = statusList[i] newNameList.append(name) newStatusList.append(status) else: print 'no scac match' return newNameList, newStatusList finalNameList, finalStatusList = scacFilter(scac, nameList, statusList)
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88079244
possible better answer: http://stackoverflow.com/a/50533684
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list

http://stackoverflow.com/q/50530834
has answer: http://stackoverflow.com/a/50530906
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88073773
answer count: 1
has comment: http://stackoverflow.com/comment/88073976
has comment: http://stackoverflow.com/comment/88074265
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88073731
score: 0
has comment: http://stackoverflow.com/comment/88073683
has comment: http://stackoverflow.com/comment/88073620
has comment: http://stackoverflow.com/comment/88073922
has title: Remove square brackets when writing to html file?
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/88073671
tagged with: python
has comment: http://stackoverflow.com/comment/88073647
has body: I've tried .replace also tried re.sub and many other suggestions online, but I can't seem to remove these things. This is for assessment so I can't use any non-standard python libraries. var = [] for itm in range(10): doSomething def itemList(itm): global var list = [list1[itm], list2[itm], list3[itm]] var.append(list) def writeToHtml(): htmlFile.write('&lt;li&gt;' + ' &lt;br&gt;&lt;/br&gt;'.join(map(str, var)) + '&lt;/li&gt;') #this is what is written in html file &gt;&gt;&gt; ['stuff', 'stuff', 'stuff'] # But I need it to be stuff stuff stuff stuff
accepted answer: http://stackoverflow.com/a/50530906
type: Question

http://stackoverflow.com/q/50401436
has answer: http://stackoverflow.com/a/50401687
score: 2
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/50382040
type: Question
tagged with: python-3.x
tagged with: iterator
has answer: http://stackoverflow.com/a/50401798
has title: How does parent class "enumerate" access an argument not set as an instance variable?
upvote count: 2
possible better answer: http://stackoverflow.com/a/50401523
has answer: http://stackoverflow.com/a/50401523
tagged with: python
tagged with: inheritance
answer count: 4
accepted answer: http://stackoverflow.com/a/50401687
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50403036
has body: I stumbled upon a question yesterday that involved enumerating over an iterable type and yeilding descending indices accompanied by ascending items in the iterable. In: letters = ['a', 'b', 'c'] for i, letter in revenumerate(letters): print('{}, {}'.format(i, letter)) Out: 2, a 1, b 0, c Instead of writing a quick and reliable answer applying built-in reverse twice, or simply i = len(letters) - i - 1, I decided to try create a child class of enumerate that redefines __iter__ and __next__ methods. The code for my original working solution was as follows: class revenumerate(enumerate): def __init__(self, iterable, start=0): self._len = len(iterable) self._start = start if isinstance(iterable, dict): self._data = iterable.keys() else: self._data = iterable def __iter__(self): _i = self._len for _item in self._data: _i -= 1 _ind = _i + self._start yield _ind, _item def __next__(self): _i, _item = super().__next__() _ind = self._len + 2 * self._start - _i - 1 return _ind, _item However, I now realize this code has redundancy as enumerate.__iter__ appears to yield the result of __next__, makes sense. After deleting the redefined __iter__ I realized that self._data was not being used anywhere, so I removed the last four lines from __init__ leaving me with the following code, which still provides the desired behavior. class revenumerate(enumerate): def __init__(self, iterable, start=0): self._len = len(iterable) self._start = start def __next__(self): _i, _item = super().__next__() _ind = self._len + 2 * self._start - _i - 1 return _ind, _item Now it appears that the iterable argument passed into revenumerate is not for anything except determining the integer self._len. My question is - where is iterable stored and how does super().__next__ access it? A quick look at builtins.py with the PyCharm debugger does not provide a lot of help in figuring this out (or so it seems to me at this stage), and I am not well traversed with the Python source code repository. My guess is so…

http://stackoverflow.com/comment/87815391
has text: An `Acton` object has attributes like `dest`, `nargs` and `default`. You can view those, and even modify them. So you might not have remove the old action, but just change its `dest`. I like testing ideas like this an interactive session where I can examine objects and make changes directly.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50397835

http://stackoverflow.com/a/56530006
has body: Correction: axis=0 refers to rows, not to columns. axis=1 refers to columns, not to rows. x = np.array([[12,11,10,9],[16,15,14,13],[20,19,18,17]]) print(x) [[12 11 10 9] [16 15 14 13] [20 19 18 17]] np.argmax(x, axis=0) array([2, 2, 2, 2] # third row, index 2 of each of the 4 columns np.argmax(x, axis=1) array([0, 0, 0] # first column, index 0 of each of the three rows.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50460994

http://stackoverflow.com/comment/87854851
has text: Ok, that's a little bit complicate, I guess I will just use &, thank you very much
comment on: http://stackoverflow.com/a/50415613
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50445870
tagged with: python-3.6
has title: ZODB python: how to avoid creating a database with only one big entry?
has answer: http://stackoverflow.com/a/50449409
type: AnsweredQuestion
score: 3
has body: I'm using the ZODB python database module for the first time. The tutorial (http://www.zodb.org/en/latest/tutorial.html) confuses me about a certain aspect of the ZODB database behavior: how can I avoid to accidentally create a database with just a single very big entry? I'll explain step-by-step my application, my current database approach, and where the confusion comes from. &nbsp; 1. The Item-object The database I want to save consists entirely of Item-objects, defined as follows (a little simplified): class Item(Persistent): def __init__(self, name, *args, **kwargs): super().__init__(*args, **kwargs) # 1. Persistent variables # ------------------------ self.__name = name self.__myList = PersistentList() # &lt;- list can hold other Item-objects self.__myVar01 = None self.__myVar02 = None self.__myVar03 = None # 2. Non-persistent variables # ---------------------------- self._v_myVar01 = None self._v_myVar02 = None self._v_myVar03 = None Visually represented as follows: &nbsp; The application constructs one such Item-object at startup. During the application, this Item-object will create 'children' (which are also Item-objects themselves). This process goes on for a while, such that the following object-structure is in memory: &nbsp; This construct can easily consist of 20.000 Item-objects. So I want to save them in a database. &nbsp; 2. How I save this structure to a ZODB-database To save this structure of Item-objects in a database, I follow the following guidelines from the tutorial: Storing objects To store an object in the ZODB we simply attach it to any other object that already lives in the database. Hence, the root object functions as a boot-strapping point. The root object is meant to serve as a namespace for top-level objects in your database. [ Quoted from ZODB Tutorial &nbsp;&nbsp;http://www.zodb.org/en/latest/tutorial.html ] The following functions create a new database (starting from the top-level item) and save it to the harddrive: from ZODB.FileSto…
upvote count: 3
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/131020337
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50449409
tagged with: python-3.x
tagged with: zodb
tagged with: database
tagged with: python

http://stackoverflow.com/q/50458082
answer count: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/50461867
type: Question
has title: PySpark Access DataFrame columns at foreachPartition() custom function
tagged with: iterator
accepted answer: http://stackoverflow.com/a/50461867
tagged with: pyspark
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: apache-spark
has body: I have a function named "inside". I want to apply this function to a pyspark dataframe. For this purpose i call the "foreachPartition(inside)" method on the dataframe I create. The "inside" function needs the values of the dataframe. The dataframe looks like this: &gt;&gt;&gt; small_df DataFrame[lon: double, lat: double, t: bigint] The code looks like this: def inside(iterator): row=iterator x=row.lon y=row.lat i=row.t #do more stuff small=pliades.iloc[0:20000,:] #take sample of rows from big dataset small_df=sqlContext.createDataFrame(small) #create dataframe test=small_df.foreachPartition(inside) My question is: how can x,y,i get the values of the first(lon),second(lat) and third(t) columns of the dataframe respectively? I tried also doing it with row.lon, row.select, treating it as a list but couldn't get the result needed.

http://stackoverflow.com/comment/87850665
comment on: http://stackoverflow.com/a/50417451
type: Comment
type: AnswerComment
has text: This returns a ` :1: DeprecationWarning: invalid escape sequence \d`. with compiler warnings turned on. I suggest you use raw strings.
score: 2

http://stackoverflow.com/comment/88008230
has text: Calling `windll.user32.MessageBoxA()` is most definitely Windows-specific. There are ways of doing the equivalent on almost _any_ system using the `tkinter` module.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50497479
type: QuestionComment

http://stackoverflow.com/q/50527666
type: AnsweredQuestion
has body: After insert the "re.compile" to row, cannot print out chinese character, thanks ! Compare output between table and rows: output from table "title="添加置顶" and output from rows "title="\u6dfb\u52a0\u7f6e\u9876" #coding:utf-8 from bs4 import BeautifulSoup import re html = """" 选 角/半 """ soup = BeautifulSoup(html, "html.parser") table = soup.find('table', id="table_live") rows = table.findAll("tr", {"id" : re.compile('tr1_\d{7}')}) print table print rows 1)table can be print out chinese character but 2)rows cannot print our chinese character output from table 选 角/半 output from rows [ \n ]
has comment: http://stackoverflow.com/comment/88067046
tagged with: python
has comment: http://stackoverflow.com/comment/88067135
has title: Cannot print out correctly when "re.compile" in python
has answer: http://stackoverflow.com/a/50528041
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50528041
type: Question
tagged with: beautifulsoup

http://stackoverflow.com/comment/87843985
type: Comment
type: QuestionComment
has text: Relative imports work in packages. You don't seem to have any package there (no *\_\_init\_\_.py(c)* file present).
comment on: http://stackoverflow.com/q/50413824
score: 0

http://stackoverflow.com/q/50415389
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50415625
accepted answer: http://stackoverflow.com/a/50415625
favorite count: 0
has body: Given an arbitrary function definition: def f(a, b, *args, kw_a=None, kw_b=123, **kwargs): ... Is there an easy way of checking whether the given args and kwargs will satisfy the following call: f(*args, **kwargs) without actually calling the function at hand? I know that in python3.3 and up there's inspect.Signature.bind(). Is there anything easier in python2.7, than using inspect.getargspec() and parsing the returned ArgSpec tuple?
type: Question
tagged with: python
has title: Check if given *args and **kwargs satisfy given function signature (Signature.bind() in python2)
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7

anaconda
tags question: http://stackoverflow.com/q/50431294
tags question: http://stackoverflow.com/q/50470014
tags question: http://stackoverflow.com/q/50488997
tags question: http://stackoverflow.com/q/50395044
tags question: http://stackoverflow.com/q/50404010
tags question: http://stackoverflow.com/q/50521774
type: Tag
tags question: http://stackoverflow.com/q/50439980
tags question: http://stackoverflow.com/q/50472873
tags question: http://stackoverflow.com/q/50506200
tags question: http://stackoverflow.com/q/50476501
tag name: anaconda
tags question: http://stackoverflow.com/q/50519802
tags question: http://stackoverflow.com/q/50436992
tags question: http://stackoverflow.com/q/50408174
tags question: http://stackoverflow.com/q/50415609
tags question: http://stackoverflow.com/q/50388529
tags question: http://stackoverflow.com/q/50391766
tags question: http://stackoverflow.com/q/50457501
tags question: http://stackoverflow.com/q/50474028
tags question: http://stackoverflow.com/q/50469796
tags question: http://stackoverflow.com/q/50419866
tags question: http://stackoverflow.com/q/50388833
tags question: http://stackoverflow.com/q/50420167
tags question: http://stackoverflow.com/q/50535911
tags question: http://stackoverflow.com/q/50398654
tags question: http://stackoverflow.com/q/50518622
tags question: http://stackoverflow.com/q/50475580
tags question: http://stackoverflow.com/q/50442202
tags question: http://stackoverflow.com/q/50537131
tags question: http://stackoverflow.com/q/50431942
tags question: http://stackoverflow.com/q/50440391
tags question: http://stackoverflow.com/q/50480903
tags question: http://stackoverflow.com/q/50412659
tags question: http://stackoverflow.com/q/50493113
tags question: http://stackoverflow.com/q/50448342
tags question: http://stackoverflow.com/q/50495232
tags question: http://stackoverflow.com/q/50504279
tags question: http://stackoverflow.com/q/50420693
tags question: http://stackoverflow.com/q/50487156
tags question: http://stackoverflow.com/q/50484397
tags question: http://stackoverflow.com/q/50535634
tags question: http://stackoverflow.com/q/50463731
tags question: http://stackoverflow.com/q/50453529
tags question: http://stackoverflow.com/q/50518926
tags question: http://stackoverflow.com/q/50499539

http://stackoverflow.com/comment/87847901
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50413824
has text: Do you name your Sphinx configuration file `config.py`? Normally the name is `conf.py`. See http://www.sphinx-doc.org/en/master/usage/configuration.html.

http://stackoverflow.com/q/50496282
type: Question
has title: batcher is not recognised as an iterator in python
answer count: 0
tagged with: bayesian
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88007043
score: 0
has body: I am trying to run a script in python that I use for a project I have for my school. Basically I am using Bayesian RNNs to train a model with my set of data and I am using the script that my professor suggested since I do not use or have a GPU. When I run the script I get this error on my bash. I am new to python, RNNs and Artificial Intelligence but I am really interested on that sector but I need some guidance from people with much more experience. I tried understanding the nature of the error but I don't know how to work out with that problem. I am using xubuntu with python version 2.7.14 and tensorflow version 1.1. I am posting the code and the error below: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf import numpy as np import logging from bayesian_rnn import BayesianRNN from reader import ptb_raw_data, Batcher from config import get_config logger = logging.getLogger(__name__) def get_running_avg_loss(name, metric, running_avg_metric, summary_writer, step, decay=0.999): """ Calculate the running average of losses. """ if running_avg_metric == 0: running_avg_metric = metric else: running_avg_metric = running_avg_metric * decay + (1 - decay) * metric loss_sum = tf.Summary() loss_sum.value.add(tag="loss", simple_value=running_avg_metric) summary_writer.add_summary(loss_sum, step) logger.info("Metric Reported: {} : {}".format(name, running_avg_metric)) return running_avg_metric def run_step(name, batcher, step_function, session, summary_writer, running_avg_metric, step, state, memory): try: inputs, targets = next(batcher) except StopIteration: batcher.refresh_generator() inputs, targets = next(batcher) summaries, loss, state, memory, step = step_function(session, inputs, targets,state, memory, step) if summaries is not None: summary_writer.add_summary(summaries, step) running_avg_loss = get_running_avg_loss(name + "_loss", running_avg_metric, loss, summary_writer, step)…
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/88006282
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88005303

http://stackoverflow.com/a/50496447
has comment: http://stackoverflow.com/comment/88005689
has comment: http://stackoverflow.com/comment/88006056
has body: query df.query('time &gt; 1') val id time 1 2 3 2 2 4 IndexSlice DataFrame index must be lexsorted df.sort_index().loc[pd.IndexSlice[:, 2:], :] val id time 1 2 3 2 2 4
has comment: http://stackoverflow.com/comment/88006288
accepted answer of: http://stackoverflow.com/q/50496433
has comment: http://stackoverflow.com/comment/88006060
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88005750
has comment: http://stackoverflow.com/comment/88006290
answers question: http://stackoverflow.com/q/50496433
has comment: http://stackoverflow.com/comment/88005984
downvote count: 0
score: 21
upvote count: 21
type: Answer

http://stackoverflow.com/q/50488410
type: UnansweredQuestion
tagged with: python
score: -1
has title: Get layers weights as network output keras
has answer: http://stackoverflow.com/a/50494566
upvote count: 0
tagged with: deep-learning
downvote count: 1
has body: I hope someone can help me with this problem. I have an autoencoder model, where I would like to get the weights W of the dense layer in the middle: I have to set some elements to zeros, and use it in the loss function. basically x = Encoder()(input) z = Dense(units=10)(x) out = Decoder()(z) and the loss should have the following interface loss(input, out, z, w) there w are the weights of the dense layer. Any idea how? Additionally, I'd like to enforce the diagonal of W to be zero. I saw Tensorflow has a matrix_set_diag function, any experience with that?
answer count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/88089005
score: 2
type: Comment
type: QuestionComment
has text: `df.groupby('code').size()`
comment on: http://stackoverflow.com/q/50538570

http://stackoverflow.com/q/50386113
tagged with: selenium
type: Question
has body: I am using Selenium + Python to browse internet. Unfortunately, it does not work with Internet Explorer (but it works with Chrome) at my firm, surely because there is a proxy and the need to use a PAC file to browse internet in my firm. Here is my code : from selenium import webdriver from selenium.webdriver.common.proxy import ProxyType from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.ie.webdriver import WebDriver as Ie ie_path=... url_of_the_pac_file=... caps = DesiredCapabilities.INTERNETEXPLORER caps["proxy"] = {"proxyType": "pac","proxyAutoconfigUrl": url_of_the_pac_file} driver=Ie(executable_path=ie_path,capabilities=caps,port=8080) driver.get("http://www.google.com") Each time I run this code, I have this message : Traceback (most recent call last): File "C:\Users\TEST\Desktop\demo\demo_ie.py", line 34, in <module> driver=Ie(executable_path=ie_path,capabilities=caps,port=8080) #, capabilities=caps, port=0, timeout=30, host=None, log_level=None, log_file=log_path, ie_options=None) File "C:\Anaconda3_3.4_32\lib\site-packages\selenium\webdriver\ie\webdriver.py", line 82, in __init__ desired_capabilities=capabilities) File "C:\Anaconda3_3.4_32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 151, in __init__ self.start_session(desired_capabilities, browser_profile) File "C:\Anaconda3_3.4_32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 240, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Anaconda3_3.4_32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute self.error_handler.check_response(response) File "C:\Anaconda3_3.4_32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 165, in check_response raise exception_class(value) selenium.common.exceptions.WebDriverException: Message: Access Denied - Web Proxy Access Denied (authentication_failed) Your credentials could not be authenticated: "Credentials …
has title: Selenium + Python + Internet Explorer + Firm Proxy + PAC file + Credentials
tagged with: internet-explorer
tagged with: credentials
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50386789
tagged with: python
tagged with: proxy
score: 0
answer count: 1

http://stackoverflow.com/a/50519117
answers question: http://stackoverflow.com/q/50518825
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50518825
has comment: http://stackoverflow.com/comment/88060312
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88051191
type: Answer
has body: That image is an edited version of an image from this paper: C. Miller, Z. Nagy, A. Schlueter, Automated daily pattern filtering of measured building performance data, Automation in Construction 49, Part A (2015) 1–17. doi:10.1016/j.autcon.2014.09.004. URL http://www.sciencedirect.com/science/article/pii/S0926580514002015 They came up with the visualisation techniques themselves and describe them there. It looks like C. Miller is the one who wrote the notebook that you already found that shows how to draw the stacked heatmaps. The augmented suffix tree is a type of visualization called a Sankey Diagram. You can plot these very beautifully using Plotly for example, or pySankey if you want to use matplotlib.

http://stackoverflow.com/q/50496821
possible better answer: http://stackoverflow.com/a/50496902
tagged with: python
has comment: http://stackoverflow.com/comment/88008426
has answer: http://stackoverflow.com/a/50496902
has comment: http://stackoverflow.com/comment/88006648
type: AnsweredQuestion
score: 0
answer count: 3
has body: I want to have a dict of functions, but some of the functions take more arguments than others. "1":func1, # This takes 0 arguments "2":func2 # This takes 1 argument ` I don't know how to call the function through the dict. Am I supposed to have an if statment or is there something I am missing?
has title: How to call functions in a dict that take different numbers of arguments?
has answer: http://stackoverflow.com/a/50497246
has answer: http://stackoverflow.com/a/50496896
type: Question
has comment: http://stackoverflow.com/comment/88006452
accepted answer: http://stackoverflow.com/a/50497246
tagged with: function

http://stackoverflow.com/a/54315320
answers question: http://stackoverflow.com/q/50446888
score: 0
has body: I had exactly the same problem. My setup: Windows 10 &amp; Python 3.6. I solved it by directly modifying the source code (non-optimal solution, but that works). This is to ignore certificate validation. Open: ~ /Lib/site-packages/ecmwfapi/api.py At the start of the script, add: import ssl Adds at the beginning of the "_transfer" function: ctx = ssl.create_default_context () ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE Then modify (always within the function): urlopen (req) by: urlopen (req, context = ctx) Source: python ignore certificate validation urllib2 Cheerio!
type: Answer

http://stackoverflow.com/q/50515725
has answer: http://stackoverflow.com/a/50515858
accepted answer: http://stackoverflow.com/a/50515858
possible better answer: http://stackoverflow.com/a/50515905
has answer: http://stackoverflow.com/a/50515905
type: Question
has body: i have an existing application data base from which my web site should only fetch the data according to user input. Added database details in the settings.py file and I tried python manage.py integratedb and get the all the 300+ tables came off to my models.py file. I was never able to do python manage.py runserver it threw a million errors. Now i found a work around but i need your opinion on this. I added the default server into the settings.py and using it i was able to run the server. settings.py looks like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', }, 'user': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME' : 'test', 'USER' : 'testuser', 'PASSWORD': 'readonly', 'HOST' : '10.20.30.40', 'PORT' : '5446', } } Now can i access the user db to fetch data from my form? for example views.py looks like this from django.shortcuts import render_to_response from .models import TestCases from django.shortcuts import HttpResponse from django.http import JsonResponse from django.forms.models import model_to_dict from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def index(request): posts = TestCases.objects.all()[:10] return render_to_response('index.html',{'posts':posts}) where TestCases is a class name from the models.py file. Now when i click the button to retrieve data i get "no such table: test_cases" models.py looks like class TestCases(models.Model): id = models.BigIntegerField(primary_key=True) clientid = models.ForeignKey(Clients, db_column='clientid') projectid = models.ForeignKey(Projects, db_column='projectid') class Meta: managed = False db_table = 'test_cases' what am i doing wrong to get the data from the user input. please help.
has title: How to use one db to run the django service and other to fetch data
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: django-views
answer count: 2

http://stackoverflow.com/q/50400686
linked to: http://stackoverflow.com/q/7091413
has comment: http://stackoverflow.com/comment/87817419
has title: Read from pipe without an end
tagged with: command
type: Question
has comment: http://stackoverflow.com/comment/87818289
tagged with: stdin
type: UnansweredQuestion
tagged with: python
has body: I have problems of reading with python from stdin if I have a pipe with continuous data stream which doesn't stop. As an example I have data_stream.py import time i = 0 while True: print(i) i += 1 time.sleep(2) Now I try to read the data with the file read_data.py import sys for line in sys.stdin: print(line) When I try to run it with python3 data_stream.py | python3 read_data.py I get no result because data_stream.py did not finished. How can I read from data_stream.py while it is still running?
duplicate of: http://stackoverflow.com/q/7091413
score: 0
has comment: http://stackoverflow.com/comment/87817792
has answer: http://stackoverflow.com/a/50401195
tagged with: pipe
answer count: 1
tagged with: shell

http://stackoverflow.com/q/50492098
answer count: 1
downvote count: 0
tagged with: django
favorite count: 0
has comment: http://stackoverflow.com/comment/87997883
type: Question
has comment: http://stackoverflow.com/comment/87997194
has comment: http://stackoverflow.com/comment/87998495
accepted answer: http://stackoverflow.com/a/50492463
has body: I have a model with 2 datetime fields which looks like this: class Booking(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() ... As test data I have 2 bookings with start_date before 17:30 and 2 bookings after 17:45, all on the same day (8 May 2018). I am trying to filter the bookings with the __time lookup to find all the bookings before (and including) 17:30. My queryset is: bookings = Booking.objects.filter(date__time__lte=datetime.time()) Where datetime.time prints as datetime.time(17, 30) and where the date part of the datetime is the same as the bookings dates. The above query is returning an empty queryset but if I use the same query except filtering for times greater than datetime.time() i.e. bookings = Booking.objects.filter(date__time__gte=datetime.time()) The queryset returns all the bookings (where it should only return the 2 bookings with start_date after 17:30). Can someone please explain to me how the __time lookup is meant to be used? EDIT I updated the filter to bookings = Booking.objects.filter(start_date__time__lte=datetime.time()) and the result is the same. When I print the values of the bookings, the values are: print Booking.objects.all().values('date', 'end_date') [ {'start_date': datetime.datetime(2018, 5, 8, 16, 30, tzinfo=&lt;DstTzInfo 'Africa/Harare' CAT+2:00:00 STD&gt;), 'end_date': datetime.datetime(2018, 5, 8, 17, 0, tzinfo=&lt;DstTzInfo 'Africa/Harare' CAT+2:00:00 STD&gt;)}, {'start_date': datetime.datetime(2018, 5, 8, 17, 0, tzinfo=&lt;DstTzInfo 'Africa/Harare' CAT+2:00:00 STD&gt;), 'end_date': datetime.datetime(2018, 5, 8, 17, 30, tzinfo=&lt;DstTzInfo 'Africa/Harare' CAT+2:00:00 STD&gt;)}, {'start_date': datetime.datetime(2018, 5, 8, 17, 45, tzinfo=&lt;DstTzInfo 'Africa/Harare' CAT+2:00:00 STD&gt;), 'end_date': datetime.datetime(2018, 5, 8, 18, 15, tzinfo=&lt;DstTzInfo 'Africa/Harare' CAT+2:00:00 STD&gt;)}, {'start_date': datetime.datetime(2018, 5, 8, 17, 45, tzinfo=&lt;DstTzInfo 'Africa/Harare' CA…
has answer: http://stackoverflow.com/a/50492463
has comment: http://stackoverflow.com/comment/87997130
tagged with: python
has title: How to use Django __time lookup in a queryset
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87997855
has comment: http://stackoverflow.com/comment/87997390
tagged with: django-queryset
upvote count: 2

http://stackoverflow.com/comment/87845304
comment on: http://stackoverflow.com/q/50414364
type: Comment
type: QuestionComment
score: 0
has text: As @wwii said, this is more suited for a dsp site than a programming site. But if you're going to keep it here, can you include a plot of the frequencies before filtering? The filter won't stop all frequencies perfectly, so it would help to see what effect the filter is having.

http://stackoverflow.com/q/50476747
has answer: http://stackoverflow.com/a/50493618
tagged with: subprocess
has body: I am having difficulty getting an nbtstat command to run in python. Whenever I run the following code, I get the error "WindowsError: [Error 2] The system cannot find the file specified". print(subprocess.check_output(["nbtstat","-A",ipaddress])) I've also tried print(subprocess.check_output(["C:\\Windows\\System32\\nbtstat.exe","-A",ipaddress])) and print(subprocess.check_output("nbtstat -A "+ipaddress)) and none of these versions worked. Is there something I'm missing from the command to get it to run properly? On Windows running python 2.7.11 (cannot update)
answer count: 1
has comment: http://stackoverflow.com/comment/87990870
type: Question
has comment: http://stackoverflow.com/comment/88000295
has title: Python Subprocess nbtstat "cannot find the file"
has comment: http://stackoverflow.com/comment/88000323
accepted answer: http://stackoverflow.com/a/50493618
has comment: http://stackoverflow.com/comment/88000236
has comment: http://stackoverflow.com/comment/87967386
has comment: http://stackoverflow.com/comment/87967470
has comment: http://stackoverflow.com/comment/88000378
tagged with: python
has comment: http://stackoverflow.com/comment/87967129
has comment: http://stackoverflow.com/comment/88000249
has comment: http://stackoverflow.com/comment/88000237
has comment: http://stackoverflow.com/comment/87969723
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87955213
type: Comment
score: 0
type: AnswerComment
has text: @PB it's not "spacing", it's the default size of the row/column elements. You need to either set the width/height of the rows/columns or of the widgets themselves
comment on: http://stackoverflow.com/a/50436862

http://stackoverflow.com/q/50453437
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has title: Perlin noise procedural roads/rivers
score: 1
upvote count: 3
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/59503166
has body: I generate procedural maps, first map 0 to 512 in x abs and second 512 to 1024 in x abs. With Perlin noise I generate an island with beaches, forests, mountains and lakes. I want to add roads and rivers but don't know how with Perlin noise, is that possible? My code: import random import noise import numpy as np from scipy.misc import toimage import math class Color: # 0 -> 255 r = 0.0 g = 0.0 b = 0.0 a = 1.0 def __init__(self, r=0.0, g=0.0, b=0.0): self.r = r self.g = g self.b = b self.a = 1 def GetTuple(self): return int(self.r), int(self.g), int(self.b) def SetColor(self, r, g, b): self.r = r self.g = g self.b = b def Copy(self, color): self.r = color.r self.g = color.g self.b = color.b def SetWhite(self): self.SetColor(1, 1, 1) def SetBlack(self): self.SetColor(0, 0, 0) def SetColorFromGrayscale(self, f=0.0): self.SetColor(f, f, f) class GenerateMap: def __init__(self, size=(50, 50), color_range=10, color_perlin_scale=0.025, scale=350, octaves=6, persistance=0.6, lacunarity=2.0, x_starting_pos=0, y_starting_pos=0): self.scale = scale self.octaves = octaves self.persistance = persistance self.lacunarity = lacunarity self.x_starting_pos=x_starting_pos self.y_starting_pos=y_starting_pos self.mapSize = size # size in pixels self.mapCenter = (self.mapSize[0] / 2, self.mapSize[1] / 2) self.heightMap = np.zeros(self.mapSize) # self.colorMap = [[Color() for j in range(self.mapSize)] for i in range(self.mapSize)] self.randomColorRange = color_range self.colorPerlinScale = color_perlin_scale self.lightblue = [0, 191, 255] self.blue = [65, 105, 225] self.darkblue = [0, 0, 139] self.green = [34, 139, 34] self.darkgreen = [0, 100, 0] self.sandy = [210, 180, 140] self.beach = [238, 214, 175] self.snow = [255, 250, 250] self.mountain = [139, 137, 137] self.threshold = -0.01 def return_initial_blank_map(self): return self.heightMap def get_map_corners(self): nw = self.heightMap[0][0] ne = self.heightMap[0][len(self.heightMap[0])-1] sw = self.heightMap[len(self.heightMap)-1][0] …
tagged with: scipy
favorite count: 0

django-generic-views
type: Tag
tag name: django-generic-views
tags question: http://stackoverflow.com/q/50521577

http://stackoverflow.com/comment/87995690
comment on: http://stackoverflow.com/q/50491192
has text: @TomDalton So where would be the ideal place to keep the database directory ? Also, If I move the database directory, should I choose to update the absoulute path in settings.py as well ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87959705
score: 0
has text: add the page source for more details
type: QuestionComment
comment on: http://stackoverflow.com/q/50472129
type: Comment

http://stackoverflow.com/comment/87818334
type: Comment
comment on: http://stackoverflow.com/q/50401236
type: QuestionComment
score: 2
has text: You can't pass variables around in Python. See https://nedbatchelder.com/text/names.html

http://stackoverflow.com/q/50401494
downvote count: 0
answer count: 1
tagged with: django
score: 1
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: sentry
has title: Django sentry - request.sentry object
tagged with: python
tagged with: raven
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/50401522
has body: I'm trying to enable the user-feedback functionality on my project. I tried several things with no success so far. I'm using django 1.11 and raven 6.8.0 I followed this solution too - [DOCS] Django Integration for User Feedback Debugging a little bit around the js snippet: {% if request.sentry.id %} &lt;script&gt; Raven.showReportDialog({ // grab the eventId generated by the Sentry SDK eventId: '{{ request.sentry.id }}', // use the public DSN (dont include your secret!) dsn: 'dsn' }); &lt;/script&gt; {% endif %} I noticed that there's no sentry object inside request but the request object is present in the 500.html template Any help will be very appreciated
has answer: http://stackoverflow.com/a/50401522

http://stackoverflow.com/a/50464928
score: 1
downvote count: 0
has body: Try - exceptional_cols = ['email'] feature_exist = pd.concat([feature_exist.drop(email, axis=1).convert_objects(convert_numeric=True), feature_exist[exceptional_cols]], , axis=1, sort=False) Explanation Drop the cols you don't want to convert and convert the remaining ones - feature_exist.drop(email, axis=1).convert_objects(convert_numeric=True) Once done, append back the column that you dropped by using concat. This will help you separate the columns that you don't want to convert.
upvote count: 1
answers question: http://stackoverflow.com/q/50464684
type: Answer

http://stackoverflow.com/a/50529069
answers question: http://stackoverflow.com/q/50495986
type: Answer
has body: I solved it! The problem was the amount of comma's in the text part of my .csv files. So after removing all comma's (just using search/replace), I used: import pandas import glob filenames = glob.glob("something*.csv") df = pandas.DataFrame() for filename in filenames: df = df.append(pandas.read_csv(filename, encoding="utf-8", sep=";")) Thanks for all the help.
score: 0
has comment: http://stackoverflow.com/comment/88069980

http://stackoverflow.com/q/50433050
score: 0
has answer: http://stackoverflow.com/a/50563070
tagged with: nao-robot
upvote count: 2
downvote count: 2
answer count: 1
favorite count: 0
type: Question
tagged with: pepper
has title: Screen share Pepper's tablet
has comment: http://stackoverflow.com/comment/88152473
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/87880690
accepted answer: http://stackoverflow.com/a/50563070
type: AnsweredQuestion
has body: How can I share the screen of Pepper's tablet? I wish to show the content displayed on the tablet on a projector so that it is engaging a larger audience. Is there any way to access it using the Java or Python SDK?

http://stackoverflow.com/comment/87914041
has text: Can you show exactly what you *did* try and explain how it failed?
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50449796

http://stackoverflow.com/q/50474482
possible better answer: http://stackoverflow.com/a/50474727
score: -3
has title: What´s the easiest way to generate specific sequence in python2?
has answer: http://stackoverflow.com/a/50474727
accepted answer: http://stackoverflow.com/a/50474720
tagged with: python
has comment: http://stackoverflow.com/comment/87962700
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87962534
answer count: 2
downvote count: 3
linked to: http://stackoverflow.com/q/49854145
has body: What would be the easiet/quickiest way to generate sequence 0,1,3,4,6,7,... as a list in python2?
has comment: http://stackoverflow.com/comment/87962520
has comment: http://stackoverflow.com/comment/87962818
has answer: http://stackoverflow.com/a/50474720
has comment: http://stackoverflow.com/comment/87962774
has comment: http://stackoverflow.com/comment/87962731
duplicate of: http://stackoverflow.com/q/49854145
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87962647

http://stackoverflow.com/comment/88095633
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50541050
type: AnswerComment
has text: Is there a way to dissociate the "o_A" in two o_Fname = **M.A.** o_Ltname = **Wood**

http://stackoverflow.com/comment/88025392
has text: @EdChum there are no missing time indices only some that do not exist in both dataframes.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50506610

http://stackoverflow.com/a/78696058
type: Answer
answers question: http://stackoverflow.com/q/50392783
has body: An other alternative could be be to fit the model to the square root of the labels and then square again the predictions. More information in this Kaggle notebook: https://www.kaggle.com/code/theudbald/optimize-mean-asolute-error-mae-with-xgboost
score: 0

http://stackoverflow.com/q/50531797
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88079156
has comment: http://stackoverflow.com/comment/88081331
has comment: http://stackoverflow.com/comment/88080819
has answer: http://stackoverflow.com/a/50535500
accepted answer: http://stackoverflow.com/a/50535500
has comment: http://stackoverflow.com/comment/88081605
has title: QThreads in Pyqt5: is this the correct C++ to Python translation of the official QThread docs?
has comment: http://stackoverflow.com/comment/88077817
tagged with: python
has comment: http://stackoverflow.com/comment/88076117
tagged with: qt5
tagged with: qthread
upvote count: 2
type: AnsweredQuestion
score: 2
has body: The official documentation on how to instantiate and use a QThread can be found here: http://doc.qt.io/qt-5/qthread.html The documentation describes two basic approaches: (1) worker-object approach and (2) QThread subclass approach. I've read in several articles that the second approach is not good, so let's focus on the first one. EDIT: @ekhumoro pointed me to the following interesting article: https://woboq.com/blog/qthread-you-were-not-doing-so-wrong.html . Apparently both approaches (1) and (2) each have their own merits: As a rule of thumb: If you do not really need an event loop in the thread, you should subclass. If you need an event loop and handle signals and slots within the thread, you may not need to subclass. As I do need some sort of communication between the QApplication thread and the new QThread (and I believe signal-slot is a good way to communicate), I'll use the worker-object approach. 1. The worker-object approach in C++ I've copy-pasted the C++ code of the worker-object approach (from the official Qt5 docs, see http://doc.qt.io/qt-5/qthread.html): class Worker : public QObject { Q_OBJECT public slots: void doWork(const QString &amp;parameter) { QString result; /* ... here is the expensive or blocking operation ... */ emit resultReady(result); } signals: void resultReady(const QString &amp;result); }; class Controller : public QObject { Q_OBJECT QThread workerThread; public: Controller() { Worker *worker = new Worker; worker-&gt;moveToThread(&amp;workerThread); connect(&amp;workerThread, &amp;QThread::finished, worker, &amp;QObject::deleteLater); connect(this, &amp;Controller::operate, worker, &amp;Worker::doWork); connect(worker, &amp;Worker::resultReady, this, &amp;Controller::handleResults); workerThread.start(); } ~Controller() { workerThread.quit(); workerThread.wait(); } public slots: void handleResults(const QString &amp;); signals: void operate(const QString &amp;); }; &nbsp; 2. The worker-object approach in Python I made an effort to tr…
has comment: http://stackoverflow.com/comment/88084571
downvote count: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/88084752
answer count: 1
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/88078116

http://stackoverflow.com/q/50394351
has comment: http://stackoverflow.com/comment/87804495
has body: How can I know who voted with reaction on the slack? I want to create a bot which gets who voted with reaction as an input, and send message based on that information. Any simple codes for it, like with slackclient or slackbot?
accepted answer: http://stackoverflow.com/a/50394854
type: AnsweredQuestion
score: 0
has title: slack: how to know who voted with reaction
has answer: http://stackoverflow.com/a/50394854
tagged with: bots
answer count: 1
tagged with: python
tagged with: slack
type: Question

http://stackoverflow.com/comment/87878182
has text: I don't get an error using the command-line (Terminal on Mac) unzip utility... curious.
comment on: http://stackoverflow.com/q/50431803
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87871579
comment on: http://stackoverflow.com/q/50428173
type: Comment
type: QuestionComment
has text: Possibly `confusion_matrix` was overwritten as a dataframe from your previous run. So now the function `sklearn.metrics.confusion_matrix()` does not work. try importing the function again or just restart Python and change the name of your confusion matrix.
score: 1

http://stackoverflow.com/q/50433159
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 2
answer count: 0
favorite count: 0
type: Question
tagged with: terminal
tagged with: tkinter
has title: How can I embed a terminal in Tkinter GUI to execute python scripts
has body: I am trying to make a Python IDE which edits python scripts and executes them and show the output in the GUI itself. I have made the GUI in tkinter. For showing the outputs, I am using os.system("python myscript.py &amp;&gt; output.txt") and displaying the output.txt file in the GUI. Now i am facing issues in raw_input() function as the execution stops and output.txt isn't generated, also i can't send values to the terminal from the GUI when raw_input() is waiting. I am thinking of embedding a terminal in the GUI. How can i do that? How can i execute python scripts in that terminal and give inputs and get outputs?
upvote count: 2

http://stackoverflow.com/comment/88078196
comment on: http://stackoverflow.com/q/50532583
score: 0
has text: @anishtain4 No, the performance is _worse_ than with `a[:,0,:]`. It is readable, but has a really bad performance.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87997131
has text: Is the question how to get the coordinates of the subplots in order to be able to position the Spin boxes to those coordinates?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50491223

http://stackoverflow.com/comment/88035887
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50508838
type: Comment
has text: Right, that makes sense. Thanks for sharing your answer.

http://stackoverflow.com/q/50529563
tagged with: selenium-webdriver
has title: How to get attribute value Selenium + Python
has comment: http://stackoverflow.com/comment/88071546
has answer: http://stackoverflow.com/a/50530054
has comment: http://stackoverflow.com/comment/88071096
has comment: http://stackoverflow.com/comment/88090878
upvote count: 0
answer count: 2
tagged with: selenium
has comment: http://stackoverflow.com/comment/88072215
has comment: http://stackoverflow.com/comment/88071782
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88071970
type: Question
tagged with: python
type: UnansweredQuestion
has body: I'm working with Selenium in Python. I would like to get the value of an attribute ['href'] and check that it is different from '#', if yes so click on the link if not out of the loop: if not driver.find_element_by_link_text('»'): break # Open next page if driver.find_element_by_xpath("//a[.='»' and not(@href='#')]"): link=WebDriverWait(driver, 20).until(expected_conditions.element_to_be_clickable((By.LINK_TEXT, "»"))) link.click() else: break Here is the source code of the web page: « 1 37 » My code does not work and I get this error: raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException Any help would be appreciated.
has answer: http://stackoverflow.com/a/50564811
has comment: http://stackoverflow.com/comment/88071501
score: -1

http://stackoverflow.com/q/50509177
answer count: 1
downvote count: 0
score: 1
upvote count: 1
tagged with: scikit-learn
has body: There is data (X, y) on which the search and training in the function GridSearchCV. Training takes place on a custom criterion T_scorer. Is it possible in the T_scorer function to get a trained model to use? I need to "T_scorer" predict data "X1". That is, the model is trained on data (X,y) at each iteration, and is predicted on (X1,y1) Again (X1, y1) do not participate in training at all and "GridSearchCV" these data do not see. Ideally, we should make the training to take place on the data(X,y), and in "scoring" the results based on predictions (X1,y1) should be transmitted) def T_scorer(y_true, y_pred, clf, **kwargs): r = np.sum((y_pred == 0) &amp; (y_pred == y_true)) y_pred1 = clf.predict(X1) #It doesn't work confmat = confusion_matrix(y, y_pred) print(confmat) print(r) return r _scorer = make_scorer(T_scorer) clf = RandomForestClassifier() grid_searcher = GridSearchCV(clf, parameter_grid, cv=StratifiedKFold(shuffle =True,random_state=42),verbose=20, scoring=_scorer) grid_searcher.fit(X, y) clf_best = grid_searcher.best_estimator_ print('Best params = ', clf_best.get_params())
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50509442
has comment: http://stackoverflow.com/comment/88030795
has answer: http://stackoverflow.com/a/50509442
tagged with: grid-search
tagged with: python
type: AnsweredQuestion
has title: How to get a "scoring" trained model(predict)

http://stackoverflow.com/comment/110642053
type: Comment
comment on: http://stackoverflow.com/a/60593449
type: AnswerComment
has text: I don't understand, why do you need to set the manually if I already have a python with a path to all my packages?
score: 0

http://stackoverflow.com/a/50494847
has comment: http://stackoverflow.com/comment/88043682
type: Answer
score: 2
has body: This problem isn't because of Colorama. The problem here is that the % operator has higher precedence than +, so Python is trying to add the name here: "? Type 'list' if you would like a discription of each class." % (name) before it combines all those strings using +. The simple solution is to wrap the entire string expression in parentheses: Warlock = "Warlock" Titan = "Titan" Hunter = "Hunter" name = "Bode" print(("%s, are you a " +str(Warlock)+ ", " +str(Titan)+", or" +str(Hunter)+ "? Type 'list' if you would like a discription of each class.") % name) output Bode, are you a Warlock, Titan, orHunter? Type 'list' if you would like a discription of each class. However, it would be easier to read if you don't add strings together manually, and use the format method instead of %. Warlock = "Warlock" Titan = "Titan" Hunter = "Hunter" name = "Bode" print("{}, are you a {}, {}. or {}?".format(name, Warlock, Titan, Hunter), end=" ") print("Type 'list' if you would like a description of each class.") output Bode, are you a Warlock, Titan. or Hunter? Type 'list' if you would like a description of each class.
upvote count: 2
answers question: http://stackoverflow.com/q/50494737
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88057523
has comment: http://stackoverflow.com/comment/88057682
accepted answer of: http://stackoverflow.com/q/50494737

http://stackoverflow.com/comment/88093878
type: Comment
type: AnswerComment
score: 1
has text: Nice solution, +1. Can you comment (briefly) on which parts are vectorised? My understanding is `applymap(sum)` and `apply(tuple)` are not vectorised (not working with contiguous memory arrays). But `stack` and `groupby` possibly are?
comment on: http://stackoverflow.com/a/50541101

http://stackoverflow.com/a/51525559
answers question: http://stackoverflow.com/q/50415356
has body: l=[('abc',10),('def',15),('ghi',10),('abc', 12),('xyz',100)] sortedlist = sorted(l,key = lambda x:x[1],reverse=True) d=dict(sortedlist) print(list(d.keys()))
score: 0
has comment: http://stackoverflow.com/comment/90026461
type: Answer

http://stackoverflow.com/q/50464625
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2396238
has answer: http://stackoverflow.com/a/50464816
tagged with: memory-management
has title: Memory Error - Python (Huge File Changes)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87942539
tagged with: python
has body: I am trying to change the End of Line(EOL) of a file from Windows to Linux, the file size is 50 GB and writing into the same file, Below is my code : filename = "D:\AddressEvaluation\AddressStandardization\infu\InfutorFile.txt" fileContents = open(filename,"r").read() f = open(filename,"w", newline="\n") f.write(fileContents) f.close() It gives me this error : MemoryError Traceback (most recent call last) &lt;ipython-input-3-a87efb13f002&gt; in &lt;module&gt;() 1 filename = "D:\AddressEvaluation\AddressStandardization\infu\InfutorFile.txt" ----&gt; 2 fileContents = open(filename,"r").read() 3 f = open(filename,"w", newline="\n") 4 f.write(fileContents) 5 f.close() MemoryError: Am I missing something ? Please help ?
score: 1

http://stackoverflow.com/a/50442798
type: Answer
score: 0
has body: There is no way to efficiently read the file and do what you want to do with pandas. Here is a way out - Use the chunksize parameter to your advantage - CHUNKSIZE = 1e6 rows = 0 for df in pd.read_sas('path/to/sas/filename.sas7bdat', chunksize=CHUNKSIZE, iterator=True): rows += df.shape[0] # whatever else you want Explanation This reads a million rows at a time (vary the chunksize depending upon how much RAM you can afford) and iteratively counts what you want. Alternatively you can use it to do other df related operations as well, as long as you keep accumulating them. Warning On commodity hardware trying to read ~100s of GBs, still going to be inefficient.
answers question: http://stackoverflow.com/q/50419361

http://stackoverflow.com/q/50443443
has comment: http://stackoverflow.com/comment/87901643
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50444600
linked to: http://stackoverflow.com/q/12203676
has comment: http://stackoverflow.com/comment/87901151
tagged with: datetime
has comment: http://stackoverflow.com/comment/87902977
tagged with: python
has body: Example Code from datetime import datetime, timezone, timedelta import pytz t11 = datetime(1918, 4, 15, 0, 0, tzinfo=timezone.utc).astimezone(pytz.timezone('Europe/Berlin')) t12 = t11 + timedelta(hours=1) t2 = datetime(1918, 4, 15, 1, 0, tzinfo=timezone.utc).astimezone(pytz.timezone('Europe/Berlin')) print(t12) print(t2) Observed 1918-04-15 02:00:00+01:00 1918-04-15 03:00:00+02:00 Expected I expected both to be what I see for t2. The crucial difference is t2.hour vs t12.hour. For a timezone-aware datetime object, I expected the hour to be the local hour. Question How can I change this behaviour? What is the reason for having it like this?
has title: Why does it make a difference if I add 1 hour to the UTC time and localize or 1 hour to the local time?
tagged with: pytz
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/87901248
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: timedelta

http://stackoverflow.com/q/50473224
tagged with: python
has comment: http://stackoverflow.com/comment/87961165
tagged with: factory-pattern
tagged with: factory
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87960426
has body: i have been looking into implementing factory method design pattern in python &amp; most examples that I get is something of this form. class Cup: color = "" # This is the factory method @staticmethod def getCup(cupColor): if (cupColor == "red"): return RedCup() elif (cupColor == "blue"): return BlueCup() else: return None class RedCup(Cup): color = "red" class BlueCup(Cup): color = "blue" # A little testing redCup = Cup.getCup("red") print "%s(%s)" % (redCup.color, redCup.__class__.__name__) blueCup = Cup.getCup("blue") print "%s(%s)" % (blueCup.color, blueCup.__class__.__name__) Why use class for a factory function? Couldn't it just be like this: def CupFactory(cupColor): if (cupColor == "red"): return RedCup() elif (cupColor == "blue"): return BlueCup() else: return None or there is a particular situation where the class-based method is prefered/desired. NOTE : Examples found on internet that use classes. Example 1. Example 2
has comment: http://stackoverflow.com/comment/87960487
linked to: http://stackoverflow.com/q/14992474
has comment: http://stackoverflow.com/comment/87960358
type: Question
has comment: http://stackoverflow.com/comment/87960541
has title: Factory design pattern implementation?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87961535

http://stackoverflow.com/comment/87979353
comment on: http://stackoverflow.com/q/50483092
type: Comment
type: QuestionComment
has text: cats2 predict3 [0.9, 1.0) 99% [0.1, 0.2) 30% [0.1, 0.2) 51% [0.0, 0.1) 0% [0.3, 0.4) 12% [0.0, 0.1) 0% [0.9, 1.0) 83% [0.8, 0.9) 76% [0.0, 0.1) 3% [0.4, 0.5) 53% [0.1, 0.2) 30% [0.9, 1.0) 99% [0.9, 1.0) 100% [0.0, 0.1) 9% [0.9, 1.0) 99% [0.9, 1.0) 98% [0.1, 0.2) 2% [0.9, 1.0) 86% [0.6, 0.7) 86% [0.2, 0.3) 54% [0.0, 0.1) 10% [0.0, 0.1) 1% [0.0, 0.1) 1% [0.8, 0.9) 75% [0.4, 0.5) 89% [0.4, 0.5) 86% [0.1, 0.2) 16% [0.9, 1.0) 88% [0.4, 0.5) 56% [0.5, 0.6) 62% [0.9, 1.0) 100%
score: 0

http://stackoverflow.com/a/50534060
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50533629
has body: import os nameList = ['abc-1', 'abc-2', 'def-1', 'def-2'] statusList = ['ok', 'ok', 'bad', 'bad'] scac = 'abc' def scacFilter (scac, nameList, statusList): resultList = [] resultVal = [] for val in nameList: if not val.find(scac): indexVal = nameList.index(val) resultList.append(nameList[indexVal]) resultVal.append(statusList[indexVal]) return resultList, resultVal finalNameList, finalStatusList = scacFilter(scac, nameList, statusList) print finalNameList print finalStatusList
type: Answer
accepted answer of: http://stackoverflow.com/q/50533629
score: 0

http://stackoverflow.com/comment/88033301
comment on: http://stackoverflow.com/q/50510407
type: Comment
score: 0
type: QuestionComment
has text: You used an hour interval in your example but you are not always grouping by hour, correct? Otherwise you could just group by hour and take the means

http://stackoverflow.com/comment/88078808
has text: What is `v`? The error most likely comes from `v` being something that `pandas.DataFrame()` is not designed to accept.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50533030

http://stackoverflow.com/a/50506367
type: Answer
score: 4
answers question: http://stackoverflow.com/q/50506305
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50506305
type: AcceptedAnswer
has body: Try to use queryset's using() method: Person.objects.using('not_default_db').create(name='James')
downvote count: 0

http://stackoverflow.com/q/50492114
possible better answer: http://stackoverflow.com/a/50492189
tagged with: python
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/50492368
has body: I am trying to write function that prints out float fractions of % of positive numbers, negative numbers and numbers that = 0, based on values passed in through *args. I figured list comprehension would be an efficient way to get those values, but the following is not working. I am getting an 'int' object is not iterable error message. Any ideas? def plusMinus(*args): list_1 = [] count = 0 for i in args: list_1.append(i) count += 1 pos = [i % sum(i) for i in list_1 if i &gt; 0] neg = [i % sum(i) for i in list_1 if i &lt; 0] zero = [i % sum(i) for i in list_1 if i == 0] num = count print(num) print(args) print(pos) print(neg) print(zero) plusMinus(10, 25, 30, 0, -45, -50)
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50492240
has comment: http://stackoverflow.com/comment/87997231
has title: Using list comprehension for fraction results in a function
accepted answer: http://stackoverflow.com/a/50492368
type: Question
has answer: http://stackoverflow.com/a/50492189

http://stackoverflow.com/q/50495710
tagged with: google-cloud-storage
accepted answer: http://stackoverflow.com/a/50798550
type: Question
has answer: http://stackoverflow.com/a/50798550
tagged with: google-app-engine
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88081422
type: AnsweredQuestion
tagged with: google-cloud-platform
score: 0
has title: Can't read video stored in Google Cloud Storage
has body: I can store my video in my Google Cloud Bucket but I can't read it. Here is my code : url_template = ( u'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' u'uploadType=resumable' ) upload_url = url_template.format(bucket=BUCKET_NAME) transport = AuthorizedSession(credentials=client._credentials) stream = io.BytesIO(stream_file.file.read()) upload = ResumableUpload(upload_url, chunk_size) metadata = {u'name': blob.name} upload.initiate(transport, stream, metadata, content_type) upload.transmit_next_chunk(transport) while upload.finished is False: upload.transmit_next_chunk(transport) After loading the file, the file in my bucket looks like this : As you can see, the size of my file in the bucket is 0, it should be 24.7 MB. So I want to know what is wrong in my code.

http://stackoverflow.com/q/50450698
has title: Mixing parametrized tests and marks
downvote count: 0
answer count: 1
tagged with: python
has body: Ok, I'm struggling with something that is literally blowing my mind. Although my actual code is different, this basically nails down the issue. Assume this sample code: import pytest @pytest.mark.parametrize('type',( pytest.param('stability', marks=pytest.mark.stability), pytest.param('integration', marks=pytest.mark.integration), )) @pytest.mark.integration @pytest.mark.stability def test_meh(type): assert type == 'integration' And the following is the output of running that test. $pytest -m integration test_meeh.py ========================================================= test session starts ========================================================= platform darwin -- Python 3.6.4, pytest-3.1.2, py-1.5.2, pluggy-0.4.0 rootdir: /Users/yzT/Desktop, inifile: collected 2 items test_meeh.py F ============================================================== FAILURES =============================================================== _________________________________________________________ test_meh[stability] _________________________________________________________ type = 'stability' @pytest.mark.parametrize('type',( pytest.param('stability', marks=pytest.mark.stability), pytest.param('integration', marks=pytest.mark.integration), )) @pytest.mark.integration @pytest.mark.stability def test_meh(type): &gt; assert type == 'integration' E AssertionError: assert 'stability' == 'integration' E - stability E + integration test_meeh.py:10: AssertionError ========================================================= 1 tests deselected ========================================================== =============================================== 1 failed, 1 deselected in 0.07 seconds ================================================ $ pytest -m stability test_meeh.py ========================================================= test session starts ========================================================= platform darwin -- Python 3.6.4, pytest-3.1.2, py-1.5.2, pluggy-0.4.0 rootdir: /Users/yzT/Deskt…
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: pytest
has answer: http://stackoverflow.com/a/50456756
accepted answer: http://stackoverflow.com/a/50456756
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50501343
answers question: http://stackoverflow.com/q/50501290
type: Answer
has body: abc_config.output_var("new_name", clustername, SP_PY_BASE) should be returning an array. First element of this array is passed to print_xyz. This could be equivalent to my_list = abc_config.output_var("new_name", clustername, SP_PY_BASE) print_xyz(my_list[0])
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/88026264
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50497472
has text: The fact that it can be loaded by *pywin32* but not by *ctypes* doesn't make sense. You're definitely doing smth wrong (maybe not using the same path)? So what is your *Python* (also *ctypes*, and *pywin32*) version? What tools are used to compile the *.dll* by the other person? The 2nd case it's normal not to find the symbol, based on how you load the dll. So with the test dll which loads the dll (everything compiled by you) everything works? What about with test dll which loads the external compiled dll?

http://stackoverflow.com/q/50395811
has answer: http://stackoverflow.com/a/50397913
type: AnsweredQuestion
has title: Python if any statement with or condition
has body: I'm using Python 3.5 and I'm trying to create an if statement to check two different variables against two different lists, I tried the following things: if not any(x in colorsA for x in colorsB) or (y in colorsA for y in colorsC): and also if not any(x in colorsA for x in colorsB) or not any(y in colorsA for y in colorsC): but none seem to work, either only the first statement is done or none at all, all the variables are strings. Is there a simple way to do this? Example: ColorsA = ['red', 'yellow', 'green'] ColorsB = ['red', 'white', 'blue'] ColorsC = ['white', 'blue', 'green'] if there is no color from colorsA in either colorsB or in colorsC print(colorA) Output: yellow
tagged with: python
possible better answer: http://stackoverflow.com/a/50397913
has comment: http://stackoverflow.com/comment/87807630
has comment: http://stackoverflow.com/comment/87807446
has comment: http://stackoverflow.com/comment/87807453
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/50398897
score: -3
has comment: http://stackoverflow.com/comment/87808424
downvote count: 3
has comment: http://stackoverflow.com/comment/87808075
has answer: http://stackoverflow.com/a/50398897
favorite count: 0
type: Question

google-cloud-functions
tag name: google-cloud-functions
type: Tag
tags question: http://stackoverflow.com/q/50415121
tags question: http://stackoverflow.com/q/50494380

http://stackoverflow.com/comment/88077735
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50531190
has text: You should use the fully qualified path, which would appear to be `@patch('me.my_class.Client')`
type: Comment

http://stackoverflow.com/comment/87884316
comment on: http://stackoverflow.com/a/50433307
has text: I opened a file but I use URL to open. that is another way.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50517004
has comment: http://stackoverflow.com/comment/88046721
linked to: http://stackoverflow.com/q/42950
tagged with: counter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88046610
duplicate of: http://stackoverflow.com/q/42950
score: 0
has comment: http://stackoverflow.com/comment/88046777
has comment: http://stackoverflow.com/comment/88046572
type: Question
has answer: http://stackoverflow.com/a/50517047
has title: Python for-loop, range counter
has answer: http://stackoverflow.com/a/50517070
answer count: 2
has body: I have made a program that prints the each date of year. Is it possible to add a counter that will allow to limit the printable dates? I would print for example every 7 days. Thanks for any advice. The original code below. def main(): for month in range(1, 13): daymax = 32 if month == 2: daymax = 29 elif month == 4: daymax = 31 elif month == 6: daymax = 31 elif month == 9: daymax = 31 elif month == 11: daymax = 31 for day in range(1, daymax): print(day,".", month,".", sep="") main()
tagged with: for-loop

http://stackoverflow.com/a/50427491
has comment: http://stackoverflow.com/comment/87872808
answers question: http://stackoverflow.com/q/50426838
score: 1
type: Answer
has body: An example with a thread that outputs the second window and outputs the result from the stream in the main window. Comments in the text of the program: import random from PyQt5 import Qt class WorkThread(Qt.QThread): ''' Streaming task in its window. Signals and Slots are used for communication between objects. ''' # Declare a signal, with an argument (int) for transmission in the connected slots threadSignal = Qt.pyqtSignal(int) def __init__(self, startParm): super().__init__() self.startParm = startParm # Initialize the parameters passed to the task def run(self, *args, **kwargs): c = self.startParm while True: Qt.QThread.msleep(200) c += 1 self.threadSignal.emit(c) # We disable the signal and pass arguments to the connected slot class WorkThreadMain(Qt.QThread): ''' Streaming Main task ''' threadSignalMain = Qt.pyqtSignal(int) def __init__(self, startParm): super().__init__() self.startParm = startParm def run(self, *args, **kwargs): c = self.startParm while True: Qt.QThread.msleep(1000) c += 1 self.threadSignalMain.emit(c) class MsgBox(Qt.QDialog): """ Window initialization class for visualizing an additional stream and a button to close the stream window if the thread is stopped! """ def __init__(self): super().__init__() layout = Qt.QVBoxLayout(self) self.label = Qt.QLabel("") layout.addWidget(self.label) close_btn = Qt.QPushButton("Close thread") layout.addWidget(close_btn) close_btn.clicked.connect(self.close) self.setGeometry(900, 65, 400, 80) self.setWindowTitle('MsgBox for WorkThread') class MainWindow(Qt.QWidget): ''' Main Window ''' def __init__(self): super().__init__() layout = Qt.QVBoxLayout(self) self.labelMain = Qt.QLabel("The result of the Main task: ") layout.addWidget(self.labelMain) self.labelThread = Qt.QLabel("The result of the Thread task: ") layout.addWidget(self.labelThread) validator = Qt.QIntValidator(1, 999, self) validator.setBottom(1) self.lineEdit = Qt.QLineEdit() self.lineEdit.setPlaceholderText("Enter the initial parameter for the …
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87963167
comment on: http://stackoverflow.com/q/50474250
type: Comment
type: QuestionComment
has text: Thanks everyone! Regarding inside-out objects, I guess I am. I never heard that before, but I've been doing it for a long time in perl. Probably learned it from somebody elses code. Hope it isn't a considered a mortal sin in python.
score: 0

http://stackoverflow.com/comment/87862861
score: 0
type: Comment
type: QuestionComment
has text: thanks for answering, i reinstalled pillow and it worked. i just wanted to know if this is the usual way to handle modules after upgrades. so this means after every python update i have to manually reinstall every module?
comment on: http://stackoverflow.com/q/50422929

http://stackoverflow.com/q/50539695
tagged with: pip
score: 1
answer count: 1
favorite count: 0
type: Question
has title: Django pip install mysqlclient error
tagged with: django
type: UnansweredQuestion
tagged with: python
has body: So, I can't seem to connect mysql with my django It used to give me an error and used to ask me to install visual c++. But then I had already installed it the day before. Scrolled a little higher and noticed that it also mentioned that a file named vcvarsall.bat was missing. I made a few changes in one of the python files (msvc9compliler and wrote the path to C:/Users/Administrator/AppData/Local/Programs/Common/Microsoft/Visual C++ for Python/9.0 AS vcvarsall = "C:/Users/Administrator/AppData/Local/Programs/Common/Microsoft/Visual C++ for Python/9.0" + "/vcvarsall.bat" And then when I tried to run the pip install mysqlclient It game me the following error (venv) C:\Users\Administrator\PycharmProjects\BugTracker&gt;pip install mysqlclient Downloading/unpacking mysqlclient Running setup.py (path:C:\Users\ADMINI~1\AppData\Local\Temp\1\pip_build_Administrator\mysqlclient\setup.py) egg_info for package mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient building '_mysql' extension C:\Users\Administrator\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,3,12,'final',0 ) -D__version__=1.3.12 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -IC:\Python34\include -IC:\Python34\include /Tc_mysql.c /Fobuild\temp.win-amd64-3.4\Release\_mys ql.obj /Zl _mysql.c _mysql.c(29) : fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 Complete output from command C:\Python34\python.exe -c "import setuptools, tokenize;__file__='C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\1\\pip_build_Administrator\\mysqlclient\\ setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\A…
has answer: http://stackoverflow.com/a/50540634
upvote count: 3
downvote count: 2

http://stackoverflow.com/q/50532857
has comment: http://stackoverflow.com/comment/88077642
has comment: http://stackoverflow.com/comment/88077674
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50533066
has comment: http://stackoverflow.com/comment/88077603
has comment: http://stackoverflow.com/comment/88077597
has comment: http://stackoverflow.com/comment/88077584
has title: Create the following pyramid in python
tagged with: python
has answer: http://stackoverflow.com/a/50533264
has answer: http://stackoverflow.com/a/50533071
downvote count: 4
answer count: 3
upvote count: 0
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/88077658
has body: Iv`e been asked to create the following pyramid in python with only using 2 for loops. 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72 81 Is there a shorter way only using 2 for loops as apposed to my program? for x in range(1, 10): for y in range(0, 1): print ('1') print("2 4") for u in range(1, 2): for v in range(0,1): print("3 6 9") print("4 8 12 16") for t in range(1, 2): for s in range(0, 1): print("5 10 15 20 25") print("6 12 18 24 30 36") for r in range(1, 2): for q in range(0, 1): print("7 14 21 28 35 42 49") print("8 16 24 32 40 48 56 64") for p in range(0,1): print("9 18 27 36 45 54 63 72 81")
has comment: http://stackoverflow.com/comment/88077645

http://stackoverflow.com/q/50494230
tagged with: jupyter-notebook
favorite count: 0
type: Question
upvote count: 15
answer count: 5
has answer: http://stackoverflow.com/a/54621256
type: UnansweredQuestion
tagged with: python
has title: A way to quick preview .ipynb files
score: 15
has body: Got a small basic question. I use a Mac, and I used to work in .py files with Sublime 3. One of the things I liked was that when Sublime is closed, for a given file in a folder--if I'm looking for a bit of code--I could hit the spacebar and Macs open a quick preview of the .py document. Now I'm working in Jupyter Notebook and saving everything as .ipynb files. Now I can't hit the spacebar and glance at files--I launch JN from the command land and it's far slower. I suspect there are quicker ways to open .ipynb files in browser windows, but what I really want to know is is there a way to quickly preview those file contents from my desktop? Alternatively, is there a way to work in Jupiter Notebook but save the files as .py (and later seamlessly reopen in JN), such that I could still use the great old spacebar trick? Thanks for you patience with a pretty small question :)
has answer: http://stackoverflow.com/a/50494409
has answer: http://stackoverflow.com/a/69388206
downvote count: 0
has answer: http://stackoverflow.com/a/58593051
has answer: http://stackoverflow.com/a/67754764

http://stackoverflow.com/comment/87837033
type: AnswerComment
comment on: http://stackoverflow.com/a/50409950
has text: Thank you. No I do not want to change the information of my data. Yes I would like to normalize it. I did not understand your last paragraph. I have also another question, when working with time series data, is it useful to keep the time frame ? The main issue I got is that the time frame for each input is not the same (for example, over 5 min, or 10 min). After padding, the size of the input become the same but now I wondering if the time matters ?(I am still a beginner with nn). Can I train my dataframe without it ?
type: Comment
score: 0

http://stackoverflow.com/a/69961052
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50435286
has body: Verify below steps : spark-launcher_*.jar is present at $SPARK_HOME/jars folder? explode spark-launcher_*.jar to verify if you have Main.class or not. If above is true then you may be running spark-submit on windows OS using cygwin terminal. Try using spark-submit.cmd instead also cygwin parses the drives like /c/ and this will not work in windows so its important to provide the absolute path for the env variables by qualifying it with 'C:/' and not '/c/'.
downvote count: 0

http://stackoverflow.com/q/50480827
tagged with: python-2.7
upvote count: 1
score: 1
has body: This is a novice question. Consider the below code block : try: import os except ImportError as error: print " Unable to import buildin module os" raise error Do we need to add exception block while importing python built-in modules(like above? What would cause to fail importing a built in module? Can someone point at python documentation explaining this theory?
has comment: http://stackoverflow.com/comment/115229880
has comment: http://stackoverflow.com/comment/87975944
favorite count: 0
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50481523
has answer: http://stackoverflow.com/a/50481523
tagged with: python
has answer: http://stackoverflow.com/a/50585665
accepted answer: http://stackoverflow.com/a/50585665
has title: Python : Do we need to add exception block while importing built in modules?
has comment: http://stackoverflow.com/comment/88157428
type: AnsweredQuestion

http://stackoverflow.com/a/50423394
upvote count: 21
has comment: http://stackoverflow.com/comment/138178978
score: 21
has comment: http://stackoverflow.com/comment/109129213
type: Answer
has comment: http://stackoverflow.com/comment/109128990
answers question: http://stackoverflow.com/q/50422404
has comment: http://stackoverflow.com/comment/87863760
accepted answer of: http://stackoverflow.com/q/50422404
has body: pd.DataFrame.dtypes returns a pd.Series object. This means you can manipulate it as you would any regular series in Pandas: df = pd.DataFrame({'A': [''], 'B': [1.0], 'C': [1], 'D': [True]}) res = df.dtypes.to_frame('dtypes').reset_index() print(res) index dtypes 0 A object 1 B float64 2 C int64 3 D bool Output to csv / excel / pickle You can then use any method you normally would to store a dataframe, such as to_csv, to_excel, to_pickle, etc. Note for distribution pickle is not recommended as it is version dependent. Output to json If you wish to easily store and load as a dictionary, a popular format is json. As you found, you need to convert to str type first: import json # first create dictionary d = res.set_index('index')['dtypes'].astype(str).to_dict() with open('types.json', 'w') as f: json.dump(d, f) with open('types.json', 'r') as f: data_types = json.load(f) print(data_types) {'A': 'object', 'B': 'float64', 'C': 'int64', 'D': 'bool'}
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50445579
type: Question
has answer: http://stackoverflow.com/a/50464558
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87907266
tagged with: python
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/87930674
has body: I have a table in Google BigQuery(GBQ) with almost 3 million records(rows) so-far that were created based on data coming from MySQL db every day. This data inserted in GBQ table using Python pandas data frame(.to_gbq()). What is the optimal way to sync changes from MySQL to GBQ, in this direction, with python.
has title: Python: How to update (overwrite) Google BigQuery table using pandas dataframe
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/50516545
answer count: 1
has answer: http://stackoverflow.com/a/50516761
has comment: http://stackoverflow.com/comment/88045581
has body: I have case that need to count and show user that doesn't have a blog. here my views.py class Blog(models.Model): desc = models.TextField(blank=True, null=True) user = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE, related_name='blogs') @property def DOESN_HAVE_BLOG(self): blog = Self.Blog.all().values_list('user', flat=True) value = Self.User.exclude(id__in=blog) return value here mytemplate.html {{ DOESN_HAVE_BLOG.count }} but its doesn't work
type: Question
has comment: http://stackoverflow.com/comment/88045770
has title: Django Model set @property with filter and show it on template
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88045810
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88045812
accepted answer: http://stackoverflow.com/a/50516761
has comment: http://stackoverflow.com/comment/88045672

http://stackoverflow.com/comment/87972921
type: QuestionComment
has text: I have multiple hard disks on this machine and I put the 3rd file in a different hard disk which is actually a parallel filesystem and using OpenMP I can read large file with many cores at the same time. I want to achieve the same performance using python.
score: 0
comment on: http://stackoverflow.com/q/50479487
type: Comment

http://stackoverflow.com/q/50419523
score: 2
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: pyqt5
favorite count: 0
accepted answer: http://stackoverflow.com/a/50419652
type: Question
tagged with: qlabel
has answer: http://stackoverflow.com/a/50419652
upvote count: 2
has body: I have searched for how to change QLabel text however I could not find anything which was not in html. Their was a few things claiming to do this but I could not get it to work really hoping for somthing I can copy and past then work out how it works by playing around with it. Thank you This is the code import sys from PyQt5 import QtWidgets, QtGui class Program(QtWidgets.QWidget): def __init__(self): super().__init__() """expierment""" test = QtWidgets.QLabel(self) test.setText("I am trying to make this red?") self.show() app = QtWidgets.QApplication(sys.argv) tradingApp = Program() sys.exit(app.exec())
has title: Change QLabel color using python code not html?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50452395
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50452324
type: Answer
has body: The order is important and your print statement must be in the inner for loop. def main(): for i in range(0,4): if i==0: D=2 elif i==1: D=4 elif i==2: D=5.5 else: D=10 for j in range(0,4): if j==0: K=1000 elif j==1: K=2000 elif j==2: K=2500 else: K=4000 print("The year with depth",D,"and K as",K,"is",K*D) main()
answers question: http://stackoverflow.com/q/50452324
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/50531940
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has body: I am writing a code about a mono-energetic gamma beam which the dominated interaction is photoelectric absorption, mu=2 cm-1, and i need to generate 50000 random numbers and sample the interaction depth(which I do not know if i did it or not). I know that the mean free path=mu-1, but I need to find the mean free path from the simulation and from mu and compare them, is what I did right in the code or not? import random import matplotlib.pyplot as plt import numpy as np mu=(2) random.seed=() data = np.random.randn(50000)*10 bins = np.arange(data.min(), data.max()+1e-8, 0.1) meanfreepath = 1/mu print(meanfreepath) plt.hist(data, bins=bins) plt.show()
has comment: http://stackoverflow.com/comment/88077923
type: Question
tagged with: physics
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
tagged with: random
upvote count: 2
score: 1
has title: mono-energetic gamma ray mean free path
has answer: http://stackoverflow.com/a/50535633

http://stackoverflow.com/a/50415861
type: Answer
answers question: http://stackoverflow.com/q/50389955
has body: Have you tried setting a wildcard? For example, if you are iterating a rule over files 1 to 22, you can set a wildcard at the top of your snakemake file: num=range(1,23) Then use that wildcard in your snakemake file names or reference it as in {wildcard.num}
score: 0

http://stackoverflow.com/q/50406312
has comment: http://stackoverflow.com/comment/87828722
has answer: http://stackoverflow.com/a/50406513
has answer: http://stackoverflow.com/a/50406469
has body: I have several txt files, that contain first and last name of the authors. Here are two examples among about thirty (that do not contain the same number of authors). authors1.txt AU - Jordan, M. AU - Thomson, J.J. AU - Einstein, A. AU - Tesla, N. authors3.txt AU - Agassi, A. AU - Herbert, P.H. AU - Agut, R.B. I want to extract the last and first name of the authors for each file. Since I am a beginner in Python, I wrote a script (more or less suitable). with open('authors3.txt', 'rb') as f: textfile_temp = f.read() #o_author1 o_author1 = textfile_temp.split('AU - ')[1] L_name1 = o_author1.split(",")[0] F_name1 = o_author1.split(",")[1] print(L_name1) print(F_name1) #o_author2 o_author2 = textfile_temp.split('AU - ')[2] L_name2 = o_author2.split(",")[0] F_name2 = o_author2.split(",")[1] print(L_name2) print(F_name2) #o_author3 o_author3 = textfile_temp.split('AU - ')[3] L_name3 = o_author3.split(",")[0] F_name3 = o_author3.split(",")[1] print(L_name3) print(F_name3) my result is: Agassi A. Herbert P.H. Agut R.B. My question: Is it possible to write a script with a loop, knowing that the files authors#.txt, don't each contain the same number of authors?
has title: How to use loop in Python to extract words (second and third in the line) from a txt file
has answer: http://stackoverflow.com/a/50406447
has answer: http://stackoverflow.com/a/50406464
has comment: http://stackoverflow.com/comment/87827994
has comment: http://stackoverflow.com/comment/87828094
has comment: http://stackoverflow.com/comment/87828304
tagged with: python
has comment: http://stackoverflow.com/comment/87828490
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50406447
score: 1
downvote count: 0
linked to: http://stackoverflow.com/q/8009882
upvote count: 1
accepted answer: http://stackoverflow.com/a/50406513
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50430336
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50430237
has comment: http://stackoverflow.com/comment/87875523
has comment: http://stackoverflow.com/comment/87875671
has body: Following the error you get: TypeError: Request url must be str or unicode, got NoneType: which occurs here: ".../refrigeratorspider/spiders/refrigeratorspider.py", line 12, in parse yield scrapy.Request(url.xpath("@href").extract_first(), self.parse_page) It looks that no url is found, as url is detected as Noneby the compiler. Try to use another rule or refine the one you have to get the url (as in the page you use, I couldn't find any div.refineCol) Make sure you have valid patterns to get a valid link: def parse(self, response): # let's only gather Time U.S. magazine covers patterns=["div.refineCol ul li", ..., ] max=len(patterns) current=0 pattern=patterns[current] url = response.css(pattern).xpath("a[contains(., 'item')]") while not url || max&gt;0: current+=1 pattern=patterns[current] url = response.css(pattern).xpath("a[contains(., 'item')]") max-=1 if not url: raise Exception('None of the patterns extracted a link') # or raise CloseSpider('None of the patterns...') link=url.xpath("@href").extract_first() print("Check %s"%link) if link: yield scrapy.Request(, self.parse_page) else: raise Exception('Not a valid url') # or raise CloseSpider('Not a valid url') yield scrapy.Request(link, self.parse_page) def close(self, reason): # add messages here or actions in case the spider closes
has comment: http://stackoverflow.com/comment/87875339

http://stackoverflow.com/comment/87807906
type: AnswerComment
comment on: http://stackoverflow.com/a/50395894
has text: try: df1.Strike = df1.Strike.astype(str)
type: Comment
score: 0

http://stackoverflow.com/a/50408071
has body: I was able to make the _FORMATTER work by setting USE_L10N = False In their documentation it says: The formatting is turned on if you have set USE_L10N = True in the your settings file. If formatting is disabled in the configuration, then in the templates will be used default formatting. In the templates you can use a special tag to format the money.
score: 0
answers question: http://stackoverflow.com/q/50388110
type: Answer
type: AcceptedAnswer
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50388110

http://stackoverflow.com/comment/87835964
comment on: http://stackoverflow.com/q/50410065
type: Comment
type: QuestionComment
has text: @Vin That won't work if the target doesn't contain valid JSON.
score: 0

http://stackoverflow.com/comment/87929804
comment on: http://stackoverflow.com/q/50440987
has text: @Sraw If you post your comment as an answer I will accept it - it's exactly what I was looking for.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50468629
type: Question
has body: So I have been trying to play around with the function in Selenium that is called: wait = WebDriverWait(browser, 20).wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="accountStandalone"]/div/div/div[2]/div/div/div[1]/button'))) wait.click() Before I'm starting to say the issue. What I'm trying to do a Selenium of is to basically make a Selenium that automatic write to the forumlar in this picture: Which isn't any complications. However whenever I press "Skapa Konto", It loads and waits until a new page comes up which is: Which is the picture above. My idea is that what I wish is that it should wait until it gives me that "picture" (Which is the same link so it doesn't make any changes) so I assume better to do is to wait until a text etc "FORTSÄTT or HELLO" is the browser. Then continue. However, I'm having an issue when trying using this. The reason is that it doesn't wait until it found but goes instant and does other stuff which it shouldn't. Right now it just skips the wait like the function doesn't work or is there at all. What did I do for wrong? Update: What I know is that whenever I try to register on the website - The website doesn't change meaning it takes me to a new page when its been a successful account. But it does automatic refresh and saying its been successful. So meaning that somehow I want to make something in a way that it checks and sees if something new happened to the page. If not, Wait again and try again?... Something like that? What I would do is etc check if there is: NU ÄR DU MEDLEM, Hello. or FORTSÄTT However the problem is as I said, whenever I press "SKAPA KONTO" - It just waits for the server to double check and then automatic refreshes the page and says successful.
score: 5
tagged with: webdriverwait
has answer: http://stackoverflow.com/a/50474905
upvote count: 6
tagged with: python
has title: Python + Selenium: Wait until element is fully loaded
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87951551
accepted answer: http://stackoverflow.com/a/50474905
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87951798
tagged with: selenium
has comment: http://stackoverflow.com/comment/87955027
tagged with: webdriver
favorite count: 0

http://stackoverflow.com/comment/88093617
has text: The code you're copying really does have an indentation issue. The contents of a function should be indented by 4 spaces
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50541174
score: 2

http://stackoverflow.com/comment/88057956
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50522676
has text: Very nice . Thank you so much it works @Thomas Kuhn.

http://stackoverflow.com/q/50455722
has answer: http://stackoverflow.com/a/50458228
tagged with: python
has body: I am very new to python 2.7 I am trying to run Decision Tree Classifier on my dataset but following a tutorial I face this problem I have first vectorized my features columns and saved it into a array and later saved target column in a array using labelencoder. Please can you explain me how do I fix this Error? Data : Code: import pandas as pd dataset = "C:/Users/ashik swaroop/Desktop/anaconda/Gene Dataset/Final.csv" datacan = pd.read_csv(dataset) datacan = datacan.fillna('') features = datacan"Tumour_Types_Somatic","Tumour_Types_Germline", "Cancer_Syndrome","Tissue_Type", "Role_in_Cancer","Mutation_Types","Translocation_Partner", "Other_Syndrome","Tier","Somatic","Germline", "Molecular_Genetics","Other_Germline_Mut" from sklearn.feature_extraction import DictVectorizer from sklearn.preprocessing import LabelEncoder X_dict = features.to_dict().values() vect = DictVectorizer(sparse=False) X_vector = vect.fit_transform(X_dict) le = LabelEncoder() y_train = le.fit_transform(datacan['Gene_Symbol'][:-1]) X_Train = X_vector[:-1] X_Test = X_vector[-1:] from sklearn import tree clf = tree.DecisionTreeClassifier(criterion='entropy') clf = clf.fit(X_Train,y_train) ` I am Getting this Error : from sklearn import tree clf = tree.DecisionTreeClassifier(criterion='entropy') clf = clf.fit(X_Train,y_train) Traceback (most recent call last): File "&lt;ipython-input-49-fef4fc045a54&gt;", line 4, in &lt;module&gt; clf = clf.fit(X_Train,y_train) File "C:\Users\ashik swaroop\Anaconda2\lib\site- packages\sklearn\tree\tree.py", line 739, in fit X_idx_sorted=X_idx_sorted) File "C:\Users\ashik swaroop\Anaconda2\lib\site- packages\sklearn\tree\tree.py", line 240, in fit "number of samples=%d" % (len(y), n_samples)) ValueError: Number of labels=21638 does not match number of samples=12 Traceback (most recent call last): File "&lt;ipython-input-49-fef4fc045a54&gt;", line 4, in &lt;module&gt; clf = clf.fit(X_Train,y_train) File "C:\Users\ashik swaroop\Anaconda2\lib\site- packages\sklearn\t…
type: AnsweredQuestion
tagged with: python-2.7
score: 2
upvote count: 2
answer count: 1
downvote count: 0
tagged with: decision-tree
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50458228
has title: How To Fix : ValueError: Number of labels=21638 does not match number of samples=13

http://stackoverflow.com/comment/88078227
has text: what is `file`, by the way? you never defined it.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50533122
type: QuestionComment

http://stackoverflow.com/q/50491932
type: UnansweredQuestion
tagged with: django
has body: I tried to read data from a shape file and save them into database. well here is my code lyr = ds[0] for feat in lyr: geom_t = feat.geom.transform(wgs84, clone=True) print(geom_t.wkt) print(feat.geom.wkt) name ='' Twoway='1' data = { 'name': name, 'Twoway': Twoway, 'geom': geom_t.wkb } form = Street_Form(data) if form.is_valid(): savedlocation = form.save() well it saves and works fine. I printed some of my geometries as wkt before saving to databse and here is the result print(geom_t.wkt): LINESTRING (50.9847540637495 35.8384680697353,50.9850968571006 35.8383655346687) print(feat.geom.wkt): LINESTRING (50.9847540637495 35.8384680697353,50.9850968571006 35.8383655346687) As you can see they are EPSG:4326 and nothing is wrong. Here is my model class str(models.Model): geom = models.LineStringField(srid=4326) but when I read data from database they are as following "LINESTRING(0.000457917485762628 0.000321907544087987,0.000457920236524686 0.000321915031075541)" the above result is from this query select st_astext(geom) from public."app_str" well the geometries are misplaced, where is the problem?why this happens?
has comment: http://stackoverflow.com/comment/88043956
score: 0
tagged with: geodjango
tagged with: python
has title: geodjango wrong srid when it saves feature
type: Question
has comment: http://stackoverflow.com/comment/88059452
answer count: 0

http://stackoverflow.com/a/50540278
score: 4
answers question: http://stackoverflow.com/q/50540159
accepted answer of: http://stackoverflow.com/q/50540159
type: AcceptedAnswer
upvote count: 4
has body: Gtk widgets are based on GObject, which means you have to access the widget's properties through the props attribute: grid.props.margin_left = 20 grid.props.margin_right = 20 grid.props.margin_top = 20 grid.props.margin_bottom = 20 Alternatively, you can use the setter functions: grid.set_margin_left(20) grid.set_margin_right(20) grid.set_margin_top(20) grid.set_margin_bottom(20)
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87990830
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50472387
type: QuestionComment
has text: Yes, I thought about that but my browser can work once I add the CA to it. So there is no problem with this. I have also been speaking with the team in charge of the proxy and they have tried to disable SSL interception for this case but the same error is appearing. There must be something really small that I am missing, any idea will be welcomed

http://stackoverflow.com/comment/88013595
score: 0
type: Comment
has text: @MateenUlhaq done
type: QuestionComment
comment on: http://stackoverflow.com/q/50500429

http://stackoverflow.com/comment/88074399
has text: Lots of people like to use this: https://github.com/PyMySQL/PyMySQL
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50531183
type: Comment

http://stackoverflow.com/a/50438468
upvote count: 2
answers question: http://stackoverflow.com/q/50438099
downvote count: 0
has body: As Alex already mentioned, you're printing a Python dictionary, which is slightly different than JSON. For instance, the "u" prefix marks the following string as unicode. You don't have to worry about getting invalid JSON responses since boto3 usually throws exceptions in case of AWS API errors.
type: Answer
score: 2

http://stackoverflow.com/q/50513589
tagged with: python-datetime
tagged with: python
has title: Saving date and time in a variable
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/50513820
accepted answer: http://stackoverflow.com/a/50513642
upvote count: 1
has answer: http://stackoverflow.com/a/50513642
downvote count: 1
has answer: http://stackoverflow.com/a/50513820
tagged with: class
type: AnsweredQuestion
score: 0
has body: I want to save in a variable the "specific" moment in which an instance of a class is created, how can I do that in Python 3? Please, take a look to the following snipped code: class Ants(object): """Workers""" ID = 1 def __init__(self): import datetime self.borningTime = datetime.datetime.now() self.ID = Ants.ID Ants.ID += 1 def get_ID(self): return "Ant ID:" + str(self.ID).zfill(5) def get_borningTime(self): return self.borningTime.strftime("%Y-%m-%d %X") my1Ant = Ants() my2Ant = Ants() print(my1Ant.get_ID(), my1Ant.get_borningTime()) print(my2Ant.get_ID(), my2Ant.get_borningTime()) When I run this, the output is: Ant ID:00001 2018-05-24 17:42:45 Ant ID:00002 2018-05-24 17:42:45 And when I run it again: Ant ID:00001 2018-05-24 17:43:05 Ant ID:00002 2018-05-24 17:43:05 Which means that "self.borningTime" is not recording and keeping its value when I created the instance at the very first time (which is what I want), is getting a new value every time I call it. How can I do what I want? what I'm missing in my code? Thanks in advance.

http://stackoverflow.com/q/50467874
tagged with: discord
type: Question
tagged with: discord.py
has body: Well, I wanted to create a bot for discord. One part should be, where the bot thinks of a random number and I have to guess it with 1 try. There is also line 15 to check, if the bot have detected my message. When I try it out, the bot is getting only to print out text 1 in line 13. Because after typing in dc a random number (after text1 appeared), the bot just do simply nothin. No errors, that's what is confusing me Question: Can I use input from discord as for example a variable in line 14 up to the end and do logical arguments with it? import random import discord from discord.ext import commands from discord.ext.commands import Bot import asyncio #line 5 drone = commands.Bot(command_prefix="!") @drone.event async def on_message(message): #line 10 if message.content.startswith("g"): await drone.send_message(message.channel, "text1") f = await drone.wait_for_message(author=message.author, content=(int)) await drone.send_message(message.channel, f) #line 16 z = random.randint(1, 10) if z == f: await drone.send_message(message.channel, "text2") #line 19
type: UnansweredQuestion
answer count: 1
tagged with: python
score: 0
has title: Do logical arguments and set variables with Discord chat input?
tagged with: bots
has answer: http://stackoverflow.com/a/50557404

http://stackoverflow.com/comment/87966732
type: AnswerComment
score: 0
has text: the second error i mentioned was a result of this code `data.groupby('color')`
type: Comment
comment on: http://stackoverflow.com/a/50476407

http://stackoverflow.com/comment/87986606
comment on: http://stackoverflow.com/q/50486732
score: 0
has text: @TimBiegeleisen the problem is that I have a lot of such tables in my data and I cannot transform them manually
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50456921
has comment: http://stackoverflow.com/comment/87927444
answers question: http://stackoverflow.com/q/50456856
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/87927574
has body: file.seek(offset[, whence]) operates on byte-positions inside the file. Not linenumbers. If you want to operate on lines, use readline() or iterate the file: with ("file.txt", "r") as f: first = next(f) # see comment Jean-François Fabre for last in f: # and tdelanys comment :o) pass # do nothing with all other lines, last will hold the last one now first and last hold the first and last line respectively. The advantage here is that you hold 1 line of text at max in memory and discard the rest. AFAIK there is no way to simply get 1st and last line of a file without stepping through it. If you want to parse the data though, follow DyZ suggestion of using the csv module and a reader - its safer. If you feel adventourous - go for pandas , it has plenty of buildin csv capability :) and is able to read big csv's chunkwise to be more memory friendly (see f.e. How to read a 6 GB csv file with pandas )
type: Answer
has comment: http://stackoverflow.com/comment/87927412
accepted answer of: http://stackoverflow.com/q/50456856

http://stackoverflow.com/comment/87815530
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50399782
type: Comment
has text: You're using `"%s.csv"` as the filename, then `filename` as the array, then `finalArray` as the format string. So, the problem is that `filename` is a 0D array (with a string dtype). You probably wanted `"%s.csv' % (filename,)` as one argument, rather than `"%s.csv", filename` as two separate arguments.

http://stackoverflow.com/a/50493713
type: Answer
answers question: http://stackoverflow.com/q/50440398
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50440398
upvote count: 1
score: 1
has body: In [280]: a = np.array([123456789, 234567891, 345678912], dtype=np.uint32) In [282]: a.tobytes() Out[282]: b'\x15\xcd[\x07\xd38\xfb\r@\xa4\x9a\x14' In [284]: a.view('uint8') Out[284]: array([ 21, 205, 91, 7, 211, 56, 251, 13, 64, 164, 154, 20], dtype=uint8) This is the same as a.view('&lt;u1') and a.view('&gt;u1') since endedness doesn't matter with single bytes. In [291]: a.view('&lt;u4') Out[291]: array([123456789, 234567891, 345678912], dtype=uint32) In [292]: a.view('&gt;u4') Out[292]: array([ 365779719, 3543726861, 1084529172], dtype=uint32) A view depends entirely on the data, not on the current (last) view: In [293]: a.view('&lt;u4').view('u1') Out[293]: array([ 21, 205, 91, 7, 211, 56, 251, 13, 64, 164, 154, 20], dtype=uint8) In [294]: a.view('&gt;u4').view('u1') Out[294]: array([ 21, 205, 91, 7, 211, 56, 251, 13, 64, 164, 154, 20], dtype=uint8) About the idea of reshaping and reversing: In [295]: a.view('u1').reshape(-1,4) Out[295]: array([[ 21, 205, 91, 7], [211, 56, 251, 13], [ 64, 164, 154, 20]], dtype=uint8) In [296]: a.view('u1').reshape(-1,4)[:,::-1] Out[296]: array([[ 7, 91, 205, 21], [ 13, 251, 56, 211], [ 20, 154, 164, 64]], dtype=uint8) But I can't change the view (to u4) of this array because it isn't contiguous: In [297]: a.view('u1').reshape(-1,4)[:,::-1].view('&lt;u4') .... ValueError: To change to a dtype of a different size, the array must be C-contiguous Look a bit more at the properties of this reversed array: In [298]: a1 = a.view('u1').reshape(-1,4)[:,::-1] In [299]: a1.flags Out[299]: C_CONTIGUOUS : False F_CONTIGUOUS : False .... In [300]: a1.strides # reversing is done with strides Out[300]: (4, -1) The 2 arrays share the same databuffer. a2 just starts at a different byte: In [301]: a.__array_interface__['data'] Out[301]: (32659520, False) In [302]: a1.__array_interface__['data'] Out[302]: (32659523, False) I can't do an inplace shape change of a1: In [304]: a1.shape = (12,) ... AttributeError: incompatible shape for a non-contiguous…

http://stackoverflow.com/comment/88033905
has text: Yes, you'll need a new virtualenv for Python 3 and install the packages from requirements.txt. And then, if the syntax of your own module is already compatible with both Python 2 and Python 3, you can be lazy and just add the path containing your module to the PYTHONPATH environment variable.
comment on: http://stackoverflow.com/q/50509868
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88045581
type: QuestionComment
has text: Why do you think you can get away without using an instance of `Blog`?
score: 0
comment on: http://stackoverflow.com/q/50516545
type: Comment

http://stackoverflow.com/a/50449582
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50447162
has body: Since we are only choosing 4 out of 64 collisions will be rare, we can therefore draw with replacement and correct afterwards. import numpy as np def multiperm(y, x, factor=16, remap=False): draw = np.random.randint(0, factor*x, (y, x)) idx = np.full((y, factor*x), -1, dtype=np.int8 if factor*x &lt; 128 else int) yi, xi = np.ogrid[:y, :x] idx[yi, draw] = xi yd, xd = np.where(idx[yi, draw] != xi) while yd.size &gt; 0: ndraw = np.random.randint(0, factor*x, yd.shape) draw[yd, xd] = ndraw good = idx[yd, ndraw] == -1 idx[yd[good], ndraw[good]] = xd[good] good[good] = idx[yd[good], ndraw[good]] == xd[good] yd, xd = yd[~good], xd[~good] if remap: idx = np.zeros((y, factor*x), dtype=np.int8) idx[yi, draw] = 1 idx[0, 0] -= 1 return idx.ravel().cumsum().reshape(idx.shape)[yi, draw] else: return draw + factor*x*yi from timeit import timeit print(timeit("multiperm(300_000, 4)", globals=globals(), number=100)*10, 'ms') # sanity checks check = multiperm(300_000, 4) print(np.all(np.arange(300_000) * 64 &lt;= check.T) and np.all(np.arange(1, 300_001) * 64 &gt; check.T)) print(len(set(check.ravel().tolist())) == check.size) Sample run: 44.83660604993929 ms True True

http://stackoverflow.com/q/50437268
has comment: http://stackoverflow.com/comment/87888809
type: Question
accepted answer: http://stackoverflow.com/a/50437451
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50437451
has comment: http://stackoverflow.com/comment/87888615
tagged with: python
tagged with: dictionary
has title: Python nested dictionary gets overwritten even after keeping a copy
has comment: http://stackoverflow.com/comment/87888591
type: AnsweredQuestion
score: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/50437485
upvote count: 2
linked to: http://stackoverflow.com/q/2612802
downvote count: 0
has answer: http://stackoverflow.com/a/50437485
has body: I have a nested dictionary to look up some information . Because of python's way of tagging data , i have created copies of the dicts using the copy method of dict . But when I update the innermost dict , it changes other dicts of all other days (mon to fri) . Here's how I initailize my main dictionary : self.faculty_to_day_hour_slot_map self.faculty_to_day_hour_slot_map = {} day_to_hour = {} faculty_to_data = {} hour_to_allotflag = {} for hour in range(1 , 9): hour_to_allotflag.update({hour : {'alloted': False}.copy()}.copy()) ; for day in ['mon' , 'tue' , 'wed' , 'thu' , 'fri' , 'sat']: day_to_hour.update({day : hour_to_allotflag.copy()}.copy()) ; for faculty_object in self.faculties: self.faculty_to_day_hour_slot_map.update({faculty_object.id : day_to_hour.copy()}.copy()) ; The problem occurs when I update the innermost dict like this : self.faculty_to_day_hour_slot_map.get(faculty).get(day).get(hour)['alloted'] = True For example : self.faculty_to_day_hour_slot_map.get('uniqueid').get('mon').get(1)['alloted'] = True This makes all the 'alloted' as True inside each day ( mon to fri) with hour = 1 How to fix this problem ? why is this occuring despite using copy method ? The original dictionary looks like this : {51: {'mon': {1: {'alloted': True}, 2: {'alloted': True}, 3: {'alloted': True}, 4: {'alloted': True}, 5: {'alloted': True}, 6: {'alloted': True}, 7: {'alloted': True}, 8: {'alloted': True}}, 'tue': {1: {'alloted': True}, 2: {'alloted': True}, 3: {'alloted': True}, 4: {'alloted': True}, 5: {'alloted': True}, 6: {'alloted': True}, 7: {'alloted': True}, 8: {'alloted': True}}, 'wed': {1: {'alloted': True}, 2: {'alloted': True}, 3: {'alloted': True}, 4: {'alloted': True}, 5: {'alloted': True}, 6: {'alloted': True}, 7: {'alloted': True}, 8: {'alloted': True}}, 'thu': {1: {'alloted': True}, 2: {'alloted': True}, 3: {'alloted': True}, 4: {'alloted': True}, 5: {'alloted': True}, 6: {'alloted': True}, 7: {'alloted': True}, 8: {'alloted': True}}, 'fri': {1: {'alloted…
favorite count: 0

http://stackoverflow.com/q/50471870
tagged with: list
has comment: http://stackoverflow.com/comment/87957337
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/87957670
type: Question
upvote count: 4
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50472076
has comment: http://stackoverflow.com/comment/87957503
has answer: http://stackoverflow.com/a/50472076
linked to: http://stackoverflow.com/q/312443
has comment: http://stackoverflow.com/comment/87957381
downvote count: 0
has answer: http://stackoverflow.com/a/50472039
has title: Join pairs of elements of list in Python
score: 4
accepted answer: http://stackoverflow.com/a/50472040
has comment: http://stackoverflow.com/comment/87957394
has body: I have a list: list_to_transform = [['Start', 'двигаться', 'конгресс', 'сша'], ['Start', 'двигаться', 'сторона', 'в'], ['Start', 'двигаться', 'сторона', 'признание', 'суверенитет', 'израильский'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'на'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'оккупировать'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'Голанский'], ['Start', 'двигаться', 'сторона', 'признание', 'и']] What i need is to combine each two words into single string, and if single word is left, combine it with previous two: result =[['Start двигаться', 'конгресс сша'], ['Start двигаться', 'сторона в'], ['Start двигаться', 'сторона признание', 'суверенитет израильский'], ['Start двигаться', 'сторона признание', 'высот на'], ['Start двигаться', 'сторона признание', 'высот оккупировать'], ['Start двигаться', 'сторона признание', 'высот Голанский'], ['Start двигаться', 'сторона признание и']] Is there some elegant way to do so? Any help would be appreciated!
favorite count: 0
has answer: http://stackoverflow.com/a/50472040
type: AnsweredQuestion

http://stackoverflow.com/comment/87882910
type: Comment
has text: I'm almost certain it's something to do with acc_no as when I just do real_account = account[1] it works
type: AnswerComment
comment on: http://stackoverflow.com/a/50434228
score: 0

http://stackoverflow.com/comment/88036737
type: QuestionComment
has text: This is a shot in the dark but basically I'm using paramiko to configure a switch remotely. Whenever I add a vlan (and ports to the vlan) to this switch, it automatically gets disabled even though the settings on the switch are to enable the ports. If I run the same commands locally on the switch, everything is fine. I'm not sure if it's the interface between my python script and the switch. This is why I'm now trying to use subprocess to see if it's paramiko that's causing the issue.
score: 0
comment on: http://stackoverflow.com/q/50497978
type: Comment

http://stackoverflow.com/q/50394099
score: -1
type: AnsweredQuestion
downvote count: 2
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: scikit-learn
has title: separate columns based on genre
has body: I have a dataset for movies recommendation and want to separate the genre feature into different genre columns . The column has all the genres together and seperates them with '|'. What is the best way to do it? movieId title genres 0 1 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy 1 2 Jumanji (1995) Adventure|Children|Fantasy 2 3 Grumpier Old Men (1995) Comedy|Romance 3 4 Waiting to Exhale (1995) Comedy|Drama|Romance 4 5 Father of the Bride Part II (1995) Comedy Thanks
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50394157
accepted answer: http://stackoverflow.com/a/50394157
tagged with: python

http://stackoverflow.com/comment/88098457
comment on: http://stackoverflow.com/a/50540679
has text: Thanks! I had to change this line because it triggered an error. `xy_summ['weighed_class'] = (xy_summ.iloc[1] + 2 * xy_summ.iloc[2]) / xy_summ.iloc[[0, 1, 2]].sum(1)`. However I'm still wondering how did you come up with the weighted function? How do I know it's the correct one for my features?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87885062
comment on: http://stackoverflow.com/q/50435468
score: 0
has text: You can create a set of the changed values and then iterate over the set at the end and call `save()`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50520142
upvote count: 2
has body: If you only want to get the unique name then try this. This is better than the upper solution. There is no need to delete the file. File automatically will be deleted. import os import tempfile path=tempfile.NamedTemporaryFile(dir='C:\\Users\\MuhammadUsman\\Documents\\Python Scripts\\Project',suffix='.png').name
downvote count: 0
answers question: http://stackoverflow.com/q/50519942
score: 2
type: Answer

http://stackoverflow.com/comment/88059200
type: QuestionComment
comment on: http://stackoverflow.com/q/50523421
has text: Yes. The kicker is the recursive sequence in which you happen to assemble the sets <currently> effects the outcome.
score: 0
type: Comment

http://stackoverflow.com/a/50387023
has comment: http://stackoverflow.com/comment/87789767
has comment: http://stackoverflow.com/comment/88261103
has body: I guess the issue you are facing is due to regex = True. As you mentioned you have a dictionary: DEF -&gt; DEFERRED, DEFERED -&gt; DEFERRED So,when you pass DEFERED , it first finds DEF and replaces it with DEFERRED in place followed by ERED. So you will get: DEFERED -&gt; DEFERREDERED Simplified: DEF +ERED -&gt; DEFERRED + ERED -&gt; DEFFEREDERED In case of any query, you can comment.
has comment: http://stackoverflow.com/comment/88302998
has comment: http://stackoverflow.com/comment/87789969
has comment: http://stackoverflow.com/comment/87793217
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88136507
downvote count: 0
has comment: http://stackoverflow.com/comment/88213061
type: Answer
has comment: http://stackoverflow.com/comment/88135214
upvote count: 1
has comment: http://stackoverflow.com/comment/87789889
has comment: http://stackoverflow.com/comment/88244084
has comment: http://stackoverflow.com/comment/88137692
has comment: http://stackoverflow.com/comment/88243604
accepted answer of: http://stackoverflow.com/q/50386772
has comment: http://stackoverflow.com/comment/88138257
score: 1
has comment: http://stackoverflow.com/comment/88319804
has comment: http://stackoverflow.com/comment/87789882
has comment: http://stackoverflow.com/comment/87789853
has comment: http://stackoverflow.com/comment/87790776
has comment: http://stackoverflow.com/comment/88164844
answers question: http://stackoverflow.com/q/50386772

http://stackoverflow.com/a/59543345
answers question: http://stackoverflow.com/q/50498672
upvote count: 2
downvote count: 0
type: Answer
has body: As for your setup.py: In pip 19.0 and later, dependency_links is ignored. Use the PEP 508 syntax to specify the URLs to be used by pip: setup( install_requires= ['shotgun-api3 @ git+https://github.com/shotgunsoftware/python-api.git@v3.0.36#egg=shotgun_api3'] dependency_links = [ "git+https://github.com/shotgunsoftware/python-api.git@v3.0.36#egg=shotgun_api3" ], # ... ) I've left your dependency_links in because nested dependencies in pip make use of setuptools, as discussed today in the comments of another StackOverflow question. Regarding the installation: Since I don't have your local packages it's not possible to check if this answer solves your problem. Be sure to remove the --process-dependency-links part when testing it though, because that is no longer supported in the latest pip either. Alternatively, to install your local package, try pip install -e . instead of manually compiling and specifying everything.
score: 2

http://stackoverflow.com/comment/87934530
type: QuestionComment
has text: Possible duplicate of [Python Server Client program error: "OSError: \[WinError 10048\]"](https://stackoverflow.com/questions/23596009/python-server-client-program-error-oserror-winerror-10048)
comment on: http://stackoverflow.com/q/50460211
score: 0
type: Comment

http://stackoverflow.com/comment/88005372
comment on: http://stackoverflow.com/q/50495848
has text: @screenpaver Nice, yes. But what I object to is that this is not the default when only the US uses this non-standard convention. The option should be `monthfirst=True`!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88086433
type: Comment
comment on: http://stackoverflow.com/q/50536494
type: QuestionComment
has text: Doing that prints out the following: `B(<Cell 'SHEET 1'.A1>,)` for each row.
score: 0

http://stackoverflow.com/a/50441083
upvote count: 1
type: Answer
score: -1
has body: You can use itertools.groupby and recursion: import itertools, sys a = {"name": "john", "phone":"123123123", "owns": {"cars": "Car 1", "motorbikes": "Motorbike 1"}} b = {"name": "john", "phone":"123", "owns": {"cars": "Car 2"}} def condense(r): return r[0] if len(set(r)) == 1 else r def update_dict(c, d): _v = {j:[c for _, c in h] for j, h in itertools.groupby(sorted(list(c.items())+list(d.items()), key=lambda x:x[0]), key=lambda x:x[0])} return {j:update_dict(*e) if all(isinstance(i, dict) for i in e) else condense(e) for j, e in _v.items()} print(update_dict(a, b)) Output: {'name': 'john', 'owns': {'cars': ['Car 1', 'Car 2'], 'motorbikes': 'Motorbike 1'}, 'phone': ['123123123', '123']}
has comment: http://stackoverflow.com/comment/139927204
downvote count: 2
answers question: http://stackoverflow.com/q/50441027

http://stackoverflow.com/comment/87875479
type: QuestionComment
comment on: http://stackoverflow.com/q/50430328
has text: I have updated my question with more details, so to better explain the real problem
score: 0
type: Comment

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

http://stackoverflow.com/q/50447737
has answer: http://stackoverflow.com/a/50447890
has body: I am trying to use the following python code Solved (Hint by @TheFool): By putting latex() into the print function it works. from sympy import * from sympy.printing.mathml import mathml init_printing(use_unicode=True) # allow LaTeX printing # independent variables x, y, z = symbols('x y z', real = True) # parameters nu, rho = symbols('nu rho', real = True, constant = True, positive = True) # dependent variables u, v, w = symbols('u v w', real = True, cls = Function) print(latex(diff(u(x,y,z),x))) The output looks like '\\frac{\\partial}{\\partial x} u{\\left (x,y,z \\right )}'. How can I remove the additional backslashes and the quotation marks at the beginning and at the end of the output?
tagged with: python
has answer: http://stackoverflow.com/a/65529469
has answer: http://stackoverflow.com/a/67119358
possible better answer: http://stackoverflow.com/a/67119358
has title: Sympy latex export using python
score: 14
upvote count: 14
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/50447890
downvote count: 0
favorite count: 0
type: Question
tagged with: latex
tagged with: sympy

http://stackoverflow.com/q/50503033
linked to: http://stackoverflow.com/q/45858155
has title: Remove Minutes and Hours from Series
tagged with: datetime
downvote count: 0
tagged with: python
score: 13
upvote count: 13
accepted answer: http://stackoverflow.com/a/50503052
has body: Good Morning, I have the following Dataframe (Year, Month, Day, Hour, Sec): print(df) Date Price 2018-01-02 09:42:00 2 2018-01-02 09:46:00 4 2018-01-02 10:22:00 6 ... I would like to get, without minutes and seconds: print(final_df) Date Price 2018-01-02 2 2018-01-02 4 2018-01-02 6 ... I tried: df['Date'] = datetime.datetime.strptime(df['Date'], '%Y-%m-%d').date() But it reports "strptime() argument 1 must be str, not Series"
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50503052
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88018337
favorite count: 0
type: Question

http://stackoverflow.com/q/50527600
type: UnansweredQuestion
tagged with: function
answer count: 1
downvote count: 0
upvote count: 1
score: 1
tagged with: alias
has answer: http://stackoverflow.com/a/50543949
tagged with: python
tagged with: shell
has title: xonsh: Clash between alias and function with same name
favorite count: 0
has body: I've this function defined in my xonshrc: def turn_into_alias(func, keep=False): aliases[func.__name__] = func del func It's supposed to convert a function into an alias. But it doesn't work. It adds the alias all right but the deleting doesn't work, because it deletes the function reference passed to it. Is it possible to setup xonsh so that it gives higher priority to the aliases? (probably not, because it's python after all, in that case:) Is there a way to achieve the effect I want in xonsh?
tagged with: xonsh
type: Question

http://stackoverflow.com/comment/87831927
has text: Please provide some sample inputs.
comment on: http://stackoverflow.com/q/50408260
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/a/50420560
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50420528
type: Answer
has body: The problem you're facing is not what you think it is. What's happening is that when your code sees the first 1 in the score list, it adds 100 to the score. Then it sees another 1 and adds 200 to the score. So you end up with a score of 300. It's not that your code thinks there's 3 1's in the list. I don't think looping over the list is necessary in this case, since list has a built-in count function. Try this: rolled_dice = [dice1, dice2, dice3, dice4, dice5, dice6] one_count = rolled_dice.count(1) return [0, 100, 200, 300, 1000][one_count] Though you should probably have a plan for what happens if you roll more than 4 1s. But I'll leave that part up to you.
has comment: http://stackoverflow.com/comment/87856667
downvote count: 0

http://stackoverflow.com/a/50524454
has comment: http://stackoverflow.com/comment/88061601
accepted answer of: http://stackoverflow.com/q/50523932
score: 0
answers question: http://stackoverflow.com/q/50523932
has body: To get the value from a Tkinter Variable you need to use its .get method. And you can use Tkinter's trace mechanism to watch the variables associated with your Entry widgets. Whenever the Entry values change the Label will automatically update. import tkinter as tk root = tk.Tk() var1 = tk.DoubleVar() t1 = tk.Entry(root, textvariable=var1) t1.pack() var2 = tk.DoubleVar() t2 = tk.Entry(root, textvariable=var2) t2.pack() result = tk.DoubleVar() l = tk.Label(root, textvariable=result) l.pack() # Put trace callbacks on the Entry DoubleVars def set_label(name, index, mode): result.set(var1.get() + var2.get()) var1.trace('w', set_label) var2.trace('w', set_label) # Setting the vars will trigger the trace var1.set(0.25) var2.set(0.5) root.mainloop()
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/a/50449710
has body: You can customize this for all the inputs Date and DateTime by adding the TIME_INPUT_FORMATS into the settings.py TIME_INPUT_FORMATS = [ '%I:%M', # '14:30' ] Django docs
score: 1
answers question: http://stackoverflow.com/q/50449555
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50449555

http://stackoverflow.com/q/50515185
has title: Find number of function parameters and their names
answer count: 2
accepted answer: http://stackoverflow.com/a/50515309
has body: I have code like this in JavaScript: function func(param1, param2) {} console.log(func.length); // 2 var getParamNames = require('get-parameter-names'); console.log(getParamNames(func)); // ['param1', 'param2'] How would you write this in Python, to which I am new?
tagged with: javascript
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88043184
score: 0
has answer: http://stackoverflow.com/a/50515301
possible better answer: http://stackoverflow.com/a/50515301
has answer: http://stackoverflow.com/a/50515309
tagged with: python
type: Question

http://stackoverflow.com/comment/87873620
comment on: http://stackoverflow.com/q/50429314
score: 0
has text: Why doesn't it work? What happens? However, your condition you wrote in words sounds more like `if int(col[-1]) == 1:`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50548102
has body: I figured out the answer, thanks to the guidance of @Ajax1234. There was a small intricacy, based on how you compare the list elements. Here is one working approach: import numpy as np from collections import deque import time d = [[[2, 1, 3], [3, 1, 2], [1, 2, -2]], [[3, 1, 2], [1, 2, 3], [1, -2, 2]], [[1, 2, 3], [2, 1, 3], [3, 1, 2]], [[1, 2, 3], [2, 1, 3], [2, 2, 1]], [[1, 2, 3], [2, 2, 1], [4, 1, 0]], [[2, 1, 3], [2, 2, 1], [-4, 1, 0]], [[3, 1, 3], [2, 2, 1], [-4, 1, 0]]] def bfs(d, start): queue = deque([d[start]]) seen = [start] results = [] while queue: _vertices = queue.popleft() current = [[i, a] for i, a in enumerate(d) if len([x for x in a if x in _vertices])==2 and i not in seen] if len(current)&gt;0: current_array = np.array(current, dtype=object) current0 = list(current_array[:, 0]) current1 = list(current_array[:, 1]) results.extend(current0) queue.extend(current1) seen.extend(current0) return results time1 = time.time() xo = bfs(d, 2) print(time.time()-time1) print(bfs(d, 2)) For an array of size (3000, 3, 3), the code currently takes 18 seconds to run. If I add @numba.jit(parallel = True, error_model='numpy'), then it actually takes 30 seconds. It is probably because queue is not supported by numba. I would be pleased if any one could suggest how this code could be made faster. Update There were some redundancies in the code, which has now been removed, and the code run in 14 seconds, instead of 30 seconds, for a of d of size (4000 X 3 X 3). Still not stellar, but a good progress, and the code looks cleaner now.
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50537967
score: 14
upvote count: 14

http://stackoverflow.com/comment/87942995
score: 0
type: AnswerComment
has text: actually, It is very close. in the thrid line for example, I do not want the output [41,61]. The searched pair [33,39] is fully covered with [32,40]. But its a minor problem, you helped me a lot already
type: Comment
comment on: http://stackoverflow.com/a/50464791

http://stackoverflow.com/q/50487511
has comment: http://stackoverflow.com/comment/88020779
score: 0
has comment: http://stackoverflow.com/comment/87988708
has comment: http://stackoverflow.com/comment/87987739
has comment: http://stackoverflow.com/comment/87987770
answer count: 1
has answer: http://stackoverflow.com/a/74146835
has body: How efficient is pytail as compared to a shell tail running as subprocess in a python script? subprocess.Popen(['tail','-f','filename.txt'])
tagged with: tail
type: Question
has comment: http://stackoverflow.com/comment/88013567
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87988377
has title: How efficient is pytail as compared to a shell tail running as subprocess (['tail','-f','filename.txt']) in a python script?
has comment: http://stackoverflow.com/comment/87987791
tagged with: python

http://stackoverflow.com/q/50475390
score: 0
has comment: http://stackoverflow.com/comment/87964284
answer count: 2
tagged with: pandas
type: Question
accepted answer: http://stackoverflow.com/a/50475467
has body: I have data coming from Redis and I'm struggling to convert this data in DF Data from Redis data = ["[Timestamp('2018-05-22 09:15:00'), 3555.75, 3559.15, 3546.45, 3548.3, 34250, 'Green', 34250]", "[Timestamp('2018-05-22 09:16:00'), 3549.05, 3551, 3543.25, 3548, 19500, 'Green', 53750]", "[Timestamp('2018-05-22 09:17:00'), 3548.95, 3553.2, 3548.05, 3548.9, 12000, 'Green', 65750]"] How to store above data in pandas dataframe in below columns df = pd.DataFrame(columns= 'date','open','high','close','low','volume','close','total_volume'])
has answer: http://stackoverflow.com/a/50475642
possible better answer: http://stackoverflow.com/a/50475642
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/10775894
has title: Convert nested list with strings to Pandas Dataframe
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50475467

http://stackoverflow.com/q/50486919
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 1
downvote count: 0
has body: For some reason I can't get VS Code to disable line wrap on format. My settings contain these entries "python.formatting.provider": "autopep8", "python.formatting.autopep8Args": [ "--max-line-length=200" ], "python.linting.pep8Args": [ "--max-line-length=200" ] editor.wordWrap is off by default. When I format the document long lines (>79) get wrapped. I've tried all kinds of combinations to get this to work. I even set the formatting provider to none to no avail. It's as if the python settings are simply not picked up. Setting "python.linting.enabled": false still lints my files.
has answer: http://stackoverflow.com/a/50487044
accepted answer: http://stackoverflow.com/a/50487044
favorite count: 0
type: Question
has title: Control line wrap for python in VS Code
tagged with: visual-studio-code
tagged with: python

http://stackoverflow.com/q/50519942
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/33322932
answer count: 2
has body: I have create the temporary file using the tempfile.mkstemp() and after creating this, I have get the unique path of the file inside the path and now I want to delete the temporary file. My code is given below. I have already visit this WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'new.dat' but did not solve my problem. Code import os import tempfile path=tempfile.mkstemp('.png', 'bingo', 'C:\\Users\\MuhammadUsman\\Documents\\PythonScripts\\Project') os.unlink(path) Error PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\MuhammadUsman\\Documents\\PythonScripts\\Project\\bingois3q1b3u.png'
tagged with: python
has comment: http://stackoverflow.com/comment/111584555
upvote count: 4
has comment: http://stackoverflow.com/comment/88052442
has answer: http://stackoverflow.com/a/50520142
possible better answer: http://stackoverflow.com/a/50520142
has comment: http://stackoverflow.com/comment/88052645
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50520072
score: 3
accepted answer: http://stackoverflow.com/a/50520072
tagged with: delete-file
has comment: http://stackoverflow.com/comment/88052701
has title: Temporary file not deletable?
tagged with: file-permissions

http://stackoverflow.com/q/50418602
has comment: http://stackoverflow.com/comment/87854874
tagged with: python
tagged with: regex
has body: I am trying to remove only select characters from xml tags + any digit that follows + the proceeding : .. for example: &lt;ns2:projectArea alias= should look like &lt;projectArea alias= and &lt;ns9:name&gt; should look like &lt;name&gt; Basically, the digit will be random (anything from 1-9) and there will always be a proceeding : that must be deleted. What I have so far is: import argparse import re # Initiates argument parser = argparse.ArgumentParser() parser.add_argument("--input", "-i", help="Set the input xml to clean up") parser.add_argument("--output", "-o", help="Set the output xml location") args = parser.parse_args() inputfile = args.input outputfile = args.output if args.input: print("inputfile location is %s" % args.input) if args.output: print("outputfile location is %s" % args.output) # End argument text = re.sub('&lt;[^&lt;]+&gt;', "", open(inputfile).read()) with open(outputfile, "w") as f: f.write(text) This piece of the code is the issue: '&lt;[^&lt;]+&gt;' It deletes entire tags, so if i need to search text later on, basically have to search plain text rather than by tags. What can I replace '&lt;[^&lt;]+&gt;' with that will delete ns + the following number (whatever number it may be) + the : that follows it?
tagged with: http://stackoverflow.com/tag/xml
type: Question
has title: Remove select characters from xml tags using regex
has answer: http://stackoverflow.com/a/50419275
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87854959
has answer: http://stackoverflow.com/a/50421087
has answer: http://stackoverflow.com/a/50418714
has comment: http://stackoverflow.com/comment/87852820
has comment: http://stackoverflow.com/comment/87852844
score: 0
has comment: http://stackoverflow.com/comment/87852866
has comment: http://stackoverflow.com/comment/87852919
answer count: 3

http://stackoverflow.com/comment/87786034
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50385200
type: Comment
has text: yes i want timestamp

http://stackoverflow.com/q/50391766
has body: So I have an old version of conda install conda -V conda 4.5.4 the current version of anaconda is 5.1 and it is running python 3.6.4 I wanted to test my code base on the newer version of conda so I tought I could install a new env first with conda and it would give me the latest version of the conda distribution conda create -n py364 python=3.6 anaconda I thought this would be installing the latest anaconda with python 3.6.4 but it is actually installing python 3.6.1 is it possible to install the new anaconda version in a env?
has comment: http://stackoverflow.com/comment/87806256
has title: Why when I install a environment with conda it does not give me the latest version
type: UnansweredQuestion
score: 0
tagged with: anaconda
tagged with: python
has answer: http://stackoverflow.com/a/50392170
has answer: http://stackoverflow.com/a/50412046
tagged with: conda
type: Question
has comment: http://stackoverflow.com/comment/87811013
answer count: 2

http://stackoverflow.com/a/50499090
accepted answer of: http://stackoverflow.com/q/50492676
has comment: http://stackoverflow.com/comment/88012299
upvote count: 17
has comment: http://stackoverflow.com/comment/88011944
answers question: http://stackoverflow.com/q/50492676
has comment: http://stackoverflow.com/comment/124733788
has comment: http://stackoverflow.com/comment/88012086
has comment: http://stackoverflow.com/comment/88012186
type: Answer
has comment: http://stackoverflow.com/comment/124461709
score: 17
has comment: http://stackoverflow.com/comment/94242006
has comment: http://stackoverflow.com/comment/98994668
type: AcceptedAnswer
downvote count: 0
has body: What you are describing is possible. What you have to keep in mind is that Tensorboard reads from saved tensorflow binaries which represent your variables on disk. More information on saving and restoring tensorflow graph and variables here The main task is therefore to get the embeddings as saved tf variables. Assumptions: in the following code embeddings is a python dict {word:np.array (np.shape==[embedding_size])} python version is 3.5+ used libraries are numpy as np, tensorflow as tf the directory to store the tf variables is model_dir/ Step 1: Stack the embeddings to get a single np.array embeddings_vectors = np.stack(list(embeddings.values(), axis=0)) # shape [n_words, embedding_size] Step 2: Save the tf.Variable on disk # Create some variables. emb = tf.Variable(embeddings_vectors, name='word_embeddings') # Add an op to initialize the variable. init_op = tf.global_variables_initializer() # Add ops to save and restore all the variables. saver = tf.train.Saver() # Later, launch the model, initialize the variables and save the # variables to disk. with tf.Session() as sess: sess.run(init_op) # Save the variables to disk. save_path = saver.save(sess, "model_dir/model.ckpt") print("Model saved in path: %s" % save_path) model_dir should contain files checkpoint, model.ckpt-1.data-00000-of-00001, model.ckpt-1.index, model.ckpt-1.meta Step 3: Generate a metadata.tsv To have a beautiful labeled cloud of embeddings, you can provide tensorboard with metadata as Tab-Separated Values (tsv) (cf. here). words = '\n'.join(list(embeddings.keys())) with open(os.path.join('model_dir', 'metadata.tsv'), 'w') as f: f.write(words) # .tsv file written in model_dir/metadata.tsv Step 4: Visualize Run $ tensorboard --logdir model_dir -> Projector. To load metadata, the magic happens here: As a reminder, some word2vec embedding projections are also available on http://projector.tensorflow.org/

http://stackoverflow.com/q/50511839
has answer: http://stackoverflow.com/a/50513757
has body: My code has this import code: import tia.analysis.ta as ta And this is on init.py line 2 in "/usr/local/lib/python2.7/dist-packages/tia/analysis" after import code above: from tia.analysis.model import * Then the python 2.7.12 shell show this: import tia.analysis.ta as ta File "/usr/local/lib/python2.7/dist-packages/tia/analysis/__init__.py", line 2, in &lt;module&gt; from tia.analysis.model import * ImportError: No module named model Can somebody tell me why the 'model' module in tia.analysis is unavailable even after I successfully install tia and using Python 2.7? If somebody can also tell me the solution, I will be grateful.
tagged with: python
has comment: http://stackoverflow.com/comment/88036464
possible better answer: http://stackoverflow.com/a/50513757
score: 2
accepted answer: http://stackoverflow.com/a/50512025
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88067596
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/50512025
upvote count: 2
downvote count: 0
has title: Python No module named model in tia.analysis
favorite count: 0
type: Question

http://stackoverflow.com/q/50443257
favorite count: 0
has answer: http://stackoverflow.com/a/50443316
type: Question
has answer: http://stackoverflow.com/a/50443325
answer count: 5
has body: This is my code: dicto = [{100: 1, 90: 2, 80: 3, 70: 4}, {100: 1, 90: 2, 80: 3}, {105: 1, 100: 2, 90: 3, 80: 4}] listo = [70,80,105] track = [] for y in dicto: for x in listo: try: track.append(y[x]) except KeyError: pass print(track) What I am trying to do is to use the numbers in 'listo' as keys to get the proper values. The first number in listo can only be searched on the first dictionary in 'dicto'. The second number in listo can only be searched in the second dictionary in the dicto, but not the first dictionary or the third one. The third number in listo can also only be searched in the third dictionary in dicto, not the other ones. The output should be like this: [4,3,1] But my code is returning: [4,3,3,4,1] How can I fix my code to give the correct output in Python 3.x
tagged with: python
possible better answer: http://stackoverflow.com/a/50443316
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50443341
tagged with: list
accepted answer: http://stackoverflow.com/a/50443308
has answer: http://stackoverflow.com/a/50443601
has answer: http://stackoverflow.com/a/50443308
score: 0
has title: How to search thoroughly in a list-dictionary to get the right results
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87900621

http://stackoverflow.com/comment/87861357
type: Comment
type: QuestionComment
has text: Well done on a first post.
comment on: http://stackoverflow.com/q/50423239
score: 0

http://stackoverflow.com/comment/88034488
comment on: http://stackoverflow.com/a/50486148
has text: @KRKirov - And what about graphs like [this](https://stackoverflow.com/a/50318954/2901002) ? People love them... :)?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50465154
has comment: http://stackoverflow.com/comment/87944084
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50468054
has comment: http://stackoverflow.com/comment/87945434
has answer: http://stackoverflow.com/a/50468054
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50465718
has answer: http://stackoverflow.com/a/50465718
type: AnsweredQuestion
has title: Django - get all related models related to each object
answer count: 2
downvote count: 0
tagged with: django
upvote count: 1
has body: Basically, I do have few models that refer to each other. I hope I relations between those alright, but I'm not 100% sure. models.py class Table(models.Model): number = models.IntegerField(unique = True) isFree = models.BooleanField(default = True) class MenuItem(models.Model): name = models.CharField(max_length = 200) price = models.DecimalField(max_digits=5, decimal_places=2) quantityInStock = models.PositiveSmallIntegerField(default=10) class Order(models.Model): tableFK = models.ForeignKey(Table, on_delete=models.CASCADE) opened_at = models.DateTimeField('date_created', default = timezone.now) closed_at = models.DateTimeField('date_closed', blank = True, null = True) paid = models.BooleanField(default = False) class Meta: ordering = ('-opened_at',) class OrderDetails(models.Model): STATUS_CHOICES = ( ('CHOICE1', 'choice1'), ('CHOICE2', 'choice2'), ('CHOICE3', 'choice3'), ('CHOICE4', 'choice4'), ('CHOICE5', 'choice5') ) orderFK = models.ForeignKey(Order, on_delete = models.CASCADE) menuitemFK = models.ForeignKey(MenuItem, on_delete = models.CASCADE) quantity = models.PositiveSmallIntegerField(default = 1) status = models.CharField(max_length=5, choices= STATUS_CHOICES, default='choice1') views.py def index(request): orders = Order.objects.select_related("tableFK").filter(paid=False) template = loader.get_template('autowaiter/index.html') context = { 'orders':orders } return HttpResponse(template.render(context)) What I'm achieving now, is that I do have Orders objects. But in index.html I would like to display something like: Table "earliest" order to table ALL orderDetails elements grouped to each orderFK Could you please point me out example and theory which I'm lacking to proceed?

http://stackoverflow.com/q/50495099
tagged with: python
favorite count: 0
score: 8
type: Question
has title: TypeError: Type aliases cannot be used with isinstance()
tagged with: python-3.x
upvote count: 8
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50496822
tagged with: string
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88003062
tagged with: pandas
has body: Ever since I upgraded pandas to 0.23.0, I'm getting this error for running a line to remove whitespace df.any_column = df.any_column.str.replace(' ','') The error message that I'm getting is below: /usr/local/lib/python3.5/dist-packages/pandas/core/strings.py in replace(self, pat, repl, n, case, flags, regex) 2427 def replace(self, pat, repl, n=-1, case=None, flags=0, regex=True): 2428 result = str_replace(self._data, pat, repl, n=n, case=case, -&gt; 2429 flags=flags, regex=regex) 2430 return self._wrap_result(result) 2431 /usr/local/lib/python3.5/dist-packages/pandas/core/strings.py in str_replace(arr, pat, repl, n, case, flags, regex) 637 raise TypeError("repl must be a string or callable") 638 --&gt; 639 is_compiled_re = is_re(pat) 640 if regex: 641 if is_compiled_re: /usr/local/lib/python3.5/dist-packages/pandas/core/dtypes/inference.py in is_re(obj) 217 """ 218 --&gt; 219 return isinstance(obj, re_type) 220 221 /usr/lib/python3.5/typing.py in __instancecheck__(self, obj) 258 259 def __instancecheck__(self, obj): --&gt; 260 raise TypeError("Type aliases cannot be used with isinstance().") 261 262 def __subclasscheck__(self, cls): TypeError: Type aliases cannot be used with isinstance(). How should I fix this?
has answer: http://stackoverflow.com/a/50496822

http://stackoverflow.com/q/50538051
downvote count: 0
tagged with: pandas
has body: While this question is closely related to Fuzzy Match Merge with Pandas, this question is specifically about merging only (or subsetting, in this case) when the key in one DataFrame is a full match, or substring of the key in another DataFrame. To illustrate my point, here are 2 DataFrames: df1 id code 0 1 E282 1 2 O0080 2 3 R52 3 4 J0100 4 5 F99 df2 code val 0 V282 11 1 O008 12 2 J0101 13 3 F99 14 4 R55 15 The problem with using difflib is that I really don't want to match the closest string, and I'm not sure I'd be able to separate matches like V282 to E282, which shouldn't happen and a match like O008 to O0080 which should merge. The expected output should be code1 id 0 O0080 2 1 F99 5 I can get to this result with import numpy as np df1[np.logical_or.reduce([df1['code'].str.contains(code) for code in df2.code.tolist()])] but since df1 is 42M rows long and df2 contains ~4000 codes, this method is unbelievably slow. Is this the best I'm going to do? It just seems unfortunate, when inner merging a 21M row df and a 7M row df on exact keys takes &lt; 1 minute.
has title: Perform a merge based on a substring match?
has comment: http://stackoverflow.com/comment/88088693
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50538119
tagged with: string
linked to: http://stackoverflow.com/q/48743662
has comment: http://stackoverflow.com/comment/88090912
favorite count: 0
has comment: http://stackoverflow.com/comment/88100868
type: Question
possible better answer: http://stackoverflow.com/a/62895112
has answer: http://stackoverflow.com/a/62895112
accepted answer: http://stackoverflow.com/a/50538119
has comment: http://stackoverflow.com/comment/88089073
tagged with: python
linked to: http://stackoverflow.com/q/13636848
tagged with: merge
type: AnsweredQuestion
tagged with: performance
answer count: 2

http://stackoverflow.com/q/50477609
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87969219
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/50478042
has body: In JavaScript, we can do the following to any object or function const myFn = () =&gt; {}; Object.defineProperties(myFn, { property: { get: () =&gt; console.log('property accessed') } }); This will allow for a @property like syntax by defining a getter function for the property property. myFn.property // property accessed Is there anything similar for functions in Python? I know we can't use property since it's not a new-style class, and assigning a lambda with setattr will not work since it'll be a function. Basically what I want to achieve is that whenever my_fn.property is to return a new instance of another class on each call. What I currently have with setattr is this setattr(my_fn, 'property', OtherClass()) My hopes are to design an API that looks like this my_fn.property.some_other_function(). I would prefer using a function as my_fn and not an instance of a class, even though I realize that it might be easier to implement. Below is the gist of what I'm trying to achieve def my_fn(): pass my_fn = property('property', lambda: OtherClass()) my_fn.property // will be a new instance of OtherClass on each call
possible better answer: http://stackoverflow.com/a/50478042
downvote count: 1
accepted answer: http://stackoverflow.com/a/50478049
favorite count: 0
type: Question
tagged with: python-3.x
has title: Define @property on function
has comment: http://stackoverflow.com/comment/87969292
tagged with: python
has answer: http://stackoverflow.com/a/50478049
upvote count: 2

http://stackoverflow.com/comment/87819538
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50399689
has text: @PrisCunha Yes, `split_list` just returns two new lists. Which is why the code right below it stores those lists into the appropriate place in the new dicts.
type: Comment

http://stackoverflow.com/comment/87869509
has text: Just have checked by using floats in whis, but no change.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50427368

http://stackoverflow.com/comment/87935499
type: AnswerComment
comment on: http://stackoverflow.com/a/50461186
has text: I didn't even come close to this solution. Thanks for this!
type: Comment
score: 0

http://stackoverflow.com/a/50434171
score: 11
has body: From the official Flask documentation: The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make sure to use uppercase letters for your config keys. Therefore, set structure your ./config/app.conf variables as: VARIABLE_NAME = "variable value" Load as: app.config.from_pyfile(os.path.join(".", "config/app.conf"), silent=False) NOTE: If you're not using instance specific configuration you don't actually need to build the path as it will take the Flask app path as its root. And access the values later as: app.config.get("VARIABLE_NAME")
answers question: http://stackoverflow.com/q/50433962
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50433962
has comment: http://stackoverflow.com/comment/102392336
type: Answer
upvote count: 11

http://stackoverflow.com/comment/88051211
has text: @Lzkatz the reference dates don't change.
score: 0
comment on: http://stackoverflow.com/q/50519098
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87914690
type: AnswerComment
has text: @Sulli Sorry, I'm not sure what's going on for you.
score: 0
comment on: http://stackoverflow.com/a/50407886
type: Comment

http://stackoverflow.com/comment/88084412
has text: You should not access objects that belong to another thread if you are going to modify it, one thing is reading and another is writing. For that, Qt offers the signals and the QMetaObject.
comment on: http://stackoverflow.com/q/50535957
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87819409
comment on: http://stackoverflow.com/a/50401315
type: Comment
has text: Amazing! I never see this strategy before.Thank you for that. But there is a bug in pred() because I did not initialize x.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50441641
upvote count: 3
answers question: http://stackoverflow.com/q/50441576
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87931267
has body: You are not getting the id of a "cell", you are getting the id of the object returned by the .loc accessor, which is a boxed version of the underlying data. So, &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(columns=list('abc'), data=np.arange(18).reshape(6, 3)) &gt;&gt;&gt; df1 = df.iloc[:3, :] &gt;&gt;&gt; df.dtypes a int64 b int64 c int64 dtype: object &gt;&gt;&gt; df1.dtypes a int64 b int64 c int64 dtype: object But since everything in Python is an object, your loc method must return an object: &gt;&gt;&gt; x = df.loc[0, 'a'] &gt;&gt;&gt; x 0 &gt;&gt;&gt; type(x) &lt;class 'numpy.int64'&gt; &gt;&gt;&gt; isinstance(x, object) True However, the actual underlying buffer is a primitive array of C fixed-size 64-bit signed integers. They are not Python objects, they are "boxed" to borrow a term from other languages which mix primitive types with objects. Now, the phenomenon you are seeing with all objects having the same id: &gt;&gt;&gt; id(df.loc[0, 'a']), id(df.loc[0, 'a']) (4539673432, 4539673432) &gt;&gt;&gt; id(df.loc[0, 'a']), id(df.loc[0, 'a']), id(df1.loc[0,'a']) (4539673432, 4539673432, 4539673432) Occurs because in Python, objects are free to re-use the memory address of recently reclaimed objects. Indeed, when you create your tuple of id's, the object's returned by loc only exist long enough to get passed and processed by the first invocation of id, the second time you use loc, the object, already deallocated, simply re-uses the same memory. You can see the same behavior with any Python object, like a list: &gt;&gt;&gt; id([]), id([]) (4545276872, 4545276872) Fundamentally, id's are only guaranteed to be unique for the lifetime of the object. Read more about this phenomenon here. But, note, in the following case, it will always be different: &gt;&gt;&gt; x = df.loc[0, 'a'] &gt;&gt;&gt; x2 = df.loc[0, 'a'] &gt;&gt;&gt; id(x), id(x2) (4539673432, 4539673408) Since you maintain references around, the objects are not reclaimed, and require new …
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50441576
has comment: http://stackoverflow.com/comment/87930803

http://stackoverflow.com/comment/120867276
comment on: http://stackoverflow.com/a/50522781
score: 1
type: Comment
type: AnswerComment
has text: This will return the list of texts of each option. For values, it should be response.xpath('//select/option/@value)').getall()

http://stackoverflow.com/comment/87944795
has text: @bro-grammer dict(x) is doing shallow copy. i need deep copy. y = dict(x) ; id(y['e']) == id(x['e'])
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50465631

http://stackoverflow.com/comment/87803161
score: 3
type: Comment
has text: Try `createDataFrame((tuple(r) for r in rows), column_names)`. A `pyodbc.Row` is just a glorified tuple anyway.
comment on: http://stackoverflow.com/q/50393696
type: QuestionComment

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/50411570
type: Tag

loops
tags question: http://stackoverflow.com/q/50437443
tags question: http://stackoverflow.com/q/50491115
tags question: http://stackoverflow.com/q/50504743
tags question: http://stackoverflow.com/q/50536494
tags question: http://stackoverflow.com/q/50479068
tags question: http://stackoverflow.com/q/50419888
tags question: http://stackoverflow.com/q/50455974
tags question: http://stackoverflow.com/q/50464123
tags question: http://stackoverflow.com/q/50523421
tags question: http://stackoverflow.com/q/50519202
tags question: http://stackoverflow.com/q/50493125
tags question: http://stackoverflow.com/q/50501299
tags question: http://stackoverflow.com/q/50386396
tags question: http://stackoverflow.com/q/50439973
tags question: http://stackoverflow.com/q/50390301
tag name: loops
tags question: http://stackoverflow.com/q/50538367
tags question: http://stackoverflow.com/q/50500095
tags question: http://stackoverflow.com/q/50426050
tags question: http://stackoverflow.com/q/50471846
tags question: http://stackoverflow.com/q/50433302
tags question: http://stackoverflow.com/q/50478415
tags question: http://stackoverflow.com/q/50396624
tags question: http://stackoverflow.com/q/50489970
tags question: http://stackoverflow.com/q/50398933
tags question: http://stackoverflow.com/q/50530519
tags question: http://stackoverflow.com/q/50446907
tags question: http://stackoverflow.com/q/50536515
tags question: http://stackoverflow.com/q/50425248
tags question: http://stackoverflow.com/q/50398188
tags question: http://stackoverflow.com/q/50537388
tags question: http://stackoverflow.com/q/50412165
tags question: http://stackoverflow.com/q/50428429
tags question: http://stackoverflow.com/q/50398535
tags question: http://stackoverflow.com/q/50534786
tags question: http://stackoverflow.com/q/50457730
type: Tag
tags question: http://stackoverflow.com/q/50520133
tags question: http://stackoverflow.com/q/50479401
tags question: http://stackoverflow.com/q/50461985
tags question: http://stackoverflow.com/q/50500345
tags question: http://stackoverflow.com/q/50530859
tags question: http://stackoverflow.com/q/50432901
tags question: http://stackoverflow.com/q/50434132
tags question: http://stackoverflow.com/q/50392129
tags question: http://stackoverflow.com/q/50427501

http://stackoverflow.com/q/50392823
tagged with: mayavi
tagged with: python-3.x
has title: input method hangs with mayavi import in Anaconda 3.5.5
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87801395
has comment: http://stackoverflow.com/comment/87801488
has body: I have an input line that asks the user to hit enter to continue. This is so that they have time to read some things at the end of the program before it exits (when I build an exe). I recently moved from a custom Python 3.6 environment to using Anaconda for Python 3.5.5 and now the code will hang after the input statement if the user hits enter without actually entering a character. My script imports mayavi, and when I remove that import line, the problem goes away. I really like using mayavi and just spent 3 days getting everything to freeze correctly, so I would prefer to keep using it. Example: junk = input('Please press enter!') If the user hits enter, the program just hangs. However, if you input a then hit enter, it works as expected. How can I get it to continue without entering any characters and simply hitting enter? EDIT For more details, I am running this in Visual Studio Code on Windows using an Anaconda Python 3.5.5 environment. It doesn't matter where in the code I run it. I thought this occurred no matter what but I started stripping imports and it started working again. I am importing a custom class, tkinter, xlwings, numpy, traceback, mayavi.mlab, sys, time, win32api.GetSystemMetrics, and win32com.client.gencache. I will continue to go through and see if it is a particular import. Also, this is all running in a wrapper function, so I don't know if that matters. Also, I have heard the issues with catching any exception but this works how I want it. def main_wrapper(): # wrapper for main program to catch any exceptions and display them to the user try: main() except Exception as ex: print('Unexpected exception occurred...') traceback.print_exc() if __name__ == '__main__': main_wrapper()
has comment: http://stackoverflow.com/comment/87801543
has comment: http://stackoverflow.com/comment/87801502
type: Question
tagged with: input
tagged with: python
type: UnansweredQuestion
tagged with: freeze
has comment: http://stackoverflow.com/comment/87801666

http://stackoverflow.com/q/50442416
tagged with: python
has answer: http://stackoverflow.com/a/50446946
type: AnsweredQuestion
score: 0
tagged with: keras-layer
answer count: 1
tagged with: keras
has title: Lambda layer in Keras with keras.backend.one_hot gives TypeError
type: Question
tagged with: one-hot-encoding
has body: I'm trying to train a character level CNN using Keras. I take as input a single word. I have already transformed the words into lists of indices, but when I try to feed it into one_hot, I get a TypeError. &gt;&gt;&gt; X_train[0] array([31, 14, 23, 29, 27, 18, 12, 30, 21, 10, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=uint8) &gt;&gt;&gt; X_train.shape (2226641, 98) But when I try to create my model like this: k_model = Sequential() k_model.add(Lambda(K.one_hot, arguments={'num_classes': 100}, input_shape=(98,), output_shape=(98,100))) k_model.add(Conv1D(filters=16, kernel_size=5, strides=1, padding='valid')) I get TypeError: Value passed to parameter 'indices' has DataType float32 not in list of allowed values: uint8, int32, int64. It's obviously not making it to a point where X_train is even read, so where is it getting a float value? I would like to have an instance shape of (98, 100), where 100 is the number of classes. I can't fit the entire dataset in memory.
accepted answer: http://stackoverflow.com/a/50446946

http://stackoverflow.com/q/50506185
has comment: http://stackoverflow.com/comment/88024964
has comment: http://stackoverflow.com/comment/88024704
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88024936
has answer: http://stackoverflow.com/a/50506587
accepted answer: http://stackoverflow.com/a/50506587
tagged with: python
has title: Python data structure to represent an unlimited tree with attributes and looping until last depth
has comment: http://stackoverflow.com/comment/88024601
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88024624
has body: I have a set of Categories on multiple levels/depths: 1. A - A1 - A11 - A12 - A121 - A122 -A2 2. B 3. C - C1 - C2 I need to represent this categories in a python data structure. I have about lists in lists but I think it doesn't help me, because I need to know the depth relation and name of the Category (A, A1, A2) l= [ A -> [A1] -> [A12] -> [A121, A122]] Loop thru the all list of categories go to the last depth and choose randomly one of the categories For example: first element A, go to the last depth and randomly om choose between A121 and A122 third element C, choose randomly between C1, C2 First, for testing, I will create the structure manually, but I want to import later from a CSV
answer count: 1

http://stackoverflow.com/comment/88071396
type: Comment
type: QuestionComment
has text: Did you try something ? :)
score: 0
comment on: http://stackoverflow.com/q/50529731

http://stackoverflow.com/q/50534269
score: 1
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
upvote count: 1
has title: json_normalize None handling change (pandas .23)
has comment: http://stackoverflow.com/comment/88080666
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I have jsons containing nested values that are sometimes None and the behavior has changed between pandas 0.22.0 and pandas 0.23.0. In 0.22.0: from pandas.io.json import json_normalize my_json = {'event': {'name': 'Bob', 'id': '12345','id2': None}, 'id': '12345', 'labels': []} json_normalize(my_json) gives: event.id event.id2 event.name id labels 12345 None Bob 12345 [] which I want. In 0.23.0: from pandas.io.json import json_normalize my_json = {'event': {'name': 'Bob', 'id': '12345','id2': None}, 'id': '12345', 'labels': []} json_normalize(my_json) returns KeyError: 'id2' Toggling ignore errors does nothing, and it's not really feasible to change the nested Nones to placeholder values. Anyone know how to achieve the prior behavior with the update?
tagged with: python
has comment: http://stackoverflow.com/comment/89476573
has comment: http://stackoverflow.com/comment/88080613
has comment: http://stackoverflow.com/comment/88080743
tagged with: pandas
answer count: 0

http://stackoverflow.com/comment/88083647
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50534924
has text: It stills gives me `unicode lists`.even when I use `json.loads`

http://stackoverflow.com/a/50449316
answers question: http://stackoverflow.com/q/50449212
has comment: http://stackoverflow.com/comment/87913852
type: Answer
has body: Here's a solution: Convert the timedelta into a date using python &gt;&gt;&gt; import datetime &gt;&gt;&gt; startTime = datetime.timedelta(0, 54915) &gt;&gt;&gt; startTime = (datetime.datetime.min + startTime).time() &gt;&gt;&gt; startTime datetime.time(15, 15, 15) Get date in format through SQL SELECT STRFTIME('%Y-%m-%d', datetime) FROM your_table; Source: How to retrieve the Date part out of a Datetime result column in SQLite? Hope this helps.
has comment: http://stackoverflow.com/comment/87912206
score: 0
accepted answer of: http://stackoverflow.com/q/50449212
type: AcceptedAnswer

http://stackoverflow.com/comment/88084047
type: QuestionComment
comment on: http://stackoverflow.com/q/50534920
score: 1
type: Comment
has text: When you do, skip this odd alias no-op and just suggest `mycd() { cd "$(myscript "$1")"; }`

http://stackoverflow.com/a/50538395
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50538335
has body: Rather than using . to match everything (and it does not match newline, at least by default), a better approach might be to match everything-except-close-brace: [^}]. You can also simplify the regex a fair bit. import re TEXT = ''' {if true eq isset( $username ) and false eq $is_logged and false} {if true eq isset( $username ) and false eq $is_logged and false} {if true eq isset( $username ) and $boolLoggedIn} Hello {$username} {/if} {if true eq isset( $username )} {assign var=username value=$fname} {/if} ''' rgx = re.compile(r'{/?if[^}]*}') for m in rgx.findall(TEXT): print() print(m)
type: Answer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50538335

http://stackoverflow.com/a/50386892
answers question: http://stackoverflow.com/q/50386682
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: import numpy as np x=[[np.array([0.44179545, 0.44251159, 0.78038469])], [np.array([0.03981791, 0.1526196 , 0.98748255])], [np.array([-0.04485713, 0.17308602, 0.98388468])], [np.array([-0.09494382, 0.43736653, 0.89425734])], [np.array([-0.30896139, 0.48596268, 0.81754702])], [np.array([-0.09564658, 0.56019186, 0.82282247])], [np.array([0.24524103, 0.40670384, 0.88002774])], [np.array([0.08200615, 0.4203557 , 0.90364599])], [np.array([0.20189239, 0.34563383, 0.91639332])], [np.array([0.0855834 , 0.34030184, 0.93641345])], [np.array([0.11078827, 0.05101894, 0.99253364])], [np.array([-0.1302858 , 0.35921852, 0.92411453])]] x1=np.concatenate(x,axis=0) x1.reshape((12,3)) print(x1.shape) Hope it helps. All the array was stored in one list. And you can use np.concatenate() to combine.

http://stackoverflow.com/q/50451649
linked to: http://stackoverflow.com/q/13670333
has title: Optimizing a function where one of the parameters is an array
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50451806
has body: I want to optimize a function by varying the parameters where two of the parameters are actually arrays. I've tried to do ... # initial parameters params0 = np.array([p1, p2, ... , p_array1, p_array2]) p_min = minimize(myfunc, params0, args) ... where the pj's are scalars and p_array1 and p_array2 are arrays of the same length, but this gave me an error saying ValueError: setting an array element with a sequence. I've also tried passing p_array1 and p_array2 as scalars into myfunc and then create predetermined arrays from those two inside myfunc (e.g. setting p_array1 = p_array1*np.arange(6) and similarly for p_array2), eliminating the error, but I don't want them to be predetermined -- instead I want 'minimize' to figure out what they should be. Is there any way that I can utilize one of Scipy's optimization functions without getting this error while still keeping p_array1 and p_array2 as arrays and not scalars? EDIT Sorry for being very broad but here is my code: NOTE: 'myfunc' here is actually norm_residual . import pandas as pd import numpy as np def f(yvec, t, a, b, c, d, M, theta): # the system of ODEs to be solved x, y = yvec dydt = [ a*x - b*y**2 + 1, -c*x - d*x*y + np.sum(M * np.cos(theta*t)) ] return dydt ni = 3 # the number of periodic forcing functions to add to the DE system M = 0.56*np.random.rand(ni) # the initial amplitudes of forcing functions theta = np.pi/6*np.arange(ni) # the initial coefficients of the forcing functions # initialize the parameters params0 = [0.75, 0.23, 1.0, 0.2, M, theta] # grabbing the data to be used later data = pd.read_csv('data.csv') y_data = data['Y'] N = y_data.shape[0] #20 t = np.linspace(0, N, N) # array of t values to integrate over yvec0 = [0.3, 0.34] # initial conditions for x and y respectively def norm_residual(params, *args): """ Computes the L^2 norm of the residual of y and the data (y as defined above). Input: params = array of parameters (scalars or arrays) for the DE system args = other arguments to pass int…
possible better answer: http://stackoverflow.com/a/50451806
tagged with: scipy
has comment: http://stackoverflow.com/comment/87952241
has comment: http://stackoverflow.com/comment/87916460
type: Question
accepted answer: http://stackoverflow.com/a/50466886
upvote count: 0
has comment: http://stackoverflow.com/comment/87925744
downvote count: 1
has answer: http://stackoverflow.com/a/50452887
has comment: http://stackoverflow.com/comment/87917056
favorite count: 0
tagged with: optimization
has answer: http://stackoverflow.com/a/50466886
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47208473
answer count: 3

http://stackoverflow.com/q/50495053
accepted answer: http://stackoverflow.com/a/50501026
has title: If I'm not specifying to use CPU/GPU, which one is my script using?
score: 16
downvote count: 0
has answer: http://stackoverflow.com/a/50501026
has answer: http://stackoverflow.com/a/66617063
upvote count: 16
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/46704352
possible better answer: http://stackoverflow.com/a/50500065
has body: In pytorch, if I'm not writing anything about using CPU/GPU, and my machine supports CUDA (torch.cuda.is_available() == True): What is my script using, CPU or GPU? If CPU, what should I do to make it run on GPU? Do I need to rewrite everything? If GPU, will this script crash if torch.cuda.is_available() == False? Does this do anything about making the training faster? I'm aware of Porting PyTorch code from CPU to GPU but this is old. Does this situation change in v0.4 or the upcoming v1.0?
has answer: http://stackoverflow.com/a/59804373
answer count: 5
has answer: http://stackoverflow.com/a/50500065
tagged with: python
has comment: http://stackoverflow.com/comment/117767905
has comment: http://stackoverflow.com/comment/117763371
linked to: http://stackoverflow.com/q/43806326
has answer: http://stackoverflow.com/a/50514664
type: AnsweredQuestion
tagged with: pytorch

http://stackoverflow.com/a/50414768
has body: You can't change an Excel file that's being used by another application because the file format does not support concurrent access.
has comment: http://stackoverflow.com/comment/87847193
has comment: http://stackoverflow.com/comment/87962087
has comment: http://stackoverflow.com/comment/87960386
has comment: http://stackoverflow.com/comment/87961107
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87937905
answers question: http://stackoverflow.com/q/50411346

http://stackoverflow.com/q/50537636
linked to: http://stackoverflow.com/q/36137602
favorite count: 0
has body: Mac stores filenames with á as "LATIN SMALL LETTER A + COMBINING ACUTE ACCENT" instead of as "LATIN SMALL LETTER A WITH ACUTE". If I am reading file names containing áéíóúÁÉÍÓÚ how can I convert them to the combined versions?
accepted answer: http://stackoverflow.com/a/50537687
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50537687
duplicate of: http://stackoverflow.com/q/36137602
tagged with: python
has title: Converting A+"COMBINING ACUTE ACCENT" to Á
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: unicode

http://stackoverflow.com/comment/88092763
comment on: http://stackoverflow.com/q/50540709
has text: i was able to import WinDLL, are you sure that you are giving the full path to the pythontest.dll?
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/50477826
favorite count: 0
type: Question
has title: how to set desired error threshold in keras?
has body: I'm trying to learn how to use keras and i'm wondering if i can set my own error threshold, but i'm confused. Can someone help me? suppose i want the learning process stop when the error reach 0.02, how do i do that? Thank you for the help. from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(512, activation = 'relu', input_shape=(dimData,))) model.add(Dense(512, activation='relu')) model.add(Dense(512, activation='relu')) model.add(Dense(nClasses, activation = 'softmax')) #configure the network model.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics=['accuracy']) #train the network history = model.fit(train_data, train_labels_one_hot, batch_size=256, epochs = 20, verbose =1, validation_data=(test_data, test_labels_one_hot))
has answer: http://stackoverflow.com/a/50478571
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: neural-network
tagged with: python
upvote count: 0
answer count: 1
tagged with: keras

http://stackoverflow.com/q/50491707
has body: I am trying to convert a folder to show the contours of each image. The code will show the image when I plot it, but not save it to image. How can I save it to an image ? Current error message : ValueError: 'arr' does not have a suitable array shape for any mode. import matplotlib.pyplot as plt import os from PIL import Image i=0 directory_in_str='C:\\directory' directory_output='C:\\output_directory' for file in os.listdir(directory_in_str): print(file) # read image to array im = array(Image.open(join(directory_in_str,file)).convert('L')) # show contours with origin upper left corner im = plt.contour(im, levels=[100], colors='black', origin='image') scipy.misc.imsave(directory_output +'image' + str(i) + '.jpg', im) i+=1 print('done') Thanks !
has answer: http://stackoverflow.com/a/50491745
score: 0
tagged with: contour
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50491888
tagged with: scikit-image
type: Question
answer count: 2
has title: Save contour as image
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/87922719
type: AnswerComment
has text: Is there anyway I can use your above code to only copy snapshots that have a status of 'completed' in source region? thank you in advance
comment on: http://stackoverflow.com/a/50421045
score: 0
type: Comment

http://stackoverflow.com/a/50446402
has comment: http://stackoverflow.com/comment/87906445
score: 0
has comment: http://stackoverflow.com/comment/87906755
type: Answer
has comment: http://stackoverflow.com/comment/87906542
answers question: http://stackoverflow.com/q/50446224
has comment: http://stackoverflow.com/comment/87906484
has comment: http://stackoverflow.com/comment/87906282
has comment: http://stackoverflow.com/comment/87906437
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50446224
has body: from documentation writelines(lines) Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end. Example: with open('test.txt', 'w') as f: f.writelines(['a\n','a\n','a\n']) Output: a a a Please note that the line separator \n is part of each string.
has comment: http://stackoverflow.com/comment/87906868
has comment: http://stackoverflow.com/comment/87906578

http://stackoverflow.com/comment/88062719
score: 1
type: Comment
has text: Just use the replace functionality of your code editor
type: AnswerComment
comment on: http://stackoverflow.com/a/50525220

http://stackoverflow.com/comment/88079133
type: Comment
has text: No. My beat terminal looks like, `LocalTime -> 2018-05-25 21:55:15 Configuration -> . broker -> redis://127.0.0.1:6379/1 . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%WARNING . maxinterval -> 5.00 minutes (300s) ` Nothing else is shown.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50533189

http://stackoverflow.com/comment/88000527
type: Comment
type: QuestionComment
has text: This is not an answer but see https://stackoverflow.com/q/9202224/2750819 and consider storing a hash of your password if you are using this for more than yourself.
comment on: http://stackoverflow.com/q/50493755
score: 0

http://stackoverflow.com/q/50393315
downvote count: 0
answer count: 1
tagged with: websocket
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50393609
tagged with: pool
has title: Python: multiprocessing Pool with 2 functions
score: 1
favorite count: 0
tagged with: multiprocessing
type: Question
has body: I have a problem with multiprocessing.Pool(). My script connects to a websocket to get a bunch of data. This data is stored in a list. My function formula() does calculations based on different desired scenarios and acts if a scenario returns True. Down below I have posted a simplified code: import multiprocessing, time, json res_array = [] def process_message(msg): res_array.insert(0, msg) if len(res_array) &gt; specificnumber: del res_array[specificnumber:] #inserts data in a list def formula(res_array1): # handles list def initiate(): ma = SocketManager(client) conn_key = ma.start_multiplex_socket(listofsockets, process_message) ma.start() # starts websocket if __name__ == '__main__': p1 = multiprocessing.Process(name='p1', target=initiate()) p2 = multiprocessing.Process(name='p2', target=formula(res_array)) p1.start() p2.start() As you can see, I have to call initiate() to start the websocket. My plan was to get data from the websocket while formula is running simultaneously. This code works perfectly but slowly. To fasten things up I wanted to try multiprocessing.Pool() but every example I found shows only one function used. Question: How can I assign 2 functions to one Pool? The pool should handle the function initiate() and formula() at the same time with cpu_count() as number of processes. Is that possible? Thank you!
type: UnansweredQuestion

http://stackoverflow.com/comment/88052171
has text: Furthermore, you might want spec your `Mock` with the Elasticsearch class in order to validate you are using the valid attributes available in the class. So, you might want to do the following: `patch('escli.settings.Escli', Mock(Elasticsearch))`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50506310

http://stackoverflow.com/comment/88224207
comment on: http://stackoverflow.com/q/50527561
type: Comment
type: QuestionComment
score: 0
has text: The modal popup is just elements in the DOM which you can find using the usual `driver.find_element_by...` API - e.g. searching for the class of the modal body, and then performing any actions etc.

http://stackoverflow.com/q/50505169
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/50834432
has body: I am currently writing a python selenium script to scrape the "Likibu.com",it is a website that offers short-term accommodation such as Airbnb, booking ... I have successfully got all data that exists in the first page and save them in a csv file, but the problem is that there are 37 pages and I would like to scrap also the data that exists in these pages. I managed this code as below : driver.get("https://www.likibu.com/") page = driver.page_source soup = BeautifulSoup(page, "lxml") driver.get("https://www.likibu.com/{0}".format(soup.find(rel=re.compile("nofollow")).attrs["href"])) You find here the source code of the web page: « 1 37 »
type: Question
tagged with: beautifulsoup
tagged with: selenium-chromedriver
answer count: 2
type: UnansweredQuestion
tagged with: python
has title: Automat acess to next page using selenium and python
has answer: http://stackoverflow.com/a/50824340
tagged with: selenium-webdriver
score: 0

http://stackoverflow.com/comment/87813054
has text: One thing can improve `pandas.concat([df1, df2], join='outer',keys=['v1','v2']) ` and you do not need assign
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50398391

http://stackoverflow.com/comment/87879644
score: 0
type: Comment
type: AnswerComment
has text: No problem, enjoy Django.
comment on: http://stackoverflow.com/a/50431195

http://stackoverflow.com/comment/87841655
type: QuestionComment
has text: So, yes, there are *two* `Price` for each entry, so what do you want to sort by…?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50413012

http://stackoverflow.com/comment/88042572
score: 0
comment on: http://stackoverflow.com/q/50514405
has text: I can get your code to run with no errors. Are your inputs exactly as in your question?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87878400
has text: Take a look here: https://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute
score: 1
comment on: http://stackoverflow.com/q/50431921
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50477784
type: Question
has body: I see that tensorflow.contrib.lite.Interpreter was recently exposed in the python API. However, when I build and install the tensorflow wheel from source per the standard Tensorflow installation instructions in Ubuntu 16.04 with python 3.5 using the repo head as of 5/22 (4dbaa65), I get a segmentation fault when I try to run it: In [1]: import tensorflow as tf In [2]: a = tf.contrib.lite.Interpreter('mobilenet_quant_v1_224.tflite') In [3]: a.get_input_details() Segmentation fault (core dumped) Am I using this incorrectly?
tagged with: tensorflow-lite
score: 1
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Python Tensorflow Lite Interpreter Crashes
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88004665
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87996196
has comment: http://stackoverflow.com/comment/88081166
favorite count: 0

http://stackoverflow.com/comment/123621800
type: AnswerComment
has text: Indeed, it is a trade off. You can simply change `has_noun = 2` to `has_noun = 1` and your examples are covered. You will also get a lot of garbage though.
score: 0
comment on: http://stackoverflow.com/a/60149686
type: Comment

http://stackoverflow.com/q/50476327
possible better answer: http://stackoverflow.com/a/50476451
downvote count: 2
tagged with: python
favorite count: 0
type: AnsweredQuestion
has body: The problem: I've got a situation with 2 dataframes: test1 = pd.DataFrame({'id_A':['Ben', 'Julie', 'Jack', 'Jack'], 'id_B':['Julie', 'Ben', 'Nina', 'Julie']}) test2 = pd.DataFrame({'id_a':['Ben', 'Ben', 'Ben', 'Julie', 'Julie', 'Nina'], 'id_b':['Julie', 'Nina', 'Jack', 'Nina', 'Jack', 'Jack'], 'value':[1,1,0,0,1,0]}) &gt;&gt;&gt; test1 id_A id_B 0 Ben Julie 1 Julie Ben 2 Jack Nina 3 Jack Julie &gt;&gt;&gt; test2 id_a id_b value 0 Ben Julie 1 1 Ben Nina 1 2 Ben Jack 0 3 Julie Nina 0 4 Julie Jack 1 5 Nina Jack 0 What I'd like to do is merge test2 with test1 where id_A == id_a and id_B == id_b OR where id_A == id_b and id_B == id_a, resulting in the following dataframe: &gt;&gt;&gt; final_df id_A id_B value 0 Ben Julie 1 1 Julie Ben 1 2 Jack Nina 0 3 Jack Julie 1 Current Solution: My solution works but seems messy, and I'd like to see if I'm overlooking some more clever way to do things. It involves concatenating test2 with itself, but reversing the 2 columns of interest (id_a becomes id_b and vice-versa), and then merging from there. test3 = pd.concat([test2, test2.rename(columns = {'id_a':'id_b', 'id_b':'id_a'})]) final_df = (test1.merge(test3, left_on = ['id_A', 'id_B'], right_on = ['id_a', 'id_b']) .drop(['id_a', 'id_b'], axis=1)) Question: Does anyone know a neater way to do this? I feel like I'm probably overlooking some amazing pandorable way of doing things. Thanks for your help!
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50476531
has answer: http://stackoverflow.com/a/50476451
tagged with: dataframe
tagged with: merge
accepted answer: http://stackoverflow.com/a/50476666
upvote count: 11
has title: Merging pandas dataframes on 2 columns but in either order
has answer: http://stackoverflow.com/a/50476666
score: 9
type: Question

http://stackoverflow.com/comment/88005973
has text: I don't see where you are using the values (London for instance) in your code.
comment on: http://stackoverflow.com/q/50496549
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50506782
has title: imgaug: load and save images
tagged with: python
tagged with: image
tagged with: scipy
possible better answer: http://stackoverflow.com/a/52147997
has body: I am using Python+Tensorflow for CNN training on a high-performance computing cluster. I am training a convolutional neural network, but have a relatively small dataset. So I am implementing techniques to augment it. Now this is the first time i am working on a core computer vision problem so am relatively new to it. As raising the number of images for training, the imgaug package (https://github.com/aleju/imgaug) which requires cv2 seems to be perfect and a simple solution to multiply the number of images. I installed opencv2 using python 2.7, all required python packages are running locally (no env/Anaconda/Docker are used here). Practically, I’ am trying to run this code from here: import os import imgaug as ia from imgaug import augmenters as iaa import scipy import cv2 import numpy as np # optional check my hint import scipy.misc import imwrite # optional check my hint import scipy.misc import imsave ia.seed(1) # Example batch of images. # The array has shape (32, 64, 64, 3) and dtype uint8. images = np.array( [ia.quokka(size=(64, 64)) for _ in range(32)], dtype=np.uint8 ) seq = iaa.Sequential([ iaa.Fliplr(0.5), # horizontal flips iaa.Crop(percent=(0, 0.1)), # random crops # Small gaussian blur with random sigma between 0 and 0.5. # But we only blur about 50% of all images. iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=(0, 0.5)) ), # Strengthen or weaken the contrast in each image. iaa.ContrastNormalization((0.75, 1.5)), # Add gaussian noise. # For 50% of all images, we sample the noise once per pixel. # For the other 50% of all images, we sample the noise per pixel AND # channel. This can change the color (not only brightness) of the # pixels. iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # Make some images brighter and some darker. # In 20% of all cases, we sample the multiplier once per channel, # which can end up changing the color of the images. iaa.Multiply((0.8, 1.2), per_channel=0.2), # Apply affine transformations to each image.…
has answer: http://stackoverflow.com/a/52147997
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/50519943
tagged with: tensorflow
favorite count: 0
linked to: http://stackoverflow.com/q/43209530
type: Question
has answer: http://stackoverflow.com/a/50519943
tagged with: opencv
has answer: http://stackoverflow.com/a/52147423
type: AnsweredQuestion
answer count: 3
upvote count: 5

http://stackoverflow.com/comment/92567906
has text: I wonder why is this answer downvoted? Did I get wrong the question or the answer?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50433274
type: AnswerComment

http://stackoverflow.com/q/50444542
type: UnansweredQuestion
tagged with: xhtml2pdf
tagged with: django
tagged with: python
has title: How to make a pdf of a specific part of a html file in django
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50444859
upvote count: 1
favorite count: 0
type: Question
has body: I want to generate pdf from html in django using xhtml2pdf. But xhtml2pdf seems to make a PDF of full HTML template. What I want to say is that suppose I have a side menu, a header, a footer and a table of some contents in my html file. Now, I want to only generate pdf of that table from the html file. How can I do that using xhtml2pdf ? Thank you.

http://stackoverflow.com/q/50472011
accepted answer: http://stackoverflow.com/a/50472153
tagged with: pyyaml
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50472153
possible better answer: http://stackoverflow.com/a/50472175
has comment: http://stackoverflow.com/comment/87959608
has title: Parsing yaml file and getting a dictionary
has answer: http://stackoverflow.com/a/50472970
downvote count: 0
score: 6
tagged with: python
upvote count: 6
has body: I'd like to be able to take the YAML defined below and turn it into a dictionary. development: user:dev_uid pass:dev_pwd host:127.0.0.1 database:dev_db production: user:uid pass:pwd host:127.0.0.2 database:db I have been able to use the YAML library to load the data in. However, my dictionary appears to contain the environmental items as a long string. This code: #!/usr/bin/python3 import yaml config = yaml.load(open('database.conf', 'r')) print(config['development']) yields the following output. user:dev_uid pass:dev_pwd host:127.0.0.1 database:dev_db I can't access any of the entries by key name or load that string subsequent using the yaml.load method. print(config['development']['user']) This code yields the following error: TypeError: string indices must be integers Ideally I would like to end up with a parsing function that returns a dictionary or a list so I can access the properties by key name or using the dot operator like: print(config['development']['user']) config.user Where am I going wrong?
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/50472175

http://stackoverflow.com/q/50491747
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50495580
has comment: http://stackoverflow.com/comment/88000271
has answer: http://stackoverflow.com/a/50494536
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87999250
tagged with: python
has title: Extracting the meaningful information from the text column using python
type: Question
tagged with: python-3.x
score: 0
answer count: 2
has body: I have a table with the two columns. I have to extract the meaningful information out of it from the Notes column. i.e. I need to extract the date in one column and the information after the date in one column and then ID Notes, ID Movie Date 05-28-2018 Passed, 1010 MTD loan slip dated 8-10-14 the Issued, 1111 Max over date 10-2-15 and repaired, 11232 output- Notes ID Date Status Movie Date 05-28-2018 Passed 1010 5/28/2018 Passed loan slip dated 8-10-14 Issued 1111 8/10/2014 Issued Max over date 10-2-15 and repaired 11232 10/2/2015 repaired Here is my code- df = pd.read_sql('select * from &lt;table&gt;', engine) searchfor = [' dated', ' date', ' Date', ' Dated'] df2 = df[df['Notes'] .str.contains('|'.join(searchfor), na = False)] .................. Appreciate your help on this. Thank you.

http://stackoverflow.com/comment/88095001
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50541775
has text: As I stated in my question, this is edited csv text, surprisingly it is not throwing any error but the original file is, that file I cannot share but if I skip 10 rows (As per your result), the original file works perfectly. Basically, Row 10 is the header and row 11-26 is data, which I want to extract.

http://stackoverflow.com/comment/87978855
type: AnswerComment
comment on: http://stackoverflow.com/a/50463283
has text: Try to install the `pillow` module.
score: 0
type: Comment

http://stackoverflow.com/comment/87882384
type: AnswerComment
comment on: http://stackoverflow.com/a/50433841
has text: Thank you for the advice, I've tried them but the issue still persists.
score: 0
type: Comment

http://stackoverflow.com/comment/88001220
comment on: http://stackoverflow.com/q/50493631
score: 0
type: Comment
type: QuestionComment
has text: The regex in the post looks for `/` followed by `dp` or `gp/product` followed by `/` followed by any number of characters (lazily) followed by a `/` or `%3` or `?` optionally. Since the `.*?` is lazy, and `(?:\/|%3|\?)?` the match will be immediately after the last `/`. See [Demo](https://regex101.com/r/HSUDaI/2)

gmail
type: Tag
tags question: http://stackoverflow.com/q/50531623
tag name: gmail

http://stackoverflow.com/comment/88046197
has text: Are you sure your file is good?
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50516864

http://stackoverflow.com/comment/88070424
score: 0
has text: Well, apart from at the end after "Cara " (with a space). That looks odd, did you paste it correctly?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50527914

http://stackoverflow.com/q/50471952
has title: Add number field to Django model
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87957764
downvote count: 0
has answer: http://stackoverflow.com/a/50472382
accepted answer: http://stackoverflow.com/a/50472382
possible better answer: http://stackoverflow.com/a/50472285
tagged with: django
has body: I have a django movie model class Film(models.Model): title = models.CharField(max_length=200) movie_id = models.CharField(max_length=8, unique=True, primary_key=True) director = models.ForeignKey('Director', on_delete=models.SET_NULL, null=True) year = models.IntegerField(null=True) genres = models.ManyToManyField(Genre) I need to use movie_id as primary key, but also i need a field, which represents number of item's row in table. It must increment automatically, just like standard "id" field. How can i add it? This question https://stackoverflow.com/users/3404040/take-care is similar, but i can't use my "number" field as primary key, because movie_id is already used for that.
linked to: http://stackoverflow.com/q/21128899
favorite count: 0
type: Question
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/87957636
tagged with: python
has comment: http://stackoverflow.com/comment/87958074
has answer: http://stackoverflow.com/a/50472285

http://stackoverflow.com/comment/87987338
type: AnswerComment
comment on: http://stackoverflow.com/a/50389624
has text: It will.... try `'test'.split('@')[-1]` and `'@test'.split('@')[-1]` to validate yourself :)
score: 0
type: Comment

http://stackoverflow.com/a/53812835
score: 6
has body: For anyone like me finding this thread somewhat later than creation. It is possible to set custom colors by HEX color codes. E.g. color_map = ["#9b59b6", "#e74c3c", "#34495e", "#2ecc71"] Then plot: ax.stackplot(x, y, colors = color_map) As a last note it is also possible to convert RGB colors to HEX colors (which I had to do in my case). As follows: rgb_code = [128, 128, 128] hex_color = '#%02x%02x%02x' % (rgb_code[0], rgb_code[1], rgb_code[2])
type: Answer
upvote count: 6
downvote count: 0
answers question: http://stackoverflow.com/q/50404913

http://stackoverflow.com/comment/87858320
type: QuestionComment
has text: Why can't you implement the linked solution? Please note that nobody can reproduce your problem, because this is not a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/50421549
score: 0
type: Comment

http://stackoverflow.com/comment/88085883
comment on: http://stackoverflow.com/a/50536854
type: Comment
has text: You probably want `m` to be bool, no?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88009484
has text: @DyZ If i print e after reading the xml I get this: "<Element TrainingCenterDatabase' at 0x0000022AF1469B38>"
score: 0
comment on: http://stackoverflow.com/q/50498261
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50388633
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50388781
has answer: http://stackoverflow.com/a/50388781
has title: Django - Render a variable which stored in database field
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: In my application, I will ask user to input some text with variable and store it into database. like this... Url id | url | ---+-----------------------------------+ 1 | http://example.com/?aaa={{para1}} | 2 | http://example.com/?aaa={{para2}} | 3 | http://example.com/?aaa={{para2}} | 4 | http://example.com/?aaa={{para1}} | And there is a table with the actual value of those parameter. Parameter id | para | ---+-----------+ 1 | 932580234 | 2 | 865234932 | I want to render a html and replace the {{para1}} or {{para2}} on it. views.py def userpage(request): url_obj = Url.objects.filter(id=..not_important...)[0] url = url_obj.url para1_obj = Parameter.objects.filter(..not_important..)[0] para1 = para1_obj.para para2_obj = Parameter.objects.filter(..not_important..)[0] para2 = para2_obj.para return render(request, 'userpage.html', {'url':url, 'para1':para1, 'para2':para2}) templates/userpage.html You URL is {{ url }} My expectation is You URL is http://example.com/?aaa=932580234 However, the actual html is You URL is http://example.com/?aaa={{para1}} How can I "pre render" the field in database before "return render...."? Or is there any other solution for this? I'm using python 3.4 and django 2.0 Thanks!!
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50391753
score: 0
answers question: http://stackoverflow.com/q/50391642
has body: I have looked at the Twilio API for sending a Fax - https://www.twilio.com/docs/fax/send It requires: * A destination phone number or SIP URI. * A From number - this can be either an Incoming Phone Number or an Outgoing Caller ID. (Optional for SIP destinations.) * A URL which points to the media that will be sent via fax (currently, this must be a PDF file; see our security page for information on how to ensure the request for your media comes from Twilio). The API does not support a local file (only a URL, with a PDF file).
type: Answer
has comment: http://stackoverflow.com/comment/90693450
has comment: http://stackoverflow.com/comment/87800230
has comment: http://stackoverflow.com/comment/87799398
has comment: http://stackoverflow.com/comment/87799916

http://stackoverflow.com/comment/87808060
comment on: http://stackoverflow.com/q/50395617
score: 0
type: Comment
type: QuestionComment
has text: Added some code to my answer, try applying median filter another time after you convert the image to binary :)

http://stackoverflow.com/comment/88080126
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50533500
has text: What Squish version are you using? On the Java end, are these `double`s or `Double`s?

http://stackoverflow.com/q/50474542
tagged with: pyenv
answer count: 1
accepted answer: http://stackoverflow.com/a/69953690
favorite count: 0
type: Question
tagged with: sudo
has title: pyenv variable not set when used with sudo
has comment: http://stackoverflow.com/comment/87997739
downvote count: 0
has answer: http://stackoverflow.com/a/69953690
tagged with: python
type: AnsweredQuestion
has body: I am following https://amaral.northwestern.edu/resources/guides/pyenv-tutorial to install pyenv. I installed pyenv and update the .bash_profile as export PYENV_ROOT=/usr/local/pyenv/ export PATH="/usr/local/pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" I added in my user and root, both can access pyenv without any issue. When I run sudo pyenv it gives error. $ sudo pyenv sudo: pyenv: command not found But when I run after login to that user, it works fine. $ sudo -i # pyenv pyenv 1.2.4 Usage: pyenv &lt;command&gt; [&lt;args&gt;] Some useful pyenv commands are: commands List all available pyenv commands local Set or show the local application-specific Python version global Set or show the global Python version shell Set or show the shell-specific Python version install Install a Python version using python-build uninstall Uninstall a specific Python version rehash Rehash pyenv shims (run this after installing executables) version Show the current Python version and its origin versions List all Python versions available to pyenv which Display the full path to an executable whence List all Python versions that contain the given executable See `pyenv help &lt;command&gt;' for information on a specific command. For full documentation, see: https://github.com/pyenv/pyenv#readme I also move that .bash_profile content to .bashrc of /root/ but still it gives same error. How to say sudo that, when you run, please load .bashrc or .bash_profile first.
tagged with: bash
has comment: http://stackoverflow.com/comment/87972345
has comment: http://stackoverflow.com/comment/87962875
upvote count: 7
score: 7

http://stackoverflow.com/comment/90063801
has text: Sorry, How can I do that
comment on: http://stackoverflow.com/a/51541369
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50515288
has comment: http://stackoverflow.com/comment/88043238
answers question: http://stackoverflow.com/q/50514973
upvote count: 0
type: Answer
score: -1
downvote count: 1
has body: Instead of jumping on an answering your question I'm going to give you a hint on how to tackle your actual problem. There is another way to store data like that (dictionaries of non-tabular form) and it is by saving it in the JSON-string format. import json with open('fname','w') as f: json.dump(dict_with_lists, f) And then the code to load it would be: import json with open('fname') as f: dict_with_lists = json.load(f)

http://stackoverflow.com/comment/87957808
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50472037
type: Comment
has text: `%H` is for a 24-hour clock and you are passing with an AM/PM. Change to `''%Y-%m-%d %I:%M:%S %p'`. `%I` handles the 12-hour clock and `%p` handles the AM/PM.

http://stackoverflow.com/a/50539788
has comment: http://stackoverflow.com/comment/88091421
accepted answer of: http://stackoverflow.com/q/50539721
has comment: http://stackoverflow.com/comment/88091486
answers question: http://stackoverflow.com/q/50539721
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Looks like 09 represents the year and not the month. import datetime s = "Jan-09" print(datetime.datetime.strptime(s, '%b-%y').strftime('%m-%d-%Y')) Output: 01-01-2009
has comment: http://stackoverflow.com/comment/88091393
score: 1
type: Answer

http://stackoverflow.com/comment/87984542
has text: @waleed i have added some code to your repo via pull request, go through it and let me know if that works for you, coz that works for me very well on server as well.
comment on: http://stackoverflow.com/a/50425762
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87980994
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50464643
has text: 1. Docker always brings some overhead, most of the time apps would be at least 5-10% slower in docker. 2. 2-3x difference between dockerless Flask and dockerless pure theano + keras means you are doing something wrong with Flask because there is no way that Flask can bring up to 1.8s overhead. 3. You can see some correlation between number of CPUs and algorithm time. It's possible that pure theano + keras uses all CPU cores (4?), but you limit docker with 1 or 2 CPUs. 4. Knowing your hardware spec and OS os quite necessary to resolve performance problems.

http://stackoverflow.com/comment/87946654
has text: @Biskit1943 OP said so
type: AnswerComment
comment on: http://stackoverflow.com/a/50466571
score: 1
type: Comment

http://stackoverflow.com/comment/88018527
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50501777
type: Comment
has text: ... even that function has late-binding variables in it, they would still give the same result. But perhaps this is too much to think about, better just use `None` and forget about it. Thanks :)

http://stackoverflow.com/comment/88081656
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50531745
has text: @mkrieger I want to get the size of the image
type: Comment

http://stackoverflow.com/comment/88040225
score: 0
comment on: http://stackoverflow.com/q/50513461
has text: **@Makoe**, it doesn't look like a Python3's syntax. It's related to the state variables that **Vyper** understands well. The coders of **Vyper** have made their own syntax to force package users to follow their syntax to work with the package so that they could work with the package nicely. You check http://viper.readthedocs.io/en/latest/structure-of-a-contract.html#structure-state-variables and read more about defining state variables
type: Comment
type: QuestionComment

deep-learning
tags question: http://stackoverflow.com/q/50539277
tags question: http://stackoverflow.com/q/50454988
tags question: http://stackoverflow.com/q/50396739
tags question: http://stackoverflow.com/q/50508816
tags question: http://stackoverflow.com/q/50495161
tags question: http://stackoverflow.com/q/50393828
tags question: http://stackoverflow.com/q/50517225
tags question: http://stackoverflow.com/q/50493836
tags question: http://stackoverflow.com/q/50488410
type: Tag
tags question: http://stackoverflow.com/q/50438738
tags question: http://stackoverflow.com/q/50479335
tags question: http://stackoverflow.com/q/50399495
tags question: http://stackoverflow.com/q/50440696
tags question: http://stackoverflow.com/q/50426349
tags question: http://stackoverflow.com/q/50452476
tags question: http://stackoverflow.com/q/50539641
tags question: http://stackoverflow.com/q/50414900
tags question: http://stackoverflow.com/q/50434710
tags question: http://stackoverflow.com/q/50437670
tags question: http://stackoverflow.com/q/50420359
tags question: http://stackoverflow.com/q/50417088
tags question: http://stackoverflow.com/q/50410799
tags question: http://stackoverflow.com/q/50405987
tags question: http://stackoverflow.com/q/50458412
tags question: http://stackoverflow.com/q/50518591
tags question: http://stackoverflow.com/q/50393014
tags question: http://stackoverflow.com/q/50495878
tags question: http://stackoverflow.com/q/50441741
tag name: deep-learning
tags question: http://stackoverflow.com/q/50435336
tags question: http://stackoverflow.com/q/50518758
tags question: http://stackoverflow.com/q/50455088
tags question: http://stackoverflow.com/q/50511212
tags question: http://stackoverflow.com/q/50513422
tags question: http://stackoverflow.com/q/50392211
tags question: http://stackoverflow.com/q/50518926
tags question: http://stackoverflow.com/q/50498755
tags question: http://stackoverflow.com/q/50458964
tags question: http://stackoverflow.com/q/50405655
tags question: http://stackoverflow.com/q/50507165

http://stackoverflow.com/q/50493836
type: AnsweredQuestion
score: 0
tagged with: deep-learning
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50536167
accepted answer: http://stackoverflow.com/a/50536167
type: Question
has title: TensorFlow: run in parallel several versions of a Python script calling TF
answer count: 1
tagged with: python
has body: I am refining a Python script that implements DQN algorithm based on Keras + TensorFlow. It is a very empirical and trial-and-error process, so I would like to run the script in background, and in the meantime tweak some hyperparameters within the code and run that second version in parallel. If I try to do that now, I receive an error because the GPU is being used. I am using a server via SSH with an Intel Xeon and a single NVIDIA GeForce GTX 780 GPU. Is that possible? How?

http://stackoverflow.com/a/50468961
upvote count: 1
score: 1
has body: Use a zip and list unpacking: &gt;&gt;&gt; [x*y*z for x, y, z in zip(*A)]
type: Answer
answers question: http://stackoverflow.com/q/50468792
downvote count: 0

http://stackoverflow.com/q/50396833
type: Question
accepted answer: http://stackoverflow.com/a/50400934
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50400934
has title: Use TextFSM to find allowed VLANs on trunk
has body: I'm trying to set up a TextFSM template for NTC ansible which will only pull the Vlans allowed on the trunk from the output of a "show interface trunk" command and can't seem to get what I want. It is giving me all the lines instead of just the single line that I want. The output of the command looks like this: switch#sh int g9/17 trunk Port Mode Encapsulation Status Native vlan Gi9/17 on 802.1q trunking 1 Port Vlans allowed on trunk Gi9/17 501,503,513,540,950-957 Port Vlans allowed and active in management domain Gi9/17 501,503,513,540,950-957 Port Vlans in spanning tree forwarding state and not pruned Gi9/17 501,503,513,540,950-957 In this output, I only want to return the line below "Vlans allowed on trunk" and not the other repeat lines that have the same info. My template looks like this: Value PORT (\S+) Value VLANS (.*) Start ^Port.*Vlans allowed on trunk -&gt; Begin Begin ^(?=\s{0,9}${PORT})\s+${VLANS} -&gt; Record ^Port.*Vlans allowed and active in management domain -&gt; End
tagged with: ansible
type: AnsweredQuestion
score: 0
tagged with: python-textfsm
answer count: 1
tagged with: text-parsing

http://stackoverflow.com/comment/87896238
has text: Now I'm using a way to solve this conflict, in my view I use: relative_news = News.objects.filter(tag__id__in=news.tag.all()).exclude(id=news_pk) and in the template I use slice filter : |slice:":6" it works.I'm wondering is any other way can solve the 'Cannot filter a query once a slice has been taken.'
type: AnswerComment
comment on: http://stackoverflow.com/a/50431825
score: 0
type: Comment

http://stackoverflow.com/comment/87849154
comment on: http://stackoverflow.com/q/50416753
score: 1
type: Comment
type: QuestionComment
has text: Why are you using the system python?

http://stackoverflow.com/q/50511942
tagged with: flask
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50516218
answer count: 1
tagged with: web
has title: Send and receive images using Flask
has answer: http://stackoverflow.com/a/50516218
has body: Currently I support sending 1 image per request like so: img_b64 = fileToB64(img) return { 'base64': [{ 'name': 'img', 'contentType': 'image/png' }], 'img': img_b64 } But I need to implement new feature than enables to send any number of images (usually 1 but max 4 images) per request. Is there an easy way to send list of images? Sth like this: img_b64s = [fileToB64(img) for img in images] return { 'base64': [{ 'name': 'img', 'contentType': 'image/png' }], 'imgs': img_b64s }
downvote count: 1
tagged with: http
favorite count: 0
type: Question
upvote count: 0
tagged with: python
score: -1

http://stackoverflow.com/comment/88050148
has text: You might want to take a look at a recurrent neural network if you want to be feeding outputs of your neural network back into itself: https://en.wikipedia.org/wiki/Recurrent_neural_network
score: 0
comment on: http://stackoverflow.com/q/50518563
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50541050
accepted answer of: http://stackoverflow.com/q/50540460
has comment: http://stackoverflow.com/comment/88095633
has body: Use filter to remove all empty elements from list. Ex: o_T = filter(None, o_t.split('T - ')) print (o_T) o_A = filter(None, o_a.split('A - ')) print (o_A) Output: ['Python and Matplotlib Essentials for Scientists and Engineers'] ['Wood, M.A.']
answers question: http://stackoverflow.com/q/50540460
upvote count: 2
downvote count: 0
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/88125479
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50521364
has text: No. The strings in my dataset differ, but they mainly contain 4 letters. They are interspersed with the timestamps and aren't in any reoccurring order. So I can't just apply the function to every n row. That's why it's different from the other question.
type: QuestionComment

shopify
tag name: shopify
tags question: http://stackoverflow.com/q/50487360
type: Tag
tags question: http://stackoverflow.com/q/50519590

conda
tags question: http://stackoverflow.com/q/50535911
tags question: http://stackoverflow.com/q/50431294
tags question: http://stackoverflow.com/q/50518622
tags question: http://stackoverflow.com/q/50476501
tag name: conda
tags question: http://stackoverflow.com/q/50454804
tags question: http://stackoverflow.com/q/50469796
tags question: http://stackoverflow.com/q/50395044
tags question: http://stackoverflow.com/q/50537131
tags question: http://stackoverflow.com/q/50519802
type: Tag
tags question: http://stackoverflow.com/q/50391766
tags question: http://stackoverflow.com/q/50453529
tags question: http://stackoverflow.com/q/50411931

http://stackoverflow.com/comment/117767905
has text: I think I was asking quite a different question, regarding implicit behavior on `torch` (which can be roughly described as "what would happen if no explicit call to `torch.set_default_tensor_type()` is done" but I'm not even sure whether this API exists in <0.4.
comment on: http://stackoverflow.com/q/50495053
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87791813
type: QuestionComment
has text: java version "10.0.1" 2018-04-17 Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10) Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)
comment on: http://stackoverflow.com/q/50387354
score: 0
type: Comment

http://stackoverflow.com/comment/88047127
type: Comment
score: 0
has text: Would the fact that the modules to be imported are in a sub-directory? I chdir to the folder and try this, but get ImportError: No module named <filename>
type: AnswerComment
comment on: http://stackoverflow.com/a/50515907

http://stackoverflow.com/q/50502148
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88017187
has body: Using a dummy file (streamt.txt) with the following contents: andrew I hate mondays. fred Python is cool. fred Ko Ko Bop Ko Ko Bop Ko Ko Bop for ever andrew @fred no it isn't, what do you think @john??? judy @fred enough with the k-pop judy RT @fred Python is cool. andrew RT @judy @fred enough with the k pop george RT @fred Python is cool. andrew DM @john Oops john DM @andrew Who are you go away! Do you know him, @judy? The first word of each line represents a user and the rest of the line is a message, similar to twitter. I need to print a list of the top n (entered by user) original posting users (most messages) next to the number of messages they sent. This doesn't include any message with 'RT' at the start. Formatted in justified columns in lexicographic order in the case of ties. As it stands, my code only finds the most used words in the messages and it doesn't exclude RT and DM messages or account for n: file=open('streamt.txt') counts=dict() for line in file: words=line.split() for word in words: counts[word]=counts.get(word, 0)+1 lst=list() for key,value in counts.items(): new=(value, key) lst.append(new) lst=sorted (lst, reverse=True) for value, key in lst[:10]: print(value,key) This is my output: 6 Ko 5 @fred 4 andrew 3 you 3 is 3 cool. 3 RT 3 Python 3 Bop 2 with The actual output should be: Enter n: 10 3 andrew 2 fred 1 john judy Any ideas as to how I should do this?
has answer: http://stackoverflow.com/a/50502271
has answer: http://stackoverflow.com/a/50502647
has answer: http://stackoverflow.com/a/50502351
possible better answer: http://stackoverflow.com/a/50502351
downvote count: 2
tagged with: file
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88017796
has comment: http://stackoverflow.com/comment/88016762
accepted answer: http://stackoverflow.com/a/50502647
upvote count: 2
has answer: http://stackoverflow.com/a/50510365
answer count: 5
has comment: http://stackoverflow.com/comment/88017091
tagged with: count
tagged with: python
has title: Counting the number of times the first word in a line appears when read from file with exceptions
has answer: http://stackoverflow.com/a/50502859
tagged with: dictionary

http://stackoverflow.com/a/50466099
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50465705
type: Answer
downvote count: 0
has body: This is one solution using str.split and a try / except clause to capture instances where only a key exists. Note io.StringIO lets us read from a string as if it were a file. from io import StringIO import csv mystr = StringIO("""andrew fred fred judy andrew fred george judy andrew john george""") # replace mystr with open("C:\\Users\\zacan\\Desktop\\Python\\follows.txt") with mystr as follows_file: d = {} for users in csv.reader(follows_file): try: key, *value = users[0].split() except ValueError: key, value = users[0], [] d[key] = value print(d) {'andrew': ['fred'], 'fred': [], 'george': ['judy', 'andrew'], 'john': ['george'], 'judy': ['andrew', 'fred']}

http://stackoverflow.com/comment/87844958
score: 0
type: Comment
type: QuestionComment
has text: I edited my answer with an efficient solution without the loop.
comment on: http://stackoverflow.com/q/50395296

greatest-n-per-group
tag name: greatest-n-per-group
tags question: http://stackoverflow.com/q/50434115
type: Tag

http://stackoverflow.com/q/50489604
has comment: http://stackoverflow.com/comment/87992110
has body: I have a huge dataset of images and I am processing them one by one. All the images are stored in a folder. My Approach: What I have tried is that I have tried reading all the filenames in memory and whenever a call for a certain index is sent, I load the corresponding image. The problem is that it is even not possible to keep the paths and the names of the files in memory due to the huge dataset. Is it possible to have an indexed file on storage and one is able to read a file name at a certain index. Thanks a lot.
has comment: http://stackoverflow.com/comment/87992838
has comment: http://stackoverflow.com/comment/87993094
type: Question
has comment: http://stackoverflow.com/comment/87993011
tagged with: python-3.x
has title: how to have indexed files in storage in python
has comment: http://stackoverflow.com/comment/87992358
has comment: http://stackoverflow.com/comment/87992416
has comment: http://stackoverflow.com/comment/87992760
tagged with: out-of-memory
type: UnansweredQuestion
tagged with: python
tagged with: indexing
score: 0
answer count: 0

http://stackoverflow.com/comment/88058713
type: AnswerComment
has text: Thank u for ur answer. Using this I was able to plot the graph. I converted this date to pd.Timestamp, and from their to POSIX timestamp before I could use the tutorials dateconv method. However, still I didn't get the plot as shown in the tutorial (my garph is not continuing for holidays (it is omitting holidays)). I know that is a totally different question but any help on it would be great.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50523016

http://stackoverflow.com/q/50513580
score: 3
tagged with: python-import
upvote count: 3
has body: I've found that IPython and python handle the loading of local modules differently and I wonder if someone could explain why this happens. Suppose that my project is structured as: top_level/ src/ a.py b.py __init__.py The contents of b.py are: from src.a import foo foo() and then a.py has a function foo: def foo(): print('It worked!') File __init__.py is blank. If I call ipython and python from top_level I get two different result: Why does one work and not the other? Is it possible to make python handle similar to IPython or is there a more pythonic way to handle cases like this? Version Info: Python: 3.6.3 IPython: 6.1.0 (with 3.6.3 Python) Edit to explain difference with "How do I import a local module?" This question is about differences between how IPython and Python handle local module imports, not how to import a local module. I should also add that - while it is true that my example would work if I changed the import statement to from a import foo - I was (implicitly) trying to avoid doing this. I like the idea of importing everything relative to some top-level directory in order to make it easier if the structure of the files change. For example, if b.py was moved from src to some sub-directory src/core then you'd need to go through and rewrite all of the imports relative to the new location of b.py.
downvote count: 0
has title: Importing local modules in python v. IPython
answer count: 1
has answer: http://stackoverflow.com/a/50514401
tagged with: import
has comment: http://stackoverflow.com/comment/88041437
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88041759
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2349991
tagged with: python
has comment: http://stackoverflow.com/comment/88040125

http://stackoverflow.com/q/50414300
upvote count: 3
has answer: http://stackoverflow.com/a/50415040
has answer: http://stackoverflow.com/a/50414548
has answer: http://stackoverflow.com/a/50414934
downvote count: 0
has comment: http://stackoverflow.com/comment/87844776
has body: I have a dataframe with a very large number of columns (>30000). I'm filling it with 1 and 0 based on the first column like this: for column in list_of_column_names: df = df.withColumn(column, when(array_contains(df['list_column'], column), 1).otherwise(0)) However this process takes a lot of time. Is there a way to do this more efficiently? Something tells me that column processing can be parallelized. Edit: Sample input data +----------------+-----+-----+-----+ | list_column | Foo | Bar | Baz | +----------------+-----+-----+-----+ | ['Foo', 'Bak'] | | | | | ['Bar', Baz'] | | | | | ['Foo'] | | | | +----------------+-----+-----+-----+
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: apache-spark-sql
answer count: 3
tagged with: apache-spark
has title: Efficient column processing in PySpark
has comment: http://stackoverflow.com/comment/87845685
tagged with: pyspark
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/87844492
possible better answer: http://stackoverflow.com/a/50414548
accepted answer: http://stackoverflow.com/a/50414934

http://stackoverflow.com/comment/87920116
comment on: http://stackoverflow.com/a/50442356
type: AnswerComment
has text: hank you men you saved me from a hurry
score: 0
type: Comment

http://stackoverflow.com/a/50452393
score: 0
has comment: http://stackoverflow.com/comment/87918072
has comment: http://stackoverflow.com/comment/87947165
answers question: http://stackoverflow.com/q/50452300
type: Answer
has comment: http://stackoverflow.com/comment/87932740
has comment: http://stackoverflow.com/comment/87918122
has body: use sklearn.feature_extraction.text.CountVectorizer. Demo: In [192]: from sklearn.feature_extraction.text import CountVectorizer In [193]: cv = CountVectorizer(token_pattern='(?u)\\b\\w+\\b', vocabulary=list('abcd')) In [194]: X = cv.fit_transform(df['col1']) In [195]: X Out[195]: &lt;3x4 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 5 stored elements in Compressed Sparse Row format&gt; In [196]: X.A Out[196]: array([[1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 0, 1]], dtype=int64) In [197]: cv.get_feature_names() Out[197]: ['a', 'b', 'c', 'd'] if we don't use vocabulary - we will get one column for each unique word: In [203]: cv = CountVectorizer(token_pattern='(?u)\\b\\w+\\b') In [204]: X = cv.fit_transform(df['col1']) In [205]: X.A Out[205]: array([[1, 0, 1, 0, 1, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 1, 1, 0, 0, 1, 0, 1]], dtype=int64) In [206]: cv.get_feature_names() Out[206]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'p', 'x'] Source DF: In [191]: df Out[191]: col1 0 a, c, e, f 1 b, c, g, p 2 d, e, i, x

jupyter
tags question: http://stackoverflow.com/q/50523950
type: Tag
tags question: http://stackoverflow.com/q/50409078
tags question: http://stackoverflow.com/q/50396359
tags question: http://stackoverflow.com/q/50483041
tags question: http://stackoverflow.com/q/50437329
tags question: http://stackoverflow.com/q/50431978
tags question: http://stackoverflow.com/q/50497374
tags question: http://stackoverflow.com/q/50440947
tags question: http://stackoverflow.com/q/50484397
tags question: http://stackoverflow.com/q/50456390
tags question: http://stackoverflow.com/q/50387532
tags question: http://stackoverflow.com/q/50439371
tags question: http://stackoverflow.com/q/50470234
tags question: http://stackoverflow.com/q/50439035
tag name: jupyter

http://stackoverflow.com/comment/87989292
type: AnswerComment
has text: I got it I was just encoding the tuple value. I didn't check carefully
comment on: http://stackoverflow.com/a/50488153
type: Comment
score: 0

http://stackoverflow.com/a/50433059
type: Answer
answers question: http://stackoverflow.com/q/50432927
accepted answer of: http://stackoverflow.com/q/50432927
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Since you have asked about an alternative approach. instead of an explicit loop in python and filling a list, one should rather use DataFrame methods directly. In your case this would be df['time'].apply(lambda x: x if len(x) != 5 else '2018-'+x) This might run faster for some datasets EDIT I actually ran a timing benchmark using a random toy dataset with ~50% of complete and incomplete dates. In short, it seems that for a small dataset the simple for-loop solution is faster for a large dataset both methods show similar performance: # 1M examples import random import numpy as np y = pd.Series(np.random.randint(0,2,1000000)) s = {0:'2015-07-08', 1:'05-11'} y = y.map(s) %%timeit -n100 _ = y.apply(lambda x: x if len(x) != 5 else '2018-'+x) &gt;&gt;&gt; 275 ms ± 6.42 ms per loop (mean ± std. dev. of 7 runs, 100 loops each) %%timeit -n100 con_time = [] for i in y: if len(i)==5: time = '2018-'+i con_time.append(time) else: con_time.append(i) con_time_a = np.array(con_time) &gt;&gt;&gt; 289 ms ± 5.23 ms per loop (mean ± std. dev. of 7 runs, 100 loops each) # 1K examples import random import numpy as np y = pd.Series(np.random.randint(0,2,1000)) s = {0:'2015-07-08', 1:'05-11'} y = y.map(s) %%timeit -n100 _ = y.apply(lambda x: x if len(x) != 5 else '2018-'+x) &gt;&gt;&gt; 431 µs ± 70.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %%timeit -n100 con_time = [] for i in y: if len(i)==5: time = '2018-'+i con_time.append(time) else: con_time.append(i) con_time_a = np.array(con_time) &gt;&gt;&gt; 289 µs ± 40.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
score: 3

http://stackoverflow.com/a/50524529
answers question: http://stackoverflow.com/q/50523421
has comment: http://stackoverflow.com/comment/88061251
has comment: http://stackoverflow.com/comment/88090035
has comment: http://stackoverflow.com/comment/88237867
type: Answer
has body: Might be worth a try from an AI constraint satisfaction perspective. If you count up how many things a set excludes, and how many sets exclude that set, you can start from least-constrained and work up. For your example above (right axis is how many things that set excludes, bottom axis is how many things exclude that set) 0 1 2 3 4 5 6 7 8 9 0: 1 1 1 1 1 1 0 1 0 1 | 2 1: 1 1 1 0 1 1 1 1 0 0 | 3 2: 1 1 1 1 1 0 0 0 1 1 | 3 3: 0 1 0 1 1 1 1 1 1 1 | 2 4: 0 1 1 1 1 1 1 0 0 0 | 4 5: 0 0 0 1 1 1 1 1 1 1 | 3 6: 0 1 1 1 0 1 1 0 1 1 | 3 7: 0 0 1 1 1 1 1 1 1 0 | 3 8: 0 0 1 0 0 1 1 1 1 1 | 4 9: 0 0 0 1 1 0 1 1 1 1 | 4 - - - - - - - - - - 7 4 3 2 2 2 3 2 3 3 Constraint sums: 0 = 9 1 = 7 2 = 6 3 = 4 4 = 6 5 = 5 6 = 6 7 = 5 8 = 7 9 = 7 So, now that you've worked out your constraints: Starting with your least-constrained set: 3 3 wipes out 0, 2, 8 Add one of your next least-constrained still valid: 5 5 wipes out 1, 9, 2 Add your next least-constrained still valid: 7 7 wipes out 4 and 6 No more valid ones You're left with a group of: 3, 5, 7
score: 0

apache-spark-sql
tags question: http://stackoverflow.com/q/50398598
tags question: http://stackoverflow.com/q/50442803
tags question: http://stackoverflow.com/q/50457079
tags question: http://stackoverflow.com/q/50467121
tags question: http://stackoverflow.com/q/50482720
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/50527953
tags question: http://stackoverflow.com/q/50496361
tags question: http://stackoverflow.com/q/50475847
tags question: http://stackoverflow.com/q/50456449
tags question: http://stackoverflow.com/q/50454850
tags question: http://stackoverflow.com/q/50508838
tags question: http://stackoverflow.com/q/50465399
type: Tag
tags question: http://stackoverflow.com/q/50414300

http://stackoverflow.com/a/50494409
has body: I had this same question at the weekend. I came across two things: a) this project on Github: https://github.com/jendas1/jupyter-notebook-quick-look and b) The Jupyter app which allows you to open Notebooks in Finder on the mac: https://github.com/jendas1/JupyterApp Caveat - I book marked these, but due to other work I have not had time to download, install or test these. If you do, please let me know how you get on!
answers question: http://stackoverflow.com/q/50494230
downvote count: 0
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/comment/88036264
type: AnswerComment
score: 0
has text: Thanks for your answer.
type: Comment
comment on: http://stackoverflow.com/a/50511481

http://stackoverflow.com/a/50403727
has body: You need to install wxPython2.8-win32-unicode-2.8.12.1-py27.exe (32 bit version) . Don't forget remove your old one . wxPython2.8-win32-unicode-2.8.12.1-py27.exe
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50389653
has comment: http://stackoverflow.com/comment/87836004
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87855846
type: AnswerComment
has text: Depending on how he's got that set up he may also be selecting the parents of the joints he wants
type: Comment
comment on: http://stackoverflow.com/a/50409719
score: 0

http://stackoverflow.com/a/50447382
downvote count: 0
has body: Using the fact that dicts preserve the insertion order of their keys (which will become part of the specification in Python 3.7 but is already true in 3.6) this can be done in one short line: # create some data &gt;&gt;&gt; import random &gt;&gt;&gt; a = [random.randint(0, 3) for _ in range(20)] &gt;&gt;&gt; b = [random.randint(0, 3) for _ in range(20)] &gt;&gt;&gt; &gt;&gt;&gt; a [0, 3, 2, 1, 2, 0, 1, 2, 0, 2, 1, 1, 0, 3, 1, 3, 1, 2, 3, 2] &gt;&gt;&gt; b [1, 0, 3, 2, 2, 2, 2, 3, 1, 2, 1, 1, 1, 1, 3, 0, 0, 0, 3, 3] &gt;&gt;&gt; # this one line is all we need &gt;&gt;&gt; au, bu = zip(*dict.fromkeys(zip(a, b))) &gt;&gt;&gt; # admire &gt;&gt;&gt; au (0, 3, 2, 1, 2, 0, 1, 3, 1, 1, 2, 3) &gt;&gt;&gt; bu (1, 0, 3, 2, 2, 2, 1, 1, 3, 0, 0, 3) Note that contrary to what one might expect this doesn't work with sets---one really has to use a dict (with dummy values).
upvote count: 1
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50446907

http://stackoverflow.com/q/50447652
tagged with: odoo-9
has comment: http://stackoverflow.com/comment/87911310
tagged with: python
has title: How to add field in "stock.quant.tree"
has comment: http://stackoverflow.com/comment/87911675
type: Question
upvote count: 2
score: 2
has body: I'm using odoo 9 and i want to add a custom field in stock.quant named "designation2" which I use odoo 9 and I want to add a custom field in "stock.quant" which takes as value the product description entered when creating the price request and purchase order ? I have created a new custom module and i added a new field in stock.quant but i don't know how to get the value of the product description ?? Any help please ? stock_quant_tree.xml <?xml version="1.0" encoding="utf-8"?> stock.quant.tree.designation stock.quant stock.py from openerp.osv import fields, osv from openerp import tools import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ class StockQuantTreeDesignation(osv.osv): _inherit = 'stock.quant' _columns = { 'designation2':fields.char( string="Désignation",required=True,select=True), }
downvote count: 0
has comment: http://stackoverflow.com/comment/87910678
has comment: http://stackoverflow.com/comment/87910474
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87910689
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87910730
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50465556
has comment: http://stackoverflow.com/comment/87910976

http://stackoverflow.com/q/50441663
type: AnsweredQuestion
has title: Django - add widget option in form.py Meta class?
answer count: 2
score: 2
downvote count: 0
tagged with: django-forms
favorite count: 0
type: Question
has body: models.py from django.db import models class user(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) forms.py from django import forms from second_app.models import user class NewUserForm(forms.ModelForm): class Meta: model = user fields = '__all__' In a normal forms.py that doesn't inherit from the models, you can use field = forms.CharField(widget=forms.HiddenInput) to specify how the input field will be displayed to the users. How can this be done, when my forms.py is inheriting the class defined in models.py?
upvote count: 2
tagged with: django
tagged with: django-models
possible better answer: http://stackoverflow.com/a/50442012
tagged with: python
accepted answer: http://stackoverflow.com/a/50441934
has answer: http://stackoverflow.com/a/50442012
has answer: http://stackoverflow.com/a/50441934

http://stackoverflow.com/comment/88011977
comment on: http://stackoverflow.com/a/50499626
type: Comment
type: AnswerComment
score: 2
has text: Fortunately there aren't any (10 uses "T" instead).

http://stackoverflow.com/comment/87863158
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50423907
has text: This code is around 25 times faster than what I did in the OP

http://stackoverflow.com/comment/88076900
comment on: http://stackoverflow.com/q/50532478
type: QuestionComment
has text: Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)
score: 3
type: Comment

http://stackoverflow.com/comment/88185590
type: AnswerComment
has text: @elkshadow5 the docs say that “The current file position is not changed” That’s the clue that lead me to see you needed to manually seek instead. I’m not sure entirely why it’s not part of the operation but there must be some use case.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50537305

http://stackoverflow.com/comment/87833038
comment on: http://stackoverflow.com/q/50408763
has text: Have you rad the [documentation](https://docs.python.org/3/howto/unicode.html#encodings)? and https://docs.python.org/3.6/c-api/buffer.html#bufferobjects
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/87854067
comment on: http://stackoverflow.com/a/50413240
type: Comment
type: AnswerComment
has text: You're right, my code indeed has some errors. I left out some bits and pieces that were irrelevant, and did not test what I posted here. Apparently I made an oversight. I ended up going with numpy's linear interpolation. Linear interpolation is good enough for my purpose, and I need every data point to have a value. I think numpy's approach of returning a list of slices instead of a list of indices is in some cases a bit unwieldy. On the other hand, if your slice is very big, a list of indices isn't what you want either. Anyways, I learned something today. Thanks!
score: 0

http://stackoverflow.com/comment/87874328
type: AnswerComment
has text: @user2285236 You've convinced me. I like your answer more.
type: Comment
comment on: http://stackoverflow.com/a/50427426
score: 0

http://stackoverflow.com/q/50402373
tagged with: numbers
answer count: 2
possible better answer: http://stackoverflow.com/a/50402396
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/50402483
score: -6
downvote count: 7
favorite count: 0
tagged with: python-3.x
tagged with: digits
type: AnsweredQuestion
has title: How can a Python string be a digit?
has body: I was under the impression that numbers in double-quotation marks become strings. Why did I get the following result? "2001".isdigit() True
has comment: http://stackoverflow.com/comment/87820695
has answer: http://stackoverflow.com/a/50402396
accepted answer: http://stackoverflow.com/a/50402483
has comment: http://stackoverflow.com/comment/87820477
tagged with: python
type: Question

http://stackoverflow.com/comment/88053340
type: QuestionComment
has text: @Kas, Show HTML code in screenshot is a bad practice, Please add them in your question as text content.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50519769

http://stackoverflow.com/comment/88023752
type: Comment
has text: Not getting what you want to achieve, do you want to show the status of processing to user on definite intervals?
score: 0
comment on: http://stackoverflow.com/q/50505628
type: QuestionComment

http://stackoverflow.com/comment/87868552
comment on: http://stackoverflow.com/q/50426238
type: QuestionComment
has text: `loadtxt` (and `genfromtxt`) reads the file, line by line, and collects the split strings in a list of lists. The arrays constructed once at the end.
score: 0
type: Comment

http://stackoverflow.com/comment/87871050
score: 0
comment on: http://stackoverflow.com/q/50428119
type: Comment
type: QuestionComment
has text: In Oracle it can be done by using "CONNECT BY" operator. I need to achieve the same in python. I need to tell an employees manager, his manager and so on.... separated by "/" in front of all employees.

http://stackoverflow.com/q/50446907
type: Question
has answer: http://stackoverflow.com/a/50447059
has answer: http://stackoverflow.com/a/50447382
has body: I have a function that has to check for duplication in two lists simultaneously. One list has x values and another has y values for a cartesian system. A single coordinate can't be repeated. Currently my code looks like this: for q in range(0, len(prows)-1, 1): for w in range(0, len(prows)-1, 1): if prows[q] == prows[w] and pcols[q] == prows[w]: prows.remove(prows[w]) pcols.remove(pcols[w]) Where prows are y values and pcols are x values. This works, the problem is that my first for loop only updates the length of prows after the second for loop has cycled through all its values. Because of this I get an indexing error, the first for loop still has the original length prows while the second for loop has the newer length with the removed duplication.
tagged with: python
tagged with: indexing
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
tagged with: loops
accepted answer: http://stackoverflow.com/a/50447059
possible better answer: http://stackoverflow.com/a/50447382
has title: Multiple List duplication removal in for loops

http://stackoverflow.com/q/50485559
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87984910
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50485873
has title: How to make a function to find duplicacy in a character string?
has answer: http://stackoverflow.com/a/50486603
has answer: http://stackoverflow.com/a/50485956
has comment: http://stackoverflow.com/comment/87987971
has comment: http://stackoverflow.com/comment/88007387
answer count: 7
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50486172
has comment: http://stackoverflow.com/comment/87984444
accepted answer: http://stackoverflow.com/a/50485947
type: Question
upvote count: 2
tagged with: algorithm
has answer: http://stackoverflow.com/a/50485947
has body: Here is the code I have written to find duplicate characters and then replace them by ')' and original characters by '(' in a string and it should ignore capitalization. def duplicate_finder(word): word1 = word.lower(); w = list(word1); w1 = ''; for i in range(0, len(word1)): if ([v in word1.replace(w[i], '') for v in w[i]]==[True]): w1 += ')'; else: w1 += '('; return (w1) But this function always returns me '((((((...((' [till the number of characters in the input string]. Can someone please point me the fault in my code!!! Thanks in advance.
has answer: http://stackoverflow.com/a/50487575
downvote count: 0
has answer: http://stackoverflow.com/a/50490226
tagged with: python
has answer: http://stackoverflow.com/a/50485873
has comment: http://stackoverflow.com/comment/88007664
has comment: http://stackoverflow.com/comment/87984129

http://stackoverflow.com/comment/87792362
comment on: http://stackoverflow.com/a/50388104
has text: Super weird. I can't believe PyCharm lies to me like that. If it was executing the command that it said it would it should have worked, shouldn't it. Anyway - this actually solved the problem. Thanks!
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50422077
has comment: http://stackoverflow.com/comment/87859752
score: 0
has comment: http://stackoverflow.com/comment/87859269
upvote count: 1
downvote count: 1
tagged with: python
has body: Define the get_triples_dict() function which is passed a string of text as a parameter. The function first converts the parameter string to lower case and then returns a dictionary with keys which are all the unique consecutive three alphabetic characters from the text, and the corresponding values are the number of times the three consecutive alphabetic characters appear in the text. Use the isalpha() method to check if a character is alphabetic or not. The dictionary should only contain entries which occur more than once. After your dictionary has been created and populated, you need to remove any key-value pairs which have a corresponding value of 1. I need help with coding this get_triples_dict function: def get_triples_dict(text): def test_get_triples_dict(): print("1.") print_dict_in_key_order(get_triples_dict('super, duper')) print("\n2.") print_dict_in_key_order(get_triples_dict("ABC ABC ABC")) print("\n3.") print_dict_in_key_order(get_triples_dict("Sometimes the smallest things make more room in your heart")) print("\n4.") print_dict_in_key_order(get_triples_dict("My favourite painting is the painting i did of my dog in that painting in my den"))
has answer: http://stackoverflow.com/a/50422650
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87859775
has title: Getting triplet characters from strings

http://stackoverflow.com/comment/87958849
type: QuestionComment
comment on: http://stackoverflow.com/q/50456362
score: 0
has text: eminent is not clickable at point (305, 587). Other element would receive the click
type: Comment

http://stackoverflow.com/a/78401815
type: Answer
answers question: http://stackoverflow.com/q/50415666
downvote count: 0
upvote count: 1
has body: I would recommend this method: def log_function(logger: Logger): def logger_wrapper(func): @wraps(func) def inner(*args, **kwargs): logger.info(f"Called {func.__name__}({args}, {kwargs})") func(*args, **kwargs) return inner return logger_wrapper You can use it like @log_function(logger=getLogger()) def foo(val): print(val/2) This allows you to configure your logger if you need to.
score: 1

http://stackoverflow.com/comment/87875913
type: QuestionComment
comment on: http://stackoverflow.com/q/50389613
has text: Can you try `%autoreload` after removing `from . import world` from your `__init__.py`? I suspect your `__init__.py` is telling IPython to import only the `world` function and not others?? The `__init__.py` need not have any content if all you want to do is to declare a folder as a module.
score: 0
type: Comment

http://stackoverflow.com/a/50493721
accepted answer of: http://stackoverflow.com/q/50483687
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Solution This answer is based on discussion in comments section present under the question. The code below is written under an assumption that the scanner sends a specific signal when a barcode is scanned. The overall idea is to run a function after that signal was sent. Clock cycle I suggest getting familiar with kivy's Clock object. It is possible to create a listener function that would check if the signal was sent every n seconds. Precisely, let's say you want to run process() function once a signal was detected. Let's also declare a variable scanned to store information if a barcode was succesfully scanned and create a listener to check if the signal was sent (so check if the scanned variable holds True). Following code sample sets the scanned variable every 2 seconds to True to mimic the scanning behaviour. from kivy.app import App from kivy.clock import Clock from kivy.uix.button import Button from kivy.uix.screenmanager import Screen # Define constants and the scanned variable, for easy example INTERVAL = 0.01 scanned = False # Process method runs every 0.01 seconds, note the use of dt argument (explained in docs) def process(dt): # Retrieve the global variable, for easy example global scanned # Check if scanned, note setting scanned to False once an item was scanned. # Here you can also check the uniqueness of the scanned barcode (to avoid having the same barcode processed many times) if scanned is True: print("Scanned! Processing the data and setting scanned to False.") scanned = False else: print("Not scanned yet!") # Mimic scanning behaviour def scan(dt): # Retrieve the global variable and set it to true global scanned scanned = True class Main(App): def __init__(self): super(Main, self).__init__() # Schedule the functions to be called every n seconds Clock.schedule_interval(process, INTERVAL) Clock.schedule_interval(scan, INTERVAL*200) def build(self): # Display screen with a single button for easy example scr = Screen() btn = Button(text="You can press…
upvote count: 1
has comment: http://stackoverflow.com/comment/88023471
has comment: http://stackoverflow.com/comment/88001648
has comment: http://stackoverflow.com/comment/88016007
has comment: http://stackoverflow.com/comment/88001565
has comment: http://stackoverflow.com/comment/88001841
type: Answer
has comment: http://stackoverflow.com/comment/88001001
has comment: http://stackoverflow.com/comment/88001274
answers question: http://stackoverflow.com/q/50483687

http://stackoverflow.com/comment/88027656
has text: I'm running pandas 0.22.0 through Anaconda/jupyter lab. But it's specifically weird because I made another example where it did work and then I implemented in the mainframe and it didn't.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50506610
type: Comment

http://stackoverflow.com/a/50403537
score: 1
has body: .+ should be non-greedy, add a ? after them. result = re.findall( "Date.+?Cent", daily_forecast_text, flags=re.DOTALL)
type: Answer
answers question: http://stackoverflow.com/q/50403483
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50480556
has comment: http://stackoverflow.com/comment/87976349
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87976950
tagged with: javascript
has title: How to determine post request inputs using javascript
has body: I am trying to login to a website using python but not having much success. Whenever I post my credentials, I get a 200 response but I'm redirected to the login screen. I think this is because the website's login is using javascript that requires more than just a username and password in the post command, but I'm not sure how to parse it to fix my login code. This is my python code: s = requests.session() login_url = "example.com" result = s.get(login_url) payload = { "user_login": "xx", "user_pass": "xx" } print(payload) postresult = s.post( login_url, data = payload, allow_redirects=True ) Here's what the input form looks like: Email: Password: Forgot Password And here's part of the javascript code that's executing: function init_login(){ var form = document.forms.loginForm; $submit(form,login_request); $listen($('a-fgt'),'click',function(){buildForgotPassword(false);},false); var lgn = getCookie('login'); if(lgn){form.user_login.value = lgn;} form[wordCount(form.user_login.value)?'user_pass':'user_login'].focus(); formVal = new FormValidator(form); } /*---\\\ LOGIN FUNCTIONS ///---*/ function login_request(form){ form = validateForm(form, 'user_pass'); $post("/JSMX/admin_login.cfc?method=login",login_response,form); }
type: Question

http://stackoverflow.com/a/50458424
has comment: http://stackoverflow.com/comment/87932285
answers question: http://stackoverflow.com/q/50458342
type: AcceptedAnswer
downvote count: 0
has body: (Updated) last_stock = 10 # You should try another value a = (df.SUM_IN + df.SUM_OUT).cumsum() df["STOCK"] = a - (a.iloc[-1] - last_stock)
has comment: http://stackoverflow.com/comment/87930956
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50458342

http://stackoverflow.com/comment/87834257
has text: Your solution will not sum values of `col1`
type: AnswerComment
comment on: http://stackoverflow.com/a/50409502
score: 0
type: Comment

http://stackoverflow.com/a/50432918
has body: What you want to do is place the sequence into a dictionary not a list. The format for a dictionary is: dictionaryName={ key:value, key1:value1, } So your code could work like this: def preprocess(s): return {word:True for word in s.lower().split()} s1 = 'This is a book' text = preprocess(s1)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50432866

http://stackoverflow.com/comment/87834994
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50407547
has text: No Errors are thrown. Everything runs fine until i try to stop an old python script and use another. I can't get them to stop so i end up running two led patterns at the same time resulting in just flashing lights.

http://stackoverflow.com/comment/87903396
comment on: http://stackoverflow.com/a/50440296
type: Comment
has text: Thank you so much for all the help, it's much appreciated!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88026009
type: QuestionComment
type: Comment
has text: This is most likely an SQL issue, can you post the actual query being ran?
score: 0
comment on: http://stackoverflow.com/q/50506667

http://stackoverflow.com/a/50415858
type: Answer
has comment: http://stackoverflow.com/comment/87847371
score: 0
has body: Dividing the loop.... the randomness is questionable.... Instead go for parallel processing.... Try below said "Joblib" library or any other library if you know for parallel processing.... https://pythonhosted.org/joblib/parallel.html Joblib provides a simple helper class to write parallel for loops using multiprocessing
has comment: http://stackoverflow.com/comment/87847515
has comment: http://stackoverflow.com/comment/87847466
answers question: http://stackoverflow.com/q/50415690

http://stackoverflow.com/q/50487145
has answer: http://stackoverflow.com/a/50488227
tagged with: django-rest-framework
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/50490220
type: Question
has answer: http://stackoverflow.com/a/50490220
tagged with: django
has body: It's possible to change a serializer depth with a GET parameter? For example calling http://localhost:8000/api-auth/?depth=1
tagged with: python
has title: DRF: Pass serializer depth with a GET parameter
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/50488227
upvote count: 2
score: 1

http://stackoverflow.com/comment/88284510
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50461887
type: Comment
has text: Alright. Thank you very very much for your suggestion. I will take care in the future.

http://stackoverflow.com/q/50413481
tagged with: python
has body: We use Django and django-graphene to provide GraphQL API. We have UUID primary keys in models. How to properly deal with it?
tagged with: graphene-python
has answer: http://stackoverflow.com/a/52483423
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: graphql
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/87892322
favorite count: 0
type: Question
score: 1
has title: How to deal with django-graphene with UUID primary keys in django?

http://stackoverflow.com/comment/87923675
score: 0
type: AnswerComment
has text: I tried using gethostbyaddr(adr), but I get an error that says: socket.herror: [Errno 11004] host not found
comment on: http://stackoverflow.com/a/50455080
type: Comment

http://stackoverflow.com/a/50474657
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103599731
has comment: http://stackoverflow.com/comment/112162055
has comment: http://stackoverflow.com/comment/119210200
upvote count: 8
has comment: http://stackoverflow.com/comment/112157300
score: 8
accepted answer of: http://stackoverflow.com/q/50474336
has comment: http://stackoverflow.com/comment/119262191
answers question: http://stackoverflow.com/q/50474336
has body: Not sure if there is a proper way of doing this, but this "gambiarra" may work quite well, it seems. Make a model joining two or more models together in parallel. The only drawback is: you need the same number of input samples when training and predicting them in parallel. How to use two models in parallel with a functional API model: input1 = Input(inputShapeOfModel1) input2 = Input(inputShapeOfModel2) output1 = model1(input1) output2 = model2(input2) #it could be model1 again, using model1 twice in parallel. parallelModel = Model([input1,input2], [output1,output2]) You train and predict with this model, passing parallel input and output data: parallelModel.fit([x_train1, x_train2], [y_train1, y_train2], ...) Working test code: from keras.layers import * from keras.models import Model, Sequential import numpy as np #simulating two "existing" models model1 = Sequential() model2 = Sequential() #creating "existing" model 1 model1.add(Conv2D(10,3,activation='tanh', input_shape=(20,20,3))) model1.add(Flatten()) model1.add(Dense(1,activation='sigmoid')) #creating "existing" model 2 model2.add(Dense(20, input_shape=(2,))) model2.add(Dense(3)) #part containing the proposed answer: joining the two models in parallel inp1 = Input((20,20,3)) inp2 = Input((2,)) out1 = model1(inp1) out2 = model2(inp2) model = Model([inp1,inp2],[out1,out2]) #treat the new model as any other model model.compile(optimizer='adam', loss='mse') #dummy input data x and y, for models 1 and 2 x1 = np.ones((30,20,20,3)) y1 = np.ones((30,1)) x2 = np.ones((30,2)) y2 = np.ones((30,3)) #training the model and predicting model.fit([x1,x2],[y1,y2], epochs = 50) ypred1,ypred2 = model.predict([x1,x2]) print(ypred1.shape) print(ypred2.shape) Advanced solution - Grouping data for speed and matching the amount of samples There is still space for more optimizing, since this approach will synchronize batches between two models. So, if a model is much faster than another, the fast model will adjust to the speed of the…
has comment: http://stackoverflow.com/comment/87963365
type: Answer
has comment: http://stackoverflow.com/comment/87963260
has comment: http://stackoverflow.com/comment/87963380
has comment: http://stackoverflow.com/comment/103537403

http://stackoverflow.com/q/50449453
has answer: http://stackoverflow.com/a/50449691
tagged with: pandas
score: 7
accepted answer: http://stackoverflow.com/a/50449495
downvote count: 0
tagged with: string
upvote count: 7
has answer: http://stackoverflow.com/a/50449495
favorite count: 0
has title: Pandas datetime64 to string
type: Question
possible better answer: http://stackoverflow.com/a/50449691
tagged with: python-3.x
has body: I am converting pandas dataframe column of datetime64 to list and then exporting into single column of csv. In CSV I get values as "[Timestamp('2018-05-20 10:20:00'), Timestamp('2018-05-20 10:30:00')]" How can I convert to string and export to CSV. I would like to have data as below: ['2018-05-20 10:20:00', '2018-05-20 10:30:00']
tagged with: datetime
tagged with: python
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/55472176
score: 1
type: AcceptedAnswer
has body: I had the same problem and turning off debug mode solved it for me: if __name__ == '__main__': app.run_server(debug=False) However, when debug mode was off, the app was reloading upon starting and trying to open the serial port again (when it had already been opened). So I changed use_reloader to False, and it turns out you can keep it in debug mode (or not) like so: if __name__ == '__main__': app.run_server(debug=True, use_reloader=False) I'm not sure how some of the official examples work without disabling reloading but they have other code after the import statements: app = dash.Dash(__name__) server = app.server and a previous commit removed the following line after the preceding two: app.scripts.config.serve_locally = True So that might take care of it in situations when you need reloading (not sure what reloading does anyway), but I haven't tested it enough to understand.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50390506
type: Answer
accepted answer of: http://stackoverflow.com/q/50390506

http://stackoverflow.com/a/50395079
has body: Let's give you a first code to start with. It may answer to your question, but you should learn more to improve it and use it for your final usage: def border(s): dash = "-" print(dash * (len(s) + 4)) print(dash + " " + s + " " + dash) print(dash * (len(s) + 4)) my_string = input("Enter some text: ") border(my_string)
accepted answer of: http://stackoverflow.com/q/50394197
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50394197

http://stackoverflow.com/comment/88029408
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50508759
has text: You made protocol optional. So that's the reason.

http://stackoverflow.com/q/50529984
accepted answer: http://stackoverflow.com/a/50530365
favorite count: 0
type: Question
tagged with: python-3.x
has body: def get_data(batchsize=None): conn = psycopg2.connect('database parameter') cursor = conn.cursor() query = 'select * from table' cursor.execute(query) if not batchsize: result = cursor.fetchall() return result else: while True: result = cursor.fetchmany(batchsize) if not result: break yield result if __name__ == '__main__': data = get_data() In above function type of data should have been a list as argument batchsize=None. but this function is returning generator in both cases. If I comment else part of the function then it's returning a list.
has comment: http://stackoverflow.com/comment/88072457
answer count: 1
tagged with: database
downvote count: 0
tagged with: python
tagged with: psycopg2
has answer: http://stackoverflow.com/a/50530365
tagged with: postgresql
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88072138
upvote count: 3
has title: Why do I still receive a generator even if I don't hit yield keyword in function
linked to: http://stackoverflow.com/q/26595895

http://stackoverflow.com/q/50409807
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87835444
upvote count: 0
score: -4
has body: I have Code that read files and compare it with user input (case-insensitive). I used the list-comprehension in order to loop through the content and compare with user-input. The problem is that the list comprehension return an empty list, although the entered word exist. Example: user-input :Bruce Excpected Result : Bruce, Bruce (because it exist in the list). result = empty list code: user_input = self.lineEditSearch.text() print(user_input) textString = self.ReadingFileContent(Item) listText = list(textString.splitlines()) print(listText) #self.varStr = [c for c in textString if c.islower() or c.isupper() or c.capitalize()] self.varStr = [item for item in textString if user_input.lower() in item.lower()] print(self.varStr) output of print(listText): ['v01 ', '', ' ', 'Bruce Demaugé', '-', 'Bost ', '', ' ', 'http://bdemauge.free.fr', ' ', 'Les hiboux', ' ', 'Charles Baudelaire', ' ', 'Cycle 3', ' ', '*', ' ', 'POÉSIE', ' ', 'Sous les ifs noirs qui les abritent', ' ', '', ' ', '', ' ', '', ' ', ' ', 'Sans remuer ils se tiendront', ' ', '', ' ', '', ' ', '', ' ', ' ', 'Leur attitude au sage enseigne', ' ', "Qu'il faut en ce monde qu'il craigne", ' ', 'Le tumulte et le mouvement', ' ', ';', ' ', ' ', "L'homme ivre d'une ombre qui passe", ' ', '', ' ', "D'avoir voulu changer de place. ", ' ', ' ', ' ', 'Les Fleurs du Mal', ' ', '1857', ' ', 'Charles Pierre Baudelaire (1821 ', '', ' ', '1867) est un poète français.', ' ', ' ', '', '', 'les et un voyage forcé aux Indes, il est revenu à Paris et a mené une vie dissolue. Un de ses recueils de poèmes, ', 'Les Fleurs du Mal', '', '', '', 'mort à Paris, en 1867, après avoir cumulé pendant un an les problèmes de santé.', ' ', '&lt;br/&gt;v01 ', '', ' ', 'Bruce Demaugé', '-', 'Bost ', '', ' ', 'http://bdemauge.free.fr', ' ', '', ' ', 'Charles Baudelaire', ' ', 'Cycle 3', ' ', '**', ' ', 'POÉSIE', ' ', '', ' ', 'Prennent des albatros, vastes oiseaux des mers,', ' ']
has title: how to find string in text file by compare it with user input using python?
tagged with: python
tagged with: list-comprehension
accepted answer: http://stackoverflow.com/a/50412333
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50412333
downvote count: 4
tagged with: case-insensitive
answer count: 1
has comment: http://stackoverflow.com/comment/87835069

http://stackoverflow.com/a/50471413
upvote count: 2
answers question: http://stackoverflow.com/q/50471064
score: 2
has body: With groupby df.groupby(['Manufacturer','Product']).agg(tuple).sum(1).apply(pd.Series).fillna(0) Out[85]: 0 1 2 3 4 5 6 7 8 Manufacturer Product Test1 Product1 1.0 2.0 3.0 0.0 0.0 0.0 0.0 0.0 0.0 Product2 4.0 5.0 6.0 0.0 0.0 0.0 0.0 0.0 0.0 Test2 Product1 1.0 2.0 3.0 0.0 0.0 0.0 0.0 0.0 0.0 Test3 Product1 1.0 4.0 7.0 2.0 5.0 8.0 3.0 6.0 9.0
downvote count: 0
type: Answer

http://stackoverflow.com/q/50535976
has body: Here we have a small piece of a html page: 1 st scenario: $45 $65 2 nd scenario $35 When the class on_sale is available I want to set the variable price_sale = the value inside the span. When it is not I want to set the variable value to -1. This teh code I am using: price_sale = product_item.find('span',class_='food_price on_sale') price_price = product_item.find('span',class_='food_price').text print(price_sale) #when there is no 'food_price on_sale' display None if price_sale=='None': price_sale = -1 else: price_sale = product_item.find('span',class_='price sale').text print(price_sale) I am getting the follow error: Traceback (most recent call last): File "/home/ila/vhosts/crawler/bucky.py", line 144, in <module> price_sale = product_item.find('span',class_='food_price on_sale').text AttributeError: 'NoneType' object has no attribute 'text' It seems that when there is no class="food_price on_sale" it is not going into if price_sale=='None':. My guess is taht it seems that None is not a string. Does someone knows how to compare this?
tagged with: python
upvote count: 1
score: 1
answer count: 1
downvote count: 0
has title: How can I select an element with multiple classes in BeautifulSoup4 - Python?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50536418
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/comment/87937227
type: AnswerComment
score: 0
has text: `data = re.search("Your booking at\s+(.*?)\s+\-", text) if data: print(data.group(1))` ?
type: Comment
comment on: http://stackoverflow.com/a/50450350

http://stackoverflow.com/comment/87802314
type: Comment
type: QuestionComment
has text: What command created the file?
score: 0
comment on: http://stackoverflow.com/q/50393155

http://stackoverflow.com/comment/139335054
has text: I uninstalled and reinstalled vscode, which indirectly updated it, and the problem went away. If you're reading this and worried about losing your extensions, in my case they were all preserved when I re-installed. I'm running MacOS.
score: 0
comment on: http://stackoverflow.com/a/76693760
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50470582
has comment: http://stackoverflow.com/comment/87983161
has comment: http://stackoverflow.com/comment/87982343
type: Answer
has comment: http://stackoverflow.com/comment/87984051
score: 0
has comment: http://stackoverflow.com/comment/87986464
has comment: http://stackoverflow.com/comment/87983235
has comment: http://stackoverflow.com/comment/87982895
has body: You are confusing the inputs and outputs. Let's simplify this, assume there are 4 labels, then your x_train = [[0,1,0,0], [0,0,0,1]] so you have 2 data points already one hot encoded. Now you can build your autoencoder as: in = Input(shape=(num_classes,)) enc = Dense(encoding_dim, activation='relu')(in) out = Dense(num_classes, activation='softmax')(enc) Your network will have to predict one of the classes as a distribution based on the encoded vector. Given it's still a classification problem, you'll have categorical_crossentropy as your loss when training.
has comment: http://stackoverflow.com/comment/87986559
answers question: http://stackoverflow.com/q/50467988
has comment: http://stackoverflow.com/comment/87984031
has comment: http://stackoverflow.com/comment/87981270

http://stackoverflow.com/q/50539880
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/88091398
upvote count: 4
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88091766
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50541959
type: UnansweredQuestion
has body: What would be a more elegant way to writing: df[df['income'] &gt; 0].count()['income'] I would like to simply count the number of column values meeting a condition (in this example, the condition is just being larger than zero, but I would like a way applicable to any arbitrary condition or set of conditions). Obviously more elegant if the column name would not need to show up twice in the expression. Should be hopefully easy.
has comment: http://stackoverflow.com/comment/88091406
has title: python count dataframe column values meeting condition

http://stackoverflow.com/a/50504655
answers question: http://stackoverflow.com/q/50504315
upvote count: 2
has body: It should be ok if the list is not empty, but it seems to be. So first check if the list isn't empty by printing it or something similar. I tested this code and it worked fine: import os import glob mypath = "C:/Users/&lt;Your username&gt;/Downloads/*.*" print(min(glob.glob(mypath), key=os.path.getmtime)) print(max(glob.glob(mypath), key=os.path.getmtime))
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50504315

http://stackoverflow.com/a/50412333
accepted answer of: http://stackoverflow.com/q/50409807
type: Answer
answers question: http://stackoverflow.com/q/50409807
score: 0
has body: It appears to me that within your list comprehension you just have one minor issue! Instead of: item for item in textString within your list comprehension, I would suggest: item for item in listText as currently you are iterating through each char of the whole text, rather than each element in the list of the split document.
type: AcceptedAnswer

http://stackoverflow.com/comment/87849987
comment on: http://stackoverflow.com/q/50416785
has text: You use `twinx` multiple times.
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/a/50439363
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50439198
accepted answer of: http://stackoverflow.com/q/50439198
has body: I'm guessing here but maybe you are looking to apply a transform() to keep the rows. Try this example: import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({ 'dates':pd.date_range(start='2018-01-01', end='2018-12-31'), 'i': np.arange(365) }).set_index('dates') df.groupby(by=[df.index.year, df.index.quarter]).mean().plot(kind='bar') df.groupby(by=[df.index.year, df.index.quarter]).transform('mean').plot() Returns:
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/50385660
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88242483
type: UnansweredQuestion
has body: import pandas as pd import tensorflow as tf PREDICTORS = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"] TARGET = ["Survived"] def load_file(path): data = pd.read_csv(path) data["Age"] = data["Age"].fillna(data["Age"].mean()) data["Sex"] = data["Sex"].apply(lambda sex: 1 if sex == "male" else 0) data["Embarked"] = data["Embarked"].fillna("S") data.loc[data["Embarked"] == "S", "Embarked"] = 0 data.loc[data["Embarked"] == "C", "Embarked"] = 1 data.loc[data["Embarked"] == "Q", "Embarked"] = 2 data["Fare"] = data["Fare"].fillna(data["Fare"].mean()) return data train, test = load_file("../input/train.csv"), load_file("../input/test.csv") train.head() test.head() train_x_data = train.loc[:, ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]] print(train_x_data.head()) test_x_data = test.loc[:, ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]] print(test_x_data.head()) train_y_data = train.loc[:, "Survived"] print(train_y_data.head()) X = tf.placeholder(tf.float32, shape=[None, 7]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([7, 1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') hypothesis = tf.matmul(X, W) + b cost = tf.reduce_mean(tf.square(hypothesis - Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5) train = optimizer.minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) for step in range(2001): sess.run(train, feed_dict={X:train_x_data, Y:train_y_data}) hello guys I'm a beginner in kaggle And trying 'titanic tutorial' in this site (https://www.kaggle.com/c/titanic) My problem is the last code of the source (sess.run(train, feed_dict={X:train_x_data, Y:train_y_data})) &lt;- this part! Computer error says I have problem in feed_dict on using shape I have used [None, 7] shape I you can see in the source and I don't get the problem. Can someone help me solve the problem??
has comment: http://stackoverflow.com/comment/87786969
tagged with: python
has comment: http://stackoverflow.com/comment/87787621
has title: ValueError: Cannot feed value of shape (891,) for Tensor 'Placeholder_37:0', which has shape '(?, 1)'
score: 0
answer count: 0
tagged with: pandas
tagged with: kaggle

http://stackoverflow.com/a/50420742
score: 4
has body: Using total_seconds pd.Series(pd.Timedelta('0days 01:25:53.0000000')).dt.total_seconds()/60 Out[334]: 0 85.883333 dtype: float64
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50420721

http://stackoverflow.com/comment/87793193
score: 0
type: Comment
type: QuestionComment
has text: Just FYI - if you have the month written as two digits (e.g. `01`, as in your code), you should write `%m` , not `%b`. You would use `%b` if the date was `"2014-Jan-01 00:00:00-06:00"`
comment on: http://stackoverflow.com/q/50388683

http://stackoverflow.com/q/50466609
accepted answer: http://stackoverflow.com/a/50466729
has body: Is there a way you can download python packages, without being able to access CMD. As it is blocked. I am trying to get Geocoder. Any help is appreciated
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87946442
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87946547
type: AnsweredQuestion
has title: Python - Packages Install
upvote count: 0
answer count: 1
downvote count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/50466729

http://stackoverflow.com/a/50386137
has body: You are trying to check if a list is a sublist of another list. You could check different segments of your bigger list and compare it to your tokenized query string. query = ["Song", "of", "Salomon"] text = ["my", "favorite", "verse", "is", "Song", "of", "Solomon", "1:2", "but", "my", "second", "favorite", "is", "Exodus", "2:15"] is_sublist = any((query == text[i:i+len(query)] for i in range(0, len(text) - len(query)))) # is_sublist will be True
answers question: http://stackoverflow.com/q/50385976
has comment: http://stackoverflow.com/comment/87788194
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87788035
score: 1
has comment: http://stackoverflow.com/comment/87787967
upvote count: 1

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/50515960
tags question: http://stackoverflow.com/q/50539497
type: Tag
tags question: http://stackoverflow.com/q/50534291
tags question: http://stackoverflow.com/q/50538793

http://stackoverflow.com/comment/87842252
has text: Thank you so much for your patience, again, I tried `query = db.session.query(UserModel.first_name,UserModel.last_name,func.sum(TicketMetaDataModel.modifier)).join(TicketMetaDataModel,TicketMetaDataModel.id=UserModel.ticket_md_id).group_by(UserModel .first_name,UserModel.last_name)` but now I end up with the error `SyntaxError: keyword can't be an expression`. After some searching around is there some wrong sequence in the ordering when you were joining?
type: AnswerComment
comment on: http://stackoverflow.com/a/50412661
score: 0
type: Comment

http://stackoverflow.com/a/51409302
has comment: http://stackoverflow.com/comment/89830586
score: 0
has body: For time-series data the standard method is bag-of-frames, chopping it up into small chunks called frames. The frames can be overlapped and windowed or disjoint. Frame size is an important hyper-parameter and depends on task. Features like min,max,median,variance,RMS are calculated on each frame. To use variation over time in the classifier one uses lagged or delta features. Lagged features are values from the frames before. Delta features are computed as the difference of current frame to the previous one. For classification you will need to label the segments of different activities. Note that for human-activity detection on accelerator data there are also tons of public datasets available, like UCI: Human Activity Recognition Using Smartphones
type: Answer
answers question: http://stackoverflow.com/q/50519856

http://stackoverflow.com/q/50484197
tagged with: python
tagged with: url-routing
tagged with: flask
has comment: http://stackoverflow.com/comment/87989093
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/87989463
score: 1
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/27760307
favorite count: 0
duplicate of: http://stackoverflow.com/q/27760307
type: Question
has title: How create friendly url in Flask?
has answer: http://stackoverflow.com/a/50485476
accepted answer: http://stackoverflow.com/a/50485476
has body: How create friendly url in Flask? What would be written in the route / And the user received(Url is constructed by categories from the database) /machines/cars/modern/Lexus LX570 Is it possible to do this and how to write this? Solution1: Redirect 302 /product/&lt;int:id_product&gt; redirect to second route(get in databases) /machines/cars/modern/Lexus LX570 Solution2: Three url and one function for get id product and other data of database @app.route('/') def index(): #use function for get data in database @app.route('/&lt;productName&gt;') def product(productName): #use function for get data in database @app.route('/&lt;path:fullPath&gt;/&lt;productName&gt;') def product_with_categories(fullPath,productName): #use function for get data in database

http://stackoverflow.com/comment/87927706
has text: @WillemVanOnsem: I've updated the post.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50457035

http://stackoverflow.com/a/50511339
answers question: http://stackoverflow.com/q/50509481
has body: Another way to visualize the data for density is with the Kernel Density Estimate: df.plot.kde() plt.xlim(-4,4) plt.grid() plt.show()
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/88035302

http://stackoverflow.com/q/50399495
answer count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/50399721
score: 0
tagged with: conv-neural-network
tagged with: python
tagged with: lstm
has title: Implement Seq2Seq in Keras with Image Seqs
type: Question
tagged with: deep-learning
type: UnansweredQuestion
has body: I have a problem with input as a sequence of images, and output as a sequence of labels, which correspond to each frame in the image. The input format is illustrated as below: Goal: Predict a list of labels [label 0, label 1, label 2, label 3] based on the list of input sequence [img 0, img 1, img 2, img 3]. The output of training model should be: P([label 0, label 1, label 2, label 3]/[img 0, img 1, img 2, img 3]). The label 0 depends on img 0, and is also correlated with img 1, img 2 and img 3. And other labels depend on all images in the input sequence as well. So, this makes a target label depends on both spatial information in each single image and temporal information. So, I plan to use Convolutional Neural Network(CNN) to encoder the spatial info for each img. In the same time, How can I encode the temporal info of the img sequence with LSTM? Here is my code: from keras.models import Sequential, Model from keras.layers import Dense, Conv2D, LSTM, Flatten, TimeDistributed, RepeatVector from keras.layers.normalization import BatchNormalization def cnn_lstm(): model = Sequential() # CNN module model.add(TimeDistributed(Conv2D(filters = 8, kernel_size = (2, 2), padding = 'same', activation='relu', name = 'Conv_1'), input_shape = (None, img_height, img_width, channels))) model.add(TimeDistributed(BatchNormalization(name='BN_1'))) model.add(TimeDistributed(MaxPooling2D())) model.add(TimeDistributed(Conv2D(filters = 8, kernel_size = (2, 2), padding = 'same', activation='relu', name = 'Conv_2'))) model.add(TimeDistributed(BatchNormalization(name='BN_2'))) model.add(TimeDistributed(MaxPooling2D())) # Flatten all features from CNN before inputing them into LSTM model.add(TimeDistributed(Flatten())) # LSTM module model.add(LSTM(50)) model.add(RepeatVector(output_seq_length)) model.add(LSTM(50, return_sequences=True, name = 'decoder')) model.add(TimeDistributed(Dense(nb_classes, activation='softmax'))) model.compile(loss='categorical_crossentropy', optimizer='rmsprop', m…

http://stackoverflow.com/comment/87926460
type: AnswerComment
comment on: http://stackoverflow.com/a/50440296
score: 0
has text: I've added a condition to the generator such that it never creates the `(0, 0)` entry, a little cleaner.
type: Comment

http://stackoverflow.com/comment/87793785
type: Comment
type: AnswerComment
has text: @ajinkygadewar, would you like to accept the answer as well?
score: 0
comment on: http://stackoverflow.com/a/50389013

http://stackoverflow.com/q/50454098
has body: I'm trying to create a 3-D Plot from a Dictionary and have hit a sticking point. The Z-access will be the key (MSE) and the X and Y axis will be the first and second values of the tuple e.g. X will be 2 and Y will be 5 in the first example of the example dataset below: 80178.37739073468: (2, 5), 81623.18006660603: (13, 14), 82583.3021359235: (8, 16), 83491.34222215343: (9, 8), 83724.73005402873: (8, 14), 83856.2891246289: (7, 8), 83984.92825308126: (6, 5), 84314.30519882984: (13, 16), 84577.4110193269: (4, 11), 86338.86146117302: (6, 20) I've found sample code to do it with a list but that's just for a 2-D plot.
answer count: 1
tagged with: data-science
favorite count: 0
tagged with: python-3.x
type: Question
has title: Python3 Create A 3-D Plot From A Dictionary (Value: Tuple)
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/50454229
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/50454229
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/87843023
has text: In general numpy is slow when you iterate over elements in a python loop and very fast when you use numpy operations. ``tolist()`` is an numpy operation and probably optimized, while ``list()`` works on the iterator of the object. Probably there is even a numpy-only option to join the values of an array (some ``reduce`` like operation).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50413286
score: 1

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/50507735
tags question: http://stackoverflow.com/q/50396479
type: Tag

http://stackoverflow.com/q/50462214
favorite count: 0
has title: AssertionError: The field 'links' was declared on serializer SprintSerializer, but has not been included in the 'fields' option
accepted answer: http://stackoverflow.com/a/50463086
type: Question
has body: I am having problems with reproducing example from Julia Elman's book models.py class Sprint(models.Model): name = models.CharField(max_length=100, blank=True, default='') description = models.TextField(blank=True, default='') end = models.DateField(unique=True) def __str__(self): return self.name or _('Sprint ending %s') % self.end serializer.py from rest_framework import serializers from django.contrib.auth import get_user_model from rest_framework.reverse import reverse from .models import Sprint, Task User = get_user_model() class SprintSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField('get_links') class Meta: model = Sprint fields = ('id', 'name', 'description', 'end', 'links',) def get_links(self, obj): request = self.context['request'] return {'self': reverse('sprint-detail',kwargs={'pk': obj.pk},request=request),} views.py from django.contrib.auth import get_user_model from rest_framework import authentication, permissions, viewsets from .models import Sprint,Task from .serializers import SprintSerializer,TaskSerializer, UserSerializer User = get_user_model() class DefaultsMixin(object): authentication_classes = (authentication.BasicAuthentication,authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) paginate_by = 25 paginate_by_param = 'page_size' max_paginate_by = 100 class SprintViewSet(DefaultsMixin, viewsets.ModelViewSet): queryset = Sprint.objects.order_by('end') serializer_class = SprintSerializer I try to see repr from shell from board.serializers import SprintSerializer &gt;&gt;&gt; s = SprintSerializer() &gt;&gt;&gt; print (repr(s)) But I have problem AssertionError: The field 'links' was declared on serializer SprintSerializer, but has not been included in the 'fields' option. My DRF print (rest_framework.VERSION) 3.8.2 How to debug this issue?
score: 3
has answer: http://stackoverflow.com/a/50463086
tagged with: python
has comment: http://stackoverflow.com/comment/87937662
type: AnsweredQuestion
upvote count: 3
downvote count: 0
tagged with: django
tagged with: django-rest-framework
answer count: 1

http://stackoverflow.com/comment/87965491
type: QuestionComment
score: 0
has text: @tdelaney Sorry. I added the line where the code breaks. xls=pd.ExcelFile(file). It looks like sys.argv[1:] is returning []
comment on: http://stackoverflow.com/q/50475523
type: Comment

http://stackoverflow.com/q/50483796
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/87981375
has answer: http://stackoverflow.com/a/50484042
tagged with: environment-variables
has title: Python : How to set environment variables on VM windows
has answer: http://stackoverflow.com/a/50505229
type: Question
tagged with: virtual
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87988166
tagged with: windows
tagged with: path
tagged with: python
has body: I want to write a python script that adds env variables to PATH. This script will be executed from ssh to windows virtual machine. I tried 2 methods and no one works. Method 1 : os.system("setx /M PATH "'"%PATH%;path1;path2"'"") Method 2 : os.environ["PATH"] += os.pathsep + os.pathsep.join(["path1"]) Could you help me please ? Thanks in advance.
has comment: http://stackoverflow.com/comment/87980654
has answer: http://stackoverflow.com/a/50499225

http://stackoverflow.com/q/50494415
type: Question
tagged with: google-drive-api
tagged with: python-3.x
has body: I want a python scripts which uploads files to google drive periodically in the background. I have created a separate google drive account for this purpose. The file should be uploaded to this account, not the user's personal account. The script should upload files to this folder without asking the user to login to his google account. How can I achieve this, as all samples that I see open up the login page in the browser? As of now, I am using this code : https://gist.github.com/macieksk/038b201a54d9e804d1b5
has comment: http://stackoverflow.com/comment/88002092
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88001981
score: 0
has title: Google Drive File Upload Daemon

http://stackoverflow.com/a/50433844
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87881947
score: 1
answers question: http://stackoverflow.com/q/50433794
type: Answer
has body: You have stored the number as in a string. The use of quotes dict1= {'CNN': '0.000002'} makes it a string. Instead, assign it `dict1= {'CNN': 0.000002} Code: dict1= {'CNN': 0.000002} s=dict1.values() print (type(s)) for i in dict1.values(): print (type(i)) Output: &lt;class 'dict_values'&gt; &lt;class 'float'&gt;
has comment: http://stackoverflow.com/comment/87881914
has comment: http://stackoverflow.com/comment/87881973

http://stackoverflow.com/q/50447023
tagged with: dataframe
has answer: http://stackoverflow.com/a/50447104
tagged with: large-data
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50447160
accepted answer: http://stackoverflow.com/a/50447104
has comment: http://stackoverflow.com/comment/87910268
has answer: http://stackoverflow.com/a/50447160
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87907457
tagged with: pandas
has title: Python dataframes Cartesian operation on large amount of data
has body: I have 2 dataframes, both with around 30k rows and 8 columns, and I need to subtract the values of every row in the first df from values of every row in second df(to compute the Euclidian distance between every pair of rows) which will probably result in a 3d structure of only the differences between every pair of rows. I've tried several approaches but each one takes a very long time to complete. Is there an efficient way to do this?

http://stackoverflow.com/a/50526840
downvote count: 1
has comment: http://stackoverflow.com/comment/88455222
answers question: http://stackoverflow.com/q/50516248
type: Answer
accepted answer of: http://stackoverflow.com/q/50516248
score: 0
has body: Continuing the discussion in the comment section of your question: Assume the following directory with a virtual environment created in the folder /venv: - main.py - /static - /js - /html - /css - /venv - /bin - activate To activate the virtual environment, thus using the local copy of Python (as opposed to your global copy), the following command must be used: . /venv/bin/activate the . essentially tells the terminal window that the activate file, located at /venv/bin (assuming we're in the top level of the above directory), must be executed. You'll know that the command is successful when you see the string (venv) at the start of a new line in your terminal window. Now, the which command will confirm that you're now using the local copy of Python: which python Now your virtual environment is activated, you can use pip to install any module you wish locally to this virtual environment. You can specify to install a certain version of a module if you wish, or just grab the latest. The version of Flask or Apache that you install depends on what you specify when installing. Lastly, the command python --version will tell you the version of this copy of Python 2. python3 --version will do the same for Python 3. Whenever you execute a script using this local copy of Python, it will be using this Python version. To get Python version from within a script: from sys import version_info print version_info Output (will depend on your version, but will look something like this): sys.version_info(major=2, minor=7, micro=13, releaselevel='final', serial=0)
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/comment/87819487
type: Comment
comment on: http://stackoverflow.com/a/50401640
type: AnswerComment
has text: It’s `lxml-xml` instead of `lxml.xml`. I typed it wrong at first.
score: 0

http://stackoverflow.com/comment/87801625
type: Comment
type: QuestionComment
has text: https://www.tutorialspoint.com/python/string_isupper.htm
comment on: http://stackoverflow.com/q/50392926
score: 1

http://stackoverflow.com/q/50410701
has comment: http://stackoverflow.com/comment/87852908
has title: matplotlib- 2 legends in one plot
has comment: http://stackoverflow.com/comment/87836756
tagged with: matplotlib
tagged with: legend
tagged with: python
has comment: http://stackoverflow.com/comment/87837323
tagged with: legend-properties
upvote count: 2
has comment: http://stackoverflow.com/comment/87836699
answer count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87837041
has body: I have the following piece of code: plt.subplot2grid(shape=(2,3),loc=(0,0)) df.Survived.value_counts(normalize=True).plot(kind="bar",alpha=0.6,color= ['b','r']) plt.title("Bar Representation- Survived wrt Age") plt.xlabel("Survived") plt.ylabel("Percentage") plt.show() The graph looks like this : I just wanted to add 2 legends on the upper right hand side of the bar graph, Survived and Died. Just like in this graph: Graph Also, I wanted to make the labels 0 and 1 vertically aligned.
downvote count: 1
has comment: http://stackoverflow.com/comment/87836965
has comment: http://stackoverflow.com/comment/87851597
favorite count: 0
has comment: http://stackoverflow.com/comment/87840909
type: Question

http://stackoverflow.com/a/50397961
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50397098
has comment: http://stackoverflow.com/comment/87817539
type: Answer
answers question: http://stackoverflow.com/q/50397098
has body: If you're using OpenCV how about trying template matching ?
score: 1

http://stackoverflow.com/comment/88005983
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50495691
has text: Can you please provide a [MCVE]?

http://stackoverflow.com/comment/88259857
type: Comment
has text: Corner detection would be a way to go. Combined with a Hough transform.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50529731

http://stackoverflow.com/q/50427992
type: Question
has comment: http://stackoverflow.com/comment/87870725
linked to: http://stackoverflow.com/q/38489386
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has answer: http://stackoverflow.com/a/50428055
score: -1
has comment: http://stackoverflow.com/comment/87875195
answer count: 2
has comment: http://stackoverflow.com/comment/87870762
tagged with: api
upvote count: 0
tagged with: python-requests
has answer: http://stackoverflow.com/a/50430425
downvote count: 1
has body: I am trying to make a post request to this website: https://www.myetherapi.com/. I'm not sure what is wrong with my request, but print(res) returns &lt;Response [403]&gt; and print(res.json()) returns the error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Code: import requests import json url = 'https://api.myetherapi.com/eth' headers = {'content-type': 'application/json'} payload = { "jsonrpc": "2.0", "method": "eth_getBalance", "params": ["0x7cB57B5A97eAbe94205C07890BE4c1aD31E486A8", "latest"], "id": 1 } res = requests.post(url, data=json.dumps(payload), headers=headers) print(res) print(res.json()) Any idea on what I am doing wrong? Edit: I had posted this question and then turned off my computer. when I returned a few hours later and read the answers on this thread, i ran the code again and it worked. Then a few minutes later it's not working again. All i did is browse some web pages between the time it worked and stopped working. I am running this in pycharm. How i am running it
favorite count: 0
has title: python JSON RPC request Response 403

http://stackoverflow.com/q/50454988
score: 2
upvote count: 2
answer count: 0
downvote count: 0
tagged with: tensorflow
favorite count: 0
has title: alternative for tf.contrib.seq2seq.prepare_attention() in tensorflow version 1.8
type: Question
tagged with: seq2seq
tagged with: python
type: UnansweredQuestion
has body: AttributeError: module 'tensorflow.contrib.seq2seq' has no attribute 'prepare_attention' I know that the prepare_attention() has been deprecated. What is the alternative for this? And also please specify the syntax also. the function I'm using is: def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope, output_fn, keep_prob, batch_size): '''Decode the training data''' attention_states = tf.zeros([batch_size, 1, dec_cell.output_size]) att_keys, att_vals, att_score_fn, att_construct_fn = tf.contrib.seq2seq.prepare_attention(attention_states, attention_option="bahdanau", num_units=dec_cell.output_size) train_decoder_fn = tf.contrib.seq2seq.attention_decoder_fn_train(encoder_state[0], att_keys, att_vals, att_score_fn, att_construct_fn, name = "attn_dec_train") train_pred, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(dec_cell, train_decoder_fn, dec_embed_input, sequence_length, scope=decoding_scope) train_pred_drop = tf.nn.dropout(train_pred, keep_prob) return output_fn(train_pred_drop)
tagged with: chatbot
tagged with: deep-learning

http://stackoverflow.com/comment/87904368
type: Comment
type: AnswerComment
has text: In my case, I will work be extending a lot of Oscar's functionality over several months, and the recommended way of customisation just does not cover that. What do you think of re-installing django-oscar using editable/developer mode - 'pip install -e path/name/'? Would that be something to consider?
comment on: http://stackoverflow.com/a/50437287
score: 0

http://stackoverflow.com/a/50500639
answers question: http://stackoverflow.com/q/50500512
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50500512
has comment: http://stackoverflow.com/comment/88013884
score: 2
has body: How about convert like this: dt = datetime.strptime(s[:-len('2-04:00')], '%Y-%m-%dT%H:%M:%S.%f') # datetime.datetime(2016, 9, 22, 13, 57, 31, 231189) https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior Suddenly found a useful method at django: from django.utils.dateparse import parse_datetime dt = parse_datetime('2016-09-22T13:57:31.2311892-04:00') # datetime.datetime(2016, 9, 22, 13, 57, 31, 231189, tzinfo=&lt;django.utils.timezone.FixedOffset object at 0x7f20184f8390&gt;) https://docs.djangoproject.com/en/2.0/ref/utils/#module-django.utils.dateparse Another pythonic format (use maya https://github.com/kennethreitz/maya): # pip install maya import maya maya.parse('2016-09-22T13:57:31.2311892-04:00').datetime() # datetime.datetime(2016, 9, 22, 17, 57, 31, 231189, tzinfo=&lt;UTC&gt;)
type: Answer
has comment: http://stackoverflow.com/comment/88026934

http://stackoverflow.com/comment/88049825
comment on: http://stackoverflow.com/q/50518438
score: 0
type: Comment
type: QuestionComment
has text: I want to kill it when the process is done executing, which I will check for externally. That doesn't affect what the question is about. Doesn't work means the dialog box doesn't disappear, which is the goal of the question. Again, run isn't satisfactory because I have no control over the process. All of these things are answered in the question.

http://stackoverflow.com/a/50427350
has comment: http://stackoverflow.com/comment/87870455
has body: The solution is in the error message: 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. Since you're passing in a single feature (not a single sample), try: y = sc_y.fit_transform(y.reshape(-1, 1))
answers question: http://stackoverflow.com/q/50426857
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50426857
has comment: http://stackoverflow.com/comment/87876149
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/105127997

http://stackoverflow.com/a/50431881
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50431611
has body: You can go for a "fuzzy" mode which is able to parse both variants: In [7]: parser.parse('Tue, 27 May 2014 20:06:08 +0800 (GMT+08:00)', fuzzy=True) Out[7]: datetime.datetime(2014, 5, 27, 20, 6, 8, tzinfo=tzoffset(None, 28800)) In [8]: parser.parse('Thu, 16 Dec 2010 12:14:05 +0000', fuzzy=True) Out[8]: datetime.datetime(2010, 12, 16, 12, 14, 5, tzinfo=tzutc())

http://stackoverflow.com/comment/87930204
has text: Thanks again. I used @Rakesh's answer as it fixed some other things as well.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50448528

http://stackoverflow.com/a/75218568
score: 0
answers question: http://stackoverflow.com/q/50483235
type: Answer
has body: pip install nltk # all package installation attempt would install dependencies first # resulting not compatible thinc, wasabi, srsly to be installed before completly # uninstalling spacy dependency pacakage if any pip uninstall srsly pip uninstall thinc pip uninstall wasabi # install wheel pip install -U pip setuptools wheel # upgrade python pip python -m pip install --upgrade pip # installing spacy for resume parser needs to be above 2.1.4 closer to this version better # to install exactly 2.1.4 version of spacy use pip install spacy==2.1.4 # below code installs any spacy version above 2.1.4 pip3 install spacy&gt;=2.1.4 # once spacy is installed check if wasabi, thinc and srsly is installed # installing en-core-web-sm from spacy pip install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.3.1/en_core_web_sm-2.3.1.tar.gz # check for spacy version installed using either of the following pip show spacy python -m spacy info python -m spacy validate # to get all installed pacakages pip freeze

http://stackoverflow.com/a/50458203
score: 1
has comment: http://stackoverflow.com/comment/87960353
type: Answer
has body: &gt;&gt;&gt; l1 = [[[1,2], 10.], [[3, 4], 5.0]] &gt;&gt;&gt; l2 = [[[1,2], 8.], [[3, 6], 5.0]] &gt;&gt;&gt; [(v1[0] == v2[0] and v1[1] == v2[1]) for (v1,_), (v2,_) in zip(l1, l2)] [True, False] Replace integer values in l1, l2 with "Points" in the above example. Obviously, this assumes that dt.Point objects can be compared directly.
answers question: http://stackoverflow.com/q/50458066
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50420429
score: 11
downvote count: 1
type: Answer
has body: This is due to the fact that is_list_like has been moved from pandas.core.common to pandas.api.types in Pandas 0.23.0. This issue has been repaired here and will be a part of the Pandas Datareader 0.7.0 release. For now, I would recommend using the dev version of Datareader. Instructions for installing can be found in the documentation.
upvote count: 12
answers question: http://stackoverflow.com/q/50394873

http://stackoverflow.com/a/50451221
has body: You should encode your string with escape characters if you want it to keep the special characters escaped, i.e.: print(password.encode("unicode_escape").decode("utf-8")) # on Python 2.x: print(password.encode("string_escape")) Using repr() will add single quotes around your string.
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50441334
score: 2
answers question: http://stackoverflow.com/q/50441334
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50525487
has comment: http://stackoverflow.com/comment/88062805
has comment: http://stackoverflow.com/comment/88064059
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50525435
upvote count: 7
accepted answer of: http://stackoverflow.com/q/50525435
has comment: http://stackoverflow.com/comment/88063559
score: 7
type: AcceptedAnswer
has body: split_items = (i.split('/') for i in my_list) my_list1, my_list2 = zip(*split_items) This creates 2 tuples. If you really need lists, you can convert them by my_list1, my_list2 = map(list, (my_list1, my_list2))

pypi
tags question: http://stackoverflow.com/q/50503025
tags question: http://stackoverflow.com/q/50468951
tags question: http://stackoverflow.com/q/50436171
tags question: http://stackoverflow.com/q/50539497
type: Tag
tag name: pypi
tags question: http://stackoverflow.com/q/50538466

http://stackoverflow.com/a/50536923
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/88086162
has comment: http://stackoverflow.com/comment/88086124
upvote count: 3
answers question: http://stackoverflow.com/q/50536762
has comment: http://stackoverflow.com/comment/88086138
type: Answer
has body: Another numpy method, using np.where: import numpy as np new_df = pd.DataFrame(np.where(df.T == df.T.max(), 1, 0),index=df.columns).T A B C 0 0 1 0 1 1 0 0 2 1 0 0 3 1 0 0 4 0 0 1
has comment: http://stackoverflow.com/comment/88086351
has comment: http://stackoverflow.com/comment/88086186

http://stackoverflow.com/comment/88037077
has text: As you can see in your code, in ElemenTree the reference to the namespace for t is not the name in the physical XML, it's the namespace URI.
type: QuestionComment
comment on: http://stackoverflow.com/q/50512198
type: Comment
score: 0

http://stackoverflow.com/comment/87811969
has text: @astro123 I'm guessing not. See my update for what I think should work in 2.7.
type: Comment
comment on: http://stackoverflow.com/a/50398068
type: AnswerComment
score: 0

http://stackoverflow.com/a/51121373
has body: I backtracked the problem and it's, after all, a bug in pip 10: https://github.com/pyenv/pyenv/issues/1141 I decided to downgrade pip and the problem is gone.
type: Answer
answers question: http://stackoverflow.com/q/50418563
score: 0
accepted answer of: http://stackoverflow.com/q/50418563
type: AcceptedAnswer

http://stackoverflow.com/q/50474486
answer count: 1
has body: I am looking for a better way of handling an issue I am having. Essentially, I have a method that takes 2 parameters, formats the strings in a certain way, and base64 encodes that. The issue I am running into is that the parameters received are encoded as bytes, and I need to decode it then re-encode it before base64 encoding the string, which seems like a not very clean solution. For an example of my current code (which works) is below: item = b64encode("{} and {}".format(first.decode('utf-8'), second.decode('utf-8')).encode('utf-8')) If I don't decode first and second, then I run into an issue where the base64 encoded value is incorrect because first and second are bytes instead of raw strings.
has title: Parameters are passed as bytes, and I need them as strings. Looking for a cleaner way to accomplish this
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50474891
tagged with: base64
tagged with: python
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/87962535
score: 0
has answer: http://stackoverflow.com/a/50474891

http://stackoverflow.com/comment/97293773
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50488373
has text: Reminder not to use `redis.call(KEYS, *)` in production if you have a few million keys it will lock your redis until it completes.

http://stackoverflow.com/q/50477638
tagged with: python
score: -1
has body: Is there any reliable way to parse the inbuilt query statements in a tableau workbook, apart from xml parsing? Since my main intention is to analyze what the tableau is doing, I don't think TabPy is what I need.
type: AnsweredQuestion
has title: Tableau integration with python
has answer: http://stackoverflow.com/a/50689610
accepted answer: http://stackoverflow.com/a/50689610
upvote count: 0
answer count: 1
tagged with: tableau-api
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88347598
has comment: http://stackoverflow.com/comment/88381706

http://stackoverflow.com/a/50838395
has body: The issue is (probably) your (new) version of MySQL. Starting with version 8.04 MySQL uses caching_sha2_password as default authentication plugin where previously mysql_native_password has been used (which causes compatibility issues with older services that expect mysql_native_password authentication). Possible solutions: Downgrade the MySQL Server to a version below that change or change the authentication plugin (on a user basis) eg when creating the user: CREATE USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
type: Answer
has comment: http://stackoverflow.com/comment/115899729
score: 6
upvote count: 7
answers question: http://stackoverflow.com/q/50469587
downvote count: 1

http://stackoverflow.com/comment/87857069
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50420637
has text: How would you structure the function to make it parallizable? That is a good call about starting the range from 1 and removing the i = i+1.

http://stackoverflow.com/q/50431638
has body: I am trying to make a gui that gives a user a range of input boxes depending on what type of statistical distribution they selected. This will be used in a calculation later in the script. Each statistical distribution requires a different amount of variables (hence the need to dynamically populate a number of input boxes). Right now my code sort of works. The problem is that if you select a distribution that gives you 5 input boxes and then switch the distribution to one that only requires 3, the 5 boxes from the previous selection are still there. For this script a truncated normal distribution is supposed to have 3 variables, a normal distribution is supposed to have 5 variables and a discrete distribution is supposed to have 4 variables. I thought that if I created a dummy input box and then removed it at the end of the if statement, it would end up deleting the box(s) that I dont need. This doesnt appear to have worked though. Below is the code that I have so far. I feel like I am almost there and am just missing something. I would greatly appreciate any advice. Again the goal is to populate just the right ammount of input boxes for each statistical distribution selection and then to be able to change that selection dynamically and have the number of input boxes change accordingly. import tkinter as tk from tkinter.ttk import * master = tk.Tk() master.title("Gas Calculator") v = tk.IntVar() combo = Combobox(master) def callbackARS(eventObject): ARDist=(comboARS.get()) if ARDist == "Truncated Normal": a1 = tk.Entry(master) a2 = tk.Entry(master) a3 = tk.Entry(master) #attempt to create a dummy input box that isnt needed and then delete it at the end of the code a4 = tk.Entry(master) a1.grid(row=3, column=4) a2.grid(row=3, column=5) a3.grid(row=3, column=6) a4.grid(row=3, column=7) tk.Label(master, text="Variable", padx=20, width=10, bg = "light blue").grid(row=2,column=4) tk.Label(master, text="Area", padx=20, width=10, bg = "light blue").grid(row=2,column=5) tk.…
has comment: http://stackoverflow.com/comment/87891866
answer count: 1
has comment: http://stackoverflow.com/comment/87878026
favorite count: 0
type: Question
has title: Dynamically adding and deleting entry boxes Tkinter
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87887586
has comment: http://stackoverflow.com/comment/87879841
has comment: http://stackoverflow.com/comment/87887559
has comment: http://stackoverflow.com/comment/87878200
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/50444092
score: 2
downvote count: 0

http://stackoverflow.com/comment/87818109
type: Comment
comment on: http://stackoverflow.com/q/50401123
type: QuestionComment
has text: You put all the code that uses `info1` inside the `except KeyError:`. That's the exact opposite of what you want. You want to use `info1` if it _worked_, not if it _failed_.
score: 2

http://stackoverflow.com/a/50428564
answers question: http://stackoverflow.com/q/50428383
score: 0
type: Answer
has body: If you can accept that the output file can have 1 space you could use pandas to read it: import pandas as pd data = '''\ test_00000.png 0 test_00001.png 0 test_00002.png 0 test_00003.png 0 test_00004.png 0 test_00005.png 0 test_00006.png 0 test_00007.png 0 test_00008.png 0 test_00009.png 0 test_00010.png 0''' file = pd.compat.StringIO(data) # replace with "path/to/file" df = pd.read_csv(file, sep='\s+', header=None).replace(0,1) df.to_csv('out.csv', sep=' ', header=False, index=False)

http://stackoverflow.com/a/50540969
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50539638
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50539638
has body: Yup that is the reason. From https://docs.python.org/3/library/functions.html#max If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc). Just find the maximum as you're doing and then use the max value i.e. result[1], and get the complete list of most common n grams, with a list comprehension.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87988188
score: 0
type: Comment
type: QuestionComment
has text: You need to covert `input` from string to int and your loop is infinite as written.
comment on: http://stackoverflow.com/q/50487703

http://stackoverflow.com/comment/87880776
comment on: http://stackoverflow.com/q/50432745
score: 0
type: QuestionComment
has text: it should be multiple... yes indeed I've checked similar topics yet found no solution
type: Comment

http://stackoverflow.com/q/50431921
has answer: http://stackoverflow.com/a/50431957
has comment: http://stackoverflow.com/comment/87878661
has comment: http://stackoverflow.com/comment/88000419
has comment: http://stackoverflow.com/comment/87878188
has comment: http://stackoverflow.com/comment/88000368
duplicate of: http://stackoverflow.com/q/4984647
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87878347
has answer: http://stackoverflow.com/a/50431941
possible better answer: http://stackoverflow.com/a/50431941
has comment: http://stackoverflow.com/comment/88000453
upvote count: 9
linked to: http://stackoverflow.com/q/1529002
has comment: http://stackoverflow.com/comment/87878196
has answer: http://stackoverflow.com/a/50432168
has comment: http://stackoverflow.com/comment/87878160
tagged with: python
accepted answer: http://stackoverflow.com/a/50432168
has comment: http://stackoverflow.com/comment/87878325
has comment: http://stackoverflow.com/comment/87878400
has comment: http://stackoverflow.com/comment/88000335
has comment: http://stackoverflow.com/comment/87878867
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87878146
has title: Accessing dictionary keys using dot(.)
has comment: http://stackoverflow.com/comment/87993951
downvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/87885268
score: 5
has comment: http://stackoverflow.com/comment/88000273
linked to: http://stackoverflow.com/q/2352181
has body: I can not access the dictionary keys with dot(.) but when I define a class that inherits from dict, I can access its keys using dot(.). Can anybody explain it? So, when I run this code: d = {'first_key':1, 'second_key':2} d.first_key I get this error: 'dict' object has no attribute 'first_key' but when I run this: class DotDict(dict): pass d = DotDict() d.first_key = 1 d.second_key = 2 print(d.first_key) print(d.second_key) I get this: 1 2
linked to: http://stackoverflow.com/q/4984647

http://stackoverflow.com/comment/88002345
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50407738
score: 0
has text: You never mentioned the python version? Can you provide a sample image or does it happen with every image?

http://stackoverflow.com/comment/87936418
type: AnswerComment
comment on: http://stackoverflow.com/a/50459712
score: 1
type: Comment
has text: This is a great answer to get me started building a web scraper. However, accepted answer explained the reasoning behind the authentication requirement and why the web scraper alternative is not great - which while it might appear secondary to my original question, was really the answer I was looking for. Wish I could accept both.

http://stackoverflow.com/comment/88090725
type: AnswerComment
comment on: http://stackoverflow.com/a/50521915
type: Comment
has text: Is there any similar way where I can do filter on LearnerQuestionAnswer model?
score: 0

http://stackoverflow.com/comment/87803409
score: 0
type: Comment
has text: Could you help me with this?
comment on: http://stackoverflow.com/q/50393849
type: QuestionComment

http://stackoverflow.com/comment/87878734
type: AnswerComment
has text: @IntiLopez Welcome, you can also tell this to community by accepting the answer ;))
score: 1
comment on: http://stackoverflow.com/a/50428554
type: Comment

http://stackoverflow.com/a/50400161
answers question: http://stackoverflow.com/q/50399494
type: Answer
score: 0
has body: You can set conditional statements depending on what you want you max household size to be, and depending on how many males and females you want in a maximum list. Below I have an example for males. Lists have a method called .pop() and another method called .append() which we can use in this example. .pop() can remove a specified element from a list based on its' index location. .append() can add an element to the end of an empty list. If the maximum household size is exceeded we can pop a specified number of values from the first list. We can also use the range function to select the range of people that we want to pop() from the list in order to divide the list in half, assuming that the number of people within the list is an even number. If it is an odd number, we can add 1. hh = {'num_members': 10, 'list_male': [30, 29, 17, 10, 15, 22, 19], 'list_female': [40, 70, 22], } if hh['num_members'] &gt;= 10: hh['list_male2'] = [] hh['list_female2'] = [] number = len(hh['list_male']) number_female = len(hh['list_female']) if number % 2 == 0: divide_num = number / 2 divide_num = int(divide_num) for person in range(0, divide_num + 1): person = hh['list_male'].pop() hh['list_male2'].append(person) if number_female % 2 == 0: divide_num_female = number_female / 2 divide_num_female = int(divide_num_female) for person in range(0, divide_num_female + 1): person = hh['list_female'].pop() hh['list_female2'].append(person) if number % 2 != 0: number = number + 1 divide_num = number / 2 divide_num = int(divide_num) for i in range(divide_num): person = hh['list_male'].pop() hh['list_male2'].append(person) if number_female % 2 != 0: number_female = number_female + 1 divide_num_female = number_female / 2 divide_num_female = int(divide_num_female) for i in range(divide_num_female): person = hh['list_female'].pop() hh['list_female2'].append(person) print(hh) The above code will give you the following output and split the list in half (based on the fact that we have an uneven amount of …

http://stackoverflow.com/comment/87919921
has text: `if x==0 or 1` always returns `True` , you need to change it to `if x==0 or x==1`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50453376
score: 6

http://stackoverflow.com/q/50402861
has title: Nested class attribute isn't being recognized as int
has comment: http://stackoverflow.com/comment/87826463
has body: The Goal I am trying to create a practice script that stores a menu that can have new items added to it. The items are things like "battle animation", "text speed", or "subtitles". And the menu will print out all its items like this (notice the spacing for all items is adjusted to fit the largest one) | border color | | (black) blue red green | | Text Speed | | slow (medium) fast | fig 1 My Methods MenuItem itself is a class. It manages the contents of a menu item and stores how much adjustment space it needs when printing. This class works perfectly fine by itself. If the above two items were created and printed using the MenuItem class methods alone, they would look like this: | border color | | (black) blue red green | | Text Speed | | slow (medium) fast | fig 2 Menu is a class I made to store the menu items and to adjust their spacing values so they will print like fig 1. My Code This code was reduced to only show the reproducible error. The value lists(black,blue, red, green, etc) are not included. #!/usr/bin/env python3 class Menu(object): class MenuItem(object): def __init__(self, propertyTitle): self.title = propertyTitle self.printsize = (len(self.title)+4) def printMenuItem(self): f_indent = 2; f_title = ((' '*f_indent)+ self.title.ljust(self.printsize-f_indent)) print('|',f_title ,'|',sep='') def __init__(self): self.width = 0; self.items = []; def addItem(self, pTitle): f_menuItem = Menu.MenuItem(pTitle) if(f_menuItem.printsize &lt; self.width): #if(f_menuItem.printsize &lt; 5): #adjusting padding on the smaller new menu item f_menuItem.printsize = self.width elif(f_menuItem.printsize &gt; self.width): #elif(f_menuItem.printsize &gt; 5): #adjusting padding on all past menu items to fit this new big item self.width = f_menuItem for x in self.items: x.printsize = self.width self.items.append(f_menuItem) def printMenu(self): for x in self.items: x.printMenuItem() print() property_1_title = "border color"; property_2_title = "text speed"; myMenu = Menu() #my…
has comment: http://stackoverflow.com/comment/87821883
tagged with: python
tagged with: python-3.6
tagged with: class
type: AnsweredQuestion
score: 0
tagged with: typeerror
has comment: http://stackoverflow.com/comment/87821431
tagged with: class-attributes
has answer: http://stackoverflow.com/a/50403002
accepted answer: http://stackoverflow.com/a/50403002
answer count: 1
type: Question

http://stackoverflow.com/comment/87958551
comment on: http://stackoverflow.com/a/50471257
type: AnswerComment
score: 0
type: Comment
has text: @HennyKo Then just use `df.cummin()`.Though this is contradictory to your question: "Only values smaller than the *last value* should be kept."

http://stackoverflow.com/comment/87821649
comment on: http://stackoverflow.com/q/50401837
score: 0
has text: Please see my edit I added a lot more information about my specific problem and what I've tried.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87945154
type: QuestionComment
has text: It's a simplified example. In my actual code, converting it to a list comprehension/reversing the loop is hard, and I need the behavior of iterators, because the data may not fit in memory. In any case, the answers on the duplicate solves my problem.
score: 0
comment on: http://stackoverflow.com/q/50465207
type: Comment

http://stackoverflow.com/q/50453073
favorite count: 0
has comment: http://stackoverflow.com/comment/87919389
has title: Convert lists to a diagonal matrix DataFrame
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50453260
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50453191
has comment: http://stackoverflow.com/comment/87919829
has answer: http://stackoverflow.com/a/50453377
type: Question
has comment: http://stackoverflow.com/comment/87919327
answer count: 3
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: I get returned a list of tuples in this format: [date1, date2, date3] [ticker1, ticker2, ticker3] [value1, value2, value3] I want to convert it into a pandas dataframe where the index are the dates, columns are the tickers and the data are the values.

http://stackoverflow.com/comment/88080375
type: Comment
type: QuestionComment
has text: Do you want to keep the empty columns?
score: 0
comment on: http://stackoverflow.com/q/50533522

http://stackoverflow.com/comment/88084511
type: AnswerComment
has text: @wim...agreed. Though the solution is correct for this question, its not MCVE.
comment on: http://stackoverflow.com/a/50535763
type: Comment
score: 0

http://stackoverflow.com/comment/87867556
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50426050
has text: it should just kind of fill up E1 and E2. they already have a shape

http://stackoverflow.com/q/50444618
accepted answer: http://stackoverflow.com/a/50444629
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87941964
downvote count: 2
upvote count: 1
has body: name = form.name.data email = form.email.data username = form.username.data password = sha256_crypt.encrypt(form.password.data) cursor = mysql.connection.cursor() cursor.execute("Insert into users(name,email.username,password) values(%s,%s,%s,%s)",(name,email,username,password)) mysql.connection.commit() cursor.close() I am using python with mysql to send the data entered in the table from a table in the database but I am getting such an error. Can you help me?
answer count: 1
tagged with: mysql
favorite count: 0
type: Question
has title: Python - MySQL "Column count doesn't match value count at row 1"
has comment: http://stackoverflow.com/comment/87902955
tagged with: database
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50444629

http://stackoverflow.com/a/50504621
score: 1
downvote count: 0
upvote count: 1
has body: You can use the default days() method which would return the number of days. If you want the hours also in the day format. I hope the below code will be helpful. delta_days.total_seconds()/86400 Similar to days() the total_seconds() will return the difference in seconds, so i divided it with number of seconds in a day. hope it helps. Happy Coding :)
type: Answer
answers question: http://stackoverflow.com/q/50504425

http://stackoverflow.com/a/50414131
upvote count: 4
answers question: http://stackoverflow.com/q/50414041
type: Answer
score: 4
downvote count: 0
has body: Python handles function arguments in the same manner as most common languages: Java, JavaScript, C (pointers), C++ (pointers, references). All objects are allocated on the heap. Variables are always a reference/pointer to the object. The value, which is the pointer, is copied. The object remains on the heap and is not copied.

http://stackoverflow.com/a/77854181
score: 0
answers question: http://stackoverflow.com/q/50541020
type: Answer
has body: Usually this happens when you use virtual environment and VS code is not able to determine the interpreter. To resolve this: Press Ctrl + Shift + p Select Interpretor Enter Interpretor path Browse from your computer Now select the python version from your virtual environment. Usually it would be YourEnvName/bin/python3.x

http://stackoverflow.com/comment/87878570
type: Comment
has text: can you give me sample command to get the firebase event data ? Thanks !
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50432142

http://stackoverflow.com/q/50497274
has body: The pandas corr function is really fast. Even for a table with a 1000 columns x 200 rows it doesn't take more than a minute to calculate a cross correlation matrix. I was trying to use a for loop to compute the slope between each pair of columns and it was taking much longer. I went back and tried to just use correlation in a loop and that was also taking a long time. So I guess I have two part question. How is the pandas corr function working so fast. Is there a similar method to to compute the pairwise slope between each column? Here is an example: here is table a b 0 0 1 1 In that case slope(a,b)=1 a b 0 0 1 2 In that case slope(a,b)=2
type: Question
has comment: http://stackoverflow.com/comment/88008742
has comment: http://stackoverflow.com/comment/88033223
answer count: 0
tagged with: python
type: UnansweredQuestion
has title: Is there a way to do cross beta matrix with pandas?
has comment: http://stackoverflow.com/comment/88033825
tagged with: pandas
score: 0

http://stackoverflow.com/a/50437653
score: 3
has body: self is passed implicitly to the super call, so adding it explicitly sends it twice: def __init__(self): super().__init__(self) That ends up calling Bicycle(self, self), which is the same as Bicycle(self, cadence=self). Later on, you have probably tried convert your instance to str (e.g. to print it), so this was called: def __str__(self): return "Cadence: {0} Gear: {1} Speed: {2}".format(self._cadence, self._gear, self._speed) That code tried to convert self._cadence to a string and self._cadence is self because of the previous error, so it continues in an endless recursion (until the recursion exception). Note that super() takes two forms: with arguments and without arguments, so there are two correct ways to fix the code. The Python 3 way (without arguments): def __init__(self): super().__init__() The old Python 2 way, which is more explicit: def __init__(self): super(MountainBike, self).__init__() Both do the same, i.e. they give you the bound __init__ method which already has the implicit self. See also here: https://docs.python.org/3/library/functions.html#super
answers question: http://stackoverflow.com/q/50437465
type: Answer
has comment: http://stackoverflow.com/comment/87889258
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87889234
accepted answer of: http://stackoverflow.com/q/50437465

http://stackoverflow.com/a/58173312
type: Answer
has body: This worked for me: pd.read_csv(myfile, encoding='latin1', quotechar='"', thousands=',')
score: 0
answers question: http://stackoverflow.com/q/50388366

http://stackoverflow.com/q/50441612
has title: How to replace first word of line in Python?
has comment: http://stackoverflow.com/comment/87897439
downvote count: 6
answer count: 2
has body: My input file data is like this. 0,@rodriigoCabrera y tu vaso tu silla y tu baño 1,Mexican rival demands vote recount: The leader of Mexico's leftist Party of the Democratic Revolution, Andres Ma... 0,Queretaro 0 - 3 Morelia Tarjeta amarilla a Carlos Adrián Morales Higuera I want to replace all the 0 in the first column with false and 1 with true.
has answer: http://stackoverflow.com/a/50441774
upvote count: 0
has comment: http://stackoverflow.com/comment/87897458
has comment: http://stackoverflow.com/comment/87897470
score: -6
tagged with: parsing
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/50441657

http://stackoverflow.com/a/50505062
has comment: http://stackoverflow.com/comment/88023950
downvote count: 0
has comment: http://stackoverflow.com/comment/88023638
answers question: http://stackoverflow.com/q/50504897
has comment: http://stackoverflow.com/comment/88023028
has comment: http://stackoverflow.com/comment/88024205
has comment: http://stackoverflow.com/comment/88023912
has body: By default, each Nearby Search or Text Search returns up to 20 establishment results per query; however, each search can return as many as 60 results, split across three pages. If your search will return more than 20, then the search response will include an additional value — next_page_token. Pass the value of the next_page_token to the pagetoken parameter of a new search to see the next set of results. If the next_page_token is null, or is not returned, then there are no further results. There is a short delay between when a next_page_token is issued, and when it will become valid. Requesting the next page before it is available will return an INVALID_REQUEST response. Retrying the request with the same next_page_token will return the next page of results. Check this url: HERE Add the PagerToken, as an additional parameter with your HTTP request url like this https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=CpQCAgEAAFxg8o-eU7_uKn7Yqjana-HQIx1hr5BrT4zBaEko29ANsXtp9mrqN0yrKWhf-y2PUpHRLQb1GT-mtxNcXou8TwkXhi1Jbk-ReY7oulyuvKSQrw1lgJElggGlo0d6indiH1U-tDwquw4tU_UXoQ_sj8OBo8XBUuWjuuFShqmLMP-0W59Vr6CaXdLrF8M3wFR4dUUhSf5UC4QCLaOMVP92lyh0OdtF_m_9Dt7lz-Wniod9zDrHeDsz_by570K3jL1VuDKTl_U1cJ0mzz_zDHGfOUf7VU1kVIs1WnM9SGvnm8YZURLTtMLMWx8-doGUE56Af_VfKjGDYW361OOIj9GmkyCFtaoCmTMIr5kgyeUSnB-IEhDlzujVrV6O9Mt7N4DagR6RGhT3g1viYLS4kO5YindU6dm3GIof1Q&amp;key=YOUR_API_KEY Copy paste this url on a browser and check it carefully. Also, please read the documentation url carefully. Cheers!
type: Answer
has comment: http://stackoverflow.com/comment/88023990
upvote count: 2
score: 2

http://stackoverflow.com/comment/88015024
type: Comment
score: 0
type: QuestionComment
has text: You need to check whether that `class` is there in that attribute and replace if it exists ?
comment on: http://stackoverflow.com/q/50501346

http://stackoverflow.com/a/50461097
answers question: http://stackoverflow.com/q/50460562
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: I think this is better. import xml.dom.minidom as minidom dic={} dom = minidom.parse("filename") root = dom.documentElement #take name1 as example dic['name1']=root.getElementsByTagName('name1')[0].firstChild.data

http://stackoverflow.com/comment/87912027
type: AnswerComment
comment on: http://stackoverflow.com/a/50449018
has text: Okay that was helpful bobah, I changed the inner loop but it is not helping much.
type: Comment
score: 0

http://stackoverflow.com/a/50469113
type: Answer
has comment: http://stackoverflow.com/comment/87951622
has comment: http://stackoverflow.com/comment/87951780
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87952580
has comment: http://stackoverflow.com/comment/87951934
downvote count: 0
answers question: http://stackoverflow.com/q/50468756
has comment: http://stackoverflow.com/comment/87951743
has body: Remembering my FORTRAN. I think it assumes datatype based on the first letter of the variable, in partilar i and j would be integers So to simulate this in Python I did: n_x = 1162 j = int(((-2.8 - (-8.4)) / 0.05) + 1) i = int(((-4.5 - (-5.1)) / 0.05) + 1 ) e = ((i-1)*n_x+j) Which gave me 12895
has comment: http://stackoverflow.com/comment/87952462

http://stackoverflow.com/comment/88072605
type: Comment
type: QuestionComment
has text: I would have thought that the biggest differences would be due to the backend being used, not the matplotlib version. Other @Paul: have you tried this with different backends? Other factors that I would consider/investigate are DPI and figure size, possibly screen resolution.
score: 1
comment on: http://stackoverflow.com/q/50437426

http://stackoverflow.com/q/50415989
upvote count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: python
has body: I'm using SQLAlchemy Automap with reflection to connect to an existing database. Some of the relationships work properly and some do not. I'd like a way to audit the results of prepare() so I can better understand what I'm working with. How can I view the relationship objects produced after I run prepare()? Base.classes.&lt;classname&gt;.__table__ shows the tables and included ForeignKey objects as described in the documentation but no relationships are backreferences are included here, probably because it's at the Table level rather than the class level.
accepted answer: http://stackoverflow.com/a/50416076
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50416076
has title: How to view relationships and backreferences generated by SQLAlchemy Automap
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50467478
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50468161
has comment: http://stackoverflow.com/comment/87954082
downvote count: 5
has body: I am trying to create a list inside a function, do some processing and return that list. The code goes as below: def fibo(num): fib = [1,2] i =2 while fib[-1] &lt;int(num): fib = fib[i-1]+fib[i-2] i+=1 return fib On calling the function, I get and error saying that while fib[-1] &lt;int(num): TypeError: 'int' object is not subscriptable Why is this issue being caused? Can I not create a list in a function in Python? EDIT: I see a lot of downvotes on my question. Can someone guide me as to why my question got so many downvotes. This would help me ask the right questions and help the community :)
score: -3
has answer: http://stackoverflow.com/a/50467540
tagged with: python
has answer: http://stackoverflow.com/a/50467547
possible better answer: http://stackoverflow.com/a/50467547
has title: Creating list inside a function
upvote count: 2
type: AnsweredQuestion
tagged with: list
answer count: 3
tagged with: function
accepted answer: http://stackoverflow.com/a/50467540

http://stackoverflow.com/q/50531308
type: Question
has body: I'm trying to create a dataframe with the results of this API request: Link json_url = https://poloniex.com/public?command=returnLoanOrders&amp;currency=ETH df = pd.read_json(json_url) I get this error message: ValueError: arrays must all be same length How do I avoid this, please?
has title: ValueError: arrays must all be same length
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50531915
score: 2
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/50531915
has comment: http://stackoverflow.com/comment/88075240
tagged with: pandas
linked to: http://stackoverflow.com/q/35120250
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87984398
type: Comment
comment on: http://stackoverflow.com/q/50484645
score: 0
type: QuestionComment
has text: @madforstrength: I think you're right. The code isn't edited except your adviced code (and in a second file Thu Yein Tuns code)

http://stackoverflow.com/comment/87820103
comment on: http://stackoverflow.com/a/50402071
score: 0
type: AnswerComment
has text: Yes the example I gave works. Turns out dtype of the AMOUNT column is "object" in the real data for some reason and if I do not specifically put ['AMOUNT'] there it does not sum up that column.
type: Comment

http://stackoverflow.com/comment/87850872
comment on: http://stackoverflow.com/a/50417522
type: Comment
type: AnswerComment
score: 0
has text: Yeah I don't think you're able to filter like that, because there's no "deal" column in the SQL.

salesforce
tags question: http://stackoverflow.com/q/50409408
type: Tag
tag name: salesforce
tags question: http://stackoverflow.com/q/50476999

http://stackoverflow.com/a/50431551
has body: urlpatterns = [ path('', home_page), path('admin/', admin.site.urls) ] As stated in the above answers, the $ is unnecessary while using path(). You are getting a syntax error due to the comma after admin.site.urls) which should be removed.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50431107

http://stackoverflow.com/comment/87870839
has text: is that format Hours:Minutes:Seconds?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50428039

http://stackoverflow.com/comment/87906890
has text: Possible duplicate of [Linux CentOS 7, how to set Python3.5.2 as default Python version?](https://stackoverflow.com/questions/45542690/linux-centos-7-how-to-set-python3-5-2-as-default-python-version)
score: 0
comment on: http://stackoverflow.com/q/50446707
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50485893
has comment: http://stackoverflow.com/comment/87986919
downvote count: 0
has comment: http://stackoverflow.com/comment/87986428
has body: You should use the command line utility comes with WhiteNoise to do the compression yourself. Quote WhiteNoise comes with a command line utility which will generate compressed versions of your files for you. $ python -m whitenoise.compress --help usage: compress.py [-h] [-q] [--no-gzip] [--no-brotli] root [extensions [extensions ...]] Search for all files inside &lt;root&gt; *not* matching &lt;extensions&gt; and produce compressed versions with '.gz' and '.br' suffixes (as long as this results in a smaller file) positional arguments: root Path root from which to search for files extensions File extensions to exclude from compression (default: jpg, jpeg, png, gif, webp, zip, gz, tgz, bz2, tbz, swf, flv, woff, woff2) optional arguments: -h, --help show this help message and exit -q, --quiet Don't produce log output --no-gzip Don't produce gzip '.gz' files --no-brotli Don't produce brotli '.br' files You can either run this during development and commit your compressed files to your repository, or you can run this as part of your build and deploy processes.
answers question: http://stackoverflow.com/q/50485530
has comment: http://stackoverflow.com/comment/87985734
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/88011385
has text: Yes, I know that works but what if I have a list that does not specify the schema? Actually it's not that weird that they don't
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50499297
type: AnswerComment

http://stackoverflow.com/a/70584335
score: 0
answers question: http://stackoverflow.com/q/50483235
type: Answer
has body: I had to delete the cache folder first. Go to C:\Users\XYZ\AppData\Local\pip and then delete the cache folder Then upgrade your pip python -m pip install --upgrade pip now install spacy pip install spacy

http://stackoverflow.com/comment/88088725
type: QuestionComment
has text: so, you want to make a dict? and then use them to group?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50538330

http://stackoverflow.com/q/50539010
has title: Python regex: change one symbol into two
upvote count: 1
has answer: http://stackoverflow.com/a/50539043
favorite count: 0
type: Question
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50539043
downvote count: 0
answer count: 1
has body: Suppose you link a symbol as follows: iff = chr(8801) And then you write that code over all your algorithm in several spaces. Now suppose you decided that the following symbol has almost all of the same properties as the previous: jiff = chr(10231) Rather than go back and change every instance of: if b == iff: to if b in [iff, jiff]: I instead was wondering if there were some regex where I could make it so that the former code if b == iff: will register true if b is either = to iff or jiff. I was thinking of some regex but you would still have to change every instance of: if b == iff:

http://stackoverflow.com/q/50446716
tagged with: google-vision
has title: google.api_core.exceptions.ServiceUnavailable: 503 Getting metadata from plugin failed with error: 'str' object has no attribute 'before_request'
score: 12
answer count: 2
downvote count: 0
has body: I'm trying to iterate through images in a directory and get their labels through goodle_api_vision. This is my code: def run_quickstart(): import io import os import cv2 import numpy as np from google.cloud import vision from google.cloud.vision import types client = vision.ImageAnnotatorClient(credentials = 'service_acc_key.json') path = 'E:\wrand\\' for image_path in os.listdir(path): file_name = path + image_path content = cv2.imread(file_name) # Loads the image into memory #with io.open(file_name, 'rb') as image_file: # content = image_file.read() content = content.tobytes() print(type(content)) image = types.Image(content=content) print(type(image)) response = client.label_detection(image=image) labels = response.label_annotations print('Labels:') for label in labels: print(label.description) # [END vision_quickstart] if __name__ == '__main__': run_quickstart() the error that I get is at this part of code image = types.Image(content=content). The full error being &lt;class 'bytes'&gt; &lt;class 'google.cloud.vision_v1.types.Image'&gt; ERROR:root:AuthMetadataPluginCallback " &lt;google.auth.transport.grpc.AuthMetadataPlugin object at 0x0000028520DCA2E8&gt;" raised exception! Traceback (most recent call last): File "C:\Users\hi_pe\AppData\Local\Programs\Python\Python36\lib\site- packages\grpc\_plugin_wrapping.py", line 77, in __call__ callback_state, callback)) File "C:\Users\hi_pe\AppData\Local\Programs\Python\Python36\lib\site- packages\google\auth\transport\grpc.py", line 77, in __call__ callback(self._get_authorization_headers(context), None) File "C:\Users\hi_pe\AppData\Local\Programs\Python\Python36\lib\site packages\google\auth\transport\grpc.py", line 61, in _get_authorization_headers self._credentials.before_request( AttributeError: 'str' object has no attribute 'before_request' Traceback (most recent call last): File "C:\Users\hi_pe\AppData\Local\Programs\Python\Python36\lib\site- packages\google\api_core\grpc_helpers.py", line 54, in error_remapped_cal…
favorite count: 0
type: Question
upvote count: 12
has answer: http://stackoverflow.com/a/56099099
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53557334
tagged with: python

http://stackoverflow.com/comment/88016490
score: 2
type: QuestionComment
has text: It might serve you better to look upstream and see why your data is coming in like this. As your dataset gets larger, changing the values becomes a more cumbersome task irrespective of performing it manually or with a function
type: Comment
comment on: http://stackoverflow.com/q/50502038

http://stackoverflow.com/comment/87894988
comment on: http://stackoverflow.com/a/50440019
has text: I’ll try but I know for certain that it doesn’t have anything because at that point the entry isn’t even created yet
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50398738
has comment: http://stackoverflow.com/comment/87813383
downvote count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/50399045
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/87813592
possible better answer: http://stackoverflow.com/a/50399040
has title: Max value for each key in a list
answer count: 2
has comment: http://stackoverflow.com/comment/87813314
has body: Given: scooby = [1, 4, 1, 4, 1, 4, 1, 1, 4] snacks = [6,28,14, 3, 9, 8,18, 6, 7] scoobysnacks = zip(scooby,snacks) How do I run max(scoobysnacks) to get: (1,18) (4,28) The logic being that 18 is the max value associated to a 1 and 28 the max value associated to a 4.
has answer: http://stackoverflow.com/a/50399040
linked to: http://stackoverflow.com/q/50251654
has comment: http://stackoverflow.com/comment/87813809
score: -3
has comment: http://stackoverflow.com/comment/87813715
has comment: http://stackoverflow.com/comment/87813360
tagged with: python
accepted answer: http://stackoverflow.com/a/50399045
type: AnsweredQuestion

http://stackoverflow.com/q/50411583
tagged with: perfplot
has answer: http://stackoverflow.com/a/50459818
has answer: http://stackoverflow.com/a/50461498
tagged with: python
score: 4
answer count: 4
type: Question
upvote count: 4
tagged with: numpy
linked to: http://stackoverflow.com/q/50380692
has comment: http://stackoverflow.com/comment/87880767
has answer: http://stackoverflow.com/a/50437790
has answer: http://stackoverflow.com/a/50414080
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/87838953
has comment: http://stackoverflow.com/comment/87839370
favorite count: 0
has comment: http://stackoverflow.com/comment/87838850
has body: I need to compute the signed area of many triangles in 2D, given by a numpy array of shape (2, 3, n) (x/y coordinate, node in triangle, number of triangles). I'm looking for a a way to do it fast, and the best I could come up with so far is import numpy import perfplot def six(p): return ( +p[0][2] * p[1][0] + p[0][0] * p[1][1] + p[0][1] * p[1][2] - p[0][2] * p[1][1] - p[0][0] * p[1][2] - p[0][1] * p[1][0] ) / 2 def mix(p): return ( +p[0][2] * (p[1][0] - p[1][1]) + p[0][0] * (p[1][1] - p[1][2]) + p[0][1] * (p[1][2] - p[1][0]) ) / 2 def mix2(p): p1 = p[1] - p[1][[1, 2, 0]] return (+p[0][2] * p1[0] + p[0][0] * p1[1] + p[0][1] * p1[2]) / 2 def cross(p): e1 = p[:, 1] - p[:, 0] e2 = p[:, 2] - p[:, 0] return (e1[0] * e2[1] - e1[1] * e2[0]) / 2 def einsum(p): return ( +numpy.einsum("ij,ij->j", p[0][[2, 0, 1]], p[1][[0, 1, 2]]) - numpy.einsum("ij,ij->j", p[0][[2, 0, 1]], p[1][[1, 2, 0]]) ) / 2 def einsum2(p): return numpy.einsum("ij,ij->j", p[0][[2, 0, 1]], p[1] - p[1][[1, 2, 0]]) / 2 def einsum3(p): return ( numpy.einsum( "ij,ij->j", numpy.roll(p[0], 1, axis=0), p[1] - numpy.roll(p[1], 2, axis=0) ) / 2 ) perfplot.save( "out.png", setup=lambda n: numpy.random.rand(2, 3, n), kernels=[six, mix, mix2, cross, einsum, einsum2, einsum3], n_range=[2 ** k for k in range(19)], ) Any hints on how make it even more efficient?
has title: Compute signed area of many triangles

http://stackoverflow.com/a/50424168
answers question: http://stackoverflow.com/q/50423726
score: 0
has body: 'Call' will always wait for the process it is calling to complete. I think you need to use Popen for both operations as it will return control to your code. There is a short tutorial at https://pythonspot.com/python-subprocess/
type: Answer

http://stackoverflow.com/a/50420485
type: Answer
has body: No metaclass mechanisms support what you're trying to do. 1 doesn't generate a name lookup, so __prepare__ doesn't help. Heck, 1 as a statement on its own doesn't generate any bytecode at all, because it gets optimized out. Even if you were willing to go so far as having the metaclass locate the function object for the class body and replace its bytecode with instrumented bytecode to try to capture these expressions, it would still find no trace of the original expressions in the bytecode, and there would be nothing to instrument. Also, the metaclass has no way to get involved in the original compilation pass for the class body. The most plausible (still utterly crazy) option seems to be to have the metaclass locate the original source code for the class, parse it, modify the AST, recompile, and replace the original code object for the class body. This would never work in interactive mode (since the source code isn't kept in interactive mode), among the many other reasons why this is a bad idea.
has comment: http://stackoverflow.com/comment/87856461
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50420295
accepted answer of: http://stackoverflow.com/q/50420295
has comment: http://stackoverflow.com/comment/87856445

http://stackoverflow.com/a/50496948
has comment: http://stackoverflow.com/comment/88154106
has comment: http://stackoverflow.com/comment/88169163
has comment: http://stackoverflow.com/comment/88155013
has comment: http://stackoverflow.com/comment/88152350
answers question: http://stackoverflow.com/q/50492626
has comment: http://stackoverflow.com/comment/88015591
accepted answer of: http://stackoverflow.com/q/50492626
has comment: http://stackoverflow.com/comment/88011326
has comment: http://stackoverflow.com/comment/88142608
has comment: http://stackoverflow.com/comment/88143260
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88143480
has comment: http://stackoverflow.com/comment/88142961
has comment: http://stackoverflow.com/comment/88144886
has comment: http://stackoverflow.com/comment/88192836
score: 1
has comment: http://stackoverflow.com/comment/88192240
has body: To get the year/course/section you need to be able to navigate from a File to a Section. However, the many-many relationship that exists between Document and Section through Historical makes it unclear how you would do that. Which Historical would you choose? It may be better if File was linked directly to Historical: class File(models.Model): titulo_file=models.ForeignKey(Historical, on_delete=models.CASCADE,null=True,verbose_name='Título de la Tesis') file = models.FileField(null=True,blank=True, upload_to=generate_path) If that was the case, you could then implement your generate_path() such as: def generate_path(instance, filename): section = instance.titulo_file.id_section year = section.year.year_number course = section.course.name return os.path.join(str(year), course, str(section.numberSection), filename) To do the same thing with the model as it currently stands, you would have to do something like this: def generate_path(instance, filename): section = instance.titulo_file.historical_set.first().id_section year = section.year.year_number course = section.course.name return os.path.join(str(year), course, str(section.numberSection), filename) That example uses historical_set.first() to get the first Historical linked the Document. Maybe that would be ok, but otherwise you'd need to know which Historical to use. Where a file with the same name is uploaded and you don't want to overwrite it, you could implement your own storage: from django.core.files.storage import FileSystemStorage class UseExistingStorage(FileSystemStorage): def save(self, name, content, max_length=None): if not self.exists(name): return super().save(name, content, max_length) return name # Don't save when the file exists, just return the name Then reference the UseExistingStorage from your File model. file = models.FileField(null=True,blank=True, upload_to=generate_path, storage=UseExistingStorage())
type: Answer
has comment: http://stackoverflow.com/comment/88016275
has comment: http://stackoverflow.com/comment/88144010

libchamplain
type: Tag
tags question: http://stackoverflow.com/q/50469170
tag name: libchamplain

http://stackoverflow.com/q/50484943
upvote count: 1
favorite count: 0
type: Question
has body: How can I implement token based authentication for each api call as explained herein tornado. Where can I store the generated access token for a user as tornado doesn't provides the session-storage mechanism ?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88017337
tagged with: tornado
has comment: http://stackoverflow.com/comment/87988530
linked to: http://stackoverflow.com/q/21300543
answer count: 0
has title: Token based authentication in Tornado
score: 1
downvote count: 0

http://stackoverflow.com/comment/90097225
comment on: http://stackoverflow.com/q/50512452
type: Comment
has text: if you came up with a solution, it'd be great if you can answer your own question, to save other the trouble of going through those links and figure the answer on their own
type: QuestionComment
score: 3

http://stackoverflow.com/a/50433307
has comment: http://stackoverflow.com/comment/87882061
has comment: http://stackoverflow.com/comment/87883147
upvote count: 2
has comment: http://stackoverflow.com/comment/87881605
score: 2
has comment: http://stackoverflow.com/comment/87881956
has comment: http://stackoverflow.com/comment/87882210
downvote count: 0
has comment: http://stackoverflow.com/comment/87881520
has comment: http://stackoverflow.com/comment/87882562
has comment: http://stackoverflow.com/comment/87881043
has comment: http://stackoverflow.com/comment/87881314
has comment: http://stackoverflow.com/comment/87881034
has comment: http://stackoverflow.com/comment/87881733
has body: Have you tested if the file is actually open at the end of the block? Because I think you'll find it is. The code in the 'finally' part of a try: except: block is obeyed regardless of whether there is an exception or not. From the python documentation: If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded:
has comment: http://stackoverflow.com/comment/87883192
answers question: http://stackoverflow.com/q/50433239
has comment: http://stackoverflow.com/comment/87882619
has comment: http://stackoverflow.com/comment/87883110
has comment: http://stackoverflow.com/comment/87881363
type: Answer
has comment: http://stackoverflow.com/comment/87880989
has comment: http://stackoverflow.com/comment/87883510
has comment: http://stackoverflow.com/comment/87884316
has comment: http://stackoverflow.com/comment/87883210
has comment: http://stackoverflow.com/comment/87881160

http://stackoverflow.com/q/50507549
linked to: http://stackoverflow.com/q/21319929
has comment: http://stackoverflow.com/comment/88027255
has comment: http://stackoverflow.com/comment/88027133
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has title: Pandas dataframe check if string is not in column to append
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50507636
tagged with: pandas
score: 1
has body: I have a pandas dataframe with one of the columns called artist. I would like to append a new row only if the new artist name is not in this column. I tried but with no success: if (all_data != name.all(axis = 0)): all_data = all_data.append({'artist':str(name), 'netWorth':str(worth.strip())}, ignore_index = True) This is all the code I have: def get_webpage(i, url): URL = url+str(i) response = requests.get(URL) return bs4.BeautifulSoup(response.text, 'html.parser') COLUMNS = ['artist', 'netWorth'] all_data = pd.DataFrame(columns = COLUMNS) def scrape(soup): artists = soup.find_all('article', class_ = 'thumb-wrap') for ar in artists: name = ar.h3.a.text worth = ar.div.find('div', class_='bc-networth').text global all_data if (all_data['artist'] != name).any(): all_data = all_data.append({'artist':str(name), 'netWorth':str(worth.strip())}, ignore_index = True) i = 1 url = 'http://www.therichest.com/celebnetworth-category/celeb/singer/page/' while (i&lt;=14): soup = get_webpage(i, url) i = i+1 data = scrape(soup) i = 1 url = 'http://www.therichest.com/celebnetworth-category/celeb/musician/page/' while (i&lt;=7): soup = get_webpage(i, url) i = i+1 data = scrape(soup)
has answer: http://stackoverflow.com/a/50507636
tagged with: dataframe
type: Question

http://stackoverflow.com/q/50514413
tagged with: interpolation
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50515337
answer count: 1
has answer: http://stackoverflow.com/a/50515337
has body: I have to find interploation between two sets of points X,Y such that: X = [2011, 2012, 2013, 2014, 2015, 2016, 2017] Y = [0.947079910779078, 0.958840491330058, 0.948653507807658, .94687561871641, 0.94732364567882, 0.953963141055096, 0.943468711524127] I tried finding the interpolation through CubicSpline F_spline = scipy.interpolate.CubicSpline(X, Y, extrapolate='periodic')) But if i cross-check, I get, In [98]: F_spline_val = [F_spline(year) for year in X] Out[98]: [array(0.94707991), array(0.95884049), array(0.94865351), array(0.94687562), array(0.94732365), array(0.95396314), array(0.94707991)] Notice the last value here, calculated for 2017, is 0.94707991, whereas in the original variable, the value for 2017 was 0.943468711524127. Which is clearly inaccurate. What am I missing here? Why there is an ambiguous value for 2017?
tagged with: scipy
type: Question
has title: scipy.interpolate.CubicSpline is giving ambiguous result
tagged with: python

http://stackoverflow.com/comment/87994333
has text: `raw_input` returns a `str`. But in `trip_cost` you add it to `int`s. You may want to convert it first using `int()`. And, as others mentioned indirectly, your indentation is off.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50490713
type: Comment

http://stackoverflow.com/a/56544678
answers question: http://stackoverflow.com/q/50391967
type: Answer
upvote count: 8
score: 8
downvote count: 0
has body: If you'd like to check bounding boxes/labels visually, you can check this TFRecord Viewer: https://github.com/sulc/tfrecord-viewer

azure-iot-hub
tags question: http://stackoverflow.com/q/50531852
type: Tag
tag name: azure-iot-hub

http://stackoverflow.com/comment/87874028
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50429243
type: Comment
has text: shouldn't your endpoint be `requests.post('http://127.0.0.1:8080/products/')` ?

http://stackoverflow.com/a/50478418
has comment: http://stackoverflow.com/comment/87971079
has body: You do not need to loop over. For df as below: xChamp xRelegation 0 &lt;1% 12% 1 &lt;1% 20% The code using regex you can remove the characters that you want to remove from df, import re df = df.applymap(lambda x: re.sub('[&lt;%$]', '', x)).astype(float)/100 df['xChamp'] = df['xChamp'].replace(dict(zip([0.01, 0.99],[0.001, 99.99]))) print(df) Gives: xChamp xRelegation 0 0.001 0.12 1 0.001 0.20 2 99.99 0.20 Have a look at docs for more information.
type: Answer
answers question: http://stackoverflow.com/q/50478331
has comment: http://stackoverflow.com/comment/87971213
score: 0

http://stackoverflow.com/q/50391555
has body: If I created a scatter with variable c which give me color per value like this: import matplotlib.pyplot as plt x=[1,2,3] y=[3,5,2] c=[10,7,19] scplot = plt.scatter(x,y,c=c) now I want to get the color that will fir the number 9, how can I do it. I know that I can get the camp using scplot.get_cmap(), but how would I get the normalization from the scatter (I also know that I can do it manually, but the question is can I extract it from the scplot) Thanks.
has comment: http://stackoverflow.com/comment/87798607
accepted answer: http://stackoverflow.com/a/50391964
has answer: http://stackoverflow.com/a/50391964
has title: get scatter c=? Colormap and Normalize
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: matplotlib
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87800222
favorite count: 0
type: Question

http://stackoverflow.com/q/50467664
upvote count: 2
type: UnansweredQuestion
tagged with: multithreading
has title: Dynamic control of mkl-based numpy multithreading
tagged with: intel-mkl
tagged with: python
score: 2
has body: I'm using Anaconda's distribution of scientific Python, where numpy is compiled with mkl library. When attempting multiprocessing, i want to constrain numpy to use a single core. I know i can set the environment variables 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS' and 'OMP_NUM_THREADS' to '1' (using os.environ). However, this will cause numpy to use a single core all around my code, and i want to be able to control that dynamically. I've encountered Python's 'mkl' package (distributed as part of Anaconda), in which the function "set_num_threads(n)" exists. I tried it, but it leads to weird behavior - for linear algebra operations, it seems large enough matrices causes numpy to resume multithreading. Can anyone suggest a solution/lead/anything regarding dynamic control of numpy/mkl multithreading? Thanks a lot!
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/65671408

http://stackoverflow.com/comment/102491878
type: Comment
comment on: http://stackoverflow.com/a/58043067
score: 0
type: AnswerComment
has text: Hi Ghazal, i have not seen this before. Looks interesting. So does this give a list of all the things relating to Spyder, even which python interpreter its using.

http://stackoverflow.com/a/50580080
answers question: http://stackoverflow.com/q/50529955
type: Answer
has body: Unfortunately the requirements got changed and the columns that i wanted were - FileName,Class_par_ratio, Confidence. Here confidence is nothing but ((freq/max_freq)*100) If the value is more than 80 then output HIGH. If the value is between 60-80 then output MEDIUM, else LOW. the output would look like - FileName COMM_CODE Confidence 17743633 - 1 OTHER GOODS MEDIUM 17743634 - 1 MEAT &amp; LIVESTOCK HIGH 17743634 - 2 MEAT &amp; LIVESTOCK HIGH 17743635 - 1 MEAT &amp; LIVESTOCK HIGH Following is the code that i wrote to get to this output- mf = (df.groupby(['FileName'])['COMM_CODE'].value_counts().reset_index(name='Freq')) we = mf.groupby(['FileName'])['Freq'].apply(lambda grp: grp.nlargest(6).sum()).reset_index(name='Tot') mf = mf.groupby(['FileName']).first().reset_index() mf['Confidence_%'] = (mf['Freq']/we['Tot'])*100 mf['Confidence'] = ['HIGH' if x &gt;= 80.0 else 'MEDIUM' if x&gt;=60.0 else 'LOW' for x in mf['Confidence_%']] mf.drop(['Freq','Confidence_%'],axis=1,inplace=True)
score: 0

http://stackoverflow.com/q/50472831
has comment: http://stackoverflow.com/comment/87961040
tagged with: sqlite
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50483466
linked to: http://stackoverflow.com/q/41396127
tagged with: sqlalchemy
linked to: http://stackoverflow.com/q/17887519
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87959419
has comment: http://stackoverflow.com/comment/87974607
score: 3
has body: I am not a programmer yet (working on it - this is my first big project), so sorry for the messy-ugly code. I have some issues using QuerySelectField and request.form['form_field_name'] to pull data from a SQlite table and to put it in another table. I am trying to get data from the name column in the Post model to fill the actual_amount_name column in the ActualPost model, but I think I am actually pulling dictionary keys. These are the 2 models/tables I am using: class Post(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(30), nullable=False, default='planned') category = db.Column(db.String(30), nullable=False, default=None) name = db.Column(db.String(30), nullable=True) planned_amount_month = db.Column(db.Float, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) date_period = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) comments = db.Column(db.Text, nullable=True) def __repr__(self): return f"Post('{self.title}, '{self.category}'\ , '{self.name}', '{self.planned_amount_month}'\ , '{self.date_period}', '{self.comments}')" #the function below queries the above model and passes the data to the QuerySelectField def db_query(): return Post.query class ActualPost(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(30), nullable=False, default='actual') category = db.Column(db.String(30), nullable=False, default=) actual_amount_name = db.Column(db.String(30), nullable=True) actual_amount = db.Column(db.Float, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) comments = db.Column(db.Text, nullable=True) def __repr__(self): return f"ActualPost('{self.title}, '{self.category}'\ , '{self.actual_amount_name}', '{self.actual_amount}'\ , '{self.date_posted}', '{self.comments}')" Now the forms: In t…
accepted answer: http://stackoverflow.com/a/50483466
tagged with: wtforms
has comment: http://stackoverflow.com/comment/87971619
has title: Python QuerySelectField and request.form returning dict key, not dict value
tagged with: python
tagged with: flask
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/87974371

http://stackoverflow.com/a/50432949
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50432668
has body: If nope can be not only at the end of the line you can use this with open('e.txt') as e: alist = [line.split() for line in e if 'nope' not in line] print(alist)
downvote count: 0

http://stackoverflow.com/a/55484426
answers question: http://stackoverflow.com/q/50523950
has comment: http://stackoverflow.com/comment/105686842
downvote count: 0
has body: After playing around with my table which has a lot of columns I decided the best thing to do to get a feel for the data is to use: df.show(n=5, truncate=False, vertical=True) This displays it vertically without truncation and is the cleanest viewing I can come up with.
has comment: http://stackoverflow.com/comment/109045135
type: Answer
upvote count: 29
score: 29

http://stackoverflow.com/q/50515476
has comment: http://stackoverflow.com/comment/88044102
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50515874
upvote count: 2
tagged with: random-forest
has comment: http://stackoverflow.com/comment/88043807
tagged with: scikit-learn
tagged with: python
accepted answer: http://stackoverflow.com/a/50515874
downvote count: 1
has comment: http://stackoverflow.com/comment/88043834
type: AnsweredQuestion
has title: RandomForestClassifier error 'object of type 'int' has no len()'
has comment: http://stackoverflow.com/comment/88044015
has body: I am writing a code? and got struggled with ''object of type 'int' has no len()'' Here's the piece of the code parameters = {'max_depth':range(3, 11, 2), 'class_weight':range(3, 11, 2), 'min_impurity_decrease':range(3, 11, 2), 'max_features':range(3, 11, 2)} knc = RandomForestClassifier() clf = GridSearchCV(knc, parameters) clf.fit(X_train, y_train) clf.best_estimator_ Here's the traceboard TypeError Traceback (most recent call last) &lt;ipython-input-71-3f7bf4b64f84&gt; in &lt;module&gt;() 4 knc = RandomForestClassifier() 5 clf = GridSearchCV(knc, parameters) ----&gt; 6 clf.fit(X_train, y_train) 7 clf.best_estimator_ ~\Anaconda3\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params) 637 error_score=self.error_score) 638 for parameters, (train, test) in product(candidate_params, --&gt; 639 cv.split(X, y, groups))) 640 641 # if one choose to see train score, "out" will contain train score info ~\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py in __call__(self, iterable) 777 # was dispatched. In particular this covers the edge 778 # case of Parallel used with an exhausted iterator. --&gt; 779 while self.dispatch_one_batch(iterator): 780 self._iterating = True 781 else: ~\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py in dispatch_one_batch(self, iterator) 623 return False 624 else: --&gt; 625 self._dispatch(tasks) 626 return True 627 ~\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py in _dispatch(self, batch) 586 dispatch_timestamp = time.time() 587 cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self) --&gt; 588 job = self._backend.apply_async(batch, callback=cb) 589 self._jobs.append(job) 590 ~\Anaconda3\lib\site-packages\sklearn\externals\joblib\_parallel_backends.py in apply_async(self, func, callback) 109 def apply_async(self, func, callback=None): 110 """Schedule a func to be run""" --&gt; 111 result = ImmediateResult(func) 112 if callback: 113 callback(result) …
has comment: http://stackoverflow.com/comment/88044113
score: 1
answer count: 1

http://stackoverflow.com/comment/89220112
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50415484
type: Comment
has text: @ramiro in which file did you place that line?

http://stackoverflow.com/comment/109234178
has text: This is flipping amazing, and should really be called a rubik's cube :D
comment on: http://stackoverflow.com/a/50463452
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50502956
answers question: http://stackoverflow.com/q/50502696
has comment: http://stackoverflow.com/comment/88020473
score: 0
has comment: http://stackoverflow.com/comment/88018738
has comment: http://stackoverflow.com/comment/88021741
has comment: http://stackoverflow.com/comment/88018753
accepted answer of: http://stackoverflow.com/q/50502696
has comment: http://stackoverflow.com/comment/88019309
type: Answer
has comment: http://stackoverflow.com/comment/88022123
has comment: http://stackoverflow.com/comment/88019477
has comment: http://stackoverflow.com/comment/88023706
has comment: http://stackoverflow.com/comment/88018876
has body: Perhaps you mean sth like this: words = ' '.join(listvalue).upper().split() idx = df.value.str.upper().isin(words) In: df[idx] Out: variable value 48 Income salary 81 Shopping clothing
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88020635
has comment: http://stackoverflow.com/comment/88019357
has comment: http://stackoverflow.com/comment/88023890
has comment: http://stackoverflow.com/comment/88023530

http://stackoverflow.com/comment/87801437
comment on: http://stackoverflow.com/a/50389918
has text: Could you please take a look at this question also :) https://stackoverflow.com/questions/50390255/lambda-function-causing-too-many-values-to-unpack
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50416336
has body: import comtypes.client as com app=com.GetActiveObject('Word.Application') app.Visible = True app.Resize(400, 400) Using this python script one can connect to opened MS Word document and resize it. I need to programmatically change currently selected ribbon item. I need to emulate click on "File", "Home", "Insert", "Design" and so on. I am especially interested to open backstage view programmatically. Do you if there are such COM interfaces?
has answer: http://stackoverflow.com/a/50416713
tagged with: windows
tagged with: python
tagged with: ms-word
type: Question
tagged with: ribbon
answer count: 2
tagged with: com
has title: MS Word change currently selected ribbon item using COM interface
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50417883

http://stackoverflow.com/comment/87853540
type: Comment
has text: Thank you very much! that works for me :) I've tried to delete the `get_initial` and worked too, could you please tell me where I should use the `get_initial` and where the `form_valid`? I know it is another question, but I have to ask to know why the first is not necessary here :)
comment on: http://stackoverflow.com/a/50418554
type: AnswerComment
score: 0

http://stackoverflow.com/q/50429243
has comment: http://stackoverflow.com/comment/87874568
has answer: http://stackoverflow.com/a/50430883
score: 2
has comment: http://stackoverflow.com/comment/87874188
has comment: http://stackoverflow.com/comment/87874128
has comment: http://stackoverflow.com/comment/87874028
has title: How to send POST request to Django REST API using python requests
linked to: http://stackoverflow.com/q/27315592
downvote count: 0
answer count: 1
has body: I have a simple rest api which I want to send a post request to using requests. My url pattern is this: url(r'^$', views.ProductList.as_view()) Inside my view I have: class ProductList(generics.ListAPIView): serializer_class = ProductSerializer def post(self, request, format=None): print('THIS IS A POST REQUEST') queryset = [product.name for product in Product.objects.all()] return Response(queryset) And I am trying to send a post request using: response = requests.post('http://127.0.0.1:8080/') However this returns a 403, and the print statement isn't printed. I have done some research and I think it may have something to do with the CSRF token not being there but i'm not to sure how to add that. Does anybody know how I can get the post request to work? I'm using python 3.6.3 and Django 1.10
tagged with: python-requests
has comment: http://stackoverflow.com/comment/87873935
tagged with: post
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87874221
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87873824
tagged with: django
has comment: http://stackoverflow.com/comment/87873213
has comment: http://stackoverflow.com/comment/87874209
tagged with: python
linked to: http://stackoverflow.com/q/4476373
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/87874557
has comment: http://stackoverflow.com/comment/87873980
has comment: http://stackoverflow.com/comment/87873226
has comment: http://stackoverflow.com/comment/87874241

http://stackoverflow.com/a/50475143
has body: If I understand correctly, you're trying to right-pad each row with zeros so that the length becomes fixed. Turns out there is a really simple solution to that, right in the first line of your code (note I've replaced tf.sparse_tensor_to_dense() to tf.sparse_to_dense() - these are different!): filter = tf.less( features.indices[ :, 1 ], params.max_doc_len ) features = tf.sparse_retain( features, filter ) features = tf.sparse_to_dense( sparse_indices = features.indices, output_shape = ( params.batch_size, params.max_doc_len ), sparse_values = features.values, default_value = 0 ) The first two lines just implement a filter to throw away any values that would be beyond the max_doc_len, so basically truncating all rows. The main idea here is that tf.sparse_to_dense() allows manual specification of the resulting tensor's shape, which we want here, and it fills the rest with zeroes anyway. So this one line does what your section of code is for. P.S. Notwithstanding, the probable bug in TensorFlow remains, but I was unable to reproduce the issue anywhere.
has comment: http://stackoverflow.com/comment/87965719
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/87971703
has comment: http://stackoverflow.com/comment/87965565
has comment: http://stackoverflow.com/comment/87965428
score: 2
has comment: http://stackoverflow.com/comment/87965220
answers question: http://stackoverflow.com/q/50401102
downvote count: 0
has comment: http://stackoverflow.com/comment/87965258

http://stackoverflow.com/comment/87941925
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50462470
has text: the "3} " inverted commas are hiding the data from being displayed in the excel file and in the notepad file the data can be viewed but with the inverted commas
score: 0

http://stackoverflow.com/a/50477153
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50476930
upvote count: 1
has body: Here's the missing steps that remove row duplicates from your dataframe: nodups = df.stack().reset_index(level=0).drop_duplicates() nodups = nodups.set_index(['level_0', nodups.index]).unstack() nodups.columns = nodups.columns.levels[1] # id val1 val2 val3 #level_0 #0 1 A None B #1 1 A B None #2 1 B C None #3 1 None B D #4 2 A D None Now you can follow with: nodups.set_index('id').stack().groupby(level=0).value_counts() Perhaps you can further optimize the code.
answers question: http://stackoverflow.com/q/50476930
type: Answer
score: 1

http://stackoverflow.com/comment/87817180
comment on: http://stackoverflow.com/q/50400632
type: Comment
score: 1
has text: Can you provide the full error traceback?
type: QuestionComment

http://stackoverflow.com/q/50531623
score: 4
possible better answer: http://stackoverflow.com/a/59742702
tagged with: gmail
type: AnsweredQuestion
answer count: 3
tagged with: api
has title: 403 insufficient permission for gmail api with python
has body: i am trying to run the gmail API to get email from a specif user. However i always receive the following error: googleapiclient.errors.HttpError: https://www.googleapis.com/gmail/v1/users/me/settings/filters?alt=json returned "Insufficient Permission"> I have tried all the different options suggested from changing the scope to enabling the less secure applications in the gmail setting. The last thing is that my code could be wrong: from __future__ import print_function from googleapiclient import discovery from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Gmail API SCOPES = 'https://mail.google.com/' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) # Call the Gmail API # results = service.users().labels().list(userId='me').execute() # labels = results.get('labels', []) # if not labels: # print('No labels found.') # else: # print('Labels:') # for label in labels: # print(label['name']) label_id = 'mine' # ID of user label to add filter = { 'criteria': { 'from': 'string@test.com' }#, #'action': { #'addLabelIds': [label_id], #'removeLabelIds': ['INBOX'] #} } result = service.users().settings().filters().create(userId='me', body=filter).execute() print ('Created filter: %s' % result.get('id')) Could please help me? Thanks
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/59742702
accepted answer: http://stackoverflow.com/a/50651441
has answer: http://stackoverflow.com/a/51524072
linked to: http://stackoverflow.com/q/24484970
has answer: http://stackoverflow.com/a/50651441
downvote count: 0
tagged with: python

http://stackoverflow.com/a/50666970
has body: It turns out the .pyx file contains a line # distutils: sources = Donline.cpp Handler.cpp Process.cpp Filter.cpp Localize.cpp which tells distutils what to compile. I wasn't aware of it, and since it looks an awful lot like a commented-out line, I didn't realise it was there. Cython tries to compile also these, other than the ones contained in the setup.pyfile, i.e. neither of the two sources list overrides the other. Apparently, these sources, despite being listed in the pyx file, which is in a subfolder, are expected to be in paths relative to the file where the setup.py file is, or perhaps relative to the folder I'm calling python from. Anyway, removing the line solved the issue.
type: Answer
accepted answer of: http://stackoverflow.com/q/50448026
upvote count: 6
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50448026
downvote count: 0
score: 6

http://stackoverflow.com/a/50456525
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: This is the input example: 0 / \ 1 2 / \ /|\ 3 4 5 6 7 Think about what you want the (recursive) function to return for each of the nodes: when called on the root (0), it should return the full result (3, 4, 5, 6, 7) when called on a leaf node (e.g. 5), it should return that node (5) for any other node (e.g. 1), it does as if that was a root node of a smaller tree So, it sometimes returns one result and sometimes many. The error in your code is here, because the function ends on the first return, it does not return many: for i in self.children: return i.find2() There are two solutions: make a generator function, or make a function which returns a list (make it return a list always, even if it has just one element!) So, option 1: def find(self): if not hasattr(self, 'children'): yield self else: for child in self.children: yield from child.find() option 2: def find(self): if not hasattr(self, 'children'): return [self] else: rtn = [] for child in self.children: for result in child.find(): rtn.append(result) return rtn I prefer the generator. Additionally, I don't particularly like the fact that some of your nodes have a children attribute, while others do not. I would make sure all of them had children, which could be empty or non-empty. Then, the code becomes: def find_leaves(self): if self.children: for child in self.children: yield from child.find_leaves() else: yield self
has comment: http://stackoverflow.com/comment/87926897
accepted answer of: http://stackoverflow.com/q/50455832
has comment: http://stackoverflow.com/comment/87928098
type: Answer
has comment: http://stackoverflow.com/comment/87927916
answers question: http://stackoverflow.com/q/50455832
has comment: http://stackoverflow.com/comment/87927646

http://stackoverflow.com/comment/87960838
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50473557
type: Comment
has text: I don't understand. How do I call the function "async def someFunction()" and make it loop forever?

http://stackoverflow.com/a/64078890
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50507194
has body: Mezzanine 4.3.1 with Django 2.2 support (until release Mezzanine v.5 will be ready) you can use the following line in your requirements -e git+git://github.com/stephenmcd/mezzanine.git@9768b46f8377796d5d51d74db54589c9d3669a47#egg=Mezzanine # feat: Add Django 2.2 compatability (#1956) or for pip pip install -e git+git://github.com/stephenmcd/mezzanine.git@9768b46f8377796d5d51d74db54589c9d3669a47#egg=Mezzanine related PR
downvote count: 0
type: Answer

http://stackoverflow.com/q/50536931
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50540484
has body: I try to collect data from twitter with coordinates. However, I got the results is'coordinates: None' from twitter import * from email.utils import parsedate stream = TwitterStream(auth = auth, secure = True) stream search_term = "candy" tweet_stream = stream.statuses.filter(track = search_term, language='en', geo=True) l =[] for tweet in tweet_stream: l.append(tweet) Do we have a parameters to collect the geo-data from twitter? Or it depends on the users with permission to access the location?
answer count: 1
has answer: http://stackoverflow.com/a/50540484
tagged with: twitter
has title: Collecting coordinates of Twitter in Python package
type: Question

http://stackoverflow.com/comment/88085740
score: 0
comment on: http://stackoverflow.com/q/50536736
type: Comment
type: QuestionComment
has text: No, myList is a list of many tuples. But always start is before end. @user4343502

redis-py
tags question: http://stackoverflow.com/q/50486563
tags question: http://stackoverflow.com/q/50511910
tag name: redis-py
tags question: http://stackoverflow.com/q/50518116
type: Tag

http://stackoverflow.com/comment/87959751
score: 0
has text: I'm getting a lot of malicious traffic from several ips that look like they're in the same subnet, however there are a few thousand ips, how do I convert a list like this into subnets so that I can block the subnet?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50472999

http://stackoverflow.com/q/50484358
tagged with: list
has comment: http://stackoverflow.com/comment/87982020
has comment: http://stackoverflow.com/comment/87982309
score: 1
answer count: 1
tagged with: python
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has body: Hi I am trying to build a model structure library with different combinations. Structure library is based on 5 variables for which I need five models. i-e modelsOne, modelsTwo and so on upto five. For simplicity I am pasting the code in bunches which is same for all five models. It has very little change in it. When I execute the code I get the following error modelOne = modelsOne[temp1] IndexError: list index out of range def ModelsProduct(modelsOne, modelsTwo, modelsThree, modelsFour,modelsFive): modelsStepOne = list(product("+-",repeat = 4)) modelsStepThree = [('a','a'),('a','b'),('a','c'),('a','d'),('a','e'),('b','b'),('b','c'),('b','d'),('b','e'),('c','c'),('c','d'),('c','e')] modelsStepFour = [('d','d'),('d','e')] modelsStepFive = [('e','e')] #produce modelsOne modelsStepTwo = [('d',),('e',)] for one in modelsStepOne: for two in modelsStepTwo: for three in modelsStepThree: for four in modelsStepFour: for five in modelsStepFive: modelsOne.append(one+two+three+four+five) #produce modelsTwo modelsStepTwo = [('c',),('d',)] for one in modelsStepOne: for two in modelsStepTwo: . . . return modelsOne, modelsTwo, modelsThree, modelsFour, modelsFive modelsOne, modelsTwo,modelsThree, modelsFour,modelsFive = ModelsProduct(modelsOne, modelsTwo, modelsThree, modelsFour, modelsFive) VarList = ["a","b","c","d","e"] initial_condi = [10, 15, 5,4,5] dictVar = {'a':0, 'b': 1, 'c': 2, 'd': 3, 'e':4} ops = { "+": operator.add, "-": operator.sub } t_range = arange(0.0,60.0,1.0) def odeFunc(Y, t, x,dictVar): if x[-5] == 3072: temp1 = 3071 else: temp1 = int(x[-5]) if x[-4] == 3072: temp2 = 3071 else: temp2 = int(x[-4]) if x[-3] == 3072: temp3 = 3071 else: temp3 = int(x[-3]) if x[-2] == 3072: temp4 = 3071 else: temp4 = int(x[-2]) if x[-1] == 3072: temp5 = 3071 else: temp5 = int(x[-1]) modelOne = modelsOne[temp1] modelTwo = modelsTwo[temp2] modelThree = modelsThree[temp3] modelFour = modelsFour[temp4] modelFive = modelsFive[temp5] return GenModel(Y, x, modelOne,modelTwo,modelThree,model…
upvote count: 1
has title: IndexError: list index out of range for making a variable structure library
has comment: http://stackoverflow.com/comment/87981976
has answer: http://stackoverflow.com/a/50484462
downvote count: 0
has comment: http://stackoverflow.com/comment/87981868
accepted answer: http://stackoverflow.com/a/50484462
type: AnsweredQuestion

http://stackoverflow.com/q/50528569
has comment: http://stackoverflow.com/comment/88084308
tagged with: mechanize
has comment: http://stackoverflow.com/comment/88072231
has comment: http://stackoverflow.com/comment/88072566
has comment: http://stackoverflow.com/comment/88072089
has comment: http://stackoverflow.com/comment/88093844
tagged with: python
has comment: http://stackoverflow.com/comment/88071232
has comment: http://stackoverflow.com/comment/88072978
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88093832
tagged with: bots
has comment: http://stackoverflow.com/comment/88093972
has comment: http://stackoverflow.com/comment/88068977
score: 1
has comment: http://stackoverflow.com/comment/88130888
answer count: 1
tagged with: request
downvote count: 0
has comment: http://stackoverflow.com/comment/88069004
upvote count: 1
accepted answer: http://stackoverflow.com/a/50560364
has comment: http://stackoverflow.com/comment/88071803
has comment: http://stackoverflow.com/comment/88094181
has answer: http://stackoverflow.com/a/50560364
favorite count: 0
type: Question
has body: I'm trying to make a bot in order to reset my router easily, so I'm using mechanize for this task. import mechanize br = mechanize.Browser() br.set_handle_robots(False) response = br.open("http://192.168.0.1/") br.select_form(nr=0) br.form['loginUsername']='support' br.form['loginPassword']='71689637' response=br.submit() if(response.read().find("wifi")) != -1: # ????? If it finds the string 'wifi', it means the bot has logged in, but here's where I get stuck, because the restart button is in another tab (Another page, I guess that from the same object indicating the new URL it should be able to follow the redirection URL without logging off). However, the button from that tab is, well, a button but not a form. Picture 1: Picture 2: And here's the source: https://github.com/SharkiPy/Code-stackoverflow/blob/master/Source
has title: Python issues, mechanize bots
has comment: http://stackoverflow.com/comment/88084162

http://stackoverflow.com/a/50416499
type: Answer
answers question: http://stackoverflow.com/q/50415752
accepted answer of: http://stackoverflow.com/q/50415752
has body: The main problem originates from the frames you used: they are never packed. So pack them and set this option: fill='both'. You also did mistakes when, sometimes, you pack two widgets of the same frame to left instead of setting one of them to the left and the other to the right. You also need to use the justify='right' for the text to show in the right inside each entry widget. Here is your code (need to be cleaned) with the demo: import tkinter class Loan: def __init__(self): #Create main Window self.main_window = tkinter.Tk() self.main_window.title("Loan Calculator") #Create the six frames self.intRate_frame = tkinter.Frame(self.main_window) self.intRate_frame.pack() self.numYears_frame = tkinter.Frame(self.main_window) self.numYears_frame.pack(fill='both') self.loanAmount_frame = tkinter.Frame(self.main_window) self.loanAmount_frame.pack(fill='both') self.monthlyPayment_frame = tkinter.Frame(self.main_window) self.monthlyPayment_frame.pack(fill='both') self.totalPayment_frame = tkinter.Frame(self.main_window) self.totalPayment_frame.pack(fill='both') self.button_frame = tkinter.Frame(self.main_window) self.button_frame.pack(fill='both') # Create and pack the widgets for interest rate self.intRate_label = tkinter.Label(self.intRate_frame, \ text='Annual Interest Rate', anchor="w") self.intRate_entry = tkinter.Entry(self.intRate_frame, \ width=20, justify='right') self.intRate_label.pack(side='left') self.intRate_entry.pack(side='left') #Create and pack the widgets for number of years self.numYears_label = tkinter.Label(self.numYears_frame, text='Number of Years') self.numYears_entry = tkinter.Entry(self.numYears_frame, justify='right') self.numYears_label.pack(side='left') self.numYears_entry.pack(side='right') #Create and pack the widgets for loan Amount self.loanAmount_label = tkinter.Label(self.loanAmount_frame, \ text='Loan Amount', anchor = "nw") self.loanAmount_entry = tkinter.Entry(self.loanAmount_frame, \ width=20, justify='right') self.loanAmount_label.p…
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/87827822
comment on: http://stackoverflow.com/a/50403655
type: AnswerComment
score: 0
has text: Thx,I understand! It preserve the probe order!
type: Comment

http://stackoverflow.com/q/50495054
tagged with: plotly
has body: import os import seaborn as sns print(os.listdir("../input")) df=pd.read_csv("../input/gun-violence-data_01-2013_03-2018.csv") //GUN violence dataset from kaggle// from plotly.offline import init_notebook_mode, iplot init_notebook_mode(connected=True) import plotly.graph_objs as go b=df.state.value_counts().sort_values() ba=pd.DataFrame(b) ans=ba.reset_index(inplace=True) //creating a dataframe only containing the state names of USA and its count// data = [ dict(type='choropleth', autocolorscale = False, locations = ba['index'], z = ba['state'], locationmode = 'USA-states', text = ba['index'], colorscale='Viridis' ) ] layout = dict( title = 'US', geo = dict( scope='usa', projection=dict( type='albers usa' ), showlakes = True, lakecolor = 'rgb(255, 165, 255)'),) fig = go.Figure( data=data,layout=layout ) iplot(fig) However, whenever I run this code, Only a blank image of USA is obtained, which is blank and shows no values. please help!
has comment: http://stackoverflow.com/comment/88003350
has title: Choropleth in Plotly python for USA is Blank
score: 0
answer count: 0
tagged with: kaggle
tagged with: python
type: UnansweredQuestion
tagged with: data-science
has comment: http://stackoverflow.com/comment/88003082
has comment: http://stackoverflow.com/comment/88003959
has comment: http://stackoverflow.com/comment/88003720
has comment: http://stackoverflow.com/comment/88003629
type: Question

http://stackoverflow.com/comment/88023606
comment on: http://stackoverflow.com/q/50504315
score: 1
type: QuestionComment
has text: @AntonvBR No, that would try to make a key from the `max` of each individual timestamp, which doesn't make a lot of sense, and `max` raises `TypeError` if you try to get the maximum of a number rather than an iterable.
type: Comment

http://stackoverflow.com/a/52244360
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50413910
has comment: http://stackoverflow.com/comment/117413192
type: Answer
has comment: http://stackoverflow.com/comment/117457737
accepted answer of: http://stackoverflow.com/q/50413910
has body: No, the IDF format is proprietary and encrypted, it seems to be. And SMI Vision was acquired by Apple in 2016, that's why the website is almost down. The utility you need, IDF Converter, is contained as part of an iTools bundle. Method 1. Download from file sharing service. The link kindly provided by Dr. Kenneth Holmqvist, Lund University. Method 2. Search FTP servers, e.g. searchftps.net. In order to use it, you have to disable AdBlock, then try searching "iTools_setup.exe", and use dedicated downloading software like FreeDownloadManager or GetRight.
score: 1

http://stackoverflow.com/q/50458412
tagged with: mxnet
tagged with: python
tagged with: computer-vision
accepted answer: http://stackoverflow.com/a/50477614
type: AnsweredQuestion
score: 0
tagged with: deep-learning
answer count: 1
has title: Is there any side effect by using ‘Sequential()’ or ‘HybridSequential()’ as a container only?
type: Question
has body: I am reading a tutorial about MxNet. The writers use ‘mxnet.gluon.nn.Sequential()’ as a container to store some blocks (see code 1); then, they rewrite the connection of blocks in ‘def forward(self, x)’ (see codes 2 and 3). Is there any side effect by doing this? By the way, what is the difference between ‘Sequential()’ and ‘HybridSequential()’. I try a list to replace the ‘Sequential’, and I get following warnings doing the initialization process. “ToySSD.downsamplers” is a container with Blocks. Note that Blocks inside the list, tuple or dict will not be registered automatically. Make sure to register them using register_child() or switching to nn.Sequential/nn.HybridSequential instead.’ As far as I know, if you put some blocks in ‘mxnet.gluon.nn.Sequential()’ or ‘mxnet.gluon.nn.HybridSequential()’, this action is telling the computer that these blocks are connected. However, if you design the relationship of blocks in the ‘forward’ function, you are telling the computer to connect these blocks in another way. Will it lead to confusion? If I only design some block connections in ‘forward’, what are the relationships of the other blocks in ‘Sequential()’ that are not designed in ‘forward’ function? The entire tutorial can be found in here. code 1： def toy_ssd_model(num_anchors, num_classes): downsamplers = nn.Sequential() for _ in range(3): downsamplers.add(down_sample(128)) class_predictors = nn.Sequential() box_predictors = nn.Sequential() for _ in range(5): class_predictors.add(class_predictor(num_anchors, num_classes)) box_predictors.add(box_predictor(num_anchors)) model = nn.Sequential() model.add(body(), downsamplers, class_predictors, box_predictors) return model code 2: def toy_ssd_forward(x, model, sizes, ratios, verbose=False): body, downsamplers, class_predictors, box_predictors = model anchors, class_preds, box_preds = [], [], [] # feature extraction x = body(x) for i in range(5): # predict anchors.append(MultiBoxPrior( x, sizes=sizes[i], ratios=ratios[…
has answer: http://stackoverflow.com/a/50477614

http://stackoverflow.com/q/50417109
has comment: http://stackoverflow.com/comment/87850066
has comment: http://stackoverflow.com/comment/87850148
score: 1
has body: I have a simple directory structure like so: lib/ dir1/ __init__.py dir2/ __init__.py file1.py file2.py main.py file1.py imports file2.py main.py does from dir1.dir2.file1 import *. However, when I run main.py I get the following error: No module named 'file2' When I run file from dir2 it's fine. How does the python3 import system work?
tagged with: python
has comment: http://stackoverflow.com/comment/87849889
has comment: http://stackoverflow.com/comment/87850729
has comment: http://stackoverflow.com/comment/87850314
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87850488
has title: Python3 import failure
answer count: 0
has comment: http://stackoverflow.com/comment/87849934
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87849956
has comment: http://stackoverflow.com/comment/87850047
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87850092
duplicate of: http://stackoverflow.com/q/37139192

http://stackoverflow.com/comment/88189887
has text: @darthbith Thanks a lot! got it!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50537131
score: 0

http://stackoverflow.com/comment/87886077
has text: Why does it need to sort them after selecting distinct ones?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50435958

http://stackoverflow.com/comment/88034320
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50509905
score: 0
has text: Add error that you are getting

http://stackoverflow.com/comment/88094313
comment on: http://stackoverflow.com/q/50540547
has text: Assuming you want `logDHT.py` to run every minute, and `checkDB.py` to run every 15 minutes, then yes, that is correct.
score: 0
type: Comment
type: QuestionComment

indexing
tags question: http://stackoverflow.com/q/50521364
tag name: indexing
tags question: http://stackoverflow.com/q/50489604
tags question: http://stackoverflow.com/q/50403041
type: Tag
tags question: http://stackoverflow.com/q/50397744
tags question: http://stackoverflow.com/q/50502150
tags question: http://stackoverflow.com/q/50534579
tags question: http://stackoverflow.com/q/50446907
tags question: http://stackoverflow.com/q/50497999
tags question: http://stackoverflow.com/q/50432185
tags question: http://stackoverflow.com/q/50510374
tags question: http://stackoverflow.com/q/50500415
tags question: http://stackoverflow.com/q/50510642
tags question: http://stackoverflow.com/q/50389518
tags question: http://stackoverflow.com/q/50500553
tags question: http://stackoverflow.com/q/50393580
tags question: http://stackoverflow.com/q/50537015

http://stackoverflow.com/comment/88020204
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50494617
has text: Possible duplicate of [Tkinter IntVar returning PY\_VAR0 instead of value](https://stackoverflow.com/questions/24768455/tkinter-intvar-returning-py-var0-instead-of-value)

http://stackoverflow.com/comment/87933704
type: QuestionComment
comment on: http://stackoverflow.com/q/50460233
has text: Maybe try `[f.dimensions for f in l.getLayerFilters()]`?
score: 0
type: Comment

http://stackoverflow.com/q/50501787
tagged with: python
accepted answer: http://stackoverflow.com/a/50501889
score: 107
has body: I'm doing some code practice and applying merging of data frames while doing this getting user warning /usr/lib64/python2.7/site-packages/pandas/core/frame.py:6201: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version of pandas will change to not sort by default. To accept the future behavior, pass 'sort=True'. To retain the current behavior and silence the warning, pass sort=False On these lines of code: Can you please help to get the solution of this warning. placement_video = [self.read_sql_vdx_summary, self.read_sql_video_km] placement_video_summary = reduce(lambda left, right: pd.merge(left, right, on='PLACEMENT', sort=False), placement_video) placement_by_video = placement_video_summary.loc[:, ["PLACEMENT", "PLACEMENT_NAME", "COST_TYPE", "PRODUCT", "VIDEONAME", "VIEW0", "VIEW25", "VIEW50", "VIEW75", "VIEW100", "ENG0", "ENG25", "ENG50", "ENG75", "ENG100", "DPE0", "DPE25", "DPE50", "DPE75", "DPE100"]] # print (placement_by_video) placement_by_video["Placement# Name"] = placement_by_video"PLACEMENT", "PLACEMENT_NAME".apply(lambda x: ".".join(x), axis=1) placement_by_video_new = placement_by_video.loc[:, ["PLACEMENT", "Placement# Name", "COST_TYPE", "PRODUCT", "VIDEONAME", "VIEW0", "VIEW25", "VIEW50", "VIEW75", "VIEW100", "ENG0", "ENG25", "ENG50", "ENG75", "ENG100", "DPE0", "DPE25", "DPE50", "DPE75", "DPE100"]] placement_by_km_video = [placement_by_video_new, self.read_sql_km_for_video] placement_by_km_video_summary = reduce(lambda left, right: pd.merge(left, right, on=['PLACEMENT', 'PRODUCT'], sort=False), placement_by_km_video) #print (list(placement_by_km_video_summary)) #print(placement_by_km_video_summary) #exit() # print(placement_by_video_new) """Conditions for 25%view""" mask17 = placement_by_km_video_summary["PRODUCT"].isin(['Display', 'Mobile']) mask18 = placement_by_km_video_summary["COST_TYPE"].isin(["CPE", "CPM", "CPCV"]) mask19 = placement_by_km_video_summary["PRODUCT"].isin(["InStream"]) mask20 = placement_by_km…
type: AnsweredQuestion
upvote count: 108
tagged with: pandas
has title: Python Pandas User Warning: Sorting because non-concatenation axis is not aligned
downvote count: 1
has answer: http://stackoverflow.com/a/50501889
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52958220
possible better answer: http://stackoverflow.com/a/52958220

http://stackoverflow.com/a/50458762
type: Answer
answers question: http://stackoverflow.com/q/50448220
score: 0
type: AcceptedAnswer
has body: It turned out I was hammering the filesystem too hard, making too many concurrent read requests for files on the same server. That server could only allow a fixed number of reads in a given period, so any requests over that limit received a Connection Timed Out response. The solution was to wrap each file read request in a while loop. Inside that while loop, try to read the appropriate file from disk. If the Connection timed out error springs, sleep for a second and try again. Only once the file has been read may the while loop be broken.
accepted answer of: http://stackoverflow.com/q/50448220

http://stackoverflow.com/comment/87931603
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50459119
has text: How do you display a 3d structure as simple rows and columns? And read it back with code that expects that same csv layout? You can't without some sort of manipulation. Basically either reshape to and from 2d, or save the planes as separate 2d blocks. It's up to you to decide what the csv is supposed to look like.
score: 2

http://stackoverflow.com/comment/88038035
comment on: http://stackoverflow.com/q/50500553
type: Comment
type: QuestionComment
has text: You need to use `[-101:-2]` or `[-2:-101:-1]` to get a reverse list. Play with numbers like that in `arange` if you don't understand.
score: 0

http://stackoverflow.com/q/50416562
has title: Where is the text parameter in Tkinter Button class?
has answer: http://stackoverflow.com/a/50416593
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
downvote count: 0
upvote count: 1
score: 1
has body: Python beginner here! I was learning Tkinter and when I came across creating a button, they used this: quitButton = Button(self, text="Quit") And I went to check the declaration of Button under tkinter module in the __init__ script and it shows: class Button(Widget): """Button widget.""" ...... ...... So my question is, Why are we able to pass a text parameter?
answer count: 1
tagged with: button
favorite count: 0
type: Question

http://stackoverflow.com/comment/87974848
comment on: http://stackoverflow.com/q/50480793
score: 1
type: QuestionComment
has text: It seems you cannot ignore a hard-coded break point. Instead you can use `python -m pdb script.py` to run your script in debug mode and use `unt(il) [lineno]` to where you want. Or you can set a break point by `b(reak) [([filename:]lineno | function) [, condition]]`
type: Comment

http://stackoverflow.com/q/50489754
has title: Conditionally replacing column values in pandas with values from a different dataframe
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87992421
accepted answer: http://stackoverflow.com/a/50489932
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50489932
tagged with: python
has body: I have two csv's which, when read as dataframes, look something like this: df: TargetIndex Current1 Current2 Current3 0 0 'D' 'D' 'G' 1 2 0 'E' 'F' 2 0 'A' 'E' 'F' 3 1 0 0 0 4 0 'A' 0 'A' 5 3 'G' 0 0 6 2 'F' 'E' 0 7 4 0 0 0 df2: TargetIndex Target1 Target2 Target3 0 1 'A' 'A' 'A' 1 2 'B' 'B' 'B' 2 3 'C' 'C' 'C' 3 4 'A' 'B' 'C' What I'm trying to do is replace only the 0 values in the Current columns with the values in the Target columns. However, only on rows in which the TargetIndex value isn't 0. I'm admittedly quite inexperienced with Python and normally I'd use a combination of additional columns and the LOOKUP function in excel for this, so I'm struggling quite a bit. What I've done so far is read a bunch of threads here, and tried various uses of .loc, .isin, .replace, and .map among other things but I've found it very hard to apply the conditions of TargetIndex != 0 and CurrentX == 0. Another thing I'm finding difficult is using the second dataframe in the first place, I've tried making it into a .dictwith such limited success that I do know how it works somewhat, I can't quite apply it. I did manage to reverse engineer the desired outcome into the following spaghetti code: df['Target1'] = df['TargetIndex'].map(df2.set_index('TargetIndex')['Target1']) df['Target2'] = df['TargetIndex'].map(df2.set_index('TargetIndex')['Target2']) df['Target3'] = df['TargetIndex'].map(df2.set_index('TargetIndex')['Target3']) S1 = df.Current1 == 0 S2 = df.Current2 == 0 S3 = df.Current3 == 0 df.loc[S1, 'Current1'] = df['TargetIndex'] df.loc[S2, 'Current2'] = df['TargetIndex'] df.loc[S3, 'Current3'] = df['TargetIndex'] df.replace({'Current1': { 1 : 'A', 2 : 'B', 3 : 'C', 4 : 'A'}}, inplace=True) df.replace({'Current2': { 1 : 'A', 2 : 'B', 3 : 'C', 4 : 'B'}}, inplace=True) df.replace({'Current3': { 1 : 'A', 2 : 'B', 3 : 'C', 4 : 'C'}}, inplace=True) df.drop(df.columns[[4, 5, 6]], axis=1, inplace=True) Which does indeed produce the desired outcome: df: TargetIndex Current1 Current2 …
tagged with: replace
tagged with: lookup
type: AnsweredQuestion

http://stackoverflow.com/comment/122584720
comment on: http://stackoverflow.com/a/62094561
score: 0
has text: @chetan 'PATH_TO_MSSQL_LOCATION' should be replaced by the server name that is hosting your MSSQL instance.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88027976
type: QuestionComment
has text: If you look up `map()` and `lambda` you can try and write this out in several longer form `def` functions
comment on: http://stackoverflow.com/q/50507990
score: 3
type: Comment

http://stackoverflow.com/a/51115933
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50534397
accepted answer of: http://stackoverflow.com/q/50534397
has body: $ export PYENV_ROOT=/usr/local/pyenv/ $ sudo /usr/local/pyenv/bin/pyenv versions This doesn't work because PYENV_ROOT won't be passed to the environment in sudo. Try this: $ sudo PYENV_ROOT=/usr/local/pyenv/ /usr/local/pyenv/bin/pyenv versions or this: $ export PYENV_ROOT=/usr/local/pyenv/ $ sudo -E /usr/local/pyenv/bin/pyenv versions -E will make the environment variables pass to pyenv. In the man page of sudo: -E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment. --preserve-env=list Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment. The security policy may return an error if the user does not have permission to preserve the environment. The .bash_profile in root doesn't work because sudo won't load it in this case. You can refer to this if you prefer to write the config in .bash_profile.
score: 1
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/comment/87850732
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50415567
type: Comment
has text: @Goyo Using Color Oracle (http://www.colororacle.org/) which changes the color of your screen to simulate various conditions (in my case luminance-preserving grayscale, which seems to produce the colors when printing a figure in grayscale on paper), the results are different for the second color. Therefore, my code is somehow altering the original color and it displays a different grayscale color than expected. I thought about bringing saturation to 0 but apparently this is not the right way to do it.

http://stackoverflow.com/q/50426462
tagged with: cgi
has comment: http://stackoverflow.com/comment/87868141
tagged with: web
tagged with: tensorflow
type: Question
has title: 500 Internal Server Error When Importing Python Modules
has comment: http://stackoverflow.com/comment/87868662
type: UnansweredQuestion
has body: I'm new to web development with Python, so this problem might be silly. I'm trying to run a Python script on my web server, but i'm encountering a problem when importing some modules. The script works fine when writing a simple script like this one: #!/usr/bin/python3.6 print("Content-Type: text/html\n") print("This is a test") And i can import most of the modules installed in the Python version of the server, but when i try to import some modules i really need for my script, i get a 500 Internal server error (these modules are tensorflow, keras and scikit-image). So this code gives a 500 error: #!/usr/bin/python3.6 import keras print("Content-Type: text/html\n") print("This is a test") I tried to print all the modules installed in the Python version with pip.get_installed_distributions() and all three modules i need, keras, tensorflow and scikit-image are installed. My questions are: How can i print the error to understand what the problem is? What could be the problem considering that the packages are installed but not working?
tagged with: python
has comment: http://stackoverflow.com/comment/87868166
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87878624
has comment: http://stackoverflow.com/comment/87867823

http://stackoverflow.com/a/50447160
type: Answer
has body: if i understand you correctly your resulting data set will contain 900.000.000 rows. scipy.spatial.distance.cdist - is one of the most efficient ways to compute distance between each pair of the two collections of inputs. If you need a cartesian product please see @zipa's answer.
answers question: http://stackoverflow.com/q/50447023
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87946253
has text: I tried the first one and it did not work, it still only shows the data without grey patches. When I print (dates) en (datenums), I get very odd values for datenums. 736570.5 etc. My (dates) look like datetime.datetime(2017, 9, 19, 11, 41) etc.
type: AnswerComment
comment on: http://stackoverflow.com/a/50466112
score: 0
type: Comment

http://stackoverflow.com/a/50431545
answers question: http://stackoverflow.com/q/50397137
type: Answer
score: 0
has body: I think* this sort key function should do the trick lambda x:(-x[1],int(x[0])) conversion will work as long as your numeric strings don't contain "," or anything in between

http://stackoverflow.com/comment/88097154
type: QuestionComment
score: 0
has text: @jferard I added minimized code that reproduce the problem. And thank you, path.pop(0) look cleaner I'll will consider it.
type: Comment
comment on: http://stackoverflow.com/q/50526291

http://stackoverflow.com/comment/87853772
comment on: http://stackoverflow.com/a/50419121
type: Comment
score: 0
type: AnswerComment
has text: True, I've realized it after you mentioned what the function does, tested again and it was obvious :)

http://stackoverflow.com/comment/87850484
type: Comment
has text: `for k,v in dict.iteritems(): print(k,':',len(v))` **NOTE** use `.items()` for python 3.x. `iteritems()` is a python 2.x thing.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50417376

http://stackoverflow.com/comment/114095740
score: 0
comment on: http://stackoverflow.com/a/51103732
type: AnswerComment
has text: in Thespian ```createActor()``` returns address of created actor, not the actor object itself.
type: Comment

http://stackoverflow.com/comment/87975212
type: QuestionComment
has text: Change `execute statement` to `exec(statement)` and `ignore error and import the next statement` to `pass` and you are good to go
score: 1
comment on: http://stackoverflow.com/q/50481023
type: Comment

http://stackoverflow.com/a/50515646
answers question: http://stackoverflow.com/q/50510554
accepted answer of: http://stackoverflow.com/q/50510554
type: Answer
score: 0
has body: Your geos/GDAL installation is probably broken. Follow the instructions in this answer for properly installing geodjango on windows.
type: AcceptedAnswer

http://stackoverflow.com/a/50450218
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50448377
has body: If you can define a function that maps each line to a distinct class, you could use itertools.groupby. For example, suppose that two strings are similar if they have the same 10 starting chars. data = """I am Harry. I am Harry. I like I am Harry. I like to eat apple. I am Garry. I am Garry. I am Hap I am Garry. I am Happy.""".split('\n') from itertools import groupby criterion = lambda s: s[:10] result = [max(g[1], key=len) for g in groupby(data, criterion)] # ['I am Harry. I like to eat apple.', 'I am Garry. I am Happy.']

http://stackoverflow.com/q/50392211
favorite count: 0
has comment: http://stackoverflow.com/comment/87800294
type: Question
upvote count: 2
type: UnansweredQuestion
has title: Weight file use for different size image
has body: I want to train CNN where image-dimension is 128*512, then I want to use this weight file to train other data which has 128*1024 dimension. That means I want to use pre-trained weight file during the training time of different data(128*1024). Is it possible or How can I do it? I want to do this because I have only 300 images which have 128*1024 dimension, while I have 5000 images which have 128*512 dimension and both datasets are different. Thank you
tagged with: python
tagged with: keras
has answer: http://stackoverflow.com/a/50392683
score: 2
has comment: http://stackoverflow.com/comment/87800828
tagged with: conv-neural-network
tagged with: deep-learning
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87800166

http://stackoverflow.com/a/50446637
has comment: http://stackoverflow.com/comment/87906792
type: Answer
answers question: http://stackoverflow.com/q/50446547
has comment: http://stackoverflow.com/comment/87906752
has comment: http://stackoverflow.com/comment/87907045
has comment: http://stackoverflow.com/comment/87908830
score: 0
has comment: http://stackoverflow.com/comment/87908159
has comment: http://stackoverflow.com/comment/87906786
has body: Try using list literal or make rdr a tuple. Because rdr is treated as a input sequence, you need to convert it to a tuple or list: [rdr] #or try this (rdr,)
has comment: http://stackoverflow.com/comment/87907179

http://stackoverflow.com/a/50427846
score: 1
upvote count: 1
type: AcceptedAnswer
has body: You can apply the pd.Series.value_counts function on each row and then after replacing the nans with zero concatenate the counts to the second axis of your dataframe. &gt;&gt;&gt; counts = qualityOfLife_df.apply(pd.Series.value_counts, axis=1)'Up', 'Down', 'Same'.fillna(0) &gt;&gt;&gt; pd.concat((qualityOfLife_df, counts), axis=1) City Crime Pollution Jobs Up Down Same 0 A Up Up Same 2.0 0.0 1.0 1 B Up Down Up 2.0 1.0 0.0 2 C Down Down Down 0.0 3.0 0.0 Also as mentioned in comment, you can use astype(int) to convert float numbers to integer. Which I'd recommend, for the sake of memory optimization, if you're dealing with larger data sets, use a smaller integer type like np.int16 or np.int8 based on the maximum number that counts can possibly hold. &gt;&gt;&gt; pd.concat((qualityOfLife_df, counts.astype(int)), axis=1) City Crime Pollution Jobs Up Down Same 0 A Up Up Same 2 0 1 1 B Up Down Up 2 1 0 2 C Down Down Down 0 3 0
answers question: http://stackoverflow.com/q/50427760
type: Answer
accepted answer of: http://stackoverflow.com/q/50427760
has comment: http://stackoverflow.com/comment/87870483
downvote count: 0

http://stackoverflow.com/comment/88046061
score: 0
type: Comment
type: QuestionComment
has text: @coldspeed Oh, you used a non capturing group! Yes that works too.
comment on: http://stackoverflow.com/q/50516666

http://stackoverflow.com/q/50511274
type: Question
tagged with: terminal
score: 0
tagged with: python
tagged with: macos
tagged with: hostname
has title: Python find and replace generic HOSTID w/ computer hostname
has answer: http://stackoverflow.com/a/50511395
type: UnansweredQuestion
answer count: 1
has body: I need "HOSTID" to resolve to the machine hostname. My goal is to take this simple command, ran manually in Terminal, and make it portable in a Python script. Sudo /library.nessusagent.run.sbin.nessuscli agent link -- key=5e30508800865f87a8dbe8993fa75d21f9e2acc7db12165050cf48b5ccbafb84 -- name=HOSTID --groups=Mac_OS_Systems --Host=Cloud.tenable.com --port=443 The below code will get me the HOSTID, how do I point it to the right place? import platform platform.node()

http://stackoverflow.com/comment/87905405
comment on: http://stackoverflow.com/a/50445809
has text: copy paste the exact code which I answered. It works fine for me. Also take care of indentation
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50435238
has comment: http://stackoverflow.com/comment/87912468
type: Question
has body: I have two time signals each containing the two same pulses but at different position. picture describing the two signals: How can I get with python the time shifts between the two signals for each pulse? Cross correlation does not seem a robust way to do the job... you can see there the cross correlation function and the two time shifts I would like to recover: Although the time shift is perfectly obtained from the maximum of the cross correlation function if we have only one pulse you can see that it does not help much in the case of multiple pulses. This is my test program: import numpy as np import matplotlib.pyplot as plt from scipy import signal N = 200 # Number of points in initial, unshifted signals N_pad = 500 # Total number of points at the end t = np.linspace(-1, 1, N) # Dummy time vector dt = t[1]-t[0] # Time step Fs = 1.0/dt # Sampling frequency pulse1 = signal.gausspulse(t, fc=5) # Create a pulse at 5 Hz pulse2 = signal.gausspulse(t, fc=8) # Create a pulse at 8 Hz # Shift and pad the pulses pulse1_shifted = np.concatenate((pulse1,np.zeros(50)), axis=0) pulse2_shifted = np.concatenate((pulse2,np.zeros(100)), axis=0) pulse1_shifted_padded = np.concatenate((np.zeros(N_pad-len(pulse1_shifted)),pulse1_shifted), axis=0) pulse2_shifted_padded = np.concatenate((np.zeros(N_pad-len(pulse2_shifted)),pulse2_shifted), axis=0) # Create signal 1 as the sum of the two pulses sig1 = pulse1_shifted_padded + pulse2_shifted_padded # Different time shift pulse1_shifted = np.concatenate((pulse1,np.zeros(60)), axis=0) pulse2_shifted = np.concatenate((pulse2,np.zeros(150)), axis=0) pulse1_shifted_padded = np.concatenate((np.zeros(N_pad-len(pulse1_shifted)),pulse1_shifted), axis=0) pulse2_shifted_padded = np.concatenate((np.zeros(N_pad-len(pulse2_shifted)),pulse2_shifted), axis=0) # Create signal 2 as the sum of the two pulses sig2 = pulse1_shifted_padded + pulse2_shifted_padded # Create new time vector at the same sampling rate t = np.arange(dt*N_pad,step=dt) # Plot the two s…
tagged with: cross-correlation
type: UnansweredQuestion
tagged with: python
has title: Identify multiple correlations between two signals
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51801544
has answer: http://stackoverflow.com/a/66513855
tagged with: signal-processing

http://stackoverflow.com/comment/87921383
has text: @SaR Have a look at this link https://docs.python.org/2/library/time.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50453982
score: 0

http://stackoverflow.com/comment/87926364
score: 0
type: QuestionComment
type: Comment
has text: the code presented is only one part of several and it is not being used to solve a problem...it's only purpose is to generate all combinations of said base...the data produced will be handled separately to determine patterns that can be quantified for use in various mediums...chances are slim that the entire output would be completed and i have no desire to store all of the output...
comment on: http://stackoverflow.com/q/50455653

http://stackoverflow.com/q/50476134
tagged with: python
upvote count: 3
score: 3
has title: How to import files from another directory without violation of PEP-8?
has body: I have to import file "BalancedTree" from DictsOrganizations to current file. (Organization of files in picture) If I use sys.path.append, I break PEP-8 rules, because there are another imported modules after this code. I also add into DictsOrganizations init.py, but there is error "Unable to import "DictsOrganizations"
favorite count: 0
has comment: http://stackoverflow.com/comment/87968331
tagged with: python-import
linked to: http://stackoverflow.com/q/50185897
has comment: http://stackoverflow.com/comment/87971543
type: Question
tagged with: pep8
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/87968604
score: 3
has text: Sets are inherently unordered data structures. You should not think of them as having *any order*, and and you shouldn't rely on the particular order you observe, because it will be an implementation detail
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50477509

http://stackoverflow.com/q/50500095
accepted answer: http://stackoverflow.com/a/50500735
possible better answer: http://stackoverflow.com/a/50500533
tagged with: loops
tagged with: string
has answer: http://stackoverflow.com/a/50500735
has title: How to add numbers into string for a loop
has answer: http://stackoverflow.com/a/50500533
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88013744
has comment: http://stackoverflow.com/comment/88012944
upvote count: 1
tagged with: python
has body: I have a long list of suburbs that I want to do something to A LOT of them have RDx (for rural Delivery) where x is a number from 1 to 30 I want to just get rid of the RDx like below for row in WorkingData['PatientSuburb']: if 'RD10' in str(row): WorkingData['PatientSuburb'].replace(regex=True,inplace=True,to_replace=r'RD10',value=r'') I was thinking If I could run a loop and increment the number somehow that'd be great. this wouldn't work but it's along the lines of what I'd like to do: for rd in range(1,31,1): if 'RD',rd in str(row): WorkingData['PatientSuburb'].replace(regex=True,inplace=True,to_replace=r'RD'rd ,value=r'') If I do this I get output with a space in between: for rd in range(1,31,1): print 'RD',rd like so: RD 1 RD 2 RD 3 RD 4 RD 5 RD 6 RD 7 RD 8 RD 9 RD 10 RD 11 RD 12 and also I would need to figure out how this piece would work... to_replace=r'RD'rd I have seen someone use a % sign in labelling a plot &amp; then it brings in a value from outside the quotes - but I don't know if that's a part of the label function (I did try it and that didn't work at all) That would look like this to_replace=r'RD%' % rd Any help on this would be great thanks!
downvote count: 1
has comment: http://stackoverflow.com/comment/88013865
type: AnsweredQuestion
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/50406852
score: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/87829342
type: Question
has answer: http://stackoverflow.com/a/50406957
answer count: 2
has body: I have a numpy vector in python and I want to find the index of the max value of the vector with the condition that it is less than one. I have as an example the following: temp_res = [0.9, 0.8, 0.7, 0.99, 1.2, 1.5, 0.1, 0.5, 0.1, 0.01, 0.12, 0.56, 0.89, 0.23, 0.56, 0.78] temp_res = np.asarray(temp_res) indices = np.where((temp_res == temp_res.max()) &amp; (temp_res &lt; 1)) However, what I tried always return an empty matrix since those two conditions cannot be met. HU want to return as final result the index = 3 which correspond to 0.99 the biggest value that it is less than 1. How can I do so?
downvote count: 0
has title: Return the biggest value less than one from a numpy vector
tagged with: python
accepted answer: http://stackoverflow.com/a/50406920
has comment: http://stackoverflow.com/comment/87829141
has answer: http://stackoverflow.com/a/50406920
type: AnsweredQuestion
favorite count: 0
upvote count: 4
possible better answer: http://stackoverflow.com/a/50406957

http://stackoverflow.com/a/50430883
has comment: http://stackoverflow.com/comment/87880041
has comment: http://stackoverflow.com/comment/87879443
has comment: http://stackoverflow.com/comment/87880158
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50429243
has comment: http://stackoverflow.com/comment/87880301
has comment: http://stackoverflow.com/comment/87880233
has comment: http://stackoverflow.com/comment/87879955
has body: ListAPIView is meant for only listing your products hence the POST requests are forbidden. ListAPIView Used for read-only endpoints to represent a collection of model instances. taken from Django Rest Framework documentation You should use ListCreateAPIView: class ProductList(generics.ListCreateAPIView): """ List all products or create a product. """ queryset = Product.objects.all() serializer_class = ProductSerializer
type: Answer
has comment: http://stackoverflow.com/comment/87880364

http://stackoverflow.com/q/50531614
has comment: http://stackoverflow.com/comment/88698178
type: Question
answer count: 1
tagged with: cluster-analysis
has body: I am trying to run machine learning models on Customers trying to segment customers using similar products together. My dataset is huge with 2.4 million records and is in the following format: customer_id prod_1 prod_2 prod_3 prod_4 ..... prod_10 000 1 0 0 1 ..... 1 001 0 0 1 1 ..... 1 011 0 1 0 1 ..... 0 021 1 0 1 1 ..... 0 ... Each row has customer number and 1 or 0 based on whether or not they have a product. I ran k-means and the results did not look impressive. Any other suggestions on what type of models can be run on such data to segment customers based on the products they use together?
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/50847190
tagged with: data-science
has answer: http://stackoverflow.com/a/50847190
has comment: http://stackoverflow.com/comment/88076312
has comment: http://stackoverflow.com/comment/88698001
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5064928
has title: Which ML model for Customer Segmentation based on the products used
score: 0
tagged with: python

http://stackoverflow.com/comment/87786348
type: QuestionComment
score: 0
has text: https://docs.python.org/2.7/library/binascii.html#binascii.hexlify
type: Comment
comment on: http://stackoverflow.com/q/50385033

http://stackoverflow.com/q/50537927
has comment: http://stackoverflow.com/comment/88087883
has comment: http://stackoverflow.com/comment/88087928
favorite count: 0
type: Question
has title: Combining multiple lists into one in a nested list
has comment: http://stackoverflow.com/comment/88087861
tagged with: python
possible better answer: http://stackoverflow.com/a/50538122
has body: I want to group some lists into one: Here is my list: myList=[[20, 'Start', '2008-10-10', 'End', '2008-11-09', 'NG'] , [21, 'Start', '2008-10-10', 'End', '2008-12-15', 'G'], [22, 'Start', '2009-11-23', 'End', '2009-12-10', 'B']] For items that the start date is the same I want to replace them with only one list that keeps the start date and maximum end date among those items with same start and id of maximum end date. For instance, in the example above, ids 20 and 21 have same start date, so I should replace them with one list like this: [21, 'Start', '2008-10-10', 'End', '2008-12-15', 'G'] So the general output for this example should be like this: myList=[[21, 'Start', '2008-10-10', 'End', '2008-12-15', 'G'], [22, 'Start', '2009-11-23', 'End', '2009-12-10', 'B']]
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50538122
tagged with: list
answer count: 2
score: 1
accepted answer: http://stackoverflow.com/a/50538016
downvote count: 0
tagged with: nested
has comment: http://stackoverflow.com/comment/88087963
upvote count: 1
has answer: http://stackoverflow.com/a/50538016

http://stackoverflow.com/comment/88076042
type: QuestionComment
has text: PyCharm can't really tell that the logic of this ensures that the name must be defined. It only looks at syntax, it can't figured out the implication of the test.
comment on: http://stackoverflow.com/q/50531898
score: 1
type: Comment

http://stackoverflow.com/a/50442356
answers question: http://stackoverflow.com/q/50442284
has comment: http://stackoverflow.com/comment/87920116
upvote count: 1
type: Answer
has body: You need to declare the array once: quantity = int(input("enter amount of data")) arr = np.zeros(quantity, dtype=float) Then fill in individual elements as desired: for i in range(quantity): arr[i] = float(input("enter value of x &gt;&gt;"))
accepted answer of: http://stackoverflow.com/q/50442284
has comment: http://stackoverflow.com/comment/87898791
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50485713
answers question: http://stackoverflow.com/q/50484937
type: Answer
has body: Nice little exercise! Here's my take on it. We'll need to sort the list, then compare pairs: customers.sort(key=lambda cust:cust['CUSTOMER'] + cust['ID']) result = [] previous_cust = None for cust in customers: if not previous_cust: # first time though previous_cust = cust continue if previous_cust['CUSTOMER'] == cust['CUSTOMER'] and\ previous_cust['ID'] == cust['ID']: previous_cust['USAGE'] += cust['USAGE'] else: result.append(previous_cust) previous_cust = cust result.append(previous_cust) # tidy up result gives: [{'CUSTOMER': 'XYZ', 'COUNTRY CODE': 'US', 'ID': 'Essential', 'USAGE': 550}, {'CUSTOMER': 'XYZ', 'COUNTRY CODE': 'US', 'ID': 'Seats', 'USAGE': 20}]
score: 0

http://stackoverflow.com/comment/88023367
has text: after I minimize the chrome window, how did you do this part ?
comment on: http://stackoverflow.com/q/50505540
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87965926
type: AnswerComment
has text: Then check `assoc .py` to find what the association you do have is called. It appears your Python installation wasn't made by the usual installer and may be missing the feature that lets it pass arguments.
type: Comment
comment on: http://stackoverflow.com/a/50476002
score: 0

http://stackoverflow.com/q/50439879
accepted answer: http://stackoverflow.com/a/50451001
has comment: http://stackoverflow.com/comment/87911433
tagged with: import
has comment: http://stackoverflow.com/comment/87911781
favorite count: 0
type: Question
tagged with: python-3.x
has body: My file layout is C:\Fourier-Recovery C:\Fourier-Recovery\cascadenet\ C:\Fourier-Recovery\main_2d.py C:\Fourier-Recovery\cascadenet\network\ C:\Fourier-Recovery\cascadenet\network\layers\ C:\Fourier-Recovery\cascadenet\network\model.py C:\Fourier-Recovery\cascadenet\network\layers\helper.py This layout is also described in following pictures. When I at 19th line when executing following script, main_2d.py, I running a error ipdb&gt; ImportError: No module named 'helper'. So here is my file layout: The root is Fourier-Recovery, where the main_2d.py resides: Inside the cascadenet, I have network and util Inside network I have layers Inside layers I have all the files like following: Here is the code in __init__.py in the Fourier-Recovery\cascadenet\network\layers So I went to the line of code where error occurs, went into Fourier-Recovery\cascadenet\network\models.py, and I see following import code: So if I comment out: import cascadenet.network.layers as l the error would be gone. So since there is a helper.py inside the layers folder, I am not sure why the error occurred because it seems it has all the dependencies needs. I am using Python 3.5 on Windows 10. Please give some hints. I am very confused at this point. I am not sure if I provide sufficient information for you guys, but if there is something you need but I am not aware, please let me know.
tagged with: python-import
has comment: http://stackoverflow.com/comment/87911217
has comment: http://stackoverflow.com/comment/87893871
has comment: http://stackoverflow.com/comment/87893866
downvote count: 0
answer count: 1
tagged with: python
has title: ImportError: No module named 'helper'
has answer: http://stackoverflow.com/a/50451001
has comment: http://stackoverflow.com/comment/87911570
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/q/50539781
linked to: http://stackoverflow.com/q/14301967
tagged with: python
downvote count: 1
score: 1
has body: In the official doc of 2. Built-in Functions — Python 3.6.5 sorted(iterable, *, key=None, reverse=False): Return a new sorted list from the items in iterable. Has two optional arguments which must be specified as keyword arguments. The docs do not mention the *, what's it's function here? There exist not such a symbol * in the previous version as sorted(iterable[, key][, reverse])
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/14301967
has title: The `*` in `sorted(iterable, *, key=None, reverse=False)`
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/50504354
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50504428
possible better answer: http://stackoverflow.com/a/50504428
favorite count: 0
tagged with: series
type: AnsweredQuestion
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50504404
accepted answer: http://stackoverflow.com/a/50504404
type: Question
answer count: 2
tagged with: pandas
has body: I want to update data based on other pandas dataframe because I just gather better data, here's the example of dataset Heres my Data No Country Language Capital 1 Indonesia Bahasa Jakarta 2 Malaysia Bahasa Kuala Lumpur 3 Brunei Bahasa Bandar Seri Begawan 4 Nigeria English Abuja My second dataframe Nation Capital City Malaysia Lagos Nigeria Putrajaya What I want is No Country Language Capital 1 Indonesia Bahasa Jakarta 2 Malaysia Bahasa Putrajaya 3 Brunei Bahasa Bandar Seri Begawan 4 Nigeria English Lagos
has title: How to update series based on other pandas dataframe

http://stackoverflow.com/q/50456149
has comment: http://stackoverflow.com/comment/87927405
score: 0
has comment: http://stackoverflow.com/comment/87937758
has title: WindowsError: [Error 183] Cannot create a file when that file already exists using os.rename
has comment: http://stackoverflow.com/comment/87927774
tagged with: python
has comment: http://stackoverflow.com/comment/87928822
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/87926555
has body: I have a file of data and I'm trying to create another file that will represent a hash table with every row representing a bucket that contains tuples (value, ptr). value - the key that I'm mapping with the hash function ptr - the row number in the data file When I'm creating the hash table I'm mapping each row from the data file to my hash file. Each row that I'm adding I'm using a temp file and copying all data from the hash file + the new line and then renaming the file to the hash file's name. I have written some code that works fine when the data file is small, when I try mapping a file with 10,000 lines it works for something like 30 seconds and then crashes with the following error: Traceback (most recent call last): File "C:/Users/�������/��� �'/����� �'/����� ������ ����� ������/����� 2/to_publish/ex2.py", line 372, in &lt;module&gt; hash.create('kiva_loans.txt', 'lid') File "C:/Users/�������/��� �'/����� �'/����� ������ ����� ������/����� 2/to_publish/ex2.py", line 317, in create self.add(value, count) File "C:/Users�������/��� �'/����� �'/����� ������ ����� ������/����� 2/to_publish/ex2.py", line 343, in add os.rename("tmp.txt", self.fileName) WindowsError: [Error 183] Cannot create a file when that file already exists This is what I have written : class Hash: def __init__(self, file_name, N=5): """ :param file_name: the name of the hash file to create. example: kiva_hash.txt :param N: number of buckets/slots. """ self.fileName=file_name self.numOfBuckets = N def create(self, source_file, col_name): """ :param source_file: name of file to create from. example: kiva.txt :param col_name: the name of the column to index by example: 'lid' Every row will represent a bucket, every tuple &lt;value|ptr&gt; will separates by comma. Example for the first 20 instances in 'kiva.txt' and N=10: 653060|11, 653091|17,653051|1, 653052|18,653062|14,653082|9, 653063|4,653053|2, 653054|16,653084|5, 653075|15, 653066|19, 653067|7, 653088|12,653048|10,653078|8,1080148|6,653068…
has comment: http://stackoverflow.com/comment/87928933
type: UnansweredQuestion

http://stackoverflow.com/comment/87904287
type: QuestionComment
has text: Need further clarification. Projection of a circle on to the map (usually becomes ellipse due to projection distortion), or a real circle overlayed on the map?
score: 0
comment on: http://stackoverflow.com/q/50436692
type: Comment

http://stackoverflow.com/q/50400211
has comment: http://stackoverflow.com/comment/87818849
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87831183
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: text-files
type: Question
has body: I am attempting to modify a file, wherein I wish to replace some brackets with added parameters. However, using re.search stops at first success and even re.findall does not help. def Modify_Brackets(file_name): input=open(file_name,"r") output = open("help.txt", "w+") for line in input: text = input.read() matches = re.findall(r'(rule).*([0-9]+).*:.*(\[.*\])(\s*)\-\-(\s*)(\[.*\])(\s*)\-\&gt;(\s*)(\[.*])', text) for m in matches: Brackets= m[5][1:-1] ModifiedBrackets = re.sub(r'\)',',changed)',Brackets) newline = text.replace(m[5], ModifiedBrackets) output.write(newline) else: output.write(text + "") Input : &lt;some text&gt; rule abc1 : [some text] --[ f(a,b), g(x,y) ]-&gt; [some text] &lt;some text&gt; &lt;some text&gt; rule abc2 : [some text] --[ f(x,b), g(a,y) ]-&gt; [some text] Present output : &lt;some text&gt; rule abc1 : [some text] --[ f(a,b,changed), g(x,y,changed) ]-&gt; [some text] &lt;some text&gt; &lt;some text&gt; rule abc2 : [some text] --[ f(x,b), g(a,y) ]-&gt; [some text] Expected output : &lt;some text&gt; rule abc1 : [some text] --[ f(a,b,changed), g(x,y,changed) ]-&gt; [some text] &lt;some text&gt; &lt;some text&gt; rule abc2 : [some text] --[ f(x,b,changed), g(a,y,changed) ]-&gt; [some text] As you can see, it works well for the first rule only and stops after that. I want this change over all the rules present in the file.
has comment: http://stackoverflow.com/comment/87837050
type: UnansweredQuestion
has title: Modifying multiple places in file in one iteration Python
tagged with: python
tagged with: regex

http://stackoverflow.com/q/50532531
downvote count: 0
has comment: http://stackoverflow.com/comment/88101142
has body: The problem is that it doesn't cange player whenever i change player Edit: I edited the code. This function create the case of the board, it's only half the code because it's the same for every pieces: def cree_case(ligne, colonne): case = Canvas(frame, width=100, height = 100,highlightthickness=1,highlightbackground="black") def click(event): joue(ligne,colonne) def click2(event): label_joueur["text"]="cchzohdc" joue2(ligne,colonne,l,c,joue) label_joueur["text"]=("choissisez une piece") case.bind('&lt;Button-1&gt;',click) case.bind('&lt;Button-3&gt;',click2) x, y = 55, 55 if board[ligne][colonne][0]== "F" and board[ligne][colonne][2]=="W": case.create_image(x,y,image=fou_blanc) elif board[ligne][colonne][0]== "F" and board[ligne][colonne][2]=="N": case.create_image(x,y,image=fou_noir) Here si the three function, that i use to play and make to movement aswell changing player: def joue(ligne, colonne): global l,c print( ligne, colonne) l,c= ligne,colonne def player(): # cette fonction permet de jouer et changer de joueur if joueur == "joueur1": return "joueur2" elif joueur=="joueur2": return "joueur1" def joue2(ligne,colonne,l,c,joue,): player() m=ligne n=colonne if not est_valide(joueur,l,c,m,n) or not pion_valide(l,c,m,n,joueur) or not dame_valide(l,c,m,n,joueur) or not fou_valide(l,c,m,n) or not roi_valide(l,c,m,n) or not cavalier_valide(l,c,m,n) or not tour_valide(l,c,m,n,joueur) or not pion_valide(l,c,m,n,joueur) : print("mauvais") faux=Toplevel(Fenetre, height= 100, width = 100) case1 = Canvas(faux, width=100, height 100,highlightthickness=1,highlightbackground="black") v= 50 w= 50 case1.create_image(v,w,image=stop) case1.grid() faux.mainloop() elif est_victorieux(joueur): board[m][n]=board[l][c] board[l][c]="___" frame.destroy() label_joueur["text"]=("Echec et mat") else: board[m][n]=board[l][c] board[l][c]="___" if est_victorieux(joueur): frame.destroy() label_joueur["text"]=("Echec et mat") else: affiche_grille() joueur="joueur1" affiche_grille()
tagged with: python
tagged with: chess
has title: Chess Gui change player with tkinter
has answer: http://stackoverflow.com/a/50544734
has comment: http://stackoverflow.com/comment/88077565
score: 1
has comment: http://stackoverflow.com/comment/88077091
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/50537819
type: UnansweredQuestion

http://stackoverflow.com/comment/88021395
type: Comment
type: QuestionComment
has text: I read somewhere to use reset instead of set , so tried reset in the code given by you instead of set . But its not helpful.
score: 0
comment on: http://stackoverflow.com/q/50501829

http://stackoverflow.com/a/50517216
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88131909
accepted answer of: http://stackoverflow.com/q/50516590
has body: Make a masked array from your first xlist: In [283]: xlist = [[1000,1001,1002,-9999], ...: [2000,2001,2002,2003]] ...: In [284]: M = np.ma.masked_equal(xlist, -9999) In [285]: M Out[285]: masked_array( data=[[1000, 1001, 1002, --], [2000, 2001, 2002, 2003]], mask=[[False, False, False, True], [False, False, False, False]], fill_value=-9999) compressed removes the masked values, but returns a 1d array. In [286]: M.compressed() Out[286]: array([1000, 1001, 1002, 2000, 2001, 2002, 2003]) We could apply compressed on a row by row basis: In [287]: [m.compressed() for m in M] Out[287]: [array([1000, 1001, 1002]), array([2000, 2001, 2002, 2003])] Or as list of lists, or even object array of lists: In [288]: [m.compressed().tolist() for m in M] Out[288]: [[1000, 1001, 1002], [2000, 2001, 2002, 2003]] In [289]: np.array(_) Out[289]: array([list([1000, 1001, 1002]), list([2000, 2001, 2002, 2003])], dtype=object)
type: Answer
answers question: http://stackoverflow.com/q/50516590

http://stackoverflow.com/q/50501299
has answer: http://stackoverflow.com/a/50501529
has comment: http://stackoverflow.com/comment/88108504
has title: Looping a variable inside a function every time the function is called in python
tagged with: loops
type: Question
possible better answer: http://stackoverflow.com/a/50501529
has body: I want to append an excel file every time a function is called. How do I do this? For example, the first time the function is called, the phone number and text are pasted in row 2, then the next time the function is called, the phone number and text are pasted in row 3, etc. I want the "i" to change. os.chdir("/Users/name/Desktop/name/name") book = openpyxl.Workbook() sheet = book.create_sheet("Sheet", 0) sheet.cell(row=1, column=6).value = "Verification Code" class func_with_memory: i = 2 def write_to_ith_excelrow(self): print ('i =', self.i) self.i += 1 def receive_sms(self, i): i = i+2 # Sender's phone numer from_number = request.values.get('From') # Receiver's phone number - Plivo number to_number = request.values.get('To') # The text which was received text = request.values.get('Text') # Print the message print 'Message received - From: %s, To: %s, Text: %s' % (from_number, to_number, text) # send 'Text' into an excel file sheet.cell(row=i, column=6).value = text book.save("numbers.xlsx") return "Message received" sms_to_xl = func_with_memory() sms_to_xl.write_to_ith_excelrow()
has comment: http://stackoverflow.com/comment/88015229
accepted answer: http://stackoverflow.com/a/50518478
has answer: http://stackoverflow.com/a/50518478
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/comment/87910380
score: 0
type: AnswerComment
has text: I have edited my question can you suggest what went wrong?
comment on: http://stackoverflow.com/a/50446792
type: Comment

http://stackoverflow.com/q/50517846
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88048594
has comment: http://stackoverflow.com/comment/88048582
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88048319
type: UnansweredQuestion
has body: I'm trying to create a program using PuLP library that when you hit the button it solves a linear problem and outputs values. So this is what I get when I tried to optimize my input values: TypeError: problem() takes 0 positional arguments but 7 were given. At this point I am not sure I understand what this TypeError is trying to tell me. from tkinter import* from pulp import* def problem(): prob=LpProblem("problem", LpMaximize) x1=LpVariable("x1", lowBound=0) x2=LpVariable("x2", lowBound=0) x3=LpVariable("x3", lowBound=0) prob+= a*x1 +b*x2 +c*x3, prob+= d*x1 +e*x2 + f*x3 &lt;= g, prob.solve () print("status:", LpStatus[prob.status]) for v in prob.variables(): print (v.name, "=", v.varValue) print("objective=%s$" % value(prob.objective)) root =Tk() root.title("System") root.geometry("1300x500+0+0") a=Entry(Top, font=("arial", 10, "bold"), bd=8) a.grid(row=1, column=1) b=Entry(Top, font=("arial", 10, "bold"), bd=8) b.grid(row=1, column=2) c=Entry(Top, font=("arial", 10, "bold"), bd=8) c.grid(row=1, column=3) d=Entry(Top, font=("arial", 10, "bold"), bd=8) d.grid(row=2, column=1) e=Entry(Top, font=("arial", 10, "bold"), bd=8) e.grid(row=2, column=2) f=Entry(Top, font=("arial", 10, "bold"), bd=8) f.grid(row=2, column=3) g=Entry(Top, font=("arial", 10, "bold"), bd=8) g.grid(row=3, column=1) def inserter (value): w.delete("0.0", "end") w.insert("0.0", value) def handler(): try: g_val = float(g.get()) a_val = float(a.get()) b_val = float(b.get()) c_val = float(c.get()) d_val = float(d.get()) e_val = float(e.get()) f_val = float(f.get()) inserter(problem(a_val,b_val,c_val,d_val,e_val,f_val, g_val)) except ValueError: inserter("Enter more values") w=Text(Top, font=("arial", 10, "bold"), bd=6) w.grid(row=4, column=1) info6=Button(Top, font=("arial", 10,"bold"), text="Optimize", bd=8, command=handler) info6.grid(row=4, column=0) root.mainloop()
has comment: http://stackoverflow.com/comment/88048758
tagged with: pulp
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88048761
has answer: http://stackoverflow.com/a/50526396
downvote count: 2
tagged with: tkinter
has title: Tkinter entry arguments : takes 0 positional arguments but 7 were given
has comment: http://stackoverflow.com/comment/88048612

deserialization
type: Tag
tags question: http://stackoverflow.com/q/50518450
tag name: deserialization

http://stackoverflow.com/q/50418645
has body: I'm trying to remove all columns from a pandas dataframe where there are fewer than 10 unique items in the column. However, some of my data is lists and I get the error unhashable type: 'list'. Makes sense, since pandas compares with a hashmap. My current code is for i in df.columns: if len(df[i].unique()) &lt; 10: df.drop(i, 1) which works fine up until I get to a list object. For my purposes, a list1 and list2 aren't unique. [1, 2] and [2, 1] are not unique, even though [1, 2] == [2, 1] is False. How should I go about performing this operation? It doesn't make sense to separate the lists, and I can't explicitly type out the columns since I have 1400 of them. Many thanks in advance!
has title: Unique Items in a pandas dataframe with a list
has answer: http://stackoverflow.com/a/50419145
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/50419169
tagged with: pandas
has comment: http://stackoverflow.com/comment/87853810
upvote count: 3
has answer: http://stackoverflow.com/a/50419169
tagged with: dataframe
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87853177
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50419145

http://stackoverflow.com/comment/87807003
has text: Please include the code in the question as text an image is useless for future users (they can't search for it). I know SO can be hard but we really are trying to create good Q/A for future users.
score: 0
comment on: http://stackoverflow.com/q/50395004
type: Comment
type: QuestionComment

http://stackoverflow.com/a/60102130
answers question: http://stackoverflow.com/q/50404010
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50404010
has body: I would attempt to get a clean nglview installation via conda (and the Anaconda distribution): Try uninstalling nglview with conda remove nglview just in case there's an old version. If this conda-remove fails then this package might have been pip or easy_installed. Try pip remove nglview. If this still not helping, you have to look for the installed nglview package and manually remove it with rm but I do not want to put copy&amp;paste instructions here as this requires careful looking at files. Once all traces of nglview have been removed, install the latest version of nglview from the conda-forge channel with conda: conda install -c conda-forge nglview

http://stackoverflow.com/q/50393856
has comment: http://stackoverflow.com/comment/87804452
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has title: Target actively refusing request
has comment: http://stackoverflow.com/comment/87803809
has body: Im trying to build a program to transfer files through Python3 sockets. Here is my server code: # server.py import socket # Import socket module port = 60000 # Reserve a port for your service. s = socket.socket() # Create a socket object host = "127.0.0.1" # Get local machine name s.bind((host, port)) # Bind to the port s.listen(4) # Now wait for client connection. print ('Server listening....') while True: conn, addr = s.accept() # Establish connection with client. print ('Got connection from', addr) filename='send.rtf' print ('File Assigned') f = open(filename,'rb') print ('File Oppened') l = f.read(1024) print ('Reading') while (l): conn.send(l) print('Sent ',repr(l)) l = f.read(1024) print ('Reading') f.close() print('Done sending') conn.close() And here is my client code: # client.py import socket # Import socket module s = socket.socket() # Create a socket object host = "127.0.0.1" # Get local machine name port = 60000 # Reserve a port for your service. s.connect((host, port)) with open('recieved', 'wb') as f: print ('file opened') while True: print('receiving data...') data = s.recv(1024) print('data=%s', (data)) if not data: break # write data to a file f.write(data) f.close() print('Successfully got the file') s.close() print('Connection closed') I have the server running on my Mac and the Client on my PC. The program runs fine if I run them both on my Mac, but not on separate machines. This is the error I get when I run the program on my PC: Traceback (most recent call last): File "C:\Users\gshin\Desktop\P2PFile\P2PFileClient2.py", line 9, in &lt;module&gt; s.connect((host, port)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Any help would be greatly appreciated!
has comment: http://stackoverflow.com/comment/87803868
answer count: 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87807253
upvote count: 1
has comment: http://stackoverflow.com/comment/87803490
favorite count: 0
has comment: http://stackoverflow.com/comment/87806289
has comment: http://stackoverflow.com/comment/87807568
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87803676
has comment: http://stackoverflow.com/comment/87804110

http://stackoverflow.com/comment/94900320
comment on: http://stackoverflow.com/a/50421288
score: 1
has text: slight variation that worked for me: `sudo apt-get purge ipython*`
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50445075
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87904623
has comment: http://stackoverflow.com/comment/87904618
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50445068
downvote count: 0
has comment: http://stackoverflow.com/comment/87903817
accepted answer of: http://stackoverflow.com/q/50445068
has body: EDIT: As @jpp poined out in comments, this is the correct answer: df[df[column_name] &gt; 3]
has comment: http://stackoverflow.com/comment/87903931

http://stackoverflow.com/comment/88108978
has text: Edit in previous comment : second one is not correct address to out in the command.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50400563
type: Comment

http://stackoverflow.com/a/50503369
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50488151
answers question: http://stackoverflow.com/q/50488151
type: Answer
has body: You can use a loop to get the values you need. #Segregate data by rows rows = soup.findAll('div',{'class':'row'}) #Create empty lists divisions = [] competitors = [] #Create and append respective lists with a loop for row in rows: raw_division = row.h4.text division = raw_division.split('/') divisions.append(division) raw_competitors = row.tfoot.tr.td.text.strip() competitor = raw_competitors.replace('Total: ','') competitors.append(competitor) You should now have a list of lists --> divisions as well as a list --> competitors.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87923538
score: 0
comment on: http://stackoverflow.com/q/50455067
type: Comment
type: QuestionComment
has text: Try merging using merge_asof

http://stackoverflow.com/comment/87804201
comment on: http://stackoverflow.com/a/50394217
has text: You don't need the list comprehension with `[` and `]`. `max` can directly take a generator expression
type: Comment
type: AnswerComment
score: 3

http://stackoverflow.com/q/50412161
has body: I'm using NetworkX to implement some papers. (Actually, Networkx is not necessary. If there are better libraries for solving this problem, could you recommend it?) And my graph looks like this image Automated_Planar_Tracking_the_Waving_Bodies_of_Mul I gave positive weight to all nodes. When I use max_flow_min_cost(G, S, E) function, the function returns paths like [S, T1, T1', E], [S, T2, T2', E], [S, T3, T3', E], [S, T4, T4', E], [S, T5, T5', E], [S, T6, T6', E] That's because these are paths with maximum flow. But what I want is paths that pass flow through all nodes and whose total cost is minimum. For example: [S, T1, T1', T2, T2', E], [S, T5, T5', E], [S, T3, T3', T6, T6', E], [S, T4, T4', E] So, I decided to use min_cost_flow() function. And it needs the demand of nodes. Of course, I can't use this method because I don't know how many paths will start from node 'S'. Is there any solutions to solve my problem? To sum up, I want some methods to find paths that go through all nodes and total cost of those is minimum. My mother tongue is not English, and It might make you confused. If you have any questions about this, please let me know.
answer count: 0
has comment: http://stackoverflow.com/comment/87982662
has comment: http://stackoverflow.com/comment/88961728
type: Question
tagged with: network-flow
type: UnansweredQuestion
tagged with: python
has title: Passing flow through all nodes with min cost in networkx
tagged with: networkx
score: 0

http://stackoverflow.com/comment/88091934
type: QuestionComment
has text: what are the contents of csv file ?
comment on: http://stackoverflow.com/q/50540215
score: 0
type: Comment

http://stackoverflow.com/comment/88053095
type: QuestionComment
comment on: http://stackoverflow.com/q/50520096
has text: ok, may be I am confused then why do you need nyctel again, why not use tel? May be I will stop commenting after this. If you comment line `nyctel = sns.load_dataset(tel)` and only use `tel` in data, wouldn't it work?
score: 1
type: Comment

http://stackoverflow.com/comment/99645366
score: 0
comment on: http://stackoverflow.com/a/53761277
has text: do you know how to avoid opening Tor, but to let it run in the background?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50540251
accepted answer of: http://stackoverflow.com/q/50524246
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50524246
has body: This is my own answer to my own question as a bottom line to this discussion: No, The Python Library Reference, Release 3.6.5, paragraph 16.16 ctypes — A foreign function library for Python is not partially outdated. But it is afflicted with at least 2 editorial slips. Although this question was caused by a silly mistake of mine, the comments and answers--some deleted by that time--have revealed that Python's transition from byte strings to Unicode strings has not been fully followed: The code snippets in Incomplete Types use a c_char_p but assign Unicode strings to it, resulting in a TypeError. The same pertains to the last code snippet in Surprises. These minor flaws are indeed worth mentioning. To quote Davis King, the creator of the Dlib C++ Library, which, BTW, offers a Python API: I consider the documentation to be the most important part of the library. So if you find anything that isn't documented, isn't clear, or has out of date documentation, tell me and I will fix it. (http://dlib.net/) (Yes, I have sent an e-mail to "docs@python.org".)
score: 0

http://stackoverflow.com/q/50490864
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50491139
has title: Accumulate 1 and Reset to 0 once condition is met
upvote count: 3
has answer: http://stackoverflow.com/a/50491139
downvote count: 0
tagged with: machine-learning
linked to: http://stackoverflow.com/q/27626542
possible better answer: http://stackoverflow.com/a/50491374
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50491374
has body: Currently I have a dataset below and I try to accumulate the value if ColA is 0 while reset the value to 0 (restart counting again) if the ColA is 1 again. ColA 1 0 1 1 0 1 0 0 0 1 0 0 0 My expected result is as below. ColA Accumulate 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 2 0 3 1 0 0 1 0 2 0 3 The current code I use test['Value'] = np.where ( (test['ColA']==1),test['ColA'].cumsum() ,0) ColA Value 1 0 0 1 1 0 1 0 0 2 1 0 0 3 0 4 0 5 1 0 0 6 0 7 0 8
score: 3
tagged with: python
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/50502230
tagged with: admin
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88024661
has comment: http://stackoverflow.com/comment/88016856
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88808806
has comment: http://stackoverflow.com/comment/88808826
score: 0
answer count: 0
has body: I'm having a problem logging into my localhost:8000/admin/ page, after entering the correct username and password, I get the "Related Object Does Not Exist at /admin/login/" error and it says the "User does not exist" but it being the admin is my main cause for worry. I removed the "django.contrib.sites" package following advice I got on a previous error. I'm using django 2.0.2 and python 3.6. settings.py: # Application definition INSTALLED_APPS = [ 'nutrients.apps.NutrientsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profile', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'nutrition.urls' CMS_TEMPLATES = ('index.html', 'Left sidebar template') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__), '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', ], }, }, ] WSGI_APPLICATION = 'nutrition.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 2.0.2 Python Version: 3.6.5 Installed Applications: ['nutrients.apps.NutrientsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.…
has title: python- Related Object Does Not Exist at /admin/login/

http://stackoverflow.com/comment/88022388
type: Comment
type: AnswerComment
has text: Hello. The code works fine for me. I updated a link for the data that I used. I have them in a .csv file and I updated my answer to show how I load them
comment on: http://stackoverflow.com/a/50494536
score: 0

http://stackoverflow.com/q/50450279
has title: Undefined variable 'player_damage' - Python text base game
has body: So this is my second mini project in python and because I'm still learning I'm using reference code and asking questions to make the project, but I keep getting an error "Undefined variable 'player_damage'" on line 49-52. Sample_FIGHT = { player_damage: "You desperately try to stop the %s for %i damage", enemy_damage: "%s gores you for %i damage", player_win: "The %s collapses with a thunderous boom", enemy_win: "You are squished" } But I do define the varibale in my function Combat. def combat (player, enemy): player_damage = random.randint (*WEAPONS[player["weapon"]]) enemy_damage = random.randint(*enemy["attack"]) player_win = player_damage &gt; enemy["health"] enemy_win= enemy_damage &gt; player["health"] return player_damage, player_win , enemy_damage, enemy_win This is the whole code. import random #initial question to start print ("The Adventures Of Magical Nadia") Answer = input ("Do you wish to embark on this adventures?") #Question to start game or end game if Answer == "Yes" or Answer == "yes": print ("You have accepted the adventure. God Speed my young rass!") else: print ("You are a coward and shall not in bark on a great adventure!") #function for questions avoide repeat def ask(question): answer = input(question + " [y/n]") return answer in ["y", "Y", "Yes", "YES", "yes"] #Dic of all the weapons in the game WEAPONS = { "Spear": (3, 10), None:(1,3), "knife":(4,16), "Gun":(16,25), "Glass Bottle":(4,16) } #Tracking weapon and player health player = {"weapon":None, "health": (100)} #to give the player weapons code player["weapon"] = "Spear" #Enemys type enemy = {"name":None, "health":None, "attack":None } Gaint_spider = {"health":(45), "attack":(7, 10) } Dogs = {"health": (50), "attack":(4,15)} Dragon = {"health": (150), "attack":(35,45)} #Function each fight gives random dmg, have a player and enemy, winner and loser def combat (player, enemy): player_damage = random.randint (*WEAPONS[player["weapon"]]) enemy_damage = random.randint(*enemy["attack"]) pla…
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87913658
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50450459
has answer: http://stackoverflow.com/a/50450459
has comment: http://stackoverflow.com/comment/87914255
tagged with: python
has comment: http://stackoverflow.com/comment/87915252
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50450433
answer count: 2
has answer: http://stackoverflow.com/a/50450433

http://stackoverflow.com/q/50541190
type: Question
score: 0
has title: Pattern searching in excel file and get row ID python
has comment: http://stackoverflow.com/comment/88093758
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88093647
has body: I am quite new to python, pandas. I am trying to read a csv file using pandas, but I am getting a csv parse error. That is my csv top pattern, See this (Cannot display image, please refer link). https://i.sstatic.net/HIBoj.jpg --------------------------------------------------------------------------------------------------------------------------------------------------,,,,,,, Data Records,,,,,,, --------------------------------------------------------------------------------------------------------------------------------------------------,,,,,,, ABC : - xxxxxxxxxxx,,,,,,, Type :- xxxxxxxxxxx,,,,,,, Date :- xxxxxxxxxx,,,,,,, Till Date :- xxxxxxxxxx,,,,,,, Report Index :- xxxxxxxxxx,,,,,,, Report Date :- 01-Jul-2017 11:18:41 AM,,,,,,, --------------------------------------------------------------------------------------------------------------------------------------------------,,,,,,, A PARTY, B PARTY, DATE, TIME, DURATION, ID, ID_A, TYPE --------------------------------------------------------------------------------------------------------------------------------------------------,,,,,,, XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:51:54,1,123456788889999, -, ZXC XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:52:06,1,123456788889999, -, QWE XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:52:11,1,123456788889999, -, RRR XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:52:12,1,123456788889999, -, BGF XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:52:25,1,123456788889999, -, OOO XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:53:23,1,123456788889999, -, BGF XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:54:00,1,123456788889999, -, NBG XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:54:38,1,123456788889999, -, BGFD XXXXXXXX,XXXXXXXX, 26-JAN-2017, 11:54:39,1,123456788889999, -, OIU XXXXXXXX,XXXXXXXX, 26-JAN-2017, 12:03:14,1,123456788889999, -, BGF XXXXXXXX,XXXXXXXX, 26-JAN-2017, 12:07:43,1,123456788889999, -, GGG XXXXXXXX,XXXXXXXX, 26-JAN-2017, 12:11:53,1,123456788889555, -, VVVV XXXXXXXX,XXXXXXXX, 26-JAN-2017, 12:13:12,1,123456788889555, -, VVVV XXXXXXXX,XXXXXXXX…
has answer: http://stackoverflow.com/a/50541775
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88094638
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/50454544
type: Answer
has body: I think you need: import matplotlib.pyplot as plt plt.suptitle('image #{}'.format(num), fontsize = 20)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50454476
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50454476

http://stackoverflow.com/comment/87912230
type: AnswerComment
comment on: http://stackoverflow.com/a/50449499
score: 1
has text: When I try to migrate, it shows me the same error.. Ive installed MySQL Connector C 6.0.2, MySQL Server 5.5, mysqlclient-1.3.12-cp37-cp37m-win_amd64.whl
type: Comment

http://stackoverflow.com/q/50454957
accepted answer: http://stackoverflow.com/a/50455020
tagged with: python
has title: Preload a .py file into python 3 enviroment
has answer: http://stackoverflow.com/a/50455020
type: Question
score: 2
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
has body: I have a python .py file with the libraries and I want to load it into my environment on startup without having to individually load it each time. E.g. I currently need to load numpy, matlab imports etc line by line, is it not possible to have a couple of files ready to load from the >>> prompt. I've tried running python3 &lt;> but it wont work. This is my .py file am I doing something incorrect. # Load libraries import sys #import OS import pandas from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn import model_selection from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC import pandas as pd from datatime import datetime import matplotlib.pyplot as plt import statsmodels.api as sm from sklearn import datasets import scipy.stats as stats import pylab
type: AnsweredQuestion

http://stackoverflow.com/comment/87977366
type: Comment
has text: Firstly make sure your script can run pass on non-headless browser which can help to watch the running process and debug to see the entered username & password is correct or not. Then switch to headless browser, like you used PhantomJS
comment on: http://stackoverflow.com/q/50481172
type: QuestionComment
score: 1

http://stackoverflow.com/a/65384238
score: 0
has body: if n%2!=0: print("Weird") elif n%2==0 and n in range(2,6): print("Not Weird") elif n%2==0 and n in range(6,21): print("Weird") elif n%2==0 and n>20: print("Not Weird")
has comment: http://stackoverflow.com/comment/115596959
type: Answer
answers question: http://stackoverflow.com/q/50467658

quantopian
tags question: http://stackoverflow.com/q/50500553
type: Tag
tag name: quantopian

http://stackoverflow.com/comment/88089079
has text: Well, that is not the way how it works.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50538470

http://stackoverflow.com/comment/87974889
score: 0
comment on: http://stackoverflow.com/q/50480518
has text: It doesn't really matter. It has `id`, `ref_id`, `timestamp`, `original_id`, `user_id` and `flag` columns. `flag` is boolean.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50440868
has comment: http://stackoverflow.com/comment/87896424
has comment: http://stackoverflow.com/comment/87896411
answers question: http://stackoverflow.com/q/50440837
type: Answer
accepted answer of: http://stackoverflow.com/q/50440837
has body: Unless I misunderstand what you're asking, you can do the following: c(v[0]) This will give you the following RGBA array: (1.0, 0.44313725490196076, 0.55686274509803924, 1.0) So if you just want the RGB, you can just index it as necessary: &gt;&gt;&gt; c(v[0])[:3] (1.0, 0.44313725490196076, 0.55686274509803924) More info in the docs
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87896339
has comment: http://stackoverflow.com/comment/87896375
score: 2

http://stackoverflow.com/comment/118703431
score: 0
has text: A tree of calls to tf.argmax, using the index output by the first call to bisect the original tensor.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50424173

http://stackoverflow.com/a/66483705
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50399547
type: Answer
has body: This is due to the computer you are using, make sure you have enough ram to allocate for the program, or try increasing your swap file size?

http://stackoverflow.com/q/50416915
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: fragmentation
score: 2
has body: I am relatively new to Python,so I would very much appreciate any constructive feedback on my code and would really appreciate it if you could guide me in the right direction if I a wrong. So I have a designed a program in Python that takes in a DNA sequence, basically a string comprising only four letters (A,T,C and G) and finds the complement of the sequence. Thereafter, it takes the two sequences and divides them into fragments of certain length such that each fragment overlaps with the neighboring fragment by same number of letters. For instance, it would take in DNA sequence, say s1, and produce the following output for its complement and fragments. s1 = "AGCCCTCCAGGACAGGCTGCATCAGAAGAGGCCATCAAGCAGGTCTGTTCCAAGGGCCTTTGCGTCAGGT" print(dna_complement(s1)) &gt;&gt;&gt;&gt; complement = TCGGGAGGTCCTGTCCGACGTAGTCTTCTCCGGTAGTTCGTCCAGACAAGGTTCCCGGAAACGCAGTCCA print(dna_fragment(s1, oligo_size=8, oligo_overlap=3)): &gt;&gt;&gt;&gt; AGCCCTCC..GACAGGCT..ATCAGAAG..GCCATCAA..AGGTCTGT..CAAGGGCC..TGCGTCAGGT .....AGGTCCTG..CGACGTAG..TTCTCCGG..GTTCGTCC..ACAAGGTT..CGGAAACG....... As you can see in the above example, the output of dna_fragmentation is two strings that share an oligo overlap of 3 base pairs ( i.e. three letters) and the size of oligos is at minimum 8 base pairs. Hereafter, the program tries to determine the value for specific parameter (Tm) for the overlapping region (Tm is the temperature at which half of the overlapping region is coiled and other half is in form of a DNA duplex). Now the program must try to change the length of overlapping region such that the Tm for the overlapping regions must be approximately the same for all overlapping regions. I have successfully completed the former tasks by essentially storing the oligos (fragments) in a list and using list comprehension to find the Tm for each oligo; however, I have failed in accomplishing the latter task. So my question is how can I take the overlapping region, store it in a variable and then change its…
answer count: 0
has title: Converting an overlapping DNA region into a variable and then changing the length of overlapping region
tagged with: string

http://stackoverflow.com/comment/87870676
comment on: http://stackoverflow.com/a/50427738
has text: What I wanted looks like jpp's solution but you were also really helpful, ty !
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50525927
possible better answer: http://stackoverflow.com/a/50526273
has answer: http://stackoverflow.com/a/50526273
accepted answer: http://stackoverflow.com/a/50527501
tagged with: python
has answer: http://stackoverflow.com/a/50527501
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
score: 0
has title: Pythonic way to get value of first XML element with specific name
has comment: http://stackoverflow.com/comment/88063676
answer count: 2
has comment: http://stackoverflow.com/comment/88063816
has body: I am looking for a better way to write this tiny piece of code: uris = [] for el in tree.iter('uri'): uris.append(el.text) break self.phoneLine = uris[0] Since I can not use this: value = tree.iter('uri')[0].text
type: Question

http://stackoverflow.com/a/50537305
accepted answer of: http://stackoverflow.com/q/50537218
has comment: http://stackoverflow.com/comment/88185590
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88185269
has body: I think you need to step back in the file anytime you do a truncate. So where you do this stats.truncate(0) add stats.seek(0) after
answers question: http://stackoverflow.com/q/50537218
score: 3
type: Answer

http://stackoverflow.com/q/50519298
has answer: http://stackoverflow.com/a/50519739
tagged with: decimal
has comment: http://stackoverflow.com/comment/88051313
answer count: 2
has comment: http://stackoverflow.com/comment/88051215
upvote count: 2
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88051410
downvote count: 1
favorite count: 0
has body: I have a data acquisition system which takes measurements for a few minutes and generates a csv file with 10 million rows and 10 columns. Then I import this csv file in Python (csv.reader), perform a bunch of operations on the acquired numeric data (but ‘only’ 10000 rows at a time, otherwise the computer memory would be overwhelmed). In the end, I export the results in another much smaller csv file (csv.writer). The problem is that the runtime is very long and I want to speed it up. When I open the original csv file with Notepad I see that the numbers have up to 16 digits each, like 0.0015800159870059, 12.0257771094508 etc. I know that the accuracy of the DAQ is 0.1% at best and most of the trailing digits are noise. Is there an elegant way of forcing Python to operate globally with only 7-8 digits from start to finish, to speed up the calculations? I know about error propagation and I’m going to try different settings for the number of digits to see what the optimum is. Please note that it is not enough for me to build a temporary csv file with ‘truncated’ data (e.g. containing 0.0015800, 12.0257771 etc) and simply import that into Python. The calculations in Python should use reduced precision as well. I looked into decimal module, with no success so far. with open(‘datafile’,newline='') as DAQfile: reader=csv.reader(DAQfile,delimiter=',') for row in reader: … calculate stuff… with open('results.csv','w',newline='') as myfile: mywriter = csv.writer(myfile) …write stuff… Adding some details, based on the comments so far: The program calculates the peak of the moving average of the 'instantaneous power'. The data in the csv file can be described like this, where 'col' means column, V means voltage and I means current: col1=time, col2=V1, col3=I1, col4=V2, col5=I2 and so on until col11=V10, col12=I10. So each row represents a data sample taken by the DAQ. The instantaneous power is Pi=V1*I1+V2*I2+...+V11*I11 To calculate moving average over 10000 rows at a time, I bu…
has title: reduce calculation precision to speed up execution
type: Question
has comment: http://stackoverflow.com/comment/88051364
has comment: http://stackoverflow.com/comment/88051352
has comment: http://stackoverflow.com/comment/88051309
has comment: http://stackoverflow.com/comment/88051320
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50519690
has comment: http://stackoverflow.com/comment/88051322
tagged with: python
has comment: http://stackoverflow.com/comment/88051227

http://stackoverflow.com/q/50438231
tagged with: dataflow
has comment: http://stackoverflow.com/comment/87891092
score: 0
linked to: http://stackoverflow.com/q/47379190
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/87891179
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87891567
has title: ETL load from google cloud storage to biquery
has comment: http://stackoverflow.com/comment/88941488
type: Question
has comment: http://stackoverflow.com/comment/87890477
has answer: http://stackoverflow.com/a/55701632
linked to: http://stackoverflow.com/q/45105669
tagged with: python
has comment: http://stackoverflow.com/comment/87891752
has body: I want to load data from hundreds of CSV files on Google cloud Storage and append them to a single table on Bigquery on a daily basis using cloud dataflow (preferable using python SDK). Can you please let me know how I Can accomplish that? Thanks
tagged with: google-bigquery
tagged with: google-cloud-storage

http://stackoverflow.com/comment/88255941
comment on: http://stackoverflow.com/q/50498162
score: 1
has text: Yeah sorry about that. The license is extremely expensive though. I've gone to WxPython now.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53297523
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/93487739
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50485089
has body: greetings from another novice. Came across your post yesterday as I was trying to add a subscriber to a list using their API. I struggled a bit and could only solve it with the help of a senior dev. so don't beat yourself up. I know it might be a tad late but hope it still helps. if you did solve it meanwhile, do let me know :-) first of, if you want to get all subscribers to a list, you need to be looking at this part https://www.campaignmonitor.com/api/lists/ The above will probably get you one subscriber at a time. I recommend using something like Postman to do some test GET calls to the API and see which one is getting you the results you need. for example, this is what I get when I made a GET call to all active subscribers to a list: { "Results": [ { "EmailAddress": "marco@polo.bro", "Name": "Marco", "Date": "2018-11-13 10:36:00", "State": "Active", "CustomFields": [], "ReadsEmailWith": "" }, { "EmailAddress": "marco@polo.broke", "Name": "Marco", "Date": "2018-11-13 10:38:00", "State": "Active", "CustomFields": [], "ReadsEmailWith": "" }, { "EmailAddress": "marco@polo.mkd", "Name": "Marco", "Date": "2018-11-13 17:22:00", "State": "Active", "CustomFields": [], "ReadsEmailWith": "" }, { "EmailAddress": "marco@polo.ro", "Name": "Marco", "Date": "2018-11-13 09:52:00", "State": "Active", "CustomFields": [], "ReadsEmailWith": "" }, { "EmailAddress": "subscriber1@example.com", "Name": "New Subscriber", "Date": "2018-11-13 16:55:00", "State": "Active", "CustomFields": [], "ReadsEmailWith": "" }, { "EmailAddress": "subscriber2@example.com", "Name": "New Subscriber 2", "Date": "2018-11-13 16:59:00", "State": "Active", "CustomFields": [], "ReadsEmailWith": "" } ], "ResultsOrderedBy": "email", "OrderDirection": "asc", "PageNumber": 1, "PageSize": 1000, "RecordsOnThisPage": 6, "TotalNumberOfRecords": 6, "NumberOfPages": 1 } Otherwise, try this (you should create an instance of the Subscriber class): from createsend import * list_id = 'your-list-id' subscriber = Subscriber( …
answers question: http://stackoverflow.com/q/50485089
has comment: http://stackoverflow.com/comment/93478328
type: Answer

http://stackoverflow.com/comment/88064059
comment on: http://stackoverflow.com/a/50525487
type: AnswerComment
has text: isn't that what this code does? The `map` part is only needed if you really need `list` instead of `tuple`, and can also be expressed as `my_list1, my_list2 = list(my_list1), list(my_list2)`
type: Comment
score: 0

http://stackoverflow.com/a/50418818
has body: When you installed Python, there would have been a tick box that wanted to know if you would like the Python Path adding to the Environment variables. As you didn't select this, your Windows Path doesn't include the folder where the Python executable lives. To fix this, rerun the installer and modify your install, it should pop up the screen with the tick boxes on, select the one mentioned above and the job should be done. This is how it works with the Python3 installer, anyhow and I assume that 2.7 will use the same basic model.
answers question: http://stackoverflow.com/q/50418775
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87854398
score: 1

http://stackoverflow.com/comment/87851149
has text: Thanks so much! I don't recall ANY books or tutorials I've read have ever explained what you just said. I added your comments to your answer and marked it as the accepted answer.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50415782
type: AnswerComment

http://stackoverflow.com/comment/87969634
score: 0
type: Comment
type: QuestionComment
has text: What are the contents of the files like? If it's text or something that can be represented as text you might want to present file contents in text widgets.
comment on: http://stackoverflow.com/q/50476102

http://stackoverflow.com/q/50526291
score: 0
tagged with: object-reference
has body: I am somehow new to python. I needed to use tree to store some data (file paths), The problem is when I generate the tree it seems that all objects after the root reference the same object, although step by step debugging showed the opposite. Here is my (minimized) code: first the node class: class PathElement: Element = "" IsStatic = True Children = [] ChildrenCount = 0 def __init__(self, Element, IsStatic=True): self.Element = Element self.IsStatic = IsStatic if not IsStatic: self.Element = [] def AddChild(self, Child): print(self, " ", Child) self.Children.append(Child) self.ChildrenCount = len(self.Children) return Child The Children is list of PathElement nodes. The code that build the tree: def UnFoldAndCheck(self): Path = PathElement("root") Handler = Path Index = 0 Count = len(self.Path) while Index &lt; Count: element = self.Path[Index] if something: Child = None Child = PathElement(element) Handler.AddChild(Child) Handler = None #Those added to debug the problem Handler = Child elif other_thing: if condition: if some_large_condition: ChildExec = None ChildExec = PathElement(element, False) for i in range(0, 5): ChildExec.Element.append(self.Path[Index + i]) Handler.AddChild(ChildExec) Handler = None Handler = ChildExec Index += 4 elif another_condition: ChildOp = None ChildOp = PathElement(element, False) Handler.AddChild(ChildOp) Handler = None Handler = ChildOp elif some_else_condition: if condition: ChildExec = None ChildExec = PathElement(element, False) for i in range(0, 3): ChildExec.Element.append(self.Path[Index + i]) Handler.AddChild(ChildExec) Handler = None Handler = ChildExec Index += 2 elif different_condition: ChildExec = None ChildExec = PathElement(element, False) for i in range(0, 3): ChildExec.Element.append(self.Path[Index + i]) Handler.AddChild(ChildExec) Handler = None Handler = ChildExec Index += 1 Index += 1 return Path My problem is that after the tree is built when I use it it will have always same structure: root -> object with 3 …
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88085059
accepted answer: http://stackoverflow.com/a/50546565
type: Question
has answer: http://stackoverflow.com/a/50546565
tagged with: python-3.x
has title: Python recursive object refrence in Tree datastructure
has comment: http://stackoverflow.com/comment/88066041
has comment: http://stackoverflow.com/comment/88064618
has comment: http://stackoverflow.com/comment/88097154
tagged with: tree
type: AnsweredQuestion
tagged with: object

http://stackoverflow.com/comment/87935736
type: AnswerComment
comment on: http://stackoverflow.com/a/50453770
type: Comment
has text: Well, it didn't really result in a solution, but i appreciate the answer anyway. I guess i'll just have to manually set up python on every system this is to be used on instead.
score: 0

http://stackoverflow.com/q/50391050
tagged with: pyqt5
downvote count: 1
has body: I'm trying to just delete the QTreeView item "Node 6 (delete me)" from within the model. I can't get it to work, as nothing is deleted. What am I doing wrong? See the MainWindow.init method for the removal code. import sys try: from PySide2 import QtWidgets except ImportError: from PyQt5 import QtWidgets try: from PySide2 import QtCore except ImportError: from PyQt5 import QtCore class Node(object): def __init__(self, name, parent=None): self._name = name self._children = [] self._parent = parent if parent is not None: parent.addChild(self) def addChild(self, child): self._children.append(child) child._parent = self def name(self): return self._name def child(self, row): return self._children[row] def insertChild(self, position, child): if position &lt; 0 or position &gt; len(self._children): return False self._children.insert(position, child) child._parent = self return True def childCount(self): return len(self._children) def parent(self): return self._parent def setParent(self, new_parent): self._parent._children.remove(self) self._parent = new_parent new_parent._children.append(self) def row(self): if self._parent is not None: return self._parent._children.index(self) def removeChild(self, position): if position &lt; 0 or position &gt; len(self._children): return False child = self._children.pop(position) child._parent = None return True def __repr__(self): return self._name class TreeModel(QtCore.QAbstractItemModel): def __init__(self, root, parent=None): super(TreeModel, self).__init__(parent) self._rootNode = root def rowCount(self, parent=QtCore.QModelIndex()): if not parent.isValid(): parentNode = self._rootNode else: parentNode = parent.internalPointer() return parentNode.childCount() def columnCount(self, parent): return 1 def data(self, index, role): """Return whatever the view should display""" if not index.isValid(): return None node = index.internalPointer() if role == QtCore.Qt.DisplayRole: if index.column() == 0: return node.name() def index(self, r…
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/87797927
tagged with: pyside2
tagged with: python
answer count: 1
tagged with: qt
has comment: http://stackoverflow.com/comment/87797620
type: Question
accepted answer: http://stackoverflow.com/a/50391283
type: AnsweredQuestion
upvote count: 3
has title: How to remove row from QTreeView using QAbstractItemModel?
has answer: http://stackoverflow.com/a/50391283

http://stackoverflow.com/a/50401303
has comment: http://stackoverflow.com/comment/87818662
downvote count: 0
answers question: http://stackoverflow.com/q/50401224
has body: This is a feature, no bug. The ticklabels are positionned at drawtime to sit at the correct locations according to the ticker in use. This ensures that the label always sits where the corresponding tick is located. If you change the limits, move or zoom the plot, the label always follows those changes. You are usually not meant to change this location, but you may, by adding a custom transform to it. This is described in Moving matplotlib xticklabels by pixel value. The general idea is to set a translating transformation on the label. E.g. to translate the second label by 20 pixels to the right, import matplotlib.transforms as mtrans # ... trans = mtrans.Affine2D().translate(20, 0) label = ax.get_xticklabels()[1] label.set_transform(label.get_transform()+trans)
has comment: http://stackoverflow.com/comment/87818747
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/87965224
type: Comment
score: 0
has text: @jeremysprofile: not sure if this requires the quite hefty numpy hammer though.
comment on: http://stackoverflow.com/q/50473835
type: QuestionComment

http://stackoverflow.com/q/50483146
duplicate of: http://stackoverflow.com/q/2600790
has comment: http://stackoverflow.com/comment/87979447
type: Question
tagged with: keyerror
has comment: http://stackoverflow.com/comment/87980208
score: 2
has comment: http://stackoverflow.com/comment/87980027
answer count: 0
tagged with: encoding
upvote count: 2
has title: KeyError when using 'devnagri'(Hindi) script for a key in creating a dictionary
type: UnansweredQuestion
downvote count: 0
favorite count: 0
tagged with: hindi
linked to: http://stackoverflow.com/q/2600790
has comment: http://stackoverflow.com/comment/87979812
has body: This part of code works fine and builds the dictionary fine. #!/usr/bin/env python #-*- coding: utf-8 -*- import collections from operator import itemgetter S_eng = "Hindi constitutional form in India first" S_hindi = "हिन्दी संवैधानिक रूप से भारत की प्रथम " word_count = collections.defaultdict( dict ) for st in S_eng .split(" "): for st_1 in S_hindi.split(" "): print type(st), type(st_1) word_count[st][st_1] = 1 print word_count But when I try to read a file having English and Hindi sentences and trying to create a dictionary the below happens #!/usr/bin/env python #-*- coding: utf-8 -*- P = defaultdict(dict) i = "your" j = "अपने" if(P[i][j] &gt;= 0): P[i][j] += 1 else: P[i][j] = 0 print P This gives error as: Traceback (most recent call last): File "lerxical_probab.py", line 31, in &lt;module&gt; if(P[i][j] &gt;= 0): KeyError: '\xe0\xa4\x85\xe0\xa4\xaa\xe0\xa4\xa8\xe0\xa5\x87' I checked the types of i and j too both are 'str' only. Can someone please help in this matter? And how come one works and other don't?
has comment: http://stackoverflow.com/comment/87979881
has comment: http://stackoverflow.com/comment/87980605
tagged with: python

http://stackoverflow.com/q/50522164
upvote count: 1
has comment: http://stackoverflow.com/comment/88057901
downvote count: 1
tagged with: python
has body: I've been having a problem with coding the file I/O program using a socket in python. The purpose of my server program is to send a text file to the client program via socket. Even though I confirmed that a client program receives some data from a server program, the client can't write the data to the file. What is the problem??? Please help me.. [server.py] import socketserver from time import sleep class TCPSocketHandler(socketserver.BaseRequestHandler): def handle(self): sock = self.request while True: with open('imageNames.txt', 'r') as file: try: names=file.readlines() for name in names: print(name) sock.send((name.encode('utf-8'))) except Exception as exc: print(exc) sleep(60) def main(): HOST, PORT = "192.168.xx.xx", 7799 server = socketserver.TCPServer((HOST, PORT), TCPSocketHandler) server.serve_forever() if __name__ == '__main__': main() [client.py] import socket def main(): HOST, PORT = "192.168.xx.xx", 7799 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((HOST, PORT)) data = (sock.recv(1024)).decode('utf-8') with open('imageNames2.txt', 'w') as file: try: while data: print(data) file.write(data) data = (sock.recv(1024)).decode('utf-8') except Exception as e: print(e) if __name__ == '__main__': main()
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50522489
type: UnansweredQuestion
tagged with: sockets
has title: About file I/O using socket in python
has comment: http://stackoverflow.com/comment/88056711
score: 0
tagged with: file-io
answer count: 1

http://stackoverflow.com/comment/88101710
type: QuestionComment
score: 0
has text: All I want is to get groupBy of domain fields in the text file. Fields with domain column are "_8" and "_16"
comment on: http://stackoverflow.com/q/50533833
type: Comment

http://stackoverflow.com/q/50428438
tagged with: list
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87871715
has body: I try to create the list of object with some attributes like this. info.py import numpy as np class MapInfo(object): """docstring forInfomation.""" def __init__(self, arg): super(MapInfo,self).__init__() self.arg = arg cost = np.array([[0,12,11,7,10,10,9,8,6,12], [12,0,8,5,9,12,14,16,17,22], [11,8,0,9,15,17,8,18,14,22], [7,5,9,0,7,9,11,12,12,17], [10,9,15,7,0,3,17,7,15,18], [10,12,17,9,3,0,18,6,15,15], [9,14,8,11,17,18,0,16,8,16], [8,16,18,12,7,6,16,0,11,11], [6,17,14,12,15,15,8,11,0,10], [12,22,22,17,18,15,16,11,10,0]]) luggage = np.array([0, 10, 15, 18, 17, 3, 5, 9, 4, 6]) capacitor = 40 class depot(object): """docstring for depot.""" def __init__(self): super(depot, self).__init__() next_pt = np.zeros((1,10)) I am trying to add data for next_pt of 10 "depot" objects like this. main.py from info import MapInfo as inf from info import depot as dp import numpy as np def init(): for i in range(0,10): depot.append(dp) """-------__init__method----------------""" def ArrangeNextDes(): temp = np.zeros((1,10)) pos = np.zeros((1,10)) for i in range(0,10):#for depot object for j in range(0,10): temp[0,j] = inf.cost[i,j] pos[0,j] = j for pt in range(0,9):# for next_pt object for jpt in range(pt+1,10): if (temp[0,jpt] &lt; temp[0,pt]): t = temp[0,pt] temp[0,pt] = temp[0,jpt] temp[0,jpt] = t p = pos[0,pt] pos[0,pt] = pos[0,jpt] pos[0,jpt] = p depot[i].next_pt = pos print(depot[i].next_pt) """-------------------------------------""" """------main program-----------""" start_pt = 0 map_status = np.zeros((10,10)) map_status[0,0]=1 depot = [] init() ArrangeNextDes() for i in range(0,10): print("depot[%d] = "%i,depot[i].next_pt) And the result like this: [[0. 8. 3. 7. 6. 5. 4. 2. 1. 9.]] [[1. 3. 2. 4. 0. 5. 6. 7. 8. 9.]] [[2. 1. 6. 3. 0. 8. 4. 5. 7. 9.]] [[3. 1. 0. 4. 2. 5. 6. 7. 8. 9.]] [[4. 5. 3. 7. 1. 0. 2. 8. 6. 9.]] [[5. 4. 7. 3. 0. 1. 8. 9. 2. 6.]] [[6. 2. 8. 0. 3. 1. 7. 9. 4. 5.]] [[7. 5. 4. 0. 8. 9. 3. 6. 1. 2.]] [[8. 0. 6. 9. 7. 3. 2. 4. 5. 1.]] [[9. 8. 7. 0. 5. 6. 3. 4. 2…
has comment: http://stackoverflow.com/comment/87871651
has comment: http://stackoverflow.com/comment/87872247
favorite count: 0
type: Question
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/534375
has title: Why list in python do that?
tagged with: python
linked to: http://stackoverflow.com/q/534375
has comment: http://stackoverflow.com/comment/87871656
has comment: http://stackoverflow.com/comment/87871710
has comment: http://stackoverflow.com/comment/87871678

http://stackoverflow.com/comment/87848824
has text: Hm, your z-values are always `-45`. Do you have more data or different subset which you can share?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50415667
score: 0

http://stackoverflow.com/a/50527757
type: Answer
accepted answer of: http://stackoverflow.com/q/50527661
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50527661
has comment: http://stackoverflow.com/comment/88083634
has body: indata in your line out_file.write(indata) is a file object. To get its content call indata.read(). out_file.write(indata.read())

http://stackoverflow.com/comment/87877436
has text: thanks, @eyllanesc, you've been really helpful, +1!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50431460
type: Comment

http://stackoverflow.com/a/50419858
type: Answer
has body: Use pd.cut to create a dummy column containing the bucketing, then group on that. &gt;&gt;&gt; df = pd.DataFrame({'Price': np.random.randint(0,20,(10,)), 'Revenue': np.random.rand(10)}) &gt;&gt;&gt; df Price Revenue 0 0 0.104462 1 9 0.976338 2 7 0.800895 3 13 0.700494 4 13 0.241352 5 0 0.535348 6 13 0.811419 7 17 0.508165 8 13 0.580809 9 5 0.711055 &gt;&gt;&gt; df['Bucket'] = pd.cut(df['Price'], [-float('inf'), 5, 10, 15, float('inf')]) &gt;&gt;&gt; df Price Revenue Bucket 0 0 0.104462 (-inf, 5.0] 1 9 0.976338 (5.0, 10.0] 2 7 0.800895 (5.0, 10.0] 3 13 0.700494 (10.0, 15.0] 4 13 0.241352 (10.0, 15.0] 5 0 0.535348 (-inf, 5.0] 6 13 0.811419 (10.0, 15.0] 7 17 0.508165 (15.0, inf] 8 13 0.580809 (10.0, 15.0] 9 5 0.711055 (-inf, 5.0] &gt;&gt;&gt; df.groupby('Bucket').sum() Price Revenue Bucket (-inf, 5.0] 5 1.350865 (5.0, 10.0] 16 1.777233 (10.0, 15.0] 52 2.334075 (15.0, inf] 17 0.508165 &gt;&gt;&gt; df.groupby('Bucket')['Revenue'] .agg(['count', 'sum']) .rename(columns={'sum': 'Net Revenue'}) count Net Revenue Bucket (-inf, 5.0] 3 2.266008 (5.0, 10.0] 3 1.477182 (10.0, 15.0] 1 0.432358 (15.0, inf] 3 2.097361
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50419435
answers question: http://stackoverflow.com/q/50419435

http://stackoverflow.com/a/50520963
score: 4
has comment: http://stackoverflow.com/comment/88089328
has comment: http://stackoverflow.com/comment/88076239
has body: You need to install the pycurl module. This is typically accomplished with pip install pycurl
has comment: http://stackoverflow.com/comment/88079525
answers question: http://stackoverflow.com/q/50520943
has comment: http://stackoverflow.com/comment/88079654
has comment: http://stackoverflow.com/comment/88079564
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88087204
upvote count: 4
has comment: http://stackoverflow.com/comment/88085971

http://stackoverflow.com/q/50449457
tagged with: beautifulsoup
type: Question
tagged with: python
type: UnansweredQuestion
has title: Python Beautiful Soup: Get links that belong to a "div class"
has answer: http://stackoverflow.com/a/50449493
score: 0
has body: I know how to get links like this: tags = soup.find_all("a", href = True) But what do I need to do if I only want to the links that belong to a specific "div class". For instance in the html code you could see "div class = "information" in the level above the "a href". Thanks in advance
answer count: 1

http://stackoverflow.com/comment/88082445
comment on: http://stackoverflow.com/q/50534961
score: 0
type: Comment
type: QuestionComment
has text: I'm actually going to leave this question for a bit before formulating an answer because my approach is going to deviate so far from just `sqlite3` and, by answering, others will be less likely to open the question at all (and I think there's a much better alternative, I just don't know it). The first step for the probabilities is that you just need to "normalize" those counts. Nice question.

http://stackoverflow.com/a/50490197
type: Answer
answers question: http://stackoverflow.com/q/50490018
has body: If you are on Mac Os X please try using: sudo find / -type f -fstype local -iname "app.py" If you are not on Mac Os X you can use: sudo find / -mount -type f -iname "app.py" The find command will start from your root folder and search recursively for all the files called "app.py" (case insensitive).
score: 0
has comment: http://stackoverflow.com/comment/87994033
has comment: http://stackoverflow.com/comment/88003497
has comment: http://stackoverflow.com/comment/87993590

http://stackoverflow.com/comment/87854961
has text: If you are talking about the list string, I changed the name to post here so that it would be obvious what it was without the rest of the code. Thanks for the heads-up.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50418779
score: 0

http://stackoverflow.com/comment/87963087
type: Comment
has text: You can use list and you can access multiple values through same variable name using indices.In the example you are trying to get hi0,hi1,hi2 variables instead use hi as list and access by hi[0] hi[1] and so on
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50474696

http://stackoverflow.com/q/50474255
has comment: http://stackoverflow.com/comment/87962093
favorite count: 0
has answer: http://stackoverflow.com/a/50474534
type: Question
accepted answer: http://stackoverflow.com/a/50474534
has comment: http://stackoverflow.com/comment/87962344
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Deleting specific rows of CSV file in python
has comment: http://stackoverflow.com/comment/87962395
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87962278
tagged with: pandas
upvote count: 1
has body: I have a CSV file, and i want to delete some rows of it based on the values of one of the columns. I do not know the related code to delete the specific rows of a CSV file which is in type pandas.core.frame.DataFrame. I read related questions, and i found that people suggest writing every line that is acceptable in a new file. I do not want to do that. The thing that i want is: 1) to delete the rows that I know the index of them (number of the row) or 2) to make a new CSV in the memory of the python (not to write and again read it )
answer count: 1
downvote count: 1

http://stackoverflow.com/q/50536193
has comment: http://stackoverflow.com/comment/88084590
linked to: http://stackoverflow.com/q/12834785
has comment: http://stackoverflow.com/comment/88084754
type: AnsweredQuestion
has body: I want to pass multiple arguments using cmd to the python script. below is the code I have used. import argparse ap = argparse.ArgumentParser() ap.add_argument('-n', '--names-list', nargs='+', default=[]) #item1 item2 item3 item4 args = vars(ap.parse_args()) a = args.names-list[0] b= args.names-list[1] c=args.names-list[2] d=args.names-list[3] print(a) print(b) print(c) print(d) when I execute the code I got an error message like below. File "D:\script.py", line 7, in &lt;module&gt; a = args.names-list[0] AttributeError: 'dict' object has no attribute 'names' as I'm very new to this, can somebody help me to solve the problem?
tagged with: argparse
score: 1
duplicate of: http://stackoverflow.com/q/12834785
answer count: 1
has comment: http://stackoverflow.com/comment/88085248
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88085078
accepted answer: http://stackoverflow.com/a/50536271
upvote count: 2
has answer: http://stackoverflow.com/a/50536271
tagged with: command-line-arguments
has title: argparse-assign list items to variables
tagged with: python

http://stackoverflow.com/comment/87913319
has text: @Heinzi: No good reason that I have ever been able to determine. It is just one more on a very long list of small mistakes that don't really matter.
type: Comment
comment on: http://stackoverflow.com/a/50434508
score: 3
type: AnswerComment

http://stackoverflow.com/comment/88055493
comment on: http://stackoverflow.com/q/50521609
has text: your code looks fine. Are you getting something in `response.body`?? And also you can also concat string and save html file.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88006021
type: QuestionComment
comment on: http://stackoverflow.com/q/50495986
type: Comment
score: 0
has text: @coldspeed, again, thanks for the quick reply. I could add the line which errors out, but it would just be a blob of text (as i can't find what's exactly wrong with it). Would that be helpful in any way?

http://stackoverflow.com/comment/87796743
type: QuestionComment
has text: @PaulaThomas Sure, here is the link https://github.com/wikilinks/sift/blob/master/sift/models/text.py
score: 0
comment on: http://stackoverflow.com/q/50390255
type: Comment

http://stackoverflow.com/comment/87956351
type: QuestionComment
comment on: http://stackoverflow.com/q/50471236
score: 0
type: Comment
has text: @JacobG., It maps to 90

http://stackoverflow.com/comment/88022641
comment on: http://stackoverflow.com/a/50504976
has text: That really helps me for the urgent solution ,but I have 1 more question. If this is not possible,Can you please tell the algorithm of google ,how can they crawl the pages ,I mean how can,they come to know , new website added , and have to crawl
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50440917
possible better answer: http://stackoverflow.com/a/50441015
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50441015
downvote count: 0
has title: Pandas: save rows unique to one category
accepted answer: http://stackoverflow.com/a/50441603
has answer: http://stackoverflow.com/a/50441603
favorite count: 0
type: Question
has body: I have many categories with items in lists like so: colors = ['green', 'red'] animals = ['cat', 'dog'] I have a large dataframe that has all items in the categories like so: largedf = pd.DataFrame({'arow': ['row1', 'row2', 'row3', 'row4'], 'green': ['a', 'b', 'b', 'a'], 'red': ['a', 'b', 'b', 'a'], 'cat': ['b', 'a', 'b', 'a'], 'dog': ['b', 'a', 'b', 'a']}) arow cat dog green red 0 row1 b b b a 1 row2 a a b b 2 row3 b b b b 3 row4 a a a a I want to save only the rows where a is the value for a certain category and only that category. row3 would not be saved because it has b for all items, row4 would not be saved because it has a for all items. row1 would be saved because it has an a for red (even though there is a b for green, at least one a is in that category). row2 would be saved because there is at least one a in cat/dog (in this case, an a in both). For each saved row, I'd like a column listing the category that has a and the percentage of a in that category (see output below). shorterdf = pd.DataFrame({'arow': ['row1', 'row2'], 'green': ['a', 'b'], 'red': ['a', 'b'], 'cat': ['b', 'a'], 'dog': ['b', 'a']}) arow cat dog green red category percent 0 row1 b b b a colors 0.5 1 row2 a a b b animals 1
upvote count: 2
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87896848
score: 2

http://stackoverflow.com/a/50452562
downvote count: 2
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50452437
has comment: http://stackoverflow.com/comment/92821191
score: 3
has body: You can use a glob here - the ** pattern indicates a recursive glob. The trailing slash matches on directories, excluding other types of files. from pathlib import Path def recursive_subdir_count(path): dirs = Path(path).glob('**/') result = sum(1 for dir in dirs) result -= 1 # discount `path` itself Using / works on windows, macOS, and Linux, so don't worry about putting os.sep instead. Beware of a weird edge case: shell globs typically exclude hidden directories, i.e. those which begin with a ., but pathlib includes those (it's a feature, not a bug: see issue26096). If you care about discounting hidden directories, filter them out in the expression when calling sum. Or, use the older module glob which excludes them by default.
has comment: http://stackoverflow.com/comment/92822198

http://stackoverflow.com/q/50454095
has title: tf.gradients - dimensions of output
score: 2
answer count: 0
upvote count: 2
has body: Here is my code: import tensorflow as tf tf.reset_default_graph() x = tf.placeholder(tf.float32, [None, 3],name='x') W_1 = tf.get_variable('W_1', [3,3], dtype = tf.float32, initializer=tf.constant_initializer(1.0)) layer_out = tf.matmul(x, W_1, name = 'layer_out') sess = tf.Session() sess.run(tf.global_variables_initializer()) sess.run([tf.gradients(layer_out, [x])], feed_dict = {x: np.array([[1,7,5]])} ) it returns: [[array([[3., 3., 3.]], dtype=float32)]] I am expecting to get 3 by 3 matrix or as per tf.gradients docs list of dim 3 with 3 elements for each list entry. What I am missing? UPDATE: I see in docs tf.gradients A list of sum(dy/dx) for each x in xs but why sum and how do I get all entries of Jacobian?
type: UnansweredQuestion
tagged with: gradient
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: dimensions
tagged with: python

http://stackoverflow.com/comment/88089073
comment on: http://stackoverflow.com/q/50538051
type: QuestionComment
type: Comment
has text: Yup, the extra characters will always be at the end.
score: 0

http://stackoverflow.com/comment/87959269
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50472476
score: 1
has text: No, the best you can do is to replace the value, eg with `None`, or some default value. Eg, `default = object(); sd['q'] = default`

http://stackoverflow.com/comment/88063816
comment on: http://stackoverflow.com/q/50525927
type: Comment
score: 0
has text: `for el in tree.iter('uri'): self.phoneLine = el.text break ` Nah use what @Rakesh said
type: QuestionComment

tkinter
tags question: http://stackoverflow.com/q/50449273
tags question: http://stackoverflow.com/q/50458394
tags question: http://stackoverflow.com/q/50459992
tags question: http://stackoverflow.com/q/50508640
tags question: http://stackoverflow.com/q/50461832
tags question: http://stackoverflow.com/q/50495799
tags question: http://stackoverflow.com/q/50414876
tags question: http://stackoverflow.com/q/50398649
tags question: http://stackoverflow.com/q/50400552
tags question: http://stackoverflow.com/q/50476102
tags question: http://stackoverflow.com/q/50533079
tags question: http://stackoverflow.com/q/50521628
tags question: http://stackoverflow.com/q/50475651
tags question: http://stackoverflow.com/q/50523932
tags question: http://stackoverflow.com/q/50411694
tags question: http://stackoverflow.com/q/50438182
tags question: http://stackoverflow.com/q/50415752
tags question: http://stackoverflow.com/q/50415496
tags question: http://stackoverflow.com/q/50528067
tags question: http://stackoverflow.com/q/50400306
tags question: http://stackoverflow.com/q/50466064
tags question: http://stackoverflow.com/q/50431638
tags question: http://stackoverflow.com/q/50494824
tags question: http://stackoverflow.com/q/50522884
tags question: http://stackoverflow.com/q/50496347
tags question: http://stackoverflow.com/q/50416935
tags question: http://stackoverflow.com/q/50412458
tags question: http://stackoverflow.com/q/50427863
tags question: http://stackoverflow.com/q/50420219
tags question: http://stackoverflow.com/q/50535832
tags question: http://stackoverflow.com/q/50507474
tags question: http://stackoverflow.com/q/50529186
tags question: http://stackoverflow.com/q/50433159
tags question: http://stackoverflow.com/q/50390471
tags question: http://stackoverflow.com/q/50515736
tags question: http://stackoverflow.com/q/50478846
tags question: http://stackoverflow.com/q/50516244
tags question: http://stackoverflow.com/q/50454280
tags question: http://stackoverflow.com/q/50520301
tags question: http://stackoverflow.com/q/50538963
tags question: http://stackoverflow.com/q/50541773
tags question: http://stackoverflow.com/q/50530834
tag name: tkinter
tags question: http://stackoverflow.com/q/50458324
tags question: http://stackoverflow.com/q/50472616
tags question: http://stackoverflow.com/q/50539858
tags question: http://stackoverflow.com/q/50494617
tags question: http://stackoverflow.com/q/50402895
tags question: http://stackoverflow.com/q/50490567
tags question: http://stackoverflow.com/q/50473210
tags question: http://stackoverflow.com/q/50484813
tags question: http://stackoverflow.com/q/50517757
tags question: http://stackoverflow.com/q/50398159
tags question: http://stackoverflow.com/q/50427898
tags question: http://stackoverflow.com/q/50387892
tags question: http://stackoverflow.com/q/50517846
tags question: http://stackoverflow.com/q/50536769
tags question: http://stackoverflow.com/q/50520283
tags question: http://stackoverflow.com/q/50526451
tags question: http://stackoverflow.com/q/50512389
tags question: http://stackoverflow.com/q/50497841
tags question: http://stackoverflow.com/q/50488628
tags question: http://stackoverflow.com/q/50439948
tags question: http://stackoverflow.com/q/50520820
tags question: http://stackoverflow.com/q/50415969
tags question: http://stackoverflow.com/q/50422735
tags question: http://stackoverflow.com/q/50449082
tags question: http://stackoverflow.com/q/50451747
tags question: http://stackoverflow.com/q/50430751
tags question: http://stackoverflow.com/q/50515209
tags question: http://stackoverflow.com/q/50482707
tags question: http://stackoverflow.com/q/50430292
tags question: http://stackoverflow.com/q/50500760
tags question: http://stackoverflow.com/q/50404195
tags question: http://stackoverflow.com/q/50416562
tags question: http://stackoverflow.com/q/50387231
tags question: http://stackoverflow.com/q/50429744
tags question: http://stackoverflow.com/q/50444889
tags question: http://stackoverflow.com/q/50446859
tags question: http://stackoverflow.com/q/50485891

http://stackoverflow.com/a/50486447
accepted answer of: http://stackoverflow.com/q/50486382
has comment: http://stackoverflow.com/comment/122885019
answers question: http://stackoverflow.com/q/50486382
type: AcceptedAnswer
type: Answer
has body: Pass the parameter ensure_ascii = False: json.dumps(data, ensure_ascii = False) Documentation here. If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
downvote count: 0
upvote count: 26
score: 26

http://stackoverflow.com/q/50483425
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1
has title: Uploading JSON to Bigquery unspecific error
has answer: http://stackoverflow.com/a/50483783
has body: I am just getting started with the python BigQuery API (https://github.com/GoogleCloudPlatform/google-cloud-python/tree/master/bigquery) after briefly trying out (https://github.com/pydata/pandas-gbq) and realizing that the pandas-gbq does not support RECORD type, i.e. no nested fields. Now I am trying to upload nested data to BigQuery. I managed to create the table with the respective Schema, however I am struggling with the upload of the json data. from google.cloud import bigquery from google.cloud.bigquery import Dataset from google.cloud.bigquery import LoadJobConfig from google.cloud.bigquery import SchemaField SCHEMA = [ SchemaField('full_name', 'STRING', mode='required'), SchemaField('age', 'INTEGER', mode='required'), SchemaField('address', 'RECORD', mode='REPEATED', fields=( SchemaField('test', 'STRING', mode='NULLABLE'), SchemaField('second','STRING', mode='NULLABLE') )) ] table_ref = client.dataset('TestApartments').table('Test2') table = bigquery.Table(table_ref, schema=SCHEMA) table = client.create_table(table) When trying to upload a very simple JSON to bigquery I get a rather ambiguous error 400 Error while reading data, error message: JSON table encountered too many errors, giving up. Rows: 1; errors: 1. Please look into the error stream for more details. Beside the fact that it makes me kinda sad that its giving up on me :), obviously that error description does not really help ... Please find below how I try to upload the JSON and the sampledata. job_config = bigquery.LoadJobConfig() job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON with open('testjson.json', 'rb') as source_file: job = client.load_table_from_file( source_file, table_ref, location='US', # Must match the destination dataset location. job_config=job_config) # API request job.result() # Waits for table load to complete. print('Loaded {} rows into {}:{}.'.format( job.output_rows, dataset_id, table_id)) This is my JSON object "[{'full_name':'test','age':2,'address…
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50485576
score: 1
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/50483783
tagged with: python
tagged with: google-bigquery
accepted answer: http://stackoverflow.com/a/50485576

http://stackoverflow.com/q/50499511
has title: Condition based on ffil() in pandas Dataframe
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I asked a similar question and got some help but after more testing the solution did not work. I am not sure how to open existing ticket so I will ask again. I have a dataframe and I am trying to fill a column based on a condition but I can't get it to work correctly in each instance. I want a 1 to be inserted in the test column if there is a 1 in the IN column and 200D column has a 1. But once the 200D column goes to 0 the TEST column should not go back to a 1 until there is a 1 in the IN column. This is a test example DF and the code I have so far df['TEST']=df.loc[df.IN==1,'IN'] df['TEST'] = df.loc[df['200D_MA']==1,'TEST'].ffill() df['TEST'].fillna(0,inplace=True) Date IN 200D TEST 12/6/2013 0 1 0 12/9/2013 0 1 0 12/10/2013 1 1 1 IN and 200D 1 &gt;&gt; TEST =1 12/11/2013 0 1 1 1 to Carry Down as long as 200D =1 12/16/2013 0 1 1 Carry Down as long as 200D =1 12/17/2013 0 1 1 12/18/2013 0 0 0 TEST = 0 bc 200D =0 12/19/2013 0 0 0 12/20/2013 0 0 0 12/23/2013 0 1 1 WRONG &gt; TEST SHOULD BE 0 bc IN not 1 12/24/2013 0 1 1 WRONG &gt; TEST SHOULD BE 0 bc IN not 1 12/25/2013 0 1 1 WRONG &gt; TEST SHOULD BE 0 bc IN not 1 12/26/2013 1 0 0 12/27/2013 1 0 0 12/28/2013 0 1 1 12/29/2013 1 1 1 IN and 200D 1 &gt;&gt; TEST =1 12/30/2013 0 1 1 12/31/2013 0 1 1 1/1/2014 0 0 0 1/2/2014 1 0 0 TEST=1 but 200D =0 &gt;&gt; TEST =0 1/3/2014 0 0 0 1/6/2014 0 0 0 1/7/2014 1 1 1 IN and 200D 1 &gt;&gt; TEST =1 1/8/2014 0 1 1
has answer: http://stackoverflow.com/a/50500605
tagged with: pandas
score: 1
tagged with: python

http://stackoverflow.com/comment/88020178
score: 0
comment on: http://stackoverflow.com/q/50502620
has text: @Arash It is important to provide Testdata for your code because some optimization technics like parallelization depends on the size of the problem. Also Add some information on the precision you need. eg. Is float32 enough or do you need double precision (float64)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87963260
has text: Thanks Daniel, I am not great in functional API but i will try the solution which you have given. Just to give an overview of my task, i am using the sequential model using LSTM architecture to predict time series. It is pretty simple code. However the problem is i need to run the same program for each dataset to build model and where i need to predict data of each dataset.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50474657
type: AnswerComment

http://stackoverflow.com/comment/88098341
type: QuestionComment
comment on: http://stackoverflow.com/q/50541020
has text: @SmartManoj I'm using the correct Django
score: 0
type: Comment

http://stackoverflow.com/comment/87841658
score: 0
has text: no i get the right output. six numbers in the file and this six numbers are the output. But i have to corrct me: i got the result of the url with the last (not first) number into the txt-file
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50412172

http://stackoverflow.com/q/50398982
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50400501
has comment: http://stackoverflow.com/comment/87816571
has body: While trying to commit rows with SQLalchemy using session.merge(), I get an error of duplicates. I think it is because the databse where I fetch the data allows duplicates of columns "hash" and the new one doesn't. Is there a simple way to avoid or remove duplicates in the current session before committing ? Here is an example: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.automap import automap_base from src.python.utils import _gen_relationship engine = create_engine('mysql+pymysql://{user}:{pssw}@{host}/{db}?charset=utf8'. format(user=config['user'], pssw=config['password'], host=config['host'], db=config['database']) ) database = [ {'c_hash': 'd182jd012jd102jd1', 'date': '2017-01-01', 'text': 'oijwdqoijwdqoiqwdm'}, {'c_hash': 'apiowjdaowndoaiwjda', 'date': '2017-01-01', 'text': 'oijwdqoijwdqoiqwdm'}, {'c_hash': 'd182jd012jd102jd1', 'date': '2017-01-02', 'text': 'adawdawdawd'} ] Base = automap_base() Base.prepare(engine, reflect=True, generate_relationship=_gen_relationship) # load necessary table information Mytable = Base.classes.mytable Session = sessionmaker(bind=engine, autoflush=False) session = Session() for row in database: new_row = { 'hash': row['c_hash'], 'date': row['date'], 'text': row['text'] } session.merge(Mytable(**new_row)) session.commit() Thank you
has comment: http://stackoverflow.com/comment/87815673
type: AnsweredQuestion
has title: SQLalchemy Avoid duplicate in session() before commiting
tagged with: mysql
score: 1
has comment: http://stackoverflow.com/comment/87813892
has comment: http://stackoverflow.com/comment/87813972
tagged with: sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/87825065
type: Question
has comment: http://stackoverflow.com/comment/87816132
downvote count: 0
has comment: http://stackoverflow.com/comment/87839062
upvote count: 1
accepted answer: http://stackoverflow.com/a/50400501
has comment: http://stackoverflow.com/comment/87816052

http://stackoverflow.com/q/50515694
tagged with: argparse
has comment: http://stackoverflow.com/comment/88044152
has comment: http://stackoverflow.com/comment/88044272
has answer: http://stackoverflow.com/a/50515861
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88044333
has comment: http://stackoverflow.com/comment/88044204
has title: Use embedded argparse in Python3
score: 2
upvote count: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88044384
favorite count: 0
has body: I want to make a Python module that can be used both by command line and other modules. Like that : python3 Capacity.py arg1 arg2 arg3 or &gt;&gt;&gt; capacity.execByString("arg1 arg2 arg3") I made a class to (with some researches) get the result of argparse within the code : class ArgumentParserError(Exception): pass class Parseur(ArgumentParser): def error(self, msg): raise ArgumentParserError(msg) def analyze(self, args): if type(args) is not list: args = args.split() # To work with a String try: result = self.parse_args(args) return True, result # Returns True and the namespace if OK except ArgumentParserError as err: return False, err.args[0] # Returns False and the error message if not OK I use it like this : class Capacity(): def __init__(self): self.parser = Parseur() # Config the parser def execByArguments(*args): # Do the job def execByString(command): isOK, result = self.parser.analyze(command) if isOk: # Launch execByArguments with the rights args in result else: # Print error message print(result) def execFromCommandLine(): args = self.parser.parse_args() # Launch execByArguments with the rights args if __name__ == "__main__": execFromCommandLine() But there's 2 main problems and surely some I have'nt yet discovered : the args are not parsed correctly (doubles quotes for example) as the split function has the "spaces" separator using the -h flag close the program anyway I'm convinced that making this another Parseur class is useless/not good and there's a workaround. Launching the module via subprocess is not a good idea neither : I want to get the returned object in that case. Can you help me to find a cool way to do what i want please ? Thanks already. PS : Write code on the online formular is such a pain ^^.
type: Question

http://stackoverflow.com/q/50522779
upvote count: 3
has title: How to open multiple webpages in separate tabs within a browser using selenium-webdriver and python
downvote count: 0
answer count: 1
tagged with: selenium
tagged with: webdriver
favorite count: 0
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/50523219
has answer: http://stackoverflow.com/a/50523219
linked to: http://stackoverflow.com/q/49219594
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: tabs
has body: I want to open mulitple local htmls within same browser window using Selenium Webdriver using Python. I have tried following in Jupyter notebook: from selenium import webdriver 1page = "file://&lt;path for 1.html&gt;" 2page = "file://&lt;path for 2.html&gt;" firefox_path = 'C:\geckodriver.exe' driver = webdriver.Firefox(executable_path= firefox_path) driver.get(1page) # For opening 2nd HTML in another Tab driver.execute_script('''window.open('''+ 2page + ''',"_blank");''') Running above code lead me to the following error: JavascriptException: Message: Error: Access to 'file://&lt;path of 2.html&gt;' from script denied How to mitigate this error?

http://stackoverflow.com/q/50436881
upvote count: 4
has title: python cProfile/snakeviz can't handle multiple functions calling same function
tagged with: cprofile
type: UnansweredQuestion
answer count: 1
downvote count: 0
score: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87888996
has answer: http://stackoverflow.com/a/51683511
tagged with: python
has comment: http://stackoverflow.com/comment/87888236
has body: I'm having issues interpreting cProfile data. To show you my problem I created this simple script. The function D calls B and C, which both call A. Function A clearly takes up 1 sec (+overhead). If we look at the snakeviz results then you can see that the reporting is a bit weird. I understand that in total 2 sec has been spent by function A, but inside function C, function A has spent only 1 sec, and that's what I am interested in. Does anybody know if there is a setting (or a different viewer) where I do not have this issue? import time import cProfile def A(): time.sleep(1) def B(): A() def C(): A() def D(): B() C() cProfile.run('D()','profileResults.prf') snakeviz results

http://stackoverflow.com/a/50449490
has comment: http://stackoverflow.com/comment/87926689
score: 5
has comment: http://stackoverflow.com/comment/87912785
answers question: http://stackoverflow.com/q/50449353
has comment: http://stackoverflow.com/comment/87912326
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87926593
has comment: http://stackoverflow.com/comment/87934128
has body: You can use pd.wide_to_long: pd.wide_to_long(df, ['A','B'], 'ID', 'value', sep='', suffix='.+')\ .reset_index()\ .sort_values('ID')\ .drop('value', axis=1) Output: ID A B 0 1 3 4 2 1 5 6 1 2 7 8 3 2 9 10
has comment: http://stackoverflow.com/comment/87927199
has comment: http://stackoverflow.com/comment/87914450
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/87927465
accepted answer of: http://stackoverflow.com/q/50449353

http://stackoverflow.com/comment/87851055
comment on: http://stackoverflow.com/q/50417711
has text: It looks like you're comparing a list of tuples (from `values_list()`) to a string.
score: 1
type: Comment
type: QuestionComment

mongodb
tags question: http://stackoverflow.com/q/50466555
tags question: http://stackoverflow.com/q/50530263
tags question: http://stackoverflow.com/q/50485756
tags question: http://stackoverflow.com/q/50453231
tags question: http://stackoverflow.com/q/50400753
tags question: http://stackoverflow.com/q/50505311
tags question: http://stackoverflow.com/q/50492820
tags question: http://stackoverflow.com/q/50516253
tags question: http://stackoverflow.com/q/50490698
tags question: http://stackoverflow.com/q/50509896
tag name: mongodb
tags question: http://stackoverflow.com/q/50436845
tags question: http://stackoverflow.com/q/50535826
tags question: http://stackoverflow.com/q/50395265
tags question: http://stackoverflow.com/q/50494550
tags question: http://stackoverflow.com/q/50485329
tags question: http://stackoverflow.com/q/50447633
tags question: http://stackoverflow.com/q/50435100
type: Tag
tags question: http://stackoverflow.com/q/50423729
tags question: http://stackoverflow.com/q/50416661
tags question: http://stackoverflow.com/q/50442971

http://stackoverflow.com/comment/87810182
has text: Just divide the length of your input array by 3 and you get the number of slices: np.split(arr, len(arr)/3)
comment on: http://stackoverflow.com/a/50397108
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87857646
has text: `y` needs to be 2d like `x`, e.g. (50000,1) shape. `np.concatenate((x, y[:,None]), axis=-1)`.
type: Comment
comment on: http://stackoverflow.com/q/50421182
score: 0
type: QuestionComment

http://stackoverflow.com/q/50535957
answer count: 1
downvote count: 0
has title: QThreads in Pyqt5: is it ok to create new objects in the constructor of the worker class?
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/88084412
has comment: http://stackoverflow.com/comment/88084559
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88084312
type: Question
has comment: http://stackoverflow.com/comment/88084618
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50536430
has comment: http://stackoverflow.com/comment/88084241
linked to: http://stackoverflow.com/q/50531797
type: UnansweredQuestion
has body: 1. Some background info The official documentation on how to instantiate and use a QThread can be found here: http://doc.qt.io/qt-5/qthread.html The documentation describes two basic approaches: (1) worker-object approach and (2) QThread subclass approach. &nbsp;&nbsp;&nbsp;&nbsp;&#62; The following article explains why one needs to be careful when using the second approach: https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ &nbsp;&nbsp;&nbsp;&nbsp;&#62; The following article explains why both approaches have their merits: https://woboq.com/blog/qthread-you-were-not-doing-so-wrong.html I quote: As a rule of thumb: If you do not really need an event loop in the thread, you should subclass. If you need an event loop and handle signals and slots within the thread, you may not need to subclass. As I do need some sort of communication between the QApplication thread and the new QThread (and I believe signal-slot is a good way to communicate), I'll use the worker-object approach. &nbsp; 2. Sample code from the official docs On the official Qt5 docs on QThreads (see http://doc.qt.io/qt-5/qthread.html), you can find sample code. I've done an effort to translate it to Python: (See this stackoverflow question to see more details on that translation: QThreads in Pyqt5: is this the correct C++ to Python translation of the official QThread docs?) import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class Worker(QObject): resultReady = pyqtSignal(str) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Note: this constructor is empty now. # But would it be okay to instantiate new # objects here, and use them in doWork(..)? # A more general question: is it okay if # doWork(..) accesses variables that were # created in another thread (perhaps the # main QApplication thread)? @pyqtSlot(str) def doWork(self, param): result = "hello world" print("foo bar") # ...here is the expe…
has comment: http://stackoverflow.com/comment/88084298
linked to: http://stackoverflow.com/q/1595649
tagged with: python
has comment: http://stackoverflow.com/comment/88084664
tagged with: qt5
tagged with: qthread
has comment: http://stackoverflow.com/comment/88084492
has comment: http://stackoverflow.com/comment/88084443
has comment: http://stackoverflow.com/comment/88084255
has comment: http://stackoverflow.com/comment/88084465
has comment: http://stackoverflow.com/comment/88084557
has comment: http://stackoverflow.com/comment/88084371
has comment: http://stackoverflow.com/comment/88084178
has comment: http://stackoverflow.com/comment/88084652
has comment: http://stackoverflow.com/comment/88084136
score: 1

http://stackoverflow.com/q/50509026
has answer: http://stackoverflow.com/a/50509330
has comment: http://stackoverflow.com/comment/88029968
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I am trying to start and stop an in-memory database server from a python script for a certain experiment I'm working on. The issue that I am facing is that I'm not able to figure out how to continue to the next instruction automatically. The following code seems to work except as I said, it will wait for the server to return. I tried to search various solutions but none worked - including the ones mentioned here on stackoverflow. pid = subprocess.Popen(r"/PATH_TO/server",shell=True,stdin=None, stdout=None, stderr=None, close_fds=True).pid # DO SOME MORE STUFF HERE
tagged with: python-2.7
score: 0
has title: Python Popen and automatically continue to the next instruction
tagged with: popen
has comment: http://stackoverflow.com/comment/88029967
has comment: http://stackoverflow.com/comment/88030199
type: Question

http://stackoverflow.com/a/50538894
upvote count: 1
has body: You need to cast the integer to a string before appending the space. new += str(int((n)**count)) + ' '
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50538882
accepted answer of: http://stackoverflow.com/q/50538882
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87960456
type: AnswerComment
type: Comment
has text: would you mind explaining how this is working exactly?
score: 0
comment on: http://stackoverflow.com/a/50473411

http://stackoverflow.com/comment/87955190
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50470431
has text: Appreciate it!! Thank you, this is working.. but can you please share any other method where in I can use these strings individually to compare with some live data which I will be fetching from another source.

http://stackoverflow.com/q/50516511
answer count: 1
has title: Django complex query for OR
tagged with: django-queryset
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50516913
has comment: http://stackoverflow.com/comment/88045679
has comment: http://stackoverflow.com/comment/88048840
tagged with: django
tagged with: python
has body: I'm using django 1.10 I've created this query which works for me: filters_qs = filters_qs.filter( Q( user__in=[cache.user for cache in caches], status_id__in=[Status.Open['id'], Status.Empty['id']], revision=0 ) | Q( user=None, status_id__in=[Status.Open['id'], Status.Empty['id']], revision=0 ) ) I used the 'OR' because I'm looking for a result where the query set is either None or in the list. But - it looks not so 'pythonic'... it repeats the same code for minor change. Is there another way? for example, something like - (doesn't work) Q( user__in=[cache.user for cache in caches] + [None], status_id__in=[ Status.Open['id'], Status.Empty['id'] ], revision=0 ) Thanks.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50516913
downvote count: 0
score: 1
upvote count: 1

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/50448131
tags question: http://stackoverflow.com/q/50425726
tags question: http://stackoverflow.com/q/50412552
tag name: kivy-language
tags question: http://stackoverflow.com/q/50522099

http://stackoverflow.com/q/50392272
has title: Word access denied with win32 python
type: Question
tagged with: django
has comment: http://stackoverflow.com/comment/87800540
tagged with: python
accepted answer: http://stackoverflow.com/a/50392695
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50392695
score: 0
has body: I use Python 3.6 and Django 1.11. I created a Word document with MailMerge and it was ok. Right now I need to save this document as a pdf document. import win32com.client as win32 from os import path word = win32.DispatchEx("Word.Application") filedoc='c:\\growthtech\\Capturar6.docx' filepdf='c:\\growthtech\\Capturar6.pdf' in_file = path.abspath(filedoc) out_file = path.abspath(filepdf) doc = word.Documents.Open(in_file, 'rb') doc.SaveAs(new_file, FileFormat=17) doc.Close() word.Quit() It occurred the error bellow in line "doc = word.Documents.Open(in_file, 'rb')". &gt;&gt;&gt; doc = word.Documents.Open(in_file, 'rb') Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "&lt;COMObject &lt;unknown&gt;&gt;", line 8, in Open pywintypes.com_error: (-2147352571, 'Tipo não correspondente.', None, 2) I appreciate any help.
answer count: 1
linked to: http://stackoverflow.com/q/37258257

http://stackoverflow.com/comment/88023652
type: QuestionComment
comment on: http://stackoverflow.com/q/50505554
type: Comment
has text: what do you expect the output file to contain?
score: 0

http://stackoverflow.com/comment/87934929
type: Comment
comment on: http://stackoverflow.com/a/50460287
has text: are you trying to do it in ipython console?
score: 0
type: AnswerComment

http://stackoverflow.com/q/50449273
tagged with: python
has title: TKinter Geometry Manager displaying multiple rows of widgets
possible better answer: http://stackoverflow.com/a/50449810
type: AnsweredQuestion
answer count: 2
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/50450822
has answer: http://stackoverflow.com/a/50449810
has body: I wish to display a list of sentences with missing words. The basic, one-line, idea is the following: The construction of the above is a "label + entry + label + spacing + label". In order to make sure that the widgets were aligned left, I used the following code: phraseLabel1 = tk.Label(questionFrame) phraseLabel1.pack(side=tk.LEFT) keyWordEntry = tk.Entry(questionFrame) keyWordEntry.pack(side=tk.LEFT) phraseLabel2 = tk.Label(questionFrame) phraseLabel2.pack(side=tk.LEFT) keyWordLabel = tk.Label(questionFrame) keyWordLabel.pack(side=tk.LEFT,padx=30) My objective is to present the users with an input screen for multiple sentence. As for example given in the following drawing: Whilst I manage to create the labels via the underneath (experimental) code, I lack understanding to manage the geometry. root = tk.Tk() root.title("myTest") root.geometry("700x700") questionFrame = tk.Frame(root) resultFrame = tk.Frame(root) for frame in (questionFrame, resultFrame): frame.grid(row=0, column=0, sticky='news') #DB Query returning a set of phrases and Keywords (zinPhrase1, zinPhrase2, keyWordFR, keyWordNL)=getPhrase() #Init lab1 = [] keyWordEntry = [] lab2 = [] keyWord = [] for i in range(4): #4 is entered as a dummy value lab1.append(tk.Label(questionFrame)) lab1[i].pack() keyWordEntry.append(tk.Entry(questionFrame)) keyWordEntry[i].pack() lab2.append(tk.Label(questionFrame)) lab2[i].pack() keyWord.append(tk.Label(questionFrame)) keyWord[i].pack() lab1[i].config(text=zinPhrase1[i]) keyWordEntry[i].config(width=8) lab2[i].config(text=zinPhrase2[i]) keyWord[i].config(text=keyWordNL[i],fg="red") questionFrame.tkraise() root.mainloop() How can I manage the placement of the widgets line by line, as shown in the drawing above? Any help would gratefully appreciated.
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50450822
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/50453834
accepted answer of: http://stackoverflow.com/q/50453626
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50453626
has body: Stop using matrix. numpy.matrix.flatten returns a 1-row matrix, because that's as flat as matrix instances get. If for some reason you are dead set on using matrix, convert to ndarray with matrix.A before flattening: flat = whatever_matrix.A.flatten() or just use A1 to get a flat ndarray directly: flat = whatever_matrix.A1
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/50476638
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87966860
has answer: http://stackoverflow.com/a/50476922
possible better answer: http://stackoverflow.com/a/50476922
has comment: http://stackoverflow.com/comment/87966907
tagged with: python
has answer: http://stackoverflow.com/a/50477061
score: -1
has title: Holiday application on Python 2.7
type: AnsweredQuestion
tagged with: python-2.7
has body: I have tried solve these tasks for a homework but I got stuck: You will need to to create four functions: Hotel cost - This function will take the number of nights as an argument and return a total cost (You can choose the price per a night) Plane cost - This function will take the city you are flying to as an argument and return a cost for the flight (Hint: use if/else if statements in the function to retrieve a price based on the chosen city) Car rental - This function will take the number of days as an argument and return the total cost. Holiday cost - This function will take three arguments, number of nights, city, and days. Using these three arguments, you can call all three of the above functions with respective arguments and finally return a total cost for your holiday. Print out the value of your Holiday function to see the result! Try using your app with different combinations to show it’s compatibility with different options This is what I have so far: def hotel_cost(nights): return nights * 875 def plane_cost(city): ticket = 0 while city != 4: if city == '1': ticket = 750 break elif city == '2': ticket = 850 break elif city == '3': ticket = 600 break elif city == '4': print 'You have selected an invalid option' else: print 'You have selected an invalid option' def car_rental(days): return days * 275 def holiday_cost(nights, city, days): nights = hotel_cost(nights) city = plane_cost(city) days = car_rental(days) return nights + city + days hotel_cost(int(raw_input('How many nights will you be staying? '))) plane_cost(raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? ')) car_rental(int(raw_input('How many days will you need a car for?: '))) total = holiday_cost(nights, city, days) print total The error I get is the following: Traceback (most recent call last): File "C:\Users\user\Dropbox\Mengezi Dlomo-9897\intro to programming\Task 24\holiday.py", line 37, in &lt;module&gt; total = holiday…
has comment: http://stackoverflow.com/comment/87966903
answer count: 3
has answer: http://stackoverflow.com/a/50476869
has comment: http://stackoverflow.com/comment/87966956
accepted answer: http://stackoverflow.com/a/50476869
has comment: http://stackoverflow.com/comment/87966952
downvote count: 2
upvote count: 1

http://stackoverflow.com/a/50517740
answers question: http://stackoverflow.com/q/50517636
has body: With the Einstein notation to switch axes np.einsum("ijk-&gt;kij", arr) Here is a nice introduction Einstein Summation in Numpy
score: 2
has comment: http://stackoverflow.com/comment/88049033
has comment: http://stackoverflow.com/comment/88049094
upvote count: 2
has comment: http://stackoverflow.com/comment/88049290
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88106908
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50535442
has text: Ok, I did 'sudo easy_install pip' to install the pip, but it seems like we are heading to the wrong direction

neural-network
tags question: http://stackoverflow.com/q/50429826
tags question: http://stackoverflow.com/q/50452598
type: Tag
tags question: http://stackoverflow.com/q/50442324
tags question: http://stackoverflow.com/q/50474524
tags question: http://stackoverflow.com/q/50390217
tags question: http://stackoverflow.com/q/50425044
tags question: http://stackoverflow.com/q/50447025
tags question: http://stackoverflow.com/q/50481178
tags question: http://stackoverflow.com/q/50422872
tags question: http://stackoverflow.com/q/50524942
tags question: http://stackoverflow.com/q/50477522
tags question: http://stackoverflow.com/q/50408243
tags question: http://stackoverflow.com/q/50437670
tags question: http://stackoverflow.com/q/50392795
tags question: http://stackoverflow.com/q/50515409
tags question: http://stackoverflow.com/q/50432476
tags question: http://stackoverflow.com/q/50498481
tags question: http://stackoverflow.com/q/50414117
tags question: http://stackoverflow.com/q/50518710
tags question: http://stackoverflow.com/q/50440497
tags question: http://stackoverflow.com/q/50487156
tags question: http://stackoverflow.com/q/50518563
tags question: http://stackoverflow.com/q/50404893
tags question: http://stackoverflow.com/q/50397142
tags question: http://stackoverflow.com/q/50477826
tags question: http://stackoverflow.com/q/50476544
tags question: http://stackoverflow.com/q/50487603
tags question: http://stackoverflow.com/q/50518758
tags question: http://stackoverflow.com/q/50534429
tags question: http://stackoverflow.com/q/50455088
tags question: http://stackoverflow.com/q/50450800
tags question: http://stackoverflow.com/q/50420559
tags question: http://stackoverflow.com/q/50405189
tags question: http://stackoverflow.com/q/50458964
tags question: http://stackoverflow.com/q/50415972
tag name: neural-network
tags question: http://stackoverflow.com/q/50425850
tags question: http://stackoverflow.com/q/50484936
tags question: http://stackoverflow.com/q/50417088
tags question: http://stackoverflow.com/q/50395170
tags question: http://stackoverflow.com/q/50516416
tags question: http://stackoverflow.com/q/50535247
tags question: http://stackoverflow.com/q/50410189
tags question: http://stackoverflow.com/q/50398154
tags question: http://stackoverflow.com/q/50450512

http://stackoverflow.com/comment/87860229
comment on: http://stackoverflow.com/a/50422501
type: AnswerComment
score: 1
has text: hmm.. i'm searching now for a better solution
type: Comment

http://stackoverflow.com/comment/87807465
type: QuestionComment
has text: I don't understand why `ls` would say `Not a directory`. Perhaps you meant `No such file or directory`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50393155

http://stackoverflow.com/a/50498676
has body: Found the solution: Use wmi.WMI.watch_for(). See wmi – Windows Management Instrumentation
accepted answer of: http://stackoverflow.com/q/50476732
type: Answer
has comment: http://stackoverflow.com/comment/131948325
score: 1
has comment: http://stackoverflow.com/comment/131889300
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50476732

http://stackoverflow.com/comment/100586414
type: AnswerComment
has text: Which format do you have for your hard driver? Is it NTFS case sensitive? https://stackoverflow.com/questions/33998669/windows-ntfs-and-case-sensitivity
score: 0
comment on: http://stackoverflow.com/a/57003275
type: Comment

http://stackoverflow.com/comment/87816273
comment on: http://stackoverflow.com/q/50400168
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ, that will raise an error, but you could use `days=365`
score: 0

http://stackoverflow.com/a/50425996
has comment: http://stackoverflow.com/comment/87866775
answers question: http://stackoverflow.com/q/50425656
type: Answer
upvote count: 4
score: 4
downvote count: 0
has body: One notable property of trees is that for every combination of node (x, y), there exist a unique non-repeating path from x to y. In particular, this path can be found by finding the first common ancestor z of x and y and by taking the path x -&gt; z + z -&gt; y. Thus an algorithm to find all path could look like this for each pair of distinct nodes x, y in the tree: find all common ancestors of x and y let z be the lowest common acestor in the tree let p be the path from x to z append the path from z to y to p, excluding the duplicate z print p Here is an object-oriented approach that implements the needed method to accomplish the above. class Tree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right self.parent = None if left is not None: left.parent = self if right is not None: right.parent = self def __iter__(self): """Return a left-to-right iterator on the tree""" if self.left: yield from iter(self.left) yield self if self.right: yield from iter(self.right) def __repr__(self): return str(self.value) def get_ancestors(self): """Return a list of all ancestors including itself""" ancestors = {self} parent = self.parent while parent: ancestors.add(parent) parent = parent.parent return ancestors def get_path_to_ancestor(self, ancestor): """ Return the path from self to ancestor as a list output format: [self, ..., ancestor] """ path = [] parent = self try: while True: path.append(parent) if parent is ancestor: break else: parent = parent.parent except AttributeError: return None return path def get_path_to(self, other): """ Return the path from self to other as a list output format: [self, ..., first common acestor, ..., other] """ common_ancestors = self.get_ancestors() &amp; other.get_ancestors() first_common_ancestor = { a for a in common_ancestors if a.left not in common_ancestors and a.right not in common_ancestors }.pop() return self.get_path_to_ancestor(first_common_ancestor)\ + list(reversed(other.get_path_…
has comment: http://stackoverflow.com/comment/87866657

http://stackoverflow.com/comment/88010456
has text: basically you need to set 3 by row, and so one
comment on: http://stackoverflow.com/q/50498744
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/50499665
downvote count: 0
has body: Python 3.6 introduced Underscores in Numeric Literals. Essentially, this is a readability feature. Compare: x = 100000000 and: x = 100_000_000
has comment: http://stackoverflow.com/comment/88012127
score: 4
answers question: http://stackoverflow.com/q/50499646
has comment: http://stackoverflow.com/comment/88012188
type: Answer
has comment: http://stackoverflow.com/comment/88012109
accepted answer of: http://stackoverflow.com/q/50499646
upvote count: 4
has comment: http://stackoverflow.com/comment/88012171
type: AcceptedAnswer

http://stackoverflow.com/comment/87795990
has text: Here's a relevant question there: https://datascience.stackexchange.com/questions/17181/would-a-convolution-network-make-sense-for-policy-based-tic-tac-toe-approach
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50390217

http://stackoverflow.com/q/50535733
has comment: http://stackoverflow.com/comment/88083709
has body: import numpy as np import math time_decay_parameter = 0.055 h_column1_formula = np.repeat(1, 10) h_column2_formula = [] h_column3_formula = [] for maturity in range(1,10): h_column2_formula.append( (1-math.exp(- time_decay_parameter*maturity))/(time_decay_parameter*maturity)) h_column3_formula.append(((1-math.exp(- time_decay_parameter*maturity))/(time_decay_parameter*maturity))- math.exp(-time_decay_parameter*maturity)) h_column2_formula_array = np.asarray(h_column2_formula) h_column3_formula_array = np.asarray(h_column3_formula) h_matrix = np.array([h_column1_formula,h_column2_formula_array,h_column3_formula_array]).T print(h_matrix) ht_h = h_matrix.T@h_matrix The Error I get is the following TypeError Traceback (most recent call last) &lt;ipython-input-10-30a08b8e87fb&gt; in &lt;module&gt;() 17 print('HMATRIX \n') 18 print(h_matrix) ---&gt; 19 ht_h = h_matrix.T@h_matrix TypeError: Object arrays are not currently supported
has comment: http://stackoverflow.com/comment/88083587
type: Question
has comment: http://stackoverflow.com/comment/88083782
has answer: http://stackoverflow.com/a/50536547
accepted answer: http://stackoverflow.com/a/50536547
has comment: http://stackoverflow.com/comment/88084953
has comment: http://stackoverflow.com/comment/88083600
tagged with: arrays
tagged with: python
has title: Error Object arrays are not currently supported Python
has comment: http://stackoverflow.com/comment/88083521
has comment: http://stackoverflow.com/comment/88083757
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88083578
answer count: 1
has comment: http://stackoverflow.com/comment/88084035

http://stackoverflow.com/q/50459260
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87949905
tagged with: python
has comment: http://stackoverflow.com/comment/87932114
has body: I have downloaded PyCharm and I am not able to add the interpreter. I have referred all the topics here, and was able to find this. But still I couldn't solve the problem, when I select the PyCharm.exe file it says "The selected file is not a valid home for Python SDK". I have rebooted my system, Uninstalled and reinstalled PyCharm, but did not find any luck. Please Help!
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/32832062
tagged with: pycharm
has title: Pycharm: unable to add pycharm.exe
accepted answer: http://stackoverflow.com/a/50467439
has comment: http://stackoverflow.com/comment/87931944
answer count: 1
has answer: http://stackoverflow.com/a/50467439

http://stackoverflow.com/q/50430337
has comment: http://stackoverflow.com/comment/87875352
answer count: 1
tagged with: formatting
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87875388
has title: How to print a list of things in columns?
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50430544
tagged with: python
has body: Currently I am working on some selenium code and I wrote a code to simply go to some website, search for a few products and then list them. Everything works good except one thing. I want to print the products in this format: 1. &lt;name&gt;\t&lt;price&gt; 2. &lt;name&gt;\t&lt;price&gt; ... The problem is that some of the products (in my particular case one of them) names are longer than the other, which produces output like this: 1. Nóż Benchmade 62 Balisong 1 275,00 zł 2. Nóż Benchmade 63 Balisong Bowie 1 290,00 zł 3. Nóż Benchmade 67 Balisong 1 295,00 zł 4. Nóż Benchmade 87 Ti Balisong 2 235,00 zł As you can see, if I just add one or two \ts, it would be okay, but I don't think it's a particularly good way to do this. So the question is: How do I align text in column-way without manually calculating the size of the longest record in the column? (Maybe there is a standard lib-way to do this, or maybe 3rd party lib?) Edit: I've added the code: from selenium import webdriver class Product: def __init__(self, name, price): self.name = name self.price = price def __str__(self): return f'{self.name}\t{self.price}' def __repr__(self): return f'Product({self.name})' def search_for(driver, input_name, query): search_field = driver.find_element_by_name(input_name) search_field.clear() search_field.send_keys(query) search_field.submit() def create_products(driver): found_elements = driver.find_elements_by_xpath("//div[@class='wrapper']") names = [ fe.find_element_by_xpath(".//img[@alt]").get_attribute("alt") for fe in found_elements ] products = [] int_parts = driver.find_elements_by_xpath( "//span[@class='price']/span[@class='price-integer-part']") decimal_parts = driver.find_elements_by_xpath( "//span[@class='price']/span[@class='price-decimal-part']") currencies = driver.find_elements_by_xpath( "//span[@class='price-currency']") for info in zip(names, int_parts, decimal_parts, currencies): name, int_part, decimal_part, currency = info price = f'{int_part.text},{decimal_pa…
has comment: http://stackoverflow.com/comment/87875467
linked to: http://stackoverflow.com/q/33323715
has comment: http://stackoverflow.com/comment/87875343
has comment: http://stackoverflow.com/comment/87875432
has comment: http://stackoverflow.com/comment/87875415
score: 0
has comment: http://stackoverflow.com/comment/87875374
tagged with: printing
has comment: http://stackoverflow.com/comment/87875277
has comment: http://stackoverflow.com/comment/87875371

http://stackoverflow.com/a/56629804
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50508262
has body: Following is a linear-interpolating lookup implementation: from bisect import bisect_left def lookup(x, xs, ys): if x &lt;= xs[0]: return ys[0] if x &gt;= xs[-1]: return ys[-1] i = bisect_left(xs, x) k = (x - xs[i-1])/(xs[i] - xs[i-1]) y = k*(ys[i]-ys[i-1]) + ys[i-1] return y For testing: xs = [1, 2, 4, 8, 16, 32, 64, 128, 256] ys = [0, 1, 2, 3, 4, 5, 6, 7, 8] i_xs = [i/1000-500 for i in range(1000000)] start_time = time.time() ys = [lookup(x, xs, ys) for x in i_xs] print("%s secs" % (time.time() - start_time)) I get around 1.8secs.
downvote count: 0

http://stackoverflow.com/q/50522099
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50562138
favorite count: 0
type: Question
has body: I am using python-2.7 and kivy .When i run test.py then i set focus on button.After that i click anywhere on window using mouse then focus does not remove . Because after click on window i press enter then it call def self.add(). Can someone tell me how to remove focus from button when click anywhere on window ? test.py from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty, ObjectProperty from kivy.clock import Clock Window.clearcolor = (0.5, 0.5, 0.5, 1) Window.size = (500, 150) class User(Screen): name = ObjectProperty(None) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) Window.bind(on_key_down=self._on_keyboard_down) Clock.schedule_once(self.name_focus, 1) def name_focus(self, *args): self.postUser.focus = True self.postUser.background_color = [0.5, 0.5, 0.5, 1] def _on_keyboard_down(self, instance, keyboard, keycode, text, modifiers): if (hasattr(self.postUser, 'focus') and self.postUser.focus) and keycode == 40: self.add() def add(self): print('button Event Call') class Test(App): def build(self): return self.root if __name__ == '__main__': Test().run() test.kv #:kivy 1.10.0 User: name: name postUser : postUser BoxLayout: orientation: "vertical" GridLayout: cols: 2 padding: 20, 20 spacing: 10, 10 Label: text: "Name" text_size: self.size valign: 'middle' TextInput: id:name text_size: self.size GridLayout: cols: 2 padding: 0, 0 spacing: 5, 0 size_hint: .5, .35 pos_hint: {'x': .25, 'y': 0} Button: id:postUser size_hint_x: .5 text: "Ok" focus: False on_release: root.add()
tagged with: python
has title: Python : How to remove focus from button when click anywhere on window
has answer: http://stackoverflow.com/a/50562138
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7
tagged with: kivy-language

http://stackoverflow.com/comment/87791225
comment on: http://stackoverflow.com/q/50387267
type: QuestionComment
has text: My code is pretty messy so I didn't include it but my function gives me the vector rv (it has nothing to do with the argument r or v in the function, I'm just bad at naming stuff).
type: Comment
score: 0

http://stackoverflow.com/q/50452437
upvote count: 2
has comment: http://stackoverflow.com/comment/87918052
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
has title: How do you count subdirectories in a folder?
tagged with: python
has comment: http://stackoverflow.com/comment/87917977
tagged with: subdirectory
has comment: http://stackoverflow.com/comment/87918073
score: 2
has body: I figured out how to count directories in a folder, but not sure how I could edit my code to recursively count subdirectories. Any help would be appreciated. This is my code so far. def nestingLevel(path): count = 0 for item in os.listdir(path): if item[0] != '.': n = os.path.join(path,item) if os.path.isdir(n): count += 1 + nestingLevel(n) return count
has comment: http://stackoverflow.com/comment/87918054
has answer: http://stackoverflow.com/a/50452517
has answer: http://stackoverflow.com/a/50452562
answer count: 3
has answer: http://stackoverflow.com/a/50452591

http://stackoverflow.com/q/50437679
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
upvote count: 1
tagged with: string-to-datetime
favorite count: 0
has title: Set the format for pd.to_datetime
type: Question
has body: Hi already referred to this post but I could not get through my issue. I have a column in my CSV which is string and the sample values are below (note that the month and year positioning are sometimes reversed). What format do I need to set in my to_datetime? I tried all the below approaches df = pd.read_csv("filename.csv") #Imagine there is a Month column #[1] df["Month"] = pd.to_datetime(df["Month"]) #[2] df["Month"] = pd.to_datetime(df["Month"], format="%m/%d/%Y") [Month] Mar-97 Apr-97 May-97 Jun-97 Nov-00 Dec-00 1-Jan 1-Feb 1-Mar 1-Apr I get the error ValueError: day is out of range for month for [1] and I get ValueError: time data 'Mar-97' does not match format '%m/%d/%Y' (match) for [2]. I tried to remove the %d too but no luck. Could you please point me what is going wrong here.
has answer: http://stackoverflow.com/a/50437759
accepted answer: http://stackoverflow.com/a/50437759
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50437828
possible better answer: http://stackoverflow.com/a/50437828
score: 1
linked to: http://stackoverflow.com/q/36848514
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/73295821

http://stackoverflow.com/comment/87797247
has text: I have a dict which which I have to alter the key and values with some other values/key and then I want to maintain a order as per my wish.
type: Comment
comment on: http://stackoverflow.com/a/50386382
score: 0
type: AnswerComment

http://stackoverflow.com/a/50431914
answers question: http://stackoverflow.com/q/50431491
upvote count: 2
type: Answer
has body: You have to learn MVC architecture(MVT in django). As a beginner first create a sample project to understand this - https://docs.djangoproject.com/en/2.0/intro/tutorial01/ Learn how models.py are written - https://docs.djangoproject.com/en/2.0/topics/db/models/ and how to writeviews.py - https://docs.djangoproject.com/en/2.0/topics/class-based-views/ Then connect them in urls.py - https://docs.djangoproject.com/en/2.0/topics/http/urls/
score: 2
downvote count: 0

http://stackoverflow.com/comment/95020417
type: AnswerComment
comment on: http://stackoverflow.com/a/50433274
score: 0
type: Comment
has text: @OmerB that can be one interpretation of the original question. However, the question does *not* mention the early stopping procedure and is vague. If there is no early stopping implemented in the configuration, then my answer is correct.

http://stackoverflow.com/comment/87953025
comment on: http://stackoverflow.com/q/50469579
score: 0
type: Comment
type: QuestionComment
has text: We can't really help with the 404s because you haven't said where the static files are located in your project, or what your [static files settings](https://docs.djangoproject.com/en/2.0/howto/static-files/) are.

http://stackoverflow.com/a/50389360
score: 1
has body: Maybe this will help...I'ts an example of your function and it is working(Python 3.5) import tkinter as tk from tkinter import * from tkinter import ttk class GUI: def __init__(self, master): def pct_from_duration(): tgt_dur_entry = ttk.Entry(mainframe, width=4) tgt_dur_entry.grid(column=5, row=3, sticky=(W, E)) for widget in secondframe.winfo_children(): widget.destroy() l3 = ttk.Label(secondframe, text = 'Label').grid(column=1, row=1) b2 = ttk.Button(mainframe, text="Calculate").grid(column=5, row=4, sticky=W) self.master = master mainframe = ttk.Frame(master) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) secondframe = ttk.Frame(mainframe) secondframe.grid(column=4, row=3) secondframe.columnconfigure(0, weight=1) secondframe.columnconfigure(0, weight=1) l = Label(secondframe, text = 'Child_mainframe') l.grid() l2 = Label(mainframe, text = 'Child_secondframe') l2.grid() r1 = Radiobutton(master, text="Radiobutton", value=1, command = pct_from_duration).grid() root = Tk() root.rowconfigure(0, weight = 1) root.columnconfigure(1, weight=1) root.columnconfigure(0, weight=1) root.columnconfigure(0, weight=2) my_gui = GUI(root) root.mainloop()
type: Answer
answers question: http://stackoverflow.com/q/50388115
has comment: http://stackoverflow.com/comment/87866200
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87836758
has text: Hmm not entirely what i want, because now i get the pop-up file-dialog (str(QtGui.QFileDialog.getOpenFileName(self, 'Single File', '*.xlsx'))) again from the OpendirREF function before it prints the data. i would like to only access the output of the OpendirREF function.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50410579

http://stackoverflow.com/q/50472440
has comment: http://stackoverflow.com/comment/87958672
linked to: http://stackoverflow.com/q/25758729
has comment: http://stackoverflow.com/comment/87963034
has comment: http://stackoverflow.com/comment/87959229
tagged with: unicode
has comment: http://stackoverflow.com/comment/87964289
has body: I have the following script (test.py), printin a non-ASCII character: # -*- coding: utf-8 -*- print u"café" It works as expected when running at shell: $ python test.py café However, if I try the usual bash redirect with &gt; it fails in the following way: $ python test.py &gt; result.txt Traceback (most recent call last): File "test.py", line 2, in &lt;module&gt; print u"café" UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) How this can be solved? Python version, in the case it helps: $ python --version Python 2.6.6 EDIT1: note this question is not a duplicated of this other. In the referred question they are using file abstraction in Python, e.g. open(), etc. while in my question these abstractions are not used and I'm using bash redirection. EDIT2: check bash unicode support, as suggested in comments: $ bash --version | head -n 1 GNU bash, versión 4.1.2(1)-release (x86_64-redhat-linux-gnu) $ stty -a speed 38400 baud; rows 35; columns 150; line = 0; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?; swtch = &lt;undef&gt;; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0; -parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr -ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel -iutf8 opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke $ echo -e '\xe2\x82\xac' €
score: 0
has comment: http://stackoverflow.com/comment/87958608
linked to: http://stackoverflow.com/q/4545661
duplicate of: http://stackoverflow.com/q/25758729
tagged with: python
linked to: http://stackoverflow.com/q/6048085
type: Question
has comment: http://stackoverflow.com/comment/87958549
has comment: http://stackoverflow.com/comment/87961790
answer count: 0
type: UnansweredQuestion
has title: 'ascii' codec can't encode character when redirecting Python script to file through Bash
has comment: http://stackoverflow.com/comment/87959947

http://stackoverflow.com/q/50505827
type: Question
has title: NoSuchElementException on all elements on page with Python Selenium
accepted answer: http://stackoverflow.com/a/50506709
tagged with: nosuchelementexception
has answer: http://stackoverflow.com/a/50506709
tagged with: python
has body: Set-up I'm trying to log in to a website using Python + Selenium. My code to load the website is, browser = webdriver.Firefox( executable_path='/mypath/to/geckodriver') url = 'https://secure6.e-boekhouden.nl/bh/' browser.get(url) Problem Selenium cannot locate the element containing the account and password fields. For example, for the field 'Gebruikersnaam', browser.find_element_by_id('txtEmail') browser.find_element_by_xpath('//*[@name="txtEmail"]') browser.find_element_by_class_name('INPUTBOX') all give NoSuchElementException: Unable to locate element. Even worse, Selenium cannot find the body element on the page, browser.find_element_by_xpath('/html/body') gives NoSuchElementException: Unable to locate element: /html/body. I'm guessing something on the page is either blocking Selenium (maybe the 'secure6' in the url) or is written in a language/form Selenium cannot handle. Any suggestions?
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: selenium

http://stackoverflow.com/comment/88085645
type: QuestionComment
has text: `where(cond)` finds the true elements in `cond`. If empty then `cond` is all false. Make sure the equality test is right. Testing floats is tricky.
score: 1
comment on: http://stackoverflow.com/q/50536713
type: Comment

http://stackoverflow.com/comment/87913991
has text: The tool you used for verification has range [0,359] for Hue, [0,100] for Saturation and Value. OpenCV's HSV range are [0,179] for Hue, [0,255] for Saturation and Value.
comment on: http://stackoverflow.com/q/50449602
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87824052
type: QuestionComment
has text: Calling methods like this: `password.username_input(self)` is very unconventional. use `self.username_input()`. But anyway, your question and title are pretty broad. The answer is, "generally, you use attributes". You could also pass values as arguments to functions and have functions return values. You've pasted a lot of code here, what exactly isn't working? Please edit your question to address a specific issue, and try to distill it down to a [mcve].
comment on: http://stackoverflow.com/q/50404156
score: 0
type: Comment

http://stackoverflow.com/comment/88074146
type: Comment
comment on: http://stackoverflow.com/q/50531077
type: QuestionComment
has text: When you delete an element from `dosya`, it gets smaller, so the larger indices are no longer valid.
score: 1

http://stackoverflow.com/q/50473286
downvote count: 0
has body: I am trying and failing to import scapy into python, which I have now been playing with for hours and all the google hits I get seem to make sense but when I try them - it fails. first off I am using python3 and have that nicely in pycharm: Correct Interpreter I have also installed the package using pip3: pip3 install scapy-python3 this appears in PyCharm as you can see in the picture. So I am now on a par with the other guides I found. So finally I try: from scapy import * and for good measure from scapy.all import * which is for Python2 and 3k from what I read. Could someone give me a hand, I don't know where to go next. Gareth
has title: PyCharm does not import Scapy module
has answer: http://stackoverflow.com/a/78285839
possible better answer: http://stackoverflow.com/a/78285839
has comment: http://stackoverflow.com/comment/87981108
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50556608
accepted answer: http://stackoverflow.com/a/50556608
tagged with: python
has comment: http://stackoverflow.com/comment/87960726
has answer: http://stackoverflow.com/a/50484557
type: AnsweredQuestion
score: 2
answer count: 3
upvote count: 2
tagged with: scapy

http://stackoverflow.com/q/50429109
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: morse-code
score: 0
tagged with: led
has answer: http://stackoverflow.com/a/50429245
has title: Morse Code Python 3: Instead of using multiple if statements for every possible word user can type in, how do I make a loop for this?
answer count: 1
has body: I made a raspberry pi morse code program: How can I simplify the if statements: I want to make it that the program plays whatever the user types in, but I do not know how to do this with multiple if statements. Help please!! I want the program to be able to play whatever word the user types in but I do not know how to do that. If i need to assign a variable to every letgter, how do i do that? import RPi.GPIO as GPIO from time import sleep LED_GPIO = 4 print("Getting ready...") GPIO.setmode(GPIO.BCM) GPIO.setup(LED_GPIO, GPIO.OUT) def lighton(timeon): print ("Light On - " , timeon) GPIO.output(LED_GPIO, True) sleep(timeon) GPIO.output(LED_GPIO, False) sleep(timeoff) dashtime = .5 dottime = .25 timeoff = .1 x = 1 while x &gt; 0: let = input("Enter a letter or * to quit") if let == "*": x=0 elif let == "s": lighton(dottime) lighton(dottime) lighton(dottime) elif let == "o": lighton(dashtime) lighton(dashtime) lighton(dashtime) elif let == "sos": lighton(s) lighton(dashtime) lighton(dashtime) lighton(dashtime) lighton(dottime) lighton(dottime) lighton(dottime) else: print ("Letter not recognized - try again") GPIO.cleanup() print("Bye Bye")
tagged with: raspberry-pi3

http://stackoverflow.com/comment/87890159
type: Comment
type: QuestionComment
score: 0
has text: _so I tried to use int() which still didn't help- what went wrong? If I `open('save.txt','w').write(str(some_int))`, then `int(open('save.txt').read())` should work.
comment on: http://stackoverflow.com/q/50438020

http://stackoverflow.com/q/50496549
has answer: http://stackoverflow.com/a/50496945
has comment: http://stackoverflow.com/comment/88005911
upvote count: 2
has comment: http://stackoverflow.com/comment/88005917
has comment: http://stackoverflow.com/comment/88005871
has title: Python Dictionary: Key with two values possible?
score: 1
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/88005913
has body: For a test program I'm crawling a webpage. I'd like to crawl all activites for specifid ID´s which are associated to the respective cities. For example, my initial code: RegionIDArray = {522: "London", 4745: "London", 2718: "London", 3487: "Tokio"} Im now wondering if its possible to sum up all IDs (values) which are related to e.g. London into one key: RegionIDArray = {522, 4745, 2718: "London} If I´m trying this, I get no results My full code so far RegionIDArray = {522: "London", 4745: "London", 2718: "London", 3487: "Tokio"} for reg in RegionIDArray: r = requests.get("https://www.getyourguide.de/-l" +str(reg) +"/") soup = BeautifulSoup(r.content, "lxml") g_data = soup.find_all("span", {"class": "intro-title"}) for item in g_data: POI_final = (str(item.text)) end_final = ("POI: " + POI_final) if end_final not in already_printed: print(end_final) already_printed.add(end_final) Is there any smart way.Appreciate any feedback.
has comment: http://stackoverflow.com/comment/88005973
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50496625
tagged with: python
tagged with: dictionary
tagged with: web-crawler
has answer: http://stackoverflow.com/a/50496579
answer count: 3

http://stackoverflow.com/q/50494451
has title: Pandas: Inconsistent concatenation
has comment: http://stackoverflow.com/comment/88003324
type: UnansweredQuestion
has body: I have two pandas DataFrames with a date-time stamp as an index called "datetime" and some floats as a column called "metric1" or "metric2". When I try to concatenate them I get the following error: ValueError: cannot reindex from a duplicate axis After reading for many hours I cannot find a solution that fixes my problem (e.g. What does `ValueError: cannot reindex from a duplicate axis` mean? "ValueError: cannot reindex from a duplicate axis" ). I then spent a long time trying to recreate the problem but couldn't whithout my specific data but my data is two big to post on here. In the end it seemed like certain parts of the dataframes were incompatible but other parts were fine. After comparing many different slices of indexes I finally found incompatible sets. Can someone please help me understand why I can't concatenate these. Basically I would like it so that all possible time-stamps are in the index and there is a column for "metric1" and "metric2". If there is no data for a column at a given timestamp then we just have NaN or something. This works fine normally with pd.concat but it is not working in this case. To recreate please use: CSV Files: test1.csv timestamp,metric1 2018-03-21 15:46:36,3.5555559999999997 2018-03-21 15:47:36,5.345001 2018-03-21 15:48:36,5.719998 test2.csv timestamp,metric2 2018-03-28 05:49:59,3.28 2018-03-28 05:50:59,3.45 2018-03-28 05:51:59,3.258332 2018-03-28 05:52:59,3.068333 2018-03-28 05:53:59,2.9733330000000002 2018-03-28 05:54:59,3.0650009999999996 2018-03-28 05:55:59,3.109999 2018-03-28 05:56:59,3.3683330000000002 2018-03-28 05:57:59,3.1516669999999998 2018-03-28 05:58:59,3.051666 2018-03-28 05:59:59,3.3083339999999994 2018-03-28 06:01:01,3.328333 2018-03-28 06:01:01,3.1 2018-03-28 06:02:00,3.305 2018-03-28 06:03:00,3.29 2018-03-28 06:04:00,3.2183330000000003 2018-03-28 06:05:00,3.176666 2018-03-28 06:06:00,3.353333 2018-03-28 06:07:00,3.3233330000000003 2018-03-28 06:08:00,3.393332 2018-03-28 06:09:00,3.053334 2018-03-28 06:10:0…
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50495721
has comment: http://stackoverflow.com/comment/88004126
linked to: http://stackoverflow.com/q/27236275
answer count: 3
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/88006074
has answer: http://stackoverflow.com/a/50495592
linked to: http://stackoverflow.com/q/38256104
has comment: http://stackoverflow.com/comment/88002135
has answer: http://stackoverflow.com/a/50494700
favorite count: 0
linked to: http://stackoverflow.com/q/27711623
type: Question

http://stackoverflow.com/comment/87916908
comment on: http://stackoverflow.com/a/50436862
type: Comment
score: 0
type: AnswerComment
has text: Oh a clarification, this refers to the first solution provided.

http://stackoverflow.com/a/50484393
type: Answer
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87985059
downvote count: 1
has body: You can use tr inside a loop to remove all new lines for each of the XML documents like this: #!/bin/bash while IFS='' read -r line do echo -n "$line" | base64 --decode | tr -d '\r\n' echo done &lt; fileContainingBase64EncodedXMLsInEachLine.txt
answers question: http://stackoverflow.com/q/50483586

http://stackoverflow.com/comment/88010925
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50498653
score: 0
has text: Mostly harmless. If its a hard-coded string then it has the same id even if set multiple times. But if its constructed, even identical strings have different ids. So, code can't use "is" (but they shouldn't anyway). `None` always has the same id, so `x is None` is fine but usually its a bad idea.

http://stackoverflow.com/q/50513461
score: 1
has comment: http://stackoverflow.com/comment/88039501
duplicate of: http://stackoverflow.com/q/48323493
has body: I came across the following syntax in some Python3 code I found online: Note: this is actually from Vyper, a subset of Python3 used for programming on Ethereum. The developers of Vyper claim that all Vyper code is valid Python3 syntax (although the converse is not true) myvariable: somefunction(someglobalvariable) I haven't been able to uncover the specific documentation from Python3 explaining the meaning of this syntax. What does this do?
tagged with: vyper
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/88039654
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88039599
has comment: http://stackoverflow.com/comment/88039491
has comment: http://stackoverflow.com/comment/88040225
has comment: http://stackoverflow.com/comment/88040278
has title: What does 'variable: value' mean in Python3?

http://stackoverflow.com/comment/87895042
has text: Could you elaborate your question about in which cases you want to use system default python and where you want anaconda python? And why do you want to use both simultaneously
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50399054
type: Comment

http://stackoverflow.com/comment/88023530
score: 0
type: AnswerComment
has text: Splitting is the easiest way to go for checking if `df.value` is in `words`. and you still have the unsplit Version stored in `listvalue`, so what is the problem here?
type: Comment
comment on: http://stackoverflow.com/a/50502956

http://stackoverflow.com/q/50420451
tagged with: http://stackoverflow.com/tag/json
has body: I am trying to write a python script which will take a bunch of urls one at a time and fetch the response content of that url and store it as json files. Here is what I wrote initially to get the response of the url def download_json() params={'id':00163E0BD0C1FA89, 'list':'141', 'queue': 'gen', 'type': 'abc_stat' } req_obj= requests.get(link, params=params) print(req_obj.url) print(req_obj.status_code) return req_obj It creates the right url as when I copy the url directly in browser it shows me the output in json format. Here is one row of json output i am seeing on the browser: { "DATA" : [ { "SCHEMA" : "abc_4_QAATu2.", "ID" : "QAATu2", "IM_ID" : "22faba86_c9e0_4dbc", "S_NUMBER" : "502379284", "CONFIG_TYPE" : "las_home_type", "CONFIG_KEY" : "las_home_key", "CONFIG_LONG_V" : "1", "CONFIG_STRING_V" : "https://abc-deg/development", "MODIFIED_DATE" : "Unknown" }, So this does show that data is returned in json format when I enter the url in browser directly. However my requests object has this for headers: Out[26]: {'content-length': '15457', 'expires': '0', 'content-encoding': 'gzip', 'cache-control': 'no-cache, no-store, private', 'set-cookie': 'login-XSRF_RZA=2018051-axJnifQUpOnrS8WCFI; path=/abc/deo/cpo; secure; HttpOnly, usercontext=client=002; path=/', 'content-type': 'text/html; charset=utf-8', 'pragma': 'no-cache, no-store, private'} Now when I do requests.json() to get the data in json python object I get the following error JSONDecodeError Traceback (most recent call last) &lt;ipython-input-28-4cfc1a694fcf&gt; in &lt;module&gt;() ----&gt; 1 req_obj.json() /Users/anaconda/envs/dl/lib/python3.5/site-packages/requests/models.py in json(self, **kwargs) 890 # used. 891 pass --&gt; 892 return complexjson.loads(self.text, **kwargs) 893 894 @property /Users/anaconda/envs/dl/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 317 parse_int is None and parse_float is None and 318 pars…
has title: Downloading Json data from website
has comment: http://stackoverflow.com/comment/87856379
has comment: http://stackoverflow.com/comment/87856494
type: Question
has answer: http://stackoverflow.com/a/50420616
answer count: 2
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50420589
score: 0

http://stackoverflow.com/q/50477815
has body: Why does grabwindow return black screen? Is a valid window and I do not receive any errors. pix = QPixmap.grabWindow(hwnd) And that way it works perfectly! pix = QPixmap.grabWindow(QApplication.desktop().winId()) Below the complete source code: def __init__(self): serverProtocol.RDCServerProtocol.__init__(self) self._array = QByteArray() self._buffer = QBuffer(self._array) self._buffer.open(QIODevice.WriteOnly) def _makeFramebuffer(self, width, height): pix = QPixmap.grabWindow(197526) # Google Chrome Window pix = pix.scaled(width, height) if width &gt;= self._maxWidth or height &gt;= self._maxHeight: width = self._maxWidth height = self._maxHeight pix.save(self._buffer, 'jpeg') pixData = self._buffer.data() self._array.clear() self._buffer.close() return "%s" % pixData I need to capture only the google window, but a black screen appears =/ Thank!
answer count: 0
has comment: http://stackoverflow.com/comment/87992448
tagged with: pyqt
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87972953
score: 0
has comment: http://stackoverflow.com/comment/87975496
has comment: http://stackoverflow.com/comment/88004237
has comment: http://stackoverflow.com/comment/88043305
has comment: http://stackoverflow.com/comment/87973008
has comment: http://stackoverflow.com/comment/88050604
has comment: http://stackoverflow.com/comment/87972263
has comment: http://stackoverflow.com/comment/88050694
has comment: http://stackoverflow.com/comment/87970012
has title: grabWindow with hwnd return black screen
tagged with: qpixmap
tagged with: qt
has comment: http://stackoverflow.com/comment/87972854
has comment: http://stackoverflow.com/comment/87991690
has comment: http://stackoverflow.com/comment/87973227
has comment: http://stackoverflow.com/comment/87973032
linked to: http://stackoverflow.com/q/14653168
has comment: http://stackoverflow.com/comment/88052295
tagged with: python
has comment: http://stackoverflow.com/comment/87972930
has comment: http://stackoverflow.com/comment/87971465
type: Question

http://stackoverflow.com/comment/87899617
type: QuestionComment
has text: What is unclear is you claim to print all the solutions in a flattened list but running the code above yields a list of 3 and a lot of -1s. Yet you say this should be a empty list.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50441677

http://stackoverflow.com/q/50511034
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/50511414
accepted answer: http://stackoverflow.com/a/50511414
type: AnsweredQuestion
upvote count: 3
score: 3
has title: Dynamically update Javascript variables using Jinja?
has comment: http://stackoverflow.com/comment/88034439
tagged with: python
has comment: http://stackoverflow.com/comment/88034786
has body: I have a web form created that requires template creation by the user. Calling all previous entries that are templates isn't an issue, but passing the information to the form when called seems to be tricky. Basically I want the user to be able to select a template from the dropdown (See the screenshots and stuff below), then based on their selection, update the variables in the script to autofill form data. Right now, it only selects the most recent entry. Is this possible just using python/flask/javascript or am I missing something? Any help would be appreciated! Thanks! Template Dropdown Select Template {% for template_info in template_search %} {{template_info.client_name}} {% endfor %} Javascript to change values {% for template_info in template_search %} {% endfor %} Python Passing in the Query template_search = newmatter_model.NewClientMatter.query.filter_by( creator=verifier, is_template='on').all()
type: Question
has comment: http://stackoverflow.com/comment/88034708
downvote count: 0
answer count: 1
tagged with: javascript

http://stackoverflow.com/comment/88079191
type: QuestionComment
has text: Have you enabled [sessions](https://docs.djangoproject.com/en/2.0/topics/http/sessions/)? I don't recall where it specified this, but I think you might run into this issue if you don't have sessions enabled...because Django only knows you've logged in from the session cookie.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50533472

http://stackoverflow.com/comment/87909095
type: Comment
comment on: http://stackoverflow.com/a/50414088
has text: Also, how does this impl ensures that if there is already an anchor tag, the href of that anchor tag is not wrapped by another anchor tag?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87834053
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50407547
has text: So you means only the `/` route work, but `/<patternName>/<action>/` route not working?

http://stackoverflow.com/a/50449410
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50449353
has body: Create a new columns object by splitting up the existing column names. This takes for granted that we have single character letters followed by a single digit. d = df.set_index('ID') d.columns = d.columns.map(tuple) d.stack().reset_index('ID') ID A B 1 1 3 4 2 1 5 6 1 2 7 8 2 2 9 10 One-line df.set_index('ID').rename(columns=tuple).stack().reset_index('ID') More generalized d = df.set_index('ID') s = d.columns.str d.columns = [ s.extract('^(\D+)', expand=False), s.extract('(\d+)$', expand=False) ] d.stack().reset_index('ID')
type: Answer

http://stackoverflow.com/a/50428090
has body: You can check if you file exists by using os.path.exists (docs here). If it does, then you can use the sys.exit you mentioned before. If you need something more than sys.exit, try the atexit module @Reblochon suggested. The script will then assume the file is ready to lock and the method will report its success back to the user via a boolean. import os import sys import fcntl FILE_NAME = 'myfile.lock' def lockFile(lockfile): fp = open(lockfile, 'w') # create a new one try: fcntl.flock(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) success = True # the file has been locked except IOError: success = False # an error occurred fp.close() # make sure to close your file return success if os.path.exists(FILE_NAME): # exit the script if it exists sys.exit(0) print('success', lockFile(FILE_NAME))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50421649

http://stackoverflow.com/comment/88032496
score: 0
has text: The output from your code and photoshop are very similar. I think you can get even closer by tweaking the kernel further. Photoshop might use a 5x5 kernel. Or you could try to change the 0 values to 1 and the 4 to 8 (the sum of the entire kernel should be 0).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50508452

http://stackoverflow.com/comment/88031499
score: 0
comment on: http://stackoverflow.com/q/50506076
type: Comment
has text: @Forrest Thumb since you provided the answer in comment you can add it as a proper answer to help others facing the same problem.
type: QuestionComment

http://stackoverflow.com/a/62136601
downvote count: 0
type: Answer
has body: I will answer the 2nd part as 1st is already answered. Yes, we can print the validation accuracy by creating a custom callback and overriding the on_epoch_end function. In the on_epoch_end we can access the logs which is the dictionary of metric_name: values. For example - I have a 13 output model. class CustomCallbacks(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): val_acc = 0 for i in range(13): val_acc += (logs.get('val_digit_{}_accuracy'.format(i)))/13 # take mean acc value print("mean val acc - ",val_acc)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50541409

http://stackoverflow.com/q/50393380
has body: I want to change a value in a specific cell of my Spark DataFrame using PySpark. Trivial example - I create a mock Spark DataFrame: df = spark.createDataFrame( [ (1, 1.87, 'new_york'), (4, 2.76, 'la'), (6, 3.3, 'boston'), (8, 4.1, 'detroit'), (2, 5.70, 'miami'), (3, 6.320, 'atlanta'), (1, 6.1, 'houston') ], ('variable_1', "variable_2", "variable_3") ) Runnning display(df) I get this table: variable_1 variable_2 variable_3 1 1.87 new_york 4 2.76 la 6 3.3 boston 8 4.1 detroit 2 5.7 miami 3 6.32 atlanta 1 6.1 houston Let´s say for example, I would like to assign a new value for the cell in the 4th row and 3rd column, i.e. changing detroit for new_orleans. I know assignments as df.iloc[4, 3] = 'new_orleans' or df.loc[4, 'detroit'] = 'new_orleans' are not valid in Spark. A valid answer to my question using when would be: from pyspark.sql.functions import when targetDf = df.withColumn("variable_3", \ when(((df["variable_1"] == 8) &amp; (df["variable_2"] == 4.1)) , 'new_orleans').otherwise(df["variable_3"])) My question is: could this be done in a more practical way in PySpark without the necessity of entering all the values and column names of the row where I want to change just 1 single cell (maybe achieving the same without using the when function)? Thanks in advance for your help and @useruser9806664 for his feedback.
has answer: http://stackoverflow.com/a/50393559
tagged with: apache-spark
has title: Assign value to specific cell in PySpark dataFrame
tagged with: dataframe
tagged with: python
answer count: 4
favorite count: 0
score: 8
type: Question
accepted answer: http://stackoverflow.com/a/69165091
has answer: http://stackoverflow.com/a/50409489
upvote count: 8
has answer: http://stackoverflow.com/a/71068574
has answer: http://stackoverflow.com/a/69165091
downvote count: 0
tagged with: pyspark
possible better answer: http://stackoverflow.com/a/50393559
type: AnsweredQuestion

http://stackoverflow.com/q/50449417
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
score: 1
has title: How to write aggregation function in Pandas with condition on other column
has answer: http://stackoverflow.com/a/72630836
possible better answer: http://stackoverflow.com/a/72630836
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87914793
has answer: http://stackoverflow.com/a/50451550
accepted answer: http://stackoverflow.com/a/50451550
tagged with: aggregate-functions
has body: Suppose a dataframe df with columns a,b,c,d. I know the way of defining a function to aggregate values in Panda like: def my_agg(x): names = { 'a_Total': x['a'].sum(), 'b_Mean': x['b'].mean() } return pd.Series(names, index=['a_Total','b_Mean']) d_aggregate = df.groupby(['c','d']).apply(my_agg) What I am looking for is a way to take total or mean on a, b respectively based on selective values in column 'c' or 'd'. Sample data: df=pd.DataFrame({"a":[10,20,30,40], "b":[1,2,3,4], "c":[c1,c1,c1,c2], "d":[100,200,300,400]}) My aggregate function: def my_agg91(x): names = { 'Sum_a': x['a'].sum(), 'Mean_b': x['b'].mean()} return pd.Series(names, index=['Sum_a','Mean_b']) df2= df.groupby(['c']).apply(my_agg91) which gives me: Sum_a Mean_b c c1 60.0 2.0 c2 40.0 4.0 What I want: Sum of 'a' for 'd'&lt;250 and mean of 'b' for 'd'>250 (in single dataframe) please suggest the changes in function to get output: Sum_a Mean_b c c1 30.0 3.0 c2 0.0 4.0
tagged with: python
tagged with: apply
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/50445511
linked to: http://stackoverflow.com/q/2262100
score: 2
has body: I cannot solve this (what seems easy) problem when using matplotlib to build some plots. I have gray scale colors represented as integers in range(0-255 - higher numbers meaning darker) which can be simplified in this example df: colors = pd.DataFrame({'color1': [15], 'color2': [27], 'color3': [89], 'color4': [123], 'color5': [220], 'color6': [100], 'color7': [123], 'color8': [247], 'color9': [255]}) Now by looping I want to change the plots background with those colors as: fig, ax = plt.subplots(3, 3, figsize=(10, 10), sharey='row', sharex='col') fig.subplots_adjust(hspace=0, wspace=0) column = 0 for i in range(3): for j in range(3): color = colors.iloc[0, column] print(f'{i}, {j}: {color}') # here I used (0.15, 0.16, 0.17) as example. #But I want to have variable "color" converted into readable color by set_facecolor ax[i, j].set_facecolor((0.15, 0.16, 0.17)) column += 1 by using matplotlib documentation I can only do it in those colors formats: Matplotlib recognizes the following formats to specify a color: an RGB or RGBA tuple of float values in [0, 1] (e.g., (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3)); a hex RGB or RGBA string (e.g., '#0F0F0F' or '#0F0F0F0F'); a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5'); one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}; a X11/CSS4 color name; a name from the xkcd color survey; prefixed with 'xkcd:' (e.g., 'xkcd:sky blue'); one of {'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'} which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle); a “CN” color spec, i.e. 'C' followed by a single digit, which is an index into the default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing occurs at artist creation time and defaults to black if the cycle does not include color. Using those SO answers: RGB Int to RGB - Python Converting a [0-255] integer range to a […
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50447125
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50447125
has title: Gray scale color (0-255) to MAtplotlib colors representation
tagged with: colors
tagged with: matplotlib
linked to: http://stackoverflow.com/q/9974863
tagged with: python

http://stackoverflow.com/q/50453789
tagged with: python-imaging-library
has body: I get some images in at most 30 colors, and I write a palette like this palette = [0,0,0,70,130,180,70,70,70,...] and then I want to read these images with this palette img= Image.open(dir).convert('P', palette=palette, colors=30) but when I check these palettes print(img.getpalette()) I get some different palettes in different images. Then what should I do?
has title: How to get an image in P mode with my own palette
tagged with: python
has comment: http://stackoverflow.com/comment/87921127
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: palette
favorite count: 0
type: Question

http://stackoverflow.com/comment/87836375
comment on: http://stackoverflow.com/q/50391868
type: Comment
type: QuestionComment
has text: Since '\_representation' is a cython-compiled file, it could be relevant and helpful to edit your question and describe your machine, OS, and method of installation (pip, easy_install, anaconda, etc). You could also look in your /home/mlv/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace directory for other '\_*' files to see if any are being built.
score: 0

http://stackoverflow.com/a/50529751
accepted answer of: http://stackoverflow.com/q/50528833
type: Answer
has comment: http://stackoverflow.com/comment/88083156
answers question: http://stackoverflow.com/q/50528833
has comment: http://stackoverflow.com/comment/88072008
has comment: http://stackoverflow.com/comment/88071681
has comment: http://stackoverflow.com/comment/88071921
has comment: http://stackoverflow.com/comment/88072082
score: 1
has body: To take advantage of zeros without putting them in dataframe you can use something like this: test = df.groupby(['user1', 'user2', 'day'])['quantity'].mean().reset_index()\ .groupby(['user1', 'user2'])\ .agg({'day': lambda x: tuple(x), 'quantity': lambda x: tuple(x)})\ .reset_index() def med_from_tuple(row): # starts with everything zero, and replaces some with the nonzero values in the dataframe z = np.zeros(365) np.put(z, row['day'], row['quantity']) return np.median(z) test['example'] = test.apply(lambda x: med_from_tuple(x), axis=1) This would create the median of quantity as if there were zeros in the dataframe. test # user1 user2 day quantity example #0 Alice Bob (1, 4) (250, 600) 0.0 #1 Bob Carol (1,) (20,) 0.0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88071954
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88072407

http://stackoverflow.com/comment/87874330
comment on: http://stackoverflow.com/q/50420198
type: QuestionComment
has text: Sure I'd be happy to try and help. The part I am working on now is saving the ZIP file format, but it's not working yet.
score: 0
type: Comment

http://stackoverflow.com/comment/87906578
score: 1
comment on: http://stackoverflow.com/a/50446402
type: Comment
has text: @SeanBreckenridge This whole question is hypothetical and so was my bite
type: AnswerComment

http://stackoverflow.com/comment/87855323
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50412719
type: AnswerComment
has text: I've updated my answer, as I had a typo in the defaults for `RaffleModel`

http://stackoverflow.com/comment/88007011
has text: @barny How would I go about tweeting multiple lines at a time?
type: Comment
comment on: http://stackoverflow.com/q/50496842
score: 0
type: QuestionComment

http://stackoverflow.com/q/50496654
score: 4
downvote count: 1
favorite count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50496711
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50496715
type: Question
has body: I've been attempting to complete one of my subjects for the OOP, but I couldn't manage to figure out what's wrong with the definition of my functions. I'm a newbie in this language, already searched the forums but I couldn't find anything useful. Error message: Traceback (most recent call last): File "/home/main.py", line 44, in add(x, y) NameError: name 'add' is not defined This is the program I wrote. class Complex(object): def __init__(self, r = 0, i = 0): self.r = r self.i = i def __str__ (self): return "%s + i%s" % (self.r, self.i) def add (self, other): summ = Complex() summ.r = self.r + other.r summ.i = self.i + other.i return "Sum is %d" % summ def dif (self, other): dif = Complex() dif.r = self.r - other.r dif.i = self.i - other.i return dif def multiply (self, other): multiply = Complex() multiply.r = self.r * other.r multiply.i = self.i * other.i return "%d" % (-1 * multiply.r * multiply.i) def divide (self, other): divide = Complex() divide.r = self.r / other.r divide.i = self.i / other.i return "%d" % (divide.r / divide.i) x = Complex() y = Complex() x.r = int(input("Type in real part of x: \n")) x.i = int(input("Type in imaginary of x: \n")) print (x, "\n") y.r = int(input("Type in real part of y: \n")) y.i = int(input("Type in imaginary of y: \n")) print (y, "\n") add(x, y)
answer count: 2
has title: Name "function name" is not defined
tagged with: function
has answer: http://stackoverflow.com/a/50496711
accepted answer: http://stackoverflow.com/a/50496715

http://stackoverflow.com/q/50392787
tagged with: python
has body: I have a Django model class who has some default attributes, and I want to change the value of the complete variable by calling a function: class Foo: complete = False def set_complete_true(): complete = True But after calling set_complete_true() the complete variable is still False.
has answer: http://stackoverflow.com/a/50392854
tagged with: class
score: 2
type: AnsweredQuestion
has title: How to change class attributes using a method?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50392875
answer count: 2
has answer: http://stackoverflow.com/a/50392875
upvote count: 2
possible better answer: http://stackoverflow.com/a/50392854
downvote count: 0
has comment: http://stackoverflow.com/comment/87801341

aws-lambda
tags question: http://stackoverflow.com/q/50516321
type: Tag
tags question: http://stackoverflow.com/q/50484019
tags question: http://stackoverflow.com/q/50515323
tags question: http://stackoverflow.com/q/50412090
tags question: http://stackoverflow.com/q/50387735
tags question: http://stackoverflow.com/q/50503912
tags question: http://stackoverflow.com/q/50516060
tags question: http://stackoverflow.com/q/50470803
tag name: aws-lambda
tags question: http://stackoverflow.com/q/50523674
tags question: http://stackoverflow.com/q/50407437

http://stackoverflow.com/q/50491740
tagged with: windows
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87996457
has title: Specify Python version to use when calling from windows cmd line
has answer: http://stackoverflow.com/a/50491875
has body: I installed both Python2 and Python3 on my computer, but if I run a Python script, my computer choose to use Python2. I tried to uninstall Python2, but it turned out that my computer could not run Python anymore if I do so. How can I do to upgrade to Python 3?
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87996398
tagged with: upgrade
downvote count: 3
linked to: http://stackoverflow.com/q/6908143
has comment: http://stackoverflow.com/comment/87997459
has answer: http://stackoverflow.com/a/50491849
favorite count: 0
type: Question
type: UnansweredQuestion

dnssec
tag name: dnssec
tags question: http://stackoverflow.com/q/50501005
type: Tag

http://stackoverflow.com/a/50409643
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50408992
accepted answer of: http://stackoverflow.com/q/50408992
has body: SOLVED it was a wrong import reference, I used from django.conf.urls.static import static instead of from django.template.context_processors import static and it worked.
type: Answer
score: 0

http://stackoverflow.com/comment/88049345
has text: It's not my downvote, but I don't get why you're showing an example of storing a function in a dict and why you're using `//` for comments in python code.
score: 2
comment on: http://stackoverflow.com/a/50518258
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50454711
has title: Docker SDK for Python- How keep container up not in interactive mode
tagged with: docker
has body: Im trying to start a container and keep it up but not in interactive mode so it will still be returned as an output by the docker ps command its something like: docker run -d alpine sleep 50 I couldn't find any reference how to do it using Docker SDK for Python Please advise
has answer: http://stackoverflow.com/a/50456243
has comment: http://stackoverflow.com/comment/87923865
score: 1
has comment: http://stackoverflow.com/comment/87922795
has comment: http://stackoverflow.com/comment/87922950
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/q/50518579
has title: How to find if Shapely LineString is complex (i.e. self-intersects)
upvote count: 2
tagged with: shapely
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: geometry
has answer: http://stackoverflow.com/a/50518781
tagged with: python
has body: Either I'm missing something - I can't see it in the docs - or it's not built-in to Shapely: how do I determine if a LineString is complex, i.e. self-intersects?
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/50518781

scons
tag name: scons
tags question: http://stackoverflow.com/q/50396802
type: Tag

http://stackoverflow.com/comment/88087061
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50537482
score: 0
has text: Your question says you want to remove things "if a certain key is None", but your sample code removes things if _any_ value is None, not just a certain key's value. Which one do you want?

http://stackoverflow.com/q/50406336
has comment: http://stackoverflow.com/comment/87828693
has comment: http://stackoverflow.com/comment/87829940
has comment: http://stackoverflow.com/comment/87828549
tagged with: for-loop
linked to: http://stackoverflow.com/q/653509
has comment: http://stackoverflow.com/comment/87828058
score: 0
has comment: http://stackoverflow.com/comment/87828785
answer count: 2
has comment: http://stackoverflow.com/comment/87830459
has comment: http://stackoverflow.com/comment/87828223
has body: I am using the below code. for x in range(100): print('inside 1st loop') for y in range(25,60): print('inside second loop') if y &gt;= x: print ('y is now greater than x') Is it possible that once the if condition is satisfied in the inner for loop, the outer loop breaks itself, after 5 more inner loops are run. Actual code is as below : for i in range(len(a1)): title_derived = [] print(i) for j in range(len(b1)): #print(b1.iloc[i][10], a1.iloc[j][3]) if b1.iloc[j][10] == a1.iloc[i][3]: print('1st if ' + str(j)) print (b1.iloc[j][1], a1.iloc[i][11], b1.iloc[j][5]) if (((pd.to_datetime(b1.iloc[j][1]) &lt;= pd.to_datetime(a1.iloc[i][11]) &lt;= pd.to_datetime(b1.iloc[j][5]))) or ((pd.to_datetime(b1.iloc[j][1]) &lt;= pd.to_datetime(a1.iloc[i][8]) &lt;= pd.to_datetime(b1.iloc[j][5])))) : print('2nd if' + str(j)) title_derived.append(b1.iloc[j][15]) print('inserted ' + b1.iloc[j][15] + ' in ' + str(i) + ' th record ') a1.iat[i,65] = title_derived Now here, I have two dataframes, each record in first (10000 approx records) looks up every record in other dataframe (40000 records). Sometimes there can be atmost 4-5 consecutive entries that match the condition. So, once the condition is satsfied in second loop, I would like to finish five more iterations and break it.
has answer: http://stackoverflow.com/a/50406714
type: Question
has answer: http://stackoverflow.com/a/50407186
tagged with: break
has title: breaking an outer Python for loop based on condition in inner for loop
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/50446004
favorite count: 0
type: Question
has title: How to use python regex library to find date and time from a string?
score: 1
has answer: http://stackoverflow.com/a/50447829
tagged with: python
tagged with: regex
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
upvote count: 1
has body: Given a text : start_KA03MM7155_RKMS121MI4-4.21005_NEW_end, 2018-01-02 09:48:23. How do i extract 2018-01-02 as 020118 in a variable and 09:48:23 as 094823 in another variable using python?
downvote count: 0
accepted answer: http://stackoverflow.com/a/50447829
has answer: http://stackoverflow.com/a/50448201
possible better answer: http://stackoverflow.com/a/50448201

http://stackoverflow.com/comment/88088049
has text: No error message, it just returns two empty lists
comment on: http://stackoverflow.com/q/50537982
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50386513
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50386396
has body: if enumerate, zip and such is overwhelming at first use a simple for loops l1 = ["fc1", "fc2"] l2 = ["fh1", "fh2"] a = [] for i1 in l1: a.append([[i1,i2] for i2 in l2]) for i in a: print(i) output [['fc1', 'fh1'], ['fc1', 'fh2']] [['fc2', 'fh1'], ['fc2', 'fh2']]

http://stackoverflow.com/comment/87918661
type: QuestionComment
comment on: http://stackoverflow.com/q/50452336
has text: Actually, I use Python 3 and my code is like this: import pandas as pd with open('1.csv', encoding="utf-8") as f: train = f.read().splitlines() print(train)
score: 0
type: Comment

http://stackoverflow.com/a/74348825
score: 1
upvote count: 1
has body: A more convenient solution is to use view_as_blocks(), which reshapes your image to introduce new axes, allowing you to address blocks via the first two axes and the pixels within each block via the last two axes. For an image with shape (Y, X) which you want to split into 2x2 blocks, the blockwise view will have dimensions (Y/2, X/2, 2, 2). Once you have that view of the data, it's easy to use np.median to compute the median of each block: In [15]: import numpy as np ...: from skimage.util import view_as_blocks ...: ...: image = np.array( ...: [[4, 6, 6, 2], ...: [6, 7, 9, 9], ...: [3, 0, 9, 0], ...: [0, 6, 6, 4]]) ...: ...: ...: block_view = view_as_blocks(image, (2,2)) ...: block_view Out[15]: array([[[[4, 6], [6, 7]], [[6, 2], [9, 9]]], [[[3, 0], [0, 6]], [[9, 0], [6, 4]]]]) In [16]: downsampled = np.median(block_view, axis=[2,3]) ...: downsampled Out[16]: array([[6. , 7.5], [1.5, 5. ]]) Generalizing that into a function for ND images and (ND blocks): import numpy as np from skimage.util import view_as_blocks def blockwise_median(a, blockshape): assert a.ndim == len(blockshape), \ "blocks must have same dimensionality as the input image" assert not (np.array(a.shape) % blockshape).any(), \ "blockshape must divide cleanly into the input image shape" block_view = view_as_blocks(a, blockshape) assert block_view.shape[a.ndim:] == blockshape block_axes = [*range(a.ndim, 2*a.ndim)] return np.median(block_view, axis=block_axes) In [18]: image = np.array( ...: [[4, 6, 6, 2], ...: [6, 7, 9, 9], ...: [3, 0, 9, 0], ...: [0, 6, 6, 4]]) ...: ...: blockwise_median(image, (2,2)) Out[18]: array([[6. , 7.5], [1.5, 5. ]])
type: Answer
answers question: http://stackoverflow.com/q/50485458
downvote count: 0

http://stackoverflow.com/comment/87953244
comment on: http://stackoverflow.com/q/50457828
type: Comment
type: QuestionComment
score: 0
has text: Yes, the scroll down list is a JavaScript Object. I have to click on each of those objects to activate the javascript function ( a new window). I can activate those objects via my code, but the problem is when at least one of those items are not in the current screen. That's why I should scroll down to that object ( here x) first to be able to click on it. But I don't know how to scroll down to that object. I have used the code I used in this post as well as this one : driver.execute_script("arguments[0].scrollIntoView();", x) but none of them worked for me!

http://stackoverflow.com/q/50392795
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: neural-network
tagged with: machine-learning
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87802650
has body: I am working to create a neural network to predict the future value of the forex currency pair EURUSD knowing values in the past 16 hours. At first i had the value for every minute from 2000 to 2017. To create the labeled data for training i have subdivided the minutes in groups of 960 and calculated the labels for every period in the following way: To calcolate the label for the i th period i took the data from the i+1 th period and checked if during the i+1 th period the price goes above or below a certain percentage in respect to the price of the last minute of the i th period. In short i have got about 6300 pairs of labeled data with 960 input values and 3 output classes each. (first class the price goes up more than X, second class the price goes down more than X, third class the price stays in the middle) About 33% of the training data falls in the first class, another 33% falls in the second class and the last 33% falls in the third class. You can find the data here: https://ufile.io/m15fa My problem lies in the output. I am not able to obtain any usefull prediction. Every execution of the script, after the training, the network classifies all of the test data in the same class, which changes nearly every execution of the script. Here the code: import tensorflow as tf import json print("Loading data...") f = open('out_x.txt', 'r') input_data_x = json.load(f) print("1/2 loaded...") f = open('out_y.txt', 'r') input_data_y = json.load(f) print("Done loading data.") # Parameters learning_rate = 0.005 training_epochs = 10 batch_size = 10 num_examples = 5500 display_step = 1 print("------------------------------------") print("learning_rate:",learning_rate) print("training_epochs:",training_epochs) print("batch_size:",batch_size) print("num_examples:",num_examples) print("data_x:",len(input_data_x)) print("data_y:",len(input_data_y)) print("------------------------------------") # Network Parameters n_input = 960 n_hidden_1 = 500 # 1st layer number of neurons n_cla…
score: 1
tagged with: tensorflow
has title: Why i get wrong/incoherent results with this neural net?
favorite count: 0
type: Question

http://stackoverflow.com/comment/88083448
score: 1
type: QuestionComment
has text: Please make some attempt at solving this yourself. There are plenty of guides available if you search online. Your code makes no use of `sqlite3` at all.
comment on: http://stackoverflow.com/q/50535725
type: Comment

http://stackoverflow.com/a/50425025
has body: apt-get supports a -y flag which automatically answers any question with yes. See https://linux.die.net/man/8/apt-get. That should solve your problem.
accepted answer of: http://stackoverflow.com/q/50424572
has comment: http://stackoverflow.com/comment/87865330
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50424572
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50459007
has comment: http://stackoverflow.com/comment/87932361
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50458956
type: Answer
has comment: http://stackoverflow.com/comment/88011687
has body: class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer): roundtrips = serializers.SerializerMethodField() def get_roundtrips(self, instance): queryset = [x.roundtrip for x in instance.roundtrips.all()] return RoundtripSerializer(queryset, many=True, context=self.context).data class Meta: model = models.Tour fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips') depth = 1 use SerializerMethodField to get whatever you want.
answers question: http://stackoverflow.com/q/50458956
has comment: http://stackoverflow.com/comment/88012073
upvote count: 2
has comment: http://stackoverflow.com/comment/88011654
has comment: http://stackoverflow.com/comment/88011979
has comment: http://stackoverflow.com/comment/88012108
has comment: http://stackoverflow.com/comment/88036068
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87933555
has comment: http://stackoverflow.com/comment/88036266
score: 2

http://stackoverflow.com/a/50445010
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50444879
has comment: http://stackoverflow.com/comment/87904931
score: 4
has body: The logging level you specify in your configuration is the minimum level will be logged. Just to recap, here the predefined levels in order of importance (from lowest to maximum): DEBUG INFO WARNING ERROR CRITICAL So, if you put INFO in your configuration you will see all logs marked as INFO, WARNING, ERROR, and CRITICAL. If you really want to see only INFO and ERROR you can try to write some custom code, but I discourage it as it smells as a bad design. References: https://docs.djangoproject.com/en/dev/topics/logging/ https://docs.python.org/3/library/logging.html?highlight=logging#module-logging Edit Here how your configuration would look like: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['console', ], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'sns': { 'level': 'ERROR', 'class': 'project.abc.snshandler.SNSHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'INFO', 'handlers': ['console', ], 'propagate': False, }, 'django.security.DisallowedHost': { 'level': 'INFO', 'handlers': ['console', ], 'propagate': False, }, 'project': { 'level': 'INFO', 'handlers': ['console', 'sns'], 'propagate': False, }, }, }
has comment: http://stackoverflow.com/comment/87904224
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/87904886
answers question: http://stackoverflow.com/q/50444879

http://stackoverflow.com/q/50391941
type: Question
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 0
score: 18
tagged with: django
has comment: http://stackoverflow.com/comment/87799527
has body: Why do I get the following error when I run the django server and how do I fix it ? : EOFError: marshal data too short details Performing system checks... Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7f6e5dbacea0&gt; Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) …
has comment: http://stackoverflow.com/comment/87799513
favorite count: 0
has answer: http://stackoverflow.com/a/72820465
has answer: http://stackoverflow.com/a/53095120
has title: EOFError: marshal data too short
answer count: 3
has comment: http://stackoverflow.com/comment/90333207
tagged with: python
has comment: http://stackoverflow.com/comment/135532802
upvote count: 18
has comment: http://stackoverflow.com/comment/87799519
has comment: http://stackoverflow.com/comment/87799492
has answer: http://stackoverflow.com/a/78563155

http://stackoverflow.com/comment/87967054
has text: Why wouldn't you be able to combine it with `find()`? It's just numbers, it doesn't matter how you get the numbers.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50476642
type: AnswerComment

http://stackoverflow.com/a/50478268
downvote count: 0
has comment: http://stackoverflow.com/comment/88009015
has body: There's probably a more elegant and generalizable solution, but this will work for the simple example you've given. A = pd.DataFrame({"a":[True, False, False], 'b':[False, True, False], 'c': [False, False, True]}, index=['a','b','c']) B = pd.DataFrame({"a":[False, False, True], 'b':[True, False, True], 'd': [True, False, True]}, index=['a','b','c']) C = pd.concat([(A | B)'a', 'b', A['c'], B['d']], axis=1) print C a b c d a True True False True b False True False False c True True True True This ORs the two frames, which will produce the correct result for the columns in common (a, b), but Nan for columns c, d. So, we just slice off columns a and b, then concatenate with c and d, since they remain unchanged by the OR operation. EDIT: Per your comment, here is more generalized solution, which will save you from having to know and/or hardcode the specific column names. # Get all column names all_columns = A.columns | B.columns # Get column names in common union = A.columns &amp; B.columns # Get disjoint column names not_B = list(set(all_columns) - set(B.columns)) not_A = list(set(all_columns) - set(A.columns)) # Logical-or common columns, and concatenate disjoint columns C = pd.concat([A[union] | B[union], A[not_B], B[not_A]], axis=1) # If columns names get disordered because of set operations, use # `all_columns` to reorder print(C[all_columns]) a b c d a True True False True b False True False False c True True True True EDIT 2: Per kmundnic's final solution, here is an updated version that works on more that two data frames. # For Python 3 from functools import reduce # A third data frame C = pd.DataFrame({'a':[False, False, False], 'b':[True, True, False], 'e': [True, True, True]}, index=['a','b','c']) def logical_merge(A, B): # Get all column names all_columns = A.columns | B.columns # Get column names in common common = A.columns &amp; B.columns # Get disjoint column names _A = [x for x in B.columns if not x in common] _B = [x for x in A.columns if not x in c…
has comment: http://stackoverflow.com/comment/88014910
type: Answer
answers question: http://stackoverflow.com/q/50478011
has comment: http://stackoverflow.com/comment/88017008
has comment: http://stackoverflow.com/comment/88007789
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/50478011
type: AcceptedAnswer

http://stackoverflow.com/q/50478326
has title: How to generate 0 and 1 matrix based on conditions in Python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50478537
tagged with: pandas
answer count: 1
has body: I am doing a scheduling task. I translate the problem to generate an 8*8 matrix with 0 and 1 in it such that each row sums to 1 and each column sums to as close to 1 as possible. The columns are actually a day divided into 8 pieces. Rows are the days. And 0 and 1 represent two tasks.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87970566
has answer: http://stackoverflow.com/a/50478537
has comment: http://stackoverflow.com/comment/87970306
tagged with: python

http://stackoverflow.com/a/50544734
type: Answer
has body: So i finally made it work, I just added this: if joueur == "joueur1": joueur = "joueur2" label_joueur["text"] = joueur #This is optionnal, it's just details else: joueur = "joueur1" label_joueur["text"] = joueur To the joue2(ligne,colonne,l,c,joue)like that: def joue2(ligne,colonne,l,c,joue): global joueur m=ligne n=colonne if not est_valide(joueur,l,c,m,n) or not pion_valide(l,c,m,n,joueur) or not dame_valide(l,c,m,n,joueur) or not fou_valide(l,c,m,n) or not roi_valide(l,c,m,n) or not cavalier_valide(l,c,m,n) or not tour_valide(l,c,m,n,joueur) or not pion_valide(l,c,m,n,joueur) : print("mauvais") faux=Toplevel(Fenetre, height= 100, width = 100) case1 = Canvas(faux, width=100, height = 100,highlightthickness=1,highlightbackground="black") v= 50 w= 50 case1.create_image(v,w,image=stop) case1.grid() faux.mainloop() elif est_victorieux(joueur): board[m][n]=board[l][c] board[l][c]="___" frame.destroy() label_joueur["text"]=("Echec et mat") else: board[m][n]=board[l][c] board[l][c]="___" if est_victorieux(joueur): frame.destroy() label_joueur["text"]=("Echec et mat") else: if joueur == "joueur1": joueur = "joueur2" label_joueur["text"] = joueur else: joueur = "joueur1" label_joueur["text"] = joueur affiche_grille() You need to add global joueur to make this work.
has comment: http://stackoverflow.com/comment/88100587
has comment: http://stackoverflow.com/comment/88100869
score: -1
has comment: http://stackoverflow.com/comment/88100521
answers question: http://stackoverflow.com/q/50532531
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/50492106
type: Question
has comment: http://stackoverflow.com/comment/87997259
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/42615527
has body: I am using matplotlib to plot some texts. Specifically, I want the width of the character to be fixed, while the height of the character to be propositional to its frequency in the text. For example, in the following sentence, "hello world", there are seven unique characters, i.e., 'd', 'e', 'h', 'l', 'o', 'r', 'w'. In the expected plotting, each character will have the same width, e.g., 1, while the height of 'l' is greater than the the height of other characters. For example, if the height of 'l' is 3, then the height of 'o' is 2 and the height of the rest characters is 1.
answer count: 0
has comment: http://stackoverflow.com/comment/88022121
score: 0
has title: How to plot text with fixed width and proportional height based on frequency?
tagged with: matplotlib

asynchronous
tags question: http://stackoverflow.com/q/50522534
tags question: http://stackoverflow.com/q/50533266
tags question: http://stackoverflow.com/q/50475564
tags question: http://stackoverflow.com/q/50398964
tags question: http://stackoverflow.com/q/50467781
tags question: http://stackoverflow.com/q/50508630
type: Tag
tags question: http://stackoverflow.com/q/50473113
tags question: http://stackoverflow.com/q/50476732
tag name: asynchronous
tags question: http://stackoverflow.com/q/50475318

http://stackoverflow.com/comment/87847002
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50415579
type: QuestionComment
has text: Perhaps you can try another User Agent?

http://stackoverflow.com/comment/87987770
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50487511
has text: 3. It's 3 efficient.

http://stackoverflow.com/q/50458566
has title: Discord bot AttributeError: 'str' object has no attribute 'id'
has body: I was messing around with making a bot, but I can't figure out how to ban someone... if message.content.upper().startswith('CHILL BAN'): if "447929519945416734" in [role.id for role in message.author.roles] or "448191759739256842" in [role.id for role in message.author.roles] or message.author.id == "218156043799101452": await bot.kick(message.mentions[0].name) await bot.send_message(message.channel, "Someone has been banned!") #["&lt;@356065937318871041&gt;"] else: await bot.send_message(message.channel, "You do not have sufficient privileges.")
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/87974066
answer count: 1
has comment: http://stackoverflow.com/comment/87930613
favorite count: 0
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/50480401
type: UnansweredQuestion
score: -2
tagged with: python

http://stackoverflow.com/comment/87826729
type: Comment
type: QuestionComment
has text: I'm not familiar with the Python API, but if you can access record metadata (offset, partition number) when you consume messages, then there should also be the timestamp.
comment on: http://stackoverflow.com/q/50405509
score: 0

http://stackoverflow.com/comment/88004397
type: QuestionComment
comment on: http://stackoverflow.com/q/50495738
has text: I think it would help if you explain the context by perhaps rephrasing your code to use meaningful function and argument names instead of `foo`, `x1`, `opt` etc. I understand literally what you're asking, but it's hard to offer opinion without understanding the actual problem you're trying to solve.
type: Comment
score: 0

http://stackoverflow.com/comment/87867934
score: 0
type: Comment
has text: @JoãoPedroOliveira I have already edited the code can you rollback the edit
type: QuestionComment
comment on: http://stackoverflow.com/q/50426629

http://stackoverflow.com/q/50432476
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/50433500
downvote count: 0
has answer: http://stackoverflow.com/a/52613051
possible better answer: http://stackoverflow.com/a/52613051
favorite count: 0
type: Question
has body: I am training a neural network with Keras using EarlyStopping based on val_acc and patience=0. EarlyStopping stops the training as soon as val_acc decreases. However the final model that I obtain is not the best model, namely the one with the highest val_acc. But I rather have the model corresponding to the epoch after, namely the one corresponding to a val_acc just a bit lower than the best one and that caused the early stopping! How do I get the best one? I tried to use the save the best model using the callback: ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True) But I get the same results.
score: 5
has answer: http://stackoverflow.com/a/50433500
upvote count: 5
tagged with: neural-network
tagged with: machine-learning
has title: How to get the best model when using EarlyStopping callback in Keras?
tagged with: python
tagged with: keras

http://stackoverflow.com/q/50530655
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50530703
has comment: http://stackoverflow.com/comment/88073384
tagged with: subprocess
has body: For example, I have a command commandA and want to get the the exit code after commandA is executed. CommandA is expected to be failed, so the exit code we should get is 1. If I type command in the terminal as commandA;echo $?, a 1 get displayed on the screen. However, when I do it with python, things went wrong. I have tried to call commandA with os.system(commandA) or subprocess.call(commandA.split()), and then call os.popen('echo $?').read(), results are 0. os.popen('commandA;echo $?').read() gives me a correct result but the process of commandA is not displayed in the screen, which is what I don't want it happens.
has answer: http://stackoverflow.com/a/50530800
has answer: http://stackoverflow.com/a/50530703
score: 4
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50530800
linked to: http://stackoverflow.com/q/1696998
upvote count: 5
tagged with: os.system
tagged with: python
has comment: http://stackoverflow.com/comment/88073229
has title: Get exit code of a command

http://stackoverflow.com/a/50437980
accepted answer of: http://stackoverflow.com/q/50437901
upvote count: 2
has body: To propose an alternate solution that might be more easily followed and avoid this dance, perhaps consider using query strings. Order agnostic and fully supported in DRF.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50437901
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87888152
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50436841
has text: If you give the same input for the decoder, then it will just learn identity! Your code was designed to do teacher forcing which only works if the sequences are different. What are you after is seq2seq auto-encoders, have a look at [this](https://blog.keras.io/building-autoencoders-in-keras.html) or [this](https://github.com/keras-team/keras/issues/9093).

http://stackoverflow.com/a/50536385
has body: First, the way you are indexing is backwards, you want row then column: for loop with iloc pairs = [(5, 3), (2, 6), (1, 3), (3, 2), (1, 3)] for pair in pairs: df.iloc[pair] += 1 # Result 00 01 02 03 04 05 06 07 0 0 0 0 0 0 0 0 0 1 0 0 0 2 0 0 0 0 2 0 0 0 0 0 0 1 0 3 0 0 1 0 0 0 0 0 4 0 0 0 0 0 0 0 0 5 0 0 0 1 0 0 0 0 6 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0
answers question: http://stackoverflow.com/q/50536300
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50536300
score: 1
type: Answer

http://stackoverflow.com/comment/87809977
score: 0
has text: How do I interpret the screenshot? Its opera, and related to your python program how? It may be better to post a line showing memory usage here in the question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50397067

http://stackoverflow.com/comment/88031664
comment on: http://stackoverflow.com/q/50509820
type: Comment
score: 1
type: QuestionComment
has text: That is because you are calling `yes_or_no()` twice

http://stackoverflow.com/comment/87845389
type: QuestionComment
has text: Maybe because you are using the debug console?
comment on: http://stackoverflow.com/q/50414626
score: 0
type: Comment

http://stackoverflow.com/comment/87816789
has text: Whatever your rule is, just write the comparison and you're done. For example, `if call_start <= ftime < call_stop:` will tell you whether `ftime` is in between `call_start` and `call_stop`, just like `2 <= n < 5` will tell you whether `n` is between 2 and 5. And if you want a closed range instead of a half-open range, change the `<` to `<=`. And so on. (Of course all reasonable rules I can think of are only going to pass `t4`, but pault already covered that.)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50400329
type: QuestionComment

http://stackoverflow.com/a/50439542
upvote count: 2
score: 2
downvote count: 0
has body: In this case, you can also use groupby instead of pivot: (df.groupby(['week', 'Year', 'Country', 'category']) .sum() .unstack(fill_value=0) .add_prefix('category_')) Which gives you: category_Value category category_A category_B category_C category_D category_E week Year Country 1 2005 Angola 19 10 11 5 0 2006 Angola 3 2 7 3 6 2 2006 Angola 3 2 7 3 0
type: Answer
answers question: http://stackoverflow.com/q/50439257

http://stackoverflow.com/comment/88044870
score: 0
has text: This is the only thing i didn't try because im very new to iy. Thanx a lot i hope it works once i get back to it
comment on: http://stackoverflow.com/q/50494617
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50508221
score: 3
upvote count: 3
has body: This will give you what you want: df.pivot_table(index='date_time', columns='country', values=['temp', 'dc']).swaplevel(axis=1).sort_index(axis=1) #country Austria France Germany # dc temp dc temp dc temp #date_time #1 3 13 9 4 0 12
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50507735
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50507735
type: Answer
has comment: http://stackoverflow.com/comment/88028478
has comment: http://stackoverflow.com/comment/88028494

http://stackoverflow.com/comment/87853889
comment on: http://stackoverflow.com/q/50418627
type: Comment
type: QuestionComment
has text: "i already have a function to calculate the slope for the entire dataframe" - how do you do that now?
score: 0

http://stackoverflow.com/comment/87891862
has text: `path('pokemon/detail/<int:pk>', PokemonDetail, name='pkmn-detail')` maybe you need to add `PokemonDetail.as_view()` ?
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50438802

http://stackoverflow.com/comment/87897420
score: 0
has text: @JohnGordon these are the small things I still need clarification about. I didn't realize that declaring the output of a function also calls it. You're right, it doesn't make a difference, I've removed the first call.
comment on: http://stackoverflow.com/q/50441421
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87866192
score: 0
type: Comment
type: QuestionComment
has text: Do you know what component is giving the `AttributeError`?
comment on: http://stackoverflow.com/q/50425008

opencv
tags question: http://stackoverflow.com/q/50403624
type: Tag
tags question: http://stackoverflow.com/q/50406354
tags question: http://stackoverflow.com/q/50395617
tags question: http://stackoverflow.com/q/50538088
tags question: http://stackoverflow.com/q/50390647
tags question: http://stackoverflow.com/q/50429079
tags question: http://stackoverflow.com/q/50449602
tags question: http://stackoverflow.com/q/50406883
tags question: http://stackoverflow.com/q/50416416
tags question: http://stackoverflow.com/q/50392449
tags question: http://stackoverflow.com/q/50491716
tags question: http://stackoverflow.com/q/50431417
tags question: http://stackoverflow.com/q/50411385
tags question: http://stackoverflow.com/q/50508692
tags question: http://stackoverflow.com/q/50479607
tags question: http://stackoverflow.com/q/50473598
tags question: http://stackoverflow.com/q/50495664
tags question: http://stackoverflow.com/q/50500542
tags question: http://stackoverflow.com/q/50416424
tags question: http://stackoverflow.com/q/50397782
tags question: http://stackoverflow.com/q/50509208
tags question: http://stackoverflow.com/q/50447007
tags question: http://stackoverflow.com/q/50438202
tags question: http://stackoverflow.com/q/50516864
tags question: http://stackoverflow.com/q/50454353
tags question: http://stackoverflow.com/q/50457074
tags question: http://stackoverflow.com/q/50506557
tags question: http://stackoverflow.com/q/50467436
tags question: http://stackoverflow.com/q/50442253
tags question: http://stackoverflow.com/q/50431647
tags question: http://stackoverflow.com/q/50434297
tags question: http://stackoverflow.com/q/50535323
tags question: http://stackoverflow.com/q/50502004
tags question: http://stackoverflow.com/q/50474302
tags question: http://stackoverflow.com/q/50450654
tags question: http://stackoverflow.com/q/50438674
tags question: http://stackoverflow.com/q/50411092
tags question: http://stackoverflow.com/q/50393741
tags question: http://stackoverflow.com/q/50493133
tags question: http://stackoverflow.com/q/50508309
tags question: http://stackoverflow.com/q/50493225
tags question: http://stackoverflow.com/q/50503960
tags question: http://stackoverflow.com/q/50479068
tags question: http://stackoverflow.com/q/50425613
tags question: http://stackoverflow.com/q/50464669
tags question: http://stackoverflow.com/q/50529703
tags question: http://stackoverflow.com/q/50447893
tags question: http://stackoverflow.com/q/50385640
tags question: http://stackoverflow.com/q/50508452
tags question: http://stackoverflow.com/q/50442597
tags question: http://stackoverflow.com/q/50516127
tags question: http://stackoverflow.com/q/50403176
tags question: http://stackoverflow.com/q/50479491
tags question: http://stackoverflow.com/q/50497945
tags question: http://stackoverflow.com/q/50445459
tags question: http://stackoverflow.com/q/50412812
tags question: http://stackoverflow.com/q/50502530
tags question: http://stackoverflow.com/q/50472180
tags question: http://stackoverflow.com/q/50417922
tags question: http://stackoverflow.com/q/50430732
tags question: http://stackoverflow.com/q/50386323
tags question: http://stackoverflow.com/q/50390995
tags question: http://stackoverflow.com/q/50420469
tags question: http://stackoverflow.com/q/50508810
tags question: http://stackoverflow.com/q/50529731
tags question: http://stackoverflow.com/q/50510430
tags question: http://stackoverflow.com/q/50506782
tags question: http://stackoverflow.com/q/50452561
tags question: http://stackoverflow.com/q/50488667
tags question: http://stackoverflow.com/q/50535498
tags question: http://stackoverflow.com/q/50540204
tags question: http://stackoverflow.com/q/50458452
tags question: http://stackoverflow.com/q/50436960
tags question: http://stackoverflow.com/q/50424138
tags question: http://stackoverflow.com/q/50533775
tags question: http://stackoverflow.com/q/50429093
tags question: http://stackoverflow.com/q/50387905
tags question: http://stackoverflow.com/q/50432349
tag name: opencv

http://stackoverflow.com/comment/87926679
type: AnswerComment
comment on: http://stackoverflow.com/a/50455321
type: Comment
has text: I didnt directly copy your code...I made the appropriate changes with os.walk
score: 0

http://stackoverflow.com/q/50439037
favorite count: 0
accepted answer: http://stackoverflow.com/a/50459066
type: Question
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/50439234
has answer: http://stackoverflow.com/a/51201895
has answer: http://stackoverflow.com/a/50439201
has answer: http://stackoverflow.com/a/52191898
tagged with: sympy
linked to: http://stackoverflow.com/q/17476704
has answer: http://stackoverflow.com/a/50459066
answer count: 5
downvote count: 0
tagged with: python
score: 4
possible better answer: http://stackoverflow.com/a/50439201
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87892671
has body: I stumbled on this as it did not behave as I expected it to. What exactly is s.evalf(subs={t: 0}) for? It seems to be neither a "shortcut" for s.evalf().subs({t: 0}) nor for s.evalf().subs({t: 0}) as import sympy omega, t = sympy.symbols("omega, t") s = sympy.pi * sympy.cos(omega*t) # both result in 3.14159265358979 print(s.evalf().subs({t: 0})) print(s.subs({t: 0}).evalf()) # results in 3.14159265358979*cos(omega*t) print(s.evalf(subs={t: 0})) results in 3.14159265358979 3.14159265358979 3.14159265358979*cos(omega*t) Couldn't find good documentation on this. Maybe someone knows the answer? Otherwise I might have to take a look at the source code to find out more...
has comment: http://stackoverflow.com/comment/87892444
has title: What exactly is the `subs` argument of the `evalf` method of SymPy Expression for? Like `s.evalf(subs={...})`?

http://stackoverflow.com/comment/87817708
comment on: http://stackoverflow.com/a/50400778
has text: Ok, I updated the question to make it look more like the actual logic
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87921257
type: Comment
comment on: http://stackoverflow.com/a/50438556
has text: It is not the same because it's more general. In your code, you have four ifs, one for each direction. By setting `dx = sign(n - c)` and `dy = sign(m - l)`, you can simply check the cells from `(l + dy, c + dx)` to `(m, n)` by steps of `(dy, dx)`. It works the same for all directions.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88002528
type: QuestionComment
comment on: http://stackoverflow.com/q/50494746
has text: pip didn't work so I installed it using conda
score: 0
type: Comment

http://stackoverflow.com/q/50535826
answer count: 1
type: AnsweredQuestion
score: 0
has title: Trying to see if values in a list exist in a mongoDB collection for a particular field
tagged with: mongodb
has body: I have a list of dictionaries called listCityStateZip. One of the keys in listCityStateZip is called cityStateZip. I want to see which of the cityStateZip values exist in a MongoDB collection called zipcodes (field: citystatezip). If no match is found, then I want to flag that record in my list as "N". If a match is found, I want to flag that record in my list as "Y". I thought the code below would address my issues, but for some reason only the very first record in listCityStateZip (the list) ends up getting a flag. Code shown below. Two questions: 1) is there an easier way to write this code using python and 2) if not, why do I get a flag only in the very first record in my list? for a in listCityStateZip: for b in db.zipcodes.find({'citystatezip': a['cityStateZip']},{'_id':1}): c.append(b) if len(c) == 0: a['flag'] = 'N' else: a['flag'] = 'Y' c=[]
type: Question
accepted answer: http://stackoverflow.com/a/50536308
tagged with: python
has answer: http://stackoverflow.com/a/50536308

http://stackoverflow.com/a/50472531
has body: Just by looking at this part of your code: #ifndef INTERFACE_H #define INTERFACE_H class Interface { public: virtual void blah() = 0; }; #endif You have a class that has a pure virtual method. This means that you can not create an object of type interface directly it will fail to compile if used. This means that you must inherit from this class and any and all classes that inherit from this class must implement the function blah(). Also since you are inheriting from a pure virtual abstract base class you should also have a virtual destructor. You can do this: #ifndef INTERFACE_H #define INTERFACE_H class Interface { public: virtual ~Interface(); virtual void blah() = 0; }; #endif #ifndef INTERFACE_IMPL #define INTERFACE_IMPL class InterfaceImpl : public Interface { public: InterfaceImpl() {} virtual ~InterfaceImpl(){} virtual void blah() override { /* implementation of blah here; */ } }; #endif Then what ever source code is using Interface directly replace it with either InterfaceImpl or with a pointer to an Inteface type. If you use the later you will have to do some casting between base and child class.
type: Answer
answers question: http://stackoverflow.com/q/50472377
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87971815
has comment: http://stackoverflow.com/comment/87970721
has comment: http://stackoverflow.com/comment/87970326

typeconverter
type: Tag
tags question: http://stackoverflow.com/q/50432533
tag name: typeconverter

http://stackoverflow.com/a/50509895
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50509625
has body: I believe there are countless ways of solving this problem. The first one that came into my mind is making best use of the sum function which can also sum up over an iterable: a = range(1,100) b = range(25,100) sum_a = sum(1 for i in b if i in a) sum_b = sum(1 for i in a if i in b) share_a = sum_a*100 / len(b) share_b = sum_b*100 / len(a) print(share_a, share_b) &gt;&gt;&gt; 100 75 This might be a bit more robus, e.g. when you are not working with ranges but with unsorted lists.

http://stackoverflow.com/comment/88019411
comment on: http://stackoverflow.com/q/50503569
type: Comment
has text: Looks like you might need this: https://docs.python.org/2/library/json.html
type: QuestionComment
score: 0

http://stackoverflow.com/q/50420229
upvote count: 4
tagged with: list-comprehension
answer count: 4
has answer: http://stackoverflow.com/a/50420498
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50420331
has comment: http://stackoverflow.com/comment/87856056
has body: Here is my code : evenorodd=[1,2,3] list1=['a','b','c'] list2=['A','B','C'] res = tuple(map(lambda x: True if x % 2 != 0 else False, evenorodd)) print(res) the output: (False, True, False, True) I want this : element of list1 if x%2!=0 (if element of evenorodd is odd) element of list2 else (if element of evenorodd is even) The output that I look for: ('a','B','c') and I want to do that on one line res = tuple(map(lambda x: ??? if x % 2 != 0 else ???, evenorodd)) Thank you
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87855934
has comment: http://stackoverflow.com/comment/87855907
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87856003
score: 4
has title: create a tuple with map, with conditional evenorodd list
has answer: http://stackoverflow.com/a/50420546
tagged with: tuples
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/50420300
has comment: http://stackoverflow.com/comment/87855969
has comment: http://stackoverflow.com/comment/87856320

http://stackoverflow.com/comment/87975675
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50480456
has text: following this tutorial https://www.tutorialspoint.com/python3/python_multithreading.htm
score: 0

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/50418449
tags question: http://stackoverflow.com/q/50396786
tags question: http://stackoverflow.com/q/50516363
tag name: google-oauth

http://stackoverflow.com/a/50510100
has comment: http://stackoverflow.com/comment/88033185
has body: If you need a dictionary comprehension then you have to use comprehension syntax, not a statement (comprehensions are expressions): docs = {"doc"+str(i): Finance.documents[i] for i in range(len(Finance.documents))} This would, however, be much better written as docs = {"doc"+str(i): documt for (i, documt) in enumerate(Finance.documents)} I am unsure, though, why a dict that can be accessed with keys like "doc1", "doc2", etc. is better than a simple list, which can be accessed with integer keys.
has comment: http://stackoverflow.com/comment/88032301
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50510037
score: 4
answers question: http://stackoverflow.com/q/50510037
has comment: http://stackoverflow.com/comment/88032781
has comment: http://stackoverflow.com/comment/88033220
has comment: http://stackoverflow.com/comment/88033352
type: Answer
upvote count: 4

http://stackoverflow.com/a/50538892
type: Answer
answers question: http://stackoverflow.com/q/50538882
score: 1
has body: n**count is an int already. You need to convert it to a str before adding it to ' '. That should say new += str(n**count) + ' '.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50432694
type: Question
has title: Pandas - Shift column values
tagged with: group-by
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50432792
score: -2
has answer: http://stackoverflow.com/a/50432840
has comment: http://stackoverflow.com/comment/87880412
tagged with: pandas
upvote count: 0
answer count: 2
downvote count: 2
favorite count: 0
has body: I have a dataframe like this: Name_A ¦ id1 ¦ date 1 ¦ 1 Name_A ¦ id1 ¦ date 2 ¦ 0 Name_A ¦ id1 ¦ date 3 ¦ 1 Name_A ¦ id1 ¦ date 4 ¦ 1 Name_A ¦ id1 ¦ date 5 ¦ 1 Name_B ¦ id2 ¦ date 6 ¦ 0 Name_B ¦ id2 ¦ date 7 ¦ 1 Name_B ¦ id2 ¦ date 8 ¦ 1 ... And I would like to get this: Name_A ¦ date1 ¦ 0 Name_A ¦ date2 ¦ 1 Name_A ¦ date3 ¦ 1 Name_A ¦ date4 ¦ 1 Name_A ¦ date5 ¦ NaN Name_B ¦ date6 ¦ 1 Name_B ¦ date7 ¦ 1 Name_B ¦ date8 ¦ NaN ... I would like to shift the values on the column for a specific name group. Any ideas/suggestions? Thanks.

http://stackoverflow.com/q/50477522
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
tagged with: multilabel-classification
has title: Accelerating training in Multilabel classification with NNs
has body: I am using Tensorflow for multi-label classification of Audio. The dataset I am using is made up of 10 different classes, and to each sample of audio correspond two labels. In other words, the number of overlapping sounds/classes per file is always 2. So the vector of labels "y" would be for example: y = [0, 0, 0, 0, 0, 1, 0, 1, 0, 0] I am using 3 convolutional layers , 1 FC layer and 1 output layer made up of 10 logistic units. And as cost function I am using the binary cross entropy for each unit and then averaging the result. For some reason(s), I guess mainly as a consequence of the initialization of the parameters (weights) of the network and the logistic units in the output layer, the network tends to predict mainly zeros. I guess after some training this trend will start to dissapear, however, I wonder if there is a smart way of doing something so the network does not predict those many zeros and predicts more ones, which I believe would make the cost higher and the gradient stronger (not 100% sure about this one though) and therefore training would be faster. I use Xavier initialization for the weights of all layers, as an example: W2 = tf.get_variable("W", [5,5,24,48], initializer=tf.contrib.layers.xavier_initializer()) Maybe using tf.truncated_normal_initializer instead could help? ----------------------------------------- EDIT 1 -------------------------------------------------------- A piece of information that I forgot to mention is that all my inputs are negative values, I don't know if that actually has any consequences.
answer count: 0
score: 1
tagged with: classification
downvote count: 0
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/q/50493039
tagged with: export-to-csv
answer count: 2
has title: Appending scraped data to CSV file
possible better answer: http://stackoverflow.com/a/50493276
has answer: http://stackoverflow.com/a/50493410
tagged with: web-scraping
tagged with: python
accepted answer: http://stackoverflow.com/a/50493410
has body: I have been messing around with python in the past few days and while following Edmund Martin's tutorial I ran into a problem: I would like to append the name and title that I scraped to a CSV file. Only problem is the data I scraped does not appear into the file. Could you explain to me the logic of why only "rank" "description" and "title" is being written onto the CSV file and not the actual data. Also how can I solve that? Below is the code I have found from the tutorial website with the last three lines that I added: import requests from bs4 import BeautifulSoup import time import csv USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 ' 'Safari/537.36'} def fetch_results(search_term, number_results, language_code): assert isinstance(search_term, str), 'Search term must be a string' assert isinstance(number_results, int), 'Number of results must be an integer' escaped_search_term = search_term.replace(' ', '+') google_url = 'https://www.google.com/search?q={}&amp;num={}&amp;hl={}'.format( escaped_search_term, number_results, language_code) response = requests.get(google_url, headers=USER_AGENT) response.raise_for_status() return search_term, response.text def parse_results(html, keyword): soup = BeautifulSoup(html, 'html.parser') found_results = [] rank = 1 result_block = soup.find_all('div', attrs={'class': 'g'}) for result in result_block: link = result.find('a', href=True) title = result.find('h3', attrs={'class': 'r'}) description = result.find('span', attrs={'class': 'st'}) if link and title: link = link['href'] title = title.get_text() description = description.get_text() if link != '#': found_results.append({ 'rank': rank, 'title': title, 'description': description }) rank += 1 return found_results def scrape_google(search_term, number_results, language_code): try: keyword, html = fetch_results(search_term, number_results, language_code) results = parse_results(html, keyword…
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50493276
has comment: http://stackoverflow.com/comment/87999506
type: Question
tagged with: beautifulsoup

http://stackoverflow.com/a/50496498
answers question: http://stackoverflow.com/q/50496439
has body: try this from selenium import webdriver driver = webdriver.Firefox() driver.get("https://instagram.com/p/") a_tag = driver.find_elements_by_xpath("//a[@href]") links = [tag.get_attribute('href') for tag in a_tag] print(links)
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88006484
type: Answer

http://stackoverflow.com/comment/87967653
type: AnswerComment
has text: It's inefficient, manual, hard to track, assumes you know your colours beforehand, prone to error, polluting the namespace, unstructured.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50476907

encoder-decoder
type: Tag
tag name: encoder-decoder
tags question: http://stackoverflow.com/q/50506087

http://stackoverflow.com/comment/87856117
type: QuestionComment
has text: Well the error should be quite clear: You try to add a string to a number, which isn't allowed. What are you trying to accomplish? Perhaps `cards` should be a list of *integers*?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50420334

http://stackoverflow.com/comment/88031318
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50509597
has text: `print(df[df["TimeStamp"].str.endswith(".0", na=False)])` working for me

http://stackoverflow.com/a/73434046
has body: indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=7) df.groupby('A').rolling(window=indexer, on='B',min_periods=0).C.sum() pandas doc
has comment: http://stackoverflow.com/comment/136149591
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50411098
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/50448817
accepted answer of: http://stackoverflow.com/q/50448199
has comment: http://stackoverflow.com/comment/87911824
answers question: http://stackoverflow.com/q/50448199
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/87912063
has body: The problem is, that your data are not(!) showing a lognormal pdf, since they are not normalized properly. Note, that the integral over a pdf has to be 1. If you numerically integrate your data and nomalize by that, e.g. y1 = y0/np.trapz(x0, y0) your approach works fine. params, extras = curve_fit(f, x0, y1) plt.plot(x0, y1, "o") plt.plot(x0, f(x0 ,params[0], params[1])) plt.legend(["data", "fit"], loc="best") plt.show() and print("mu=%g, sigma=%g" % (params[0], params[1])) resulting in mu=1.80045, sigma=0.372185
score: 5
type: AcceptedAnswer
downvote count: 0

discord
tags question: http://stackoverflow.com/q/50400079
tags question: http://stackoverflow.com/q/50439729
tags question: http://stackoverflow.com/q/50467874
tags question: http://stackoverflow.com/q/50455049
tag name: discord
tags question: http://stackoverflow.com/q/50457509
tags question: http://stackoverflow.com/q/50402437
type: Tag
tags question: http://stackoverflow.com/q/50494829
tags question: http://stackoverflow.com/q/50505434
tags question: http://stackoverflow.com/q/50486917
tags question: http://stackoverflow.com/q/50478264
tags question: http://stackoverflow.com/q/50525752

http://stackoverflow.com/q/50442889
has comment: http://stackoverflow.com/comment/87899834
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50443034
has answer: http://stackoverflow.com/a/50443034
possible better answer: http://stackoverflow.com/a/50443036
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50443036
has comment: http://stackoverflow.com/comment/87899772
has body: I want to convert an object to an iterable. I have the output of the format &gt;&gt;&gt;result[0] &lt;Particle [0.015270307267929021, -0.0009933688866323714, -0.004208897534490854, -0.011275132115610775, 0.0029132053067140572, 0.005608170262839968, 0.0005401367846572976, -0.013393458586919493, 0.0003998091070805884, 0.0002900137732599478]&gt; The full code of the problem is from fstpso import FuzzyPSO def example_fitness( particle ): return sum(map(lambda x: x**2, particle)) if __name__ == '__main__': dims = 10 FP = FuzzyPSO() FP.set_search_space( [[-10, 10]]*dims ) FP.set_fitness(example_fitness) result = FP.solve_with_fstpso() print "Best solution:", result[0] print "Whose fitness is:", result[1] I want to use result[0] as the list. Source
has title: How to convert an object to iterable (list)?
type: Question
has comment: http://stackoverflow.com/comment/87899705
answer count: 2
tagged with: python

http://stackoverflow.com/a/50465314
has body: I have the following: firstArray=[[1,10],[11,31],[32,40],[41,61],[62,78]] secondArray=[[1,10],[12,32],[33,39],[41,78]] for s2, e2 in secondArray: foundYou = [] for entry in firstArray: s1, e1 = entry if s1 &lt;= s2 and e1 &gt;= e2: foundYou.append(entry) # We are fully contained within one entry elif s1 &lt;= s2 and e1 &lt;= e2 and s2 &lt;= e1: foundYou.append(entry) # The start is within this entry but the end is in another elif s1 &gt;= s2 and e1 &gt;= e2 and s1 &lt;= e2: foundYou.append(entry) # The end is within this entry but the start is in another elif s1 &gt;= s2 and e1 &lt;= e2: foundYou.append(entry) # This entry is entirely enveloped print(foundYou) Output: [[1, 10]] [[11, 31], [32, 40]] [[32, 40]] [[41, 61], [62, 78]] If anyone fancies minimising this please do!
score: 1
answers question: http://stackoverflow.com/q/50464273
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/q/50490944
has body: I'm looping over a csv of links, visiting those links, and then trying to write information from those links to a new file: with open("hrefs.csv", "rb") as f: reader = csv.reader(f) for row in reader: newUrl = row[0] response = requests.get(newUrl) newData = response.text newSoup = BeautifulSoup(newData, 'lxml') newstring = '' titles = newSoup.findAll('span', {'id': 'titletextonly'}) prices = newSoup.findAll('span', {'class': 'price'}) newstring += titles[0].text + ',' + prices[0].text + ',' for ana in newSoup.findAll('p',{'class':'attrgroup'}): for myb in ana.findAll('b'): newstring += myb.text + ',' print newstring listFile = open("output.csv", 'wb') writer = csv.writer(listFile) writer.writerow(newstring.encode('ascii', 'ignore').decode('ascii')) There are a couple problems I'm running into. First, I thought the csv would realize that there are comma separated values and put each attribute in a new column. Second, it seems that one letter is getting put in each column. When I simple print each newstring it is giving me a coherent string.
has title: Looping over a csv, trying to write to another csv
tagged with: python
has comment: http://stackoverflow.com/comment/87994801
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/87994979
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50491137
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50491137
answer count: 1
type: Question

http://stackoverflow.com/q/50494746
has comment: http://stackoverflow.com/comment/88002991
has comment: http://stackoverflow.com/comment/88002951
tagged with: tensorflow
favorite count: 0
type: Question
has title: Issues working with tensorflow
has comment: http://stackoverflow.com/comment/88003116
has body: First of all I have read all previous answers on this topic but that didn't solve my problem. When I installed cpu version of tensorflow on my windows 10 it worked fine but when I installed the gpu version I keep getting error message ModuleNotFoundError: No module named 'tensorflow' in spyder on anaconda. I have also tried updating the toolkit but that too didn't solve the problem. enter image description here
has comment: http://stackoverflow.com/comment/88002664
tagged with: python
has comment: http://stackoverflow.com/comment/88002528
has comment: http://stackoverflow.com/comment/88003046
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88003294
has comment: http://stackoverflow.com/comment/88002918
has comment: http://stackoverflow.com/comment/88002900
has comment: http://stackoverflow.com/comment/88003085
accepted answer: http://stackoverflow.com/a/50494986
has comment: http://stackoverflow.com/comment/88002879
score: 1
has answer: http://stackoverflow.com/a/50494986
has comment: http://stackoverflow.com/comment/88002432
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/88082901
comment on: http://stackoverflow.com/q/50535323
score: 0
has text: I wrote this code 'workon facecourse-py3' than try to import the lib.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87830746
type: AnswerComment
has text: Thanks a lot I will try that as soon as a can and keep you post !=)
score: 0
comment on: http://stackoverflow.com/a/50403307
type: Comment

http://stackoverflow.com/comment/87811533
type: Comment
score: 0
has text: Can you explain your use case better? Sounds like you need to define a static method.
type: QuestionComment
comment on: http://stackoverflow.com/q/50397904

http://stackoverflow.com/comment/88000271
has text: In the above post, "output" as my desired output. Please let me know if its not clear.
type: Comment
comment on: http://stackoverflow.com/q/50491747
score: 0
type: QuestionComment

http://stackoverflow.com/q/50475502
linked to: http://stackoverflow.com/q/2612802
has answer: http://stackoverflow.com/a/50475591
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Assignment to a 2d list
score: 1
linked to: http://stackoverflow.com/q/240178
has body: I was having a go at making a simple machine learning program so I could understand more about AI, but ran into a problem. My program has a 2D list (101 lists of 3 Boolean values (303 total)). It does several loops, and has to set 1, or 2 values from one of the sub lists to True in each loop. When running my program, all values changed to true far too quickly. At first, I thought this might be due to bad luck with random(), but then I saw that all the values changed after only 90 to 100 loops, which should be impossible. I decided to experiment in the shell. &gt;&gt;&gt; Choises=[[False]*3]*101 &gt;&gt;&gt; Choises[1][1]=True &gt;&gt;&gt; Choises [[False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [False, True, False], [F…
tagged with: python
duplicate of: http://stackoverflow.com/q/240178
accepted answer: http://stackoverflow.com/a/50475591

http://stackoverflow.com/comment/88027683
type: Comment
comment on: http://stackoverflow.com/q/50506610
score: 0
type: QuestionComment
has text: Don't know is `df` really a Pandas dataframe? what does `type(df)` show?

http://stackoverflow.com/a/50541054
answers question: http://stackoverflow.com/q/50540807
downvote count: 0
has body: Technically yes. Your code has to capture the exception in except and handle any partial actions in try block that may have happened. The logic to all this should be after the excpet block def i_div(x,y): exp = None try: res = x/y; except Exception as e: exp = e if isinstance(exp, ZeroDivisionError) and x == 0: return 'undefined' elif isinstance(exp, ZeroDivisionError): return 'infinity' elif isinstance(exp, TypeError): return 'some_value missing' else: return res i_div(1, 0) i_div(0, 0) i_div(0, 1) i_div(1, 2) However note that this code becomes very messy and prone to error, since ou have to anticipate all possible scenarios where the exception may or may not have occurred along with the partial/complete results. If possible avoid such approach. Exception is a way to identify some bad is is preventing the expected flow (success case) of the program.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88238033
score: 1

http://stackoverflow.com/comment/87949768
has text: Need define parameter `values` like `dfFFB = pd.pivot_table(dfFF, index='Country', columns='Sector', values='Amount', aggfunc='sum', fill_value=0)`
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/50468322
type: Comment

http://stackoverflow.com/comment/87817973
has text: Please can you add the output of the command `apt-cache policy libpython3.6-stdlib python3-lib2to3` to your question?
comment on: http://stackoverflow.com/q/50397705
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88437807
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50392007
type: Comment
has text: and in this answer there is no way define to save my uploaded data to dynamodb ? like I am getting "errorType": "ResourceNotFoundException", "errorMessage": "An error occurred (ResourceNotFoundException) when calling the IndexFaces operation: The collection id: athlete_collection does not exist"

http://stackoverflow.com/a/50488644
has comment: http://stackoverflow.com/comment/87990387
has body: A basic thing going wrong here is you are plotting a point as a line. list3b = [121800016.0, nan, nan....... Goes from one point to nothing. If you change the second nan to a value: list3b = [121800016.0, 121800016.0, nan, ..... then you will see a result. Maybe you should plot those values as bars or scatter points.
has comment: http://stackoverflow.com/comment/87990144
answers question: http://stackoverflow.com/q/50488251
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87962098
type: Comment
comment on: http://stackoverflow.com/q/50474051
score: 0
type: QuestionComment
has text: Also, weird thing is I can't uninstall pip in Pycharm as the button is disabled.

http://stackoverflow.com/q/50489450
favorite count: 0
has body: I have implemented a genetic algorithm in python 3, and have posted a question on code review with no answers yet, basically because my algorithm is running very slowly. By selectively commenting out different parts of my code, I have narrowed down the bottleneck to this section of code, the crossover algorithm: def crossover(self, mum, dad): """Implements ordered crossover""" size = len(mum.vertices) # Choose random start/end position for crossover alice, bob = [-1] * size, [-1] * size start, end = sorted([random.randrange(size) for _ in range(2)]) # Replicate mum's sequence for alice, dad's sequence for bob for i in range(start, end + 1): alice[i] = mum.vertices[i] bob[i] = dad.vertices[i] # # Fill the remaining position with the other parents' entries # current_dad_position, current_mum_position = 0, 0 # # for i in chain(range(start), range(end + 1, size)): # # while dad.vertices[current_dad_position] in alice: # current_dad_position += 1 # # while mum.vertices[current_mum_position] in bob: # current_mum_position += 1 # # alice[i] = dad.vertices[current_dad_position] # bob[i] = mum.vertices[current_mum_position] # # # Return twins # return graph.Tour(self.g, alice), graph.Tour(self.g, bob) return mum, dad The part which is commented out makes my program runtime go from ~7 seconds to 5-6 minutes (I am running 5000 iterations of the GA). Is there any way this ordered crossover can be carried out more efficiently? What the crossover function does For those unfamiliar, I am implementing an order-based crossover (OX2). Given two arrays of consecutive integers (the parents), two random start/end positions are selected. mum = 4 9 2 8 3 1 5 7 6 dad = 6 4 1 3 7 2 8 5 9 ^ ^ start end The two children then share the resulting slices: child 1 = _ _ 2 8 3 1 _ _ _ child 2 = _ _ 1 3 7 2 _ _ _ ^ ^ Now the remaining slots are filled in with the entries of the other parents in the order in which they appear, as long as repetitions are avoided. So since child 1 has their slice take…
type: Question
score: 1
tagged with: python
tagged with: python-3.x
has title: Genetic algorithm - ordered crossover in python
answer count: 2
has answer: http://stackoverflow.com/a/50489955
tagged with: genetic-algorithm
type: UnansweredQuestion
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50490928
upvote count: 1

http://stackoverflow.com/q/50441027
has comment: http://stackoverflow.com/comment/87896521
has answer: http://stackoverflow.com/a/76978634
has answer: http://stackoverflow.com/a/50441083
has comment: http://stackoverflow.com/comment/87896530
tagged with: python
tagged with: merge
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/50441283
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87896726
linked to: http://stackoverflow.com/q/7204805
linked to: http://stackoverflow.com/q/5946236
linked to: http://stackoverflow.com/q/2365921
has body: I have two dicts that I want to merge: a = {"name": "john", "phone":"123123123", "owns": {"cars": "Car 1", "motorbikes": "Motorbike 1"}} b = {"name": "john", "phone":"123", "owns": {"cars": "Car 2"}} If a and b have a common key on the same nesting level, the result should be a list, with both values in it, which is assigned as the value for the shared key. The result should look like this: {"name": "john", "phone":["123123123","123"], "owns": {"cars": ["Car 1", "Car 2"], "motorbikes": "Motorbike 1"}} Using a.update(b) does not work since it overwrites the shared value of a with the shared value of b, such that result is something like this: {'name': 'john', 'phone': '123', 'owns': {'cars': 'Car 2'}} The goal is to merge the dicts without overwriting and to keep all information related to a specific key (in either of the dicts).
score: 7
has comment: http://stackoverflow.com/comment/87896459
has comment: http://stackoverflow.com/comment/87896599
downvote count: 0
accepted answer: http://stackoverflow.com/a/50441142
upvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/87896563
has answer: http://stackoverflow.com/a/50441142
type: Question
has answer: http://stackoverflow.com/a/50441283
tagged with: union
has title: Recursively merge dicts so that elements with shared key are combined into a list

http://stackoverflow.com/q/50464241
accepted answer: http://stackoverflow.com/a/50464296
has title: Returning the actual index value of max & min values from a Pandas Dataframe column
upvote count: 6
has answer: http://stackoverflow.com/a/50464296
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87942135
has body: How do I print/return the index of a particular value? movies_per_year = pd.DataFrame(movies_per_year) movies_per_year.columns = ["count"] print(movies_per_year) count year 1891 1 1893 1 1894 2 1895 2 1896 2 1898 5 Here, my index is the year. I want to return all the indexes where count is 1. Furthermore movies_per_year.max() returns 5. So, it should return 1898.
type: AnsweredQuestion
score: 5
tagged with: python
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87941855
type: Question
tagged with: pandas
linked to: http://stackoverflow.com/q/17071871
has comment: http://stackoverflow.com/comment/87941832
tagged with: dataframe

http://stackoverflow.com/q/50387146
has title: select distinct records with exclusion after table join
tagged with: sql
has comment: http://stackoverflow.com/comment/87790967
has body: I have 2 tables and I join them. The resulting table contains duplicate ids. How do I just keep the last record for those duplicate records? Furthermore, table3 contains a set of ids that should be removed from the resultant table obtained previously. What should the command be? start_date = datetime.datetime(2018,1,1) cmd1 = "(select id, filename from table1 where group = 1) m" cmd2 = "(select id, type, date from table2 where is_good = 1 and date &gt; '" + start_date.strftime('%Y-%m-%d') +"') n " cmd = "select m.id, m.filename, n.type, n.date, from " + \ cmd1 + " join " + cmd2 + " on " + "m.id = n.id"
score: 0
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87790326
type: Question

http://stackoverflow.com/comment/87867686
comment on: http://stackoverflow.com/q/50426050
type: Comment
type: QuestionComment
has text: `for k in range(len(D)):` looks wrong to me. Leaving questions of style to one side wouldn't you want the length of `AAA` here?
score: 0

http://stackoverflow.com/comment/88012485
comment on: http://stackoverflow.com/q/50499628
type: Comment
has text: If you could [edit] your question with an [mcve] that shows a small sample DataFrame as well as your desired result, people may be able to better understand your issue and provide alternative (perhaps more elegant) solutions.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88080644
type: Comment
has text: @Led, you mean duplicates in `array_1`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50533752

http://stackoverflow.com/comment/87929686
type: Comment
comment on: http://stackoverflow.com/a/50457922
has text: Thank you for your reply, I'll look into Spark and Apache Ignite further
type: AnswerComment
score: 1

http://stackoverflow.com/a/50410579
has body: I believe your asking how to call the function in same class .if so If you want to refer to it, something like this classname.OpendirREF(self).
has comment: http://stackoverflow.com/comment/87836758
has comment: http://stackoverflow.com/comment/87836986
has comment: http://stackoverflow.com/comment/87838356
answers question: http://stackoverflow.com/q/50410272
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87838903

http://stackoverflow.com/comment/88034332
has text: As far as I understood you don't want a specific solution or all solutions but only any specific solution. So if you change (0, 0) (1,1) to (1, 0), (1, 1) you would get one solution which still fullfills y-x=0. I.e. if you are underdetermined add arbitrary constraints until your solution is determined. I think this should work if you only need any solution, shouldn't it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50510558
score: 0

http://stackoverflow.com/comment/130313767
type: QuestionComment
has text: There's python code for the old hash function on https://peps.python.org/pep-0456/ under "Current implementation with modified FNV"
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50470815

http://stackoverflow.com/q/50507947
linked to: http://stackoverflow.com/q/902408
tagged with: hiveql
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50509781
downvote count: 0
type: UnansweredQuestion
answer count: 1
has title: How to pass parameters in hive query when executing using impyla?
tagged with: parameter-passing
tagged with: impyla
favorite count: 0
tagged with: hive
type: Question
has body: I referred to How to use variables in SQL statement in Python? but couldn't get an answer. I am trying what you suggested, but I get this error - :( tbl_nm = 'EMPLOYEE_TABLE' con.execute('select max(emp_id) from schema.?', tbl_nm) Getting below error: Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/site-packages/impala/hiveserver2.py", line 302, in execute configuration=configuration) File "/usr/local/lib/python2.7/site-packages/impala/hiveserver2.py", line 343, in execute_async self._execute_async(op) File "/usr/local/lib/python2.7/site-packages/impala/hiveserver2.py", line 362, in _execute_async operation_fn() File "/usr/local/lib/python2.7/site-packages/impala/hiveserver2.py", line 334, in op parameters) File "/usr/local/lib/python2.7/site-packages/impala/interface.py", line 267, in _bind_parameters raise ProgrammingError("Query parameters argument should be a " impala.error.ProgrammingError: Query parameters argument should be a list, tuple, or dict object &gt;

http://stackoverflow.com/q/50460562
downvote count: 1
possible better answer: http://stackoverflow.com/a/50461097
has answer: http://stackoverflow.com/a/50461097
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has comment: http://stackoverflow.com/comment/87934312
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/50460667
accepted answer: http://stackoverflow.com/a/50460667
has body: How to read the values from the config file which is in XML format looks below.here the tags name1,name2 will increase like name4,name5... xxxxxxxxx yyyyyyyyy zzzzzzzzz 1234 1242 1212
tagged with: configuration-files
tagged with: python
has title: how to read config file in xml formate using python
type: AnsweredQuestion
score: 0
upvote count: 1

http://stackoverflow.com/comment/109425308
comment on: http://stackoverflow.com/a/50436510
score: 0
type: AnswerComment
has text: That was it. But how to keep tzinfo? It's better to store tzinfo…
type: Comment

http://stackoverflow.com/comment/88089016
comment on: http://stackoverflow.com/q/50538447
score: 0
type: QuestionComment
type: Comment
has text: The code has run to anoter problem now Traceback (most recent call last): File "project.py", line 7, in <module> qr = qrtools.QR() AttributeError: module 'qrtools' has no attribute 'QR' but i will check it later

http://stackoverflow.com/q/50408174
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
score: 3
tagged with: anaconda
type: UnansweredQuestion
has body: I am trying to set up a dev environment for python and anaconda in a machine where Visual Studio 2017 is also installed. The problem is, there are too many paths and duplicated installations. I uninstalled all python versions and removed the remained folders. Then I used the Visual Studio installer tool and selected Python and Anaconda The following folders appeared: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64 C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64 These folders contain each one the Script subfolder, where some tools like the package manager pip resides. Now when I use python and pip the found executable is the one under Python36_64 but when I use anaconda it tries to use the python and packages from Anaconda3_64 where the list of installed packages is differente and I would like to keep both installation folders up to date with the latest packages' versions. How can I manage to synchronize both folders?
tagged with: python
has title: Setting up Python / Anaconda environment along with Visual studio
tagged with: visual-studio
answer count: 0

http://stackoverflow.com/q/50476200
upvote count: 9
answer count: 3
has comment: http://stackoverflow.com/comment/87966474
has comment: http://stackoverflow.com/comment/87966145
possible better answer: http://stackoverflow.com/a/66380675
tagged with: python
has comment: http://stackoverflow.com/comment/87966206
has answer: http://stackoverflow.com/a/50476504
favorite count: 0
type: Question
score: 9
accepted answer: http://stackoverflow.com/a/50476472
tagged with: python-3.x
has body: In recent Python 3.x, the default behavior of open is to open files in the universal newlines mode (newline=None), which means that if I open a file like this: f = open("file.txt") then all the different line endings (CRLF/CR/LF) get converted into "\n" when using f.readline(), for line in f:, etc. However, when dealing with sys.stdin, the different line endings are not converted (at least on Linux, reading a CRLF file means that the result of sys.stdin.readline() ends with "\r\n"). This means that sys.stdin is opened using a different newline setting. Is there any way of influencing the parameters that are used for opening sys.stdin? More generally, is there in Python something akin to Perl's binmode that would allow changing the way reading from sys.stdin / writing to sys.stdout works? Just to be clear, I know that I can do the CRLF→LF conversion myself. That is not what this question is about.
has answer: http://stackoverflow.com/a/50476472
downvote count: 0
has answer: http://stackoverflow.com/a/66380675
has comment: http://stackoverflow.com/comment/87966004
has title: Changing the way stdin/stdout is opened in Python 3
has comment: http://stackoverflow.com/comment/87966292
has comment: http://stackoverflow.com/comment/87966136
has comment: http://stackoverflow.com/comment/87966347
has comment: http://stackoverflow.com/comment/87966269
type: AnsweredQuestion

http://stackoverflow.com/q/50524562
answer count: 1
has title: calling functions for a password checker
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88062638
has answer: http://stackoverflow.com/a/50524840
accepted answer: http://stackoverflow.com/a/50524840
upvote count: 1
has body: this is my password checker code (whether it is valid or not) I need to run the password checker for 5 times, until it's valid. If it's valid, I have to break out of the loop. The password should be more than 7 characters. The password needs to include both numbers (at least two) and characters. (If not, return False) There should be no space. If there is anything else than numbers and characters, I need to return False I need to run my password_checker function in the for loop, but I'm not so sure what to say after 'if'. I have tried - if a=False: print(password_checker(i)) print(Invalid password) but it didn't work. Also, I don't understand how should I call my password_checker() in the for loop. Finally, I need to put a break in my for loop if the password in the input is valid. But I'm not sure where is the appropriate part to place it def password_checker(password): a=True num_Count = 0 if password.isalpha() == True: print ("error! needs numbers") a = False if password.isnum() == True: print ("error! needs characters") a = False if password.isspace() == True: print ("error! no space allowed") a = False if len(password)&lt;=8: print ("error! needs more than 8 characters") a = False for i in range(0, 10): num_Count += password.count(i) if num_Count(password.count()) &lt; 2: print("error! needs at least 2 numbers") a = False password = str(input("Enter password: ")) for i in range(0,5): if ____________________: print(password_checker(i)) print("Invalid password") else: print(password_checker(i)) print("Valid password") break How should I correct my code in order to make my function work?
has comment: http://stackoverflow.com/comment/88061099
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88061133
has comment: http://stackoverflow.com/comment/88062609
has comment: http://stackoverflow.com/comment/88061466
downvote count: 5
score: -4

http://stackoverflow.com/comment/131948325
type: Comment
has text: watch_for() is not asynchronous (nor I said it was) but you can make so by running it in its own thread.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50498676

http://stackoverflow.com/comment/88052804
type: Comment
has text: What is the reason to have a process inside a Class as a method? and why do you need a process for such simple task?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50486441

http://stackoverflow.com/a/50534799
score: 0
type: AcceptedAnswer
has body: Thank you for the help of Mark. The solution to this problem is: import cv2 import requests import numpy as np url =r'https://drive.google.com/uc?id=1xrKyFZAIIR_XVhlhYGHlfLvIr5vQ5EnW' resp = requests.get(url).content image = np.asarray(bytearray(resp), dtype="uint8") arr = cv2.imdecode(image, cv2.IMREAD_COLOR)
accepted answer of: http://stackoverflow.com/q/50531745
type: Answer
answers question: http://stackoverflow.com/q/50531745

http://stackoverflow.com/comment/88089922
has text: http://python-reference.readthedocs.io/en/latest/docs/str/escapes.html
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50538989

http://stackoverflow.com/q/50534072
has answer: http://stackoverflow.com/a/50534127
downvote count: 0
tagged with: python
type: UnansweredQuestion
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/50534142
has body: r=[True, False,True,False, False] print([i for i in r if str(r[i])=="True"]) this code gives the following unexpected result: [False, False, False] Why is this the behavior? I would expect: [True, True]
score: 4
tagged with: boolean
has answer: http://stackoverflow.com/a/50534170
has title: unexpected result when using a list comprehension on a list of booleans Python
answer count: 5
favorite count: 0
upvote count: 4
has answer: http://stackoverflow.com/a/50534161
type: Question
has answer: http://stackoverflow.com/a/50534186
has comment: http://stackoverflow.com/comment/88080421

http://stackoverflow.com/q/50457095
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87954172
has title: Connection Error using Requests
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: python-requests
has body: link="https://report-abc.com/crp/cdo" node_id_1="00163E0F0D0C1ED895" params={'id':node_id_1, 'list':'142', 'queue': 'gen', 'type': 'crp_stat' } headers = {'accept': 'application/json'} req_obj= requests.get(link, params=params,headers=headers) print(req_obj.url) print(req_obj.status_code) However while it was working yesterday and I was getting the data albeit in html format instead of json. today it is throwing me connection error: ConnectionError: HTTPSConnectionPool(host='report-abc.com', port=443): Max retries exceeded with url: /crp/cdo?queue=gen&amp;list=142&amp;id=00163E0F0D0C1ED895&amp;type=crp_stat (Caused by NewConnectionError('&lt;urllib3.connection.VerifiedHTTPSConnection object at 0x107362a90&gt;: Failed to establish a new connection: [Errno 61] Connection refused',)) I have tried the suggestions mentioned in this stack overflow question including installing pyopenssl: Max retries exceeded with URL But it doesn't seem to help. Any idea would be very appreciated. Thanks
favorite count: 0
linked to: http://stackoverflow.com/q/23013220
has comment: http://stackoverflow.com/comment/87960002

http://stackoverflow.com/q/50412002
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50412206
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/50412206
has body: I have some recorded data from sensor done over night. I want to plot the result as a graph with pyplot. The source file is a csv of timestamp, value. For parsing date I use: pd.read_csv(..., date_parser=pd.datetime.strtime(x, 'H%:%M:%S:%f'),...) The timestamp of the data is from 23:30:00:000 to 02:30:00:000(only time). When plot'ing my dataframe pyplot assume that the data I want to plot after 23:59:59 is supposed to by plotted earlier that same day. It is because the day(date) is the same for all timestamps, even tough the day changed. ... 1900-01-01 23:20:27.832 95.0 1900-01-01 23:20:28.165 95.0 ... ... 1900-01-01 02:01:14.247 95.0 1900-01-01 02:01:14.580 95.0 ... The questions is therefore, can I and how can I ignore date and just plot the hours/time sequentially. Or, how do I read in data from cvs that add one day to the timestamp when needed.
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50412745
has title: How to plot a Pandas df with index timestamp being over midnight, but same date
has answer: http://stackoverflow.com/a/50412745
type: Question

http://stackoverflow.com/q/50529226
has comment: http://stackoverflow.com/comment/88070416
tagged with: pandas
has title: Pandas giving memory error
has answer: http://stackoverflow.com/a/50530410
type: Question
tagged with: python-3.x
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I have the code that goes to almost 10K+ csv files and each file has almost 16K + lines having multiple columns. I run the code and after 5 minutes I got this below error. I can understand that if I set low_memory=False, it will suppress error. But how to fix this issue ? The error seems coming because of below. Can it be fixed? df.groupby(['A', 'B'])['C'] DtypeWarning: Columns (9,11,12,13,14) have mixed types. Specify dtype option on import or set low_memory=False. File "\Python36-32\lib\site-packages\pandas\io\parsers.py", line 705, in parser_f return _read(filepath_or_buffer, kwds) File "\Python36-32\lib\site-packages\pandas\io\parsers.py", line 451, in _read data = parser.read(nrows) File "\Python36-32\lib\site-packages\pandas\io\parsers.py", line 1083, in read df = DataFrame(col_dict, columns=columns, index=index) File "\Python36-32\lib\site-packages\pandas\core\frame.py", line 330, in __init__ mgr = self._init_dict(data, index, columns, dtype=dtype) File "\Python36-32\lib\site-packages\pandas\core\frame.py", line 461, in _init_dict return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype) File "\Python36-32\lib\site-packages\pandas\core\frame.py", line 6140, in _arrays_to_mgr return create_block_manager_from_arrays(arrays, arr_names, axes) File "\Python36-32\lib\site-packages\pandas\core\internals.py", line 4632, in create_block_manager_from_arrays blocks = form_blocks(arrays, names, axes) File "\Python36-32\lib\site-packages\pandas\core\internals.py", line 4704, in form_blocks int_blocks = _multi_blockify(int_items) File "\Python36-32\lib\site-packages\pandas\core\internals.py", line 4773, in _multi_blockify values, placement = _stack_arrays(list(tup_block), dtype) File "\Python36-32\lib\site-packages\pandas\core\internals.py", line 4816, in _stack_arrays stacked = np.empty(shape, dtype=dtype) MemoryError

http://stackoverflow.com/comment/87929225
type: AnswerComment
has text: Will this keep repeats? If `main_df` has 10 samples per point (angle and radius)? I would like to keep repeats.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50457801

http://stackoverflow.com/comment/87943923
has text: @jezrael please explain. This is an amazing one-liner!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50465216

http://stackoverflow.com/comment/87789519
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50386729
score: 0
has text: Maybe what you are looking for is the codecs library. But all 3 lines of `var1`, `var2`, `var3` are all invalid. For actual help, you should correct them.

http://stackoverflow.com/comment/87874099
has text: cool glad to hear you got a solution
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50420198
type: QuestionComment

http://stackoverflow.com/comment/88000290
comment on: http://stackoverflow.com/q/50493621
has text: As documented here, https://docs.python.org/3/library/stdtypes.html#str.isdigit isdigit() is a string method, it can't be called for integers or floats.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50421509
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87858180
favorite count: 0
type: AnsweredQuestion
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/32400867
tagged with: pandas
tagged with: finance
has answer: http://stackoverflow.com/a/50421938
accepted answer: http://stackoverflow.com/a/50421938
tagged with: dataframe
has title: Google historical prices into pandas dataframe
has body: I want to get daily historical stock prices into a pandas dataframe. I know how to get call the google api using the intraday url of api = 'http://finance.google.com/finance/getprices?q=SPY&amp;i=300&amp;p=3d&amp;f=d,o,h,l,c,' price = pd.read_csv(api, skiprows=8, header=None) But I don't know how to get daily history.
type: Question
downvote count: 0

http://stackoverflow.com/comment/88006186
type: AnswerComment
comment on: http://stackoverflow.com/a/50496477
has text: interesting, this is along the lines of what i would have guessed the answer should look like. will keep in mind that query is standard practice
score: 1
type: Comment

http://stackoverflow.com/q/50479845
has title: not working Morse Code Decryptor in Python
tagged with: python-3.1
has answer: http://stackoverflow.com/a/50479976
tagged with: python
has comment: http://stackoverflow.com/comment/87973107
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50479959
downvote count: 0
answer count: 3
has body: I'm making a program where the Morse Code is decrypted into English. However, when the program is running and I put the Morse Code in (ex. *- which should result in the program printing out A) the program only gives a blank space. message = input("Please type a message to encrypt. ") new_message = "" letters = {"*-": "A", "-***": "B", "-*-*": "C"} for let in message: if let in letters: new_message += letters[let] print(new_message) I'm looking for a way to solve this problem by using the replacing method above.
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50480033
possible better answer: http://stackoverflow.com/a/50480033
has comment: http://stackoverflow.com/comment/87973199
accepted answer: http://stackoverflow.com/a/50479976
has comment: http://stackoverflow.com/comment/87973124
favorite count: 0
type: Question

http://stackoverflow.com/comment/94653326
type: Comment
has text: reopened because part time dupe.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50521987

http://stackoverflow.com/comment/88124072
has text: @seuling um..I get what you mean. so if I am not using `virtualenv` in my config should be `home=/usr/bin/python` ?
comment on: http://stackoverflow.com/q/50480388
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87970781
comment on: http://stackoverflow.com/q/50478594
type: QuestionComment
type: Comment
has text: The operating system is centOS 7.2
score: 0

http://stackoverflow.com/a/50502507
downvote count: 1
answers question: http://stackoverflow.com/q/50502353
type: Answer
score: -1
has body: https://regexper.com I find this helpful when working with RegEx. I think it depends on whether you work on your text char by char, then you might have to do that. If you go line by line, the name lines should not have any numbers in them, so you could work with that, maybe. It also depends on the data that you work with and how sure you are that it is free of errors. If it is always 4 lines per person, you could check line by line and use RegEx to also make sure it matches your expectation so that if you find a number in a name you throw an exception or at least log it somewhere. Hope this helps, good luck!
upvote count: 0

http://stackoverflow.com/comment/87830121
has text: You have to create "coin flipping tree" and cacululate results by iterating trough that tree with 50% propability left/right for e.g. 100 coins. Recommending to have several/user defineable number of layers in the tree. https://www.youtube.com/watch?v=5lpqiGixDd0.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50406664

http://stackoverflow.com/q/50524040
score: 7
has title: How to filter the data use equal or greater than condition in the url?
tagged with: python
downvote count: 0
accepted answer: http://stackoverflow.com/a/50527125
upvote count: 7
has body: I can use the bellow link to filter the id=16's data: http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id=16 this is my list api view: class PhysicalServerTaskListAPIView(ListAPIView): serializer_class = PhysicalServerTaskListSerializer permission_classes = [IsAdminUser] def get_queryset(self): query_params = self.request.query_params filters = {'{}__contains'.format(key): value for key, value in query_params.items() } return PhysicalServerTask.objects.filter(**filters) I have a question, how can I query the id&gt;= 16's data list through the url? I mean whether I can through the: http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id__gte=16 to filter the data. I know I can in the ListAPIView query like this: id_gte = self.request.query_params.copy().get('id_gte') ... qs = PhysicalServerTask.objects.filter(**filters) qs.filter(Q(id__gte=id__gte)) but whether there is a more convenient way to realize this?
answer count: 1
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50527125

http://stackoverflow.com/comment/87845301
score: 0
comment on: http://stackoverflow.com/a/50413679
type: Comment
has text: @martineau agree about the constants
type: AnswerComment

http://stackoverflow.com/a/50430544
downvote count: 0
upvote count: 1
has body: I actually found the answer myself: humanfriendly library. Just added this code: from humanfriendly.tables import format_pretty_table Changed my Product class to: class Product: def __init__(self, name, price): self.name = name self.price = price def __str__(self): return f'{self.name}\t{self.price}' def __repr__(self): return f'Product({self.name})' def __iter__(self): return iter((self.name, self.price)) And printed it out: column_names = ['Name', 'Price'] print(format_pretty_table(products, column_names)) where products is a list of objects of type Product. Given output: ------------------------------------------------- | Name | Price | ------------------------------------------------- | Nóż Benchmade 62 Balisong | 1 275,00 zł | | Nóż Benchmade 63 Balisong Bowie | 1 290,00 zł | | Nóż Benchmade 67 Balisong | 1 295,00 zł | | Nóż Benchmade 87 Ti Balisong | 2 235,00 zł | ------------------------------------------------- And I didn't have to use fixed-size strings (total waste and it just looks ugly) plus I didn't have to calculate by hand. So I guess that would be an answer to my question, so happy to find that library
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50430337

http://stackoverflow.com/q/50495657
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88025917
answer count: 0
has comment: http://stackoverflow.com/comment/95660413
tagged with: python-3.5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/95624224
has comment: http://stackoverflow.com/comment/88017512
upvote count: 1
tagged with: python
has body: This is the email output when I ran '.body' on my email object. I got the following output: Sender: xxxxxxxxx.com Subject: yyyyyyyy Message-Id: xxxx-xxxx-xx-xxx-xxx@mail.outlook.com> To: xxxxxxx.com instead of the email body text. Am i missing something here ? or is there an alternative way to extract email body content using any of the available ews attributes ( message-id etc) Below is my python code : account = Account( primary_smtp_address=username_to_access, config=config, autodiscover=False, access_type=DELEGATE ) items = account.inbox.all() for mail in items: print(str(mail.body)) OUTPUT: Sender: xxxxxxxxxxx.com Subject: xxxxxxxxxx Message-Id: &lt;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@mail.outlook.com&gt; To: xxxxxxxxxx.com
tagged with: exchangewebservices
has comment: http://stackoverflow.com/comment/88037641
score: 1
tagged with: email
downvote count: 0
has title: EWS exchangelib python: Unable to extract the content of an email using '.body' attribute
tagged with: exchangelib
has comment: http://stackoverflow.com/comment/88030129

http://stackoverflow.com/comment/98015786
type: QuestionComment
comment on: http://stackoverflow.com/q/50478033
has text: @VikramSinghChandel I ended up removing that droplet and creating a new one and that seems to fix it. I also started running Django off of Nginx instead of using the built-in development server
score: 0
type: Comment

http://stackoverflow.com/comment/88041458
score: 0
comment on: http://stackoverflow.com/q/50514409
type: QuestionComment
has text: Yes, it would be simple then. The separator just needs to be something that can't appear in your column names.
type: Comment

http://stackoverflow.com/q/50440686
has comment: http://stackoverflow.com/comment/87896065
has comment: http://stackoverflow.com/comment/87896019
has comment: http://stackoverflow.com/comment/87895761
has comment: http://stackoverflow.com/comment/87895975
has body: I tried using this Python module but I receive this traceback and can not for the life of me figure out how to solve it. I tried to download different geckodriver,firefox, selenium. I am running this on a ubuntu machine in the interactive shell. Any help is greatly appreciated. from selenium import webdriver browser = webdriver.Firefox() Traceback (most recent call last): File "", line 1, in File "/home/david/.local/lib/python3.6/site-packages/selenium/webdriver /firefox/webdriver.py", line 170, in init keep_alive=True) File "/home/david/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 156, in init self.start_session(capabilities, browser_profile) File "/home/david/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 245, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/david/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 314, in execute self.error_handler.check_response(response) File "/home/david/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities
has comment: http://stackoverflow.com/comment/87896068
has comment: http://stackoverflow.com/comment/87895991
has title: unresolved traceback using selenium webdriver in python3
tagged with: python
has comment: http://stackoverflow.com/comment/87896412
tagged with: selenium-webdriver
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87895908
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/87795154
has text: Related?: https://github.com/Microsoft/vscode-python/issues/423
comment on: http://stackoverflow.com/q/50389852
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50512912
tagged with: sdk
has answer: http://stackoverflow.com/a/50530821
has body: Python 2.7.10, Docker Version 18.03.1-ce-mac65 (24312) This may be a lack of understanding on my part as to how the docker exec_run command works but I'm struggling to get it to work. The following code works without issue from __future__ import print_function import docker if __name__ == '__main__': client = docker.from_env() image = client.images.pull('oraclelinux:7') container = client.containers.run('oraclelinux:7', command='ls', stderr=True, stdout=True, auto_remove=False, remove=False, detach=True ) log = container.logs(stdout=True, stderr=True, stream=True) for line in log: print(line, end='') container.stop() print(container.status) container.remove() And returns a list of directories in the root directory. However the following which I had hoped would be equivalent fails. from __future__ import print_function import docker if __name__ == '__main__': client = docker.from_env() image = client.images.pull('oraclelinux:7') container = client.containers.create('oraclelinux:7', command='/bin/bash', auto_remove=False) container.start() log = container.exec_run('ls', stderr=True, stdout=True, detach=True) for line in log: print(line, end='') container.stop() print(container.status) container.remove() with the following error /Users/user/PythonVirtualEnv/bin/python "/Users/user/DockerAutomation.py" Traceback (most recent call last): File "/Users/user/DockerAutomation.py", line 16, in &lt;module&gt; detach=True) File "/Users/user/PythonVirtualEnv/lib/python2.7/site-packages/docker/models/containers.py", line 185, in exec_run resp['Id'], detach=detach, tty=tty, stream=stream, socket=socket File "/Users/user/PythonVirtualEnv/lib/python2.7/site-packages/docker/utils/decorators.py", line 19, in wrapped return f(self, resource_id, *args, **kwargs) File "/Users/user/PythonVirtualEnv/lib/python2.7/site-packages/docker/api/exec_api.py", line 162, in exec_start return self._result(res) File "/Users/user/PythonVirtualEnv/lib/python2.7/site-packages/docker/api/client.py", line …
tagged with: python
tagged with: docker
has answer: http://stackoverflow.com/a/50513710
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50513710
favorite count: 0
possible better answer: http://stackoverflow.com/a/50530821
has title: Python Docker SDK docker exec_run fails whilst run works

http://stackoverflow.com/comment/95646244
comment on: http://stackoverflow.com/a/50613191
type: Comment
has text: How did you end up structuring the document? We also want to store xUnit reports in ES but struggling a bit with nested objects. Just storing them is not a problem but if you want to query later the index and visualize some reports (eg. most long running tests, test duration between X and Y seconds, etc.) is not really easy.
score: 2
type: AnswerComment

http://stackoverflow.com/comment/87893787
type: QuestionComment
has text: `if not x > y:` => simplify as `if x <= y` that's already better...
score: 0
comment on: http://stackoverflow.com/q/50439839
type: Comment

http://stackoverflow.com/q/50431592
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87885820
tagged with: python
has answer: http://stackoverflow.com/a/54140019
has comment: http://stackoverflow.com/comment/94788862
has body: In Python, Pandas: g = pd.Series(dict(a = 5, b =datetime(2018, 1,1))) g['datetime'] = pd.Timestamp('2018-01-02') g returns: a 5 b 2018-01-01 00:00:00 datetime 1514851200000000000 dtype: object Anyone has an idea why the timestamp is converted to its int value here, and how to avoid the problem and properly attach a timestamp to the Series?
tagged with: pandas
has comment: http://stackoverflow.com/comment/87878368
answer count: 1
has comment: http://stackoverflow.com/comment/87878155
has title: Assigning a timestamp value to a series with pandas creates an int instead
favorite count: 0
score: 8
type: Question
upvote count: 8

http://stackoverflow.com/q/50497926
has comment: http://stackoverflow.com/comment/88008756
has body: I need help with something. I'm using PyQT to make a game in Python. So, I'm trying to change the background image of the self.botaoVermelho for 1 second (basically, the button "activates" and after 1 second it "deactivates"), but I don't know how to do it because I need to do this WITHOUT clicking on the button. This is my code: class Interface(Mediado): def __init__(self, janela): self.janela = janela self.centralwidget = QtWidgets.QWidget(self.janela) self.botaoVermelho = QtWidgets.QPushButton(self.centralwidget) self.menubar = QtWidgets.QMenuBar(self.janela) self.statusbar = QtWidgets.QStatusBar(self.janela) self.configuraUi() def configuraUi(self): self.janela.setObjectName("Genius") self.janela.resize(451, 498) self.janela.setStyleSheet("background-color:#1d1d1d;") self.centralwidget.setObjectName("centralwidget") self.botaoVermelho.setGeometry(QtCore.QRect(230, 20, 200, 200)) self.botaoVermelho.setStyleSheet("#botaoVermelho{\n" "background-color:transparent;\n" "border-image: url(\"src/images/bt_vermelho.png\");\n" "}\n" "\n" "#botaoVermelho:pressed{\n" "background-color:transparent;\n" "border-image: url(\"src/images/bt_vermelhoAct.png\");\n" "}") self.botaoVermelho.setObjectName("botaoVermelho") self.botaoVermelho.raise_() self.janela.setCentralWidget(self.centralwidget) self.menubar.setGeometry(QtCore.QRect(0, 0, 451, 21)) self.menubar.setObjectName("menubar") self.janela.setMenuBar(self.menubar) self.statusbar.setObjectName("statusbar") self.janela.setStatusBar(self.statusbar) _translate = QtCore.QCoreApplication.translate self.janela.setWindowTitle(_translate("Genius", "MainWindow")) QtCore.QMetaObject.connectSlotsByName(self.janela) I'm using QtDesigner/QtCreator to create the design of interface and using a terminal command to convert .ui -> .py Thanks if you can help me.
type: AnsweredQuestion
score: 0
tagged with: interface
tagged with: python
has answer: http://stackoverflow.com/a/50498131
type: Question
has comment: http://stackoverflow.com/comment/88008873
has title: How to send a pressed event to a QPushButton PyQT5?
tagged with: pyqt
answer count: 1
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/50498131

http://stackoverflow.com/a/50422719
has comment: http://stackoverflow.com/comment/87860539
has body: It appears are looping way more than you have to. For every student you do NxN iterations, where N is the total number of classes. But your student has only taken a subset of those classes. So you can cut down on iterations significantly. Your have_taken_both_courses() lookup is also more expensive than it needs to be. Something like this will probably go a lot faster: import numpy as np import itertools import pandas as pd df = pd.read_table('/path/to/data.tsv') students_df = pd.DataFrame(df['student'].unique()) students_lkp = {x[1][0]: x[0] for x in students_df.iterrows()} classes_df = pd.DataFrame(df['class'].unique()) classes_lkp = {x[1][0]: x[0] for x in classes_df.iterrows()} df['student_key'] = df['student'].apply(lambda x: students_lkp[x]) df['class_key'] = df['class'].apply(lambda x: classes_lkp[x]) df.set_index(['student_key', 'class_key'], inplace=True) matr = np.zeros((len(classes_df), len(classes_df))) for s in range(0, len(students_df)): print s # get all the classes for this student classes = df.loc[s].index.unique().tolist() for x, y in itertools.permutations(classes, 2): matr[x][y] += 1
has comment: http://stackoverflow.com/comment/87860450
upvote count: 3
has comment: http://stackoverflow.com/comment/87860365
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50422052
has comment: http://stackoverflow.com/comment/87860564
score: 3
answers question: http://stackoverflow.com/q/50422052
type: Answer

http://stackoverflow.com/a/50482231
answers question: http://stackoverflow.com/q/50471676
has comment: http://stackoverflow.com/comment/87996803
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88015813
has body: Its because you have URL http://www.piaov.com and scrapy ignores the duplicate URLs unless dont_filter=True is specified in Request like Request(url_here, dont_filter=True) Also I don't like your logic of scraper, why are you calling parse_item at all? it is not necessary. Please see the code below and do it like that. import scrapy class PvSpider(scrapy.Spider): name = 'pv' allowed_domains = ['www.piaov.com'] start_urls = ['http://www.piaov.com/'] def start_requests(self): yield scrapy.Request(url='http://www.piaov.com/list/7.html') def parse(self, response): for name in response.xpath("//ul[@class='mlist']//li/a/@title").extract(): yield {"name": name} for p in range(2, 7): yield scrapy.Request(url='http://www.piaov.com/list/7_{}.html'.format(p), callback=self.parse)
accepted answer of: http://stackoverflow.com/q/50471676
type: Answer

http://stackoverflow.com/a/50534124
answers question: http://stackoverflow.com/q/50533940
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: you could try the same using apply function dates2[dates2.apply(lambda x: x['date'] &lt;= most_recent_dates1,axis=1)]

http://stackoverflow.com/q/50392373
tagged with: python
has answer: http://stackoverflow.com/a/50401446
accepted answer: http://stackoverflow.com/a/50401446
type: AnsweredQuestion
score: 0
has title: Not able to use installed libraries
tagged with: amazon-ec2
answer count: 1
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/87825760
has body: I have installed face_recognition model using command pip3 install face_recognition and it is installed in my AWS instance. But while importing face_recognition in my jupyter notebook it is giving me import error. Thanks
has comment: http://stackoverflow.com/comment/87814734

http://stackoverflow.com/q/50393828
has title: keras_contrib - load_all_weights causing ValueError due to optimizer weights
type: Question
has body: I have a Keras model that with layers Embedding, LSTM, and Dropout, as well as the CRF implementation of keras_contrib. I was trying to resume the training of a partly-trained model weights of which I had previously saved. However, when I tried loading a previously trained model via save_load_utils.load_all_weights of keras_contrib, I received the following error. line 108, in load_all_weights: model.optimizer.set_weights(optimizer_weight_values) line 113, in set_weights: 'of the optimizer (' + str(len(params)) + ')') ValueError: Length of the specified weight list (36) does not match the number of weights of the optimizer (0)model.optimizer.set_weights(optimizer_weight_values) Apparently, the list of optimizer weights have the length 0. In keras implementation of the optimizers.py it is stated that set_weights "should only be called after computing the gradients, (otherwise the optimizer has no weights)." I was wondering how to somehow manually initialize the optimizer weights so that the model weights I am trying to load can overwrite them. I thought of training the model for a single epoch with a dummy batch of size 1, but are there any other, more elegant ways to achieve this? The entire code is on Github, but below is the model I trained, to provide a brief reference. # Initialize vocab_size & embedding_weights # Initialize C, U, N, M, H model = Sequential() embedding_layer = Embedding(vocab_size, N, weights=[embedding_weights], mask_zero=True, embeddings_regularizer=regularizers.l2(0.0001)) model.add(TimeDistributed(embedding_layer, input_shape=(C, U))) model.add(TimeDistributed(Bidirectional(LSTM(M // 2, return_sequences=True, kernel_regularizer=regularizers.l2(0.0001))))) model.add(TimeDistributed(Dropout(0.2))) model.add(TimeDistributed(GlobalMaxPooling1D())) model.add(Bidirectional(LSTM(H // 2, return_sequences = True, kernel_regularizer=regularizers.l2(0.0001)))) model.add(Dropout(0.2)) crf = CRF(num_tags, sparse_target=False, kernel_regularizer=regulariz…
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: keras
answer count: 1
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/50805539
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50805539
score: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/88000384
comment on: http://stackoverflow.com/a/50473213
has text: Thanks again, this worked as expected once I brought my code base in line with the sample code I provided.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87867912
score: 0
type: Comment
has text: What is the size of window you provided in the game?
type: QuestionComment
comment on: http://stackoverflow.com/q/50426629

http://stackoverflow.com/comment/88134377
comment on: http://stackoverflow.com/a/50533752
type: Comment
score: 0
type: AnswerComment
has text: yes duplicates must be recounted both array 1 and 2

http://stackoverflow.com/q/50436845
tagged with: pymongo
has title: MemoryError with too large cursor in PyMongo with Pagination
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has body: I have a cursor of objects that I'm trying Paginate. The total items I want is 25, but the way Pagination with Django works, it requires the whole cursor. In private testing, presumably because my home box has more RAM and the like, I do not have these issues. However, when pushing to the production machine, which has only 2GB of memory, I get a MemoryError, presumably because the cursor is too big. I can use .limit(25) and .skip() in order to only retrieve 25 things at a time, however in order for Pagination to work, I need the total number of objects. Unfortunately, .count() seems to require getting the entire data of the cursor. Ideally, I can make this work if I can somehow get the size of a lookup and only 25 actual objects out of the cursor. So I suppose the question is, is there a way to get a cursor's size that's not via .count() (which gets the whole cursor's data). lookup = players.find({field: {'$exists': True}}).sort(field, DESCENDING) //This returns a MemoryError lookup = players.find({field: {'$exists': True}}).limit(25).skip(25).sort(field, DESCENDING) //This does NOT return a Memory Error. However, when I do the following: lookup.count() //This also has a MemoryError. For clarification, I am using Django 1.5.11 and pymongo 3.2.1.
has answer: http://stackoverflow.com/a/50440822
favorite count: 0
type: Question
score: 1
tagged with: python
tagged with: mongodb
type: UnansweredQuestion

http://stackoverflow.com/comment/88079866
score: 0
type: AnswerComment
has text: So are you giving a bunch of images as x and the coordinate vector as y?
comment on: http://stackoverflow.com/a/50525464
type: Comment

http://stackoverflow.com/comment/87961040
has text: first thing you need if you doubt about a value : print it. If you're not sure about the result of `request.form['actual_amount_name']`, just print it or use a debugger to pause the program in your function. Then did you give a look at these answers ? https://stackoverflow.com/questions/17887519/how-to-use-queryselectfield-in-flask
comment on: http://stackoverflow.com/q/50472831
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88039623
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50497472
has text: Read about `LOAD_LIBRARY_AS_DATAFILE` [here](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx). It simply maps the DLL into memory and does no other preparation like looking for other dependencies or preparing the functions to be called. If method 1 doesn't work, it looks like a dependency is missing.
type: Comment

http://stackoverflow.com/comment/88077585
type: AnswerComment
score: 1
has text: Maybe you should use `read_until` with a timeout, to wait for each prompt.
type: Comment
comment on: http://stackoverflow.com/a/50532123

http://stackoverflow.com/a/68105557
has body: Try giving a width to the line (the last parameter to the line method) and update the display pygame.draw.line(screen, Color_line, (60, 80), (130, 100), 1) pygame.display.update()
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50534617

http://stackoverflow.com/q/50449396
has body: I use pySerial for communication between RaspberryPi 2 and Arduino but after my first 100 write-calls it starts to become very slowly when writing. My Code looks like this: import serial ser = serial.Serial("/dev/ttyACM0", 2000000, write_timeout=0) while True: byteData = getData() sentBytes = ser.write(byteData) if sentBytes == 4: print("All Data was sent successfully!") Everything is fine for the first second but then it hangs and I only send like 4 bytes each second. I also saw this post here but on my Raspbian machine a /dev/serial0 or /dev/ttyS0 doesn't exist. How I get this rushing like in the first second permanently?
type: Question
tagged with: raspbian
tagged with: raspberry-pi
tagged with: pyserial
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50476894
score: 0
has title: Python hangs when using serial.write() on my Raspberry 2
answer count: 1

http://stackoverflow.com/comment/88073866
type: QuestionComment
comment on: http://stackoverflow.com/q/50530893
has text: @Tim-Erwin Yes, that's correct. Because MongoDB docs specifically mention *array field **must** appear as part of the query document*
score: 0
type: Comment

http://stackoverflow.com/a/50416189
downvote count: 0
answers question: http://stackoverflow.com/q/50415752
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/87848236
has comment: http://stackoverflow.com/comment/87848528
has body: try packing the frames, or not using them. frames are used to group widgets together. you can also use "anchor" with "side" import tkinter class Loan: def __init__(self): #Create main Window self.main_window = tkinter.Tk() self.main_window.title("Loan Calculator") #make a frame for alignment self.entry_frame = tkinter.Frame(self.main_window) self.entry_frame.pack(side="right", anchor="n") # Create and pack the widgets for interest rate self.intRate_label = tkinter.Label(self.main_window, \ text='Annual Interest Rate', anchor="w") self.intRate_entry = tkinter.Entry(self.entry_frame, \ width=20) self.intRate_label.pack(side="top", anchor="w") self.intRate_entry.pack(side="top", anchor="w", pady=1) #Create and pack the widgets for number of years self.numYears_label = tkinter.Label(self.main_window, \ text='Number of Years', anchor = "w") self.numYears_entry = tkinter.Entry(self.entry_frame, \ width=20) self.numYears_label.pack(side="top", anchor="w") self.numYears_entry.pack(side="top", anchor="w", pady=1) #Create and pack the widgets for loan Amount self.loanAmount_label = tkinter.Label(self.main_window, \ text='Loan Amount', anchor = "nw") self.loanAmount_entry = tkinter.Entry(self.entry_frame, \ width=20) self.loanAmount_label.pack(side="top", anchor="w") self.loanAmount_entry.pack(side="top", anchor="w", pady=1) #pack the frame #self.entry_frame.pack(side="top", anchor="e") #Create and pack the widgets for monthly payment self.result_label = tkinter.Label(self.main_window, \ text='Monthly Payment', anchor="w") self.monthlyPayment = tkinter.StringVar() # To update avg_label self.monthlyPayment_label = tkinter.Label(self.main_window, \ textvariable=self.monthlyPayment) self.result_label.pack(side="top", anchor="w") self.monthlyPayment_label.pack(side="top", anchor="w") #Create and pack the widgets for total payment self.result2_label = tkinter.Label(self.main_window, \ text='Total Payment', anchor="w") self.totalPayment = tkinter.StringVar() # To update avg_label se…
score: 2

http://stackoverflow.com/comment/88053742
comment on: http://stackoverflow.com/q/50495330
type: Comment
type: QuestionComment
has text: @hcheung Bummer. It still doesn't run on reboot. Take a look at my latest cut and paste code section. Nice to meet you! Hopefully we can talk some more tomorrow night. Signing off for now.
score: 0

http://stackoverflow.com/comment/87862729
type: QuestionComment
comment on: http://stackoverflow.com/q/50409623
score: 0
has text: `url = http://my_ip` should be `url = http://my_ip:6800`
type: Comment

http://stackoverflow.com/comment/87995125
type: Comment
type: QuestionComment
has text: For example, using BeautifulSoup you'd just use `[l['href'] for l in BeautifulSoup(content).select('a[href]')]`
comment on: http://stackoverflow.com/q/50491037
score: 1

http://stackoverflow.com/q/50458910
downvote count: 0
has comment: http://stackoverflow.com/comment/87956212
has answer: http://stackoverflow.com/a/50662562
accepted answer: http://stackoverflow.com/a/50662562
answer count: 1
tagged with: websocket
has body: Hello Everyone and thank you for your time. In the previous couple of days I have been undergoing a little project of mine to create a online chatbot for LINE. I understand the API but ran into a problem. I am trying to get my chabot to use online responses to user text. To accomplish this I am trying to use a websocket between python and JavaScript. The API I am using is in python hence the websocket must also be written in Python. I picked asyncio websockets. In short, I am trying to fetch a response from a user input on Line --> Send that response over a websocket to my javascript in a browser console --> The javascript will proceed with it's logic and send the response back to the server --> the Program will proceed with it's execution. My problem is that both the Websocket programming as well as my Line programming use a loop. The Line Code can be seen at https://github.com/fadhiilrachman/line-py/blob/master/examples/groupbot.py As you can see at the end of the code there is a while statement which traces the READ_MESSAGE Function over and over again for each message. You can ignore the NOTIFIED_LEAVE one. So basically my code while proceed with it's own logic and then do something like: else: #ExternalBot code ExtText = text[6:] I now wish to send this ExtText over my websocket to my javascript which will fetch a response from the browser and send it back. The javascript will do something like this: exampleSocket = new WebSocket("ws://192.168.1.9:8765/") exampleSocket.onmessage = function(e){ var server_message = e.data; console.log(server_message); (logic) exampleSocket.send(response); Now this is where the problem begins as I simply do not know how to proceed. The python asyncio Websockets requires a loop to run as seen below: async def Send(websocket, path): await websocket.send(ExtText) await Receive(websocket, path) async def Receive(websocket, path): resposne = await websocket.recv() if response is None: await Recieve(websocket, path) else: print (Respon…
tagged with: javascript
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87968269
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88002052
tagged with: bots
tagged with: python-asyncio
tagged with: python
has title: Python - Bots, Asyncio, Javascript, and Loops
has comment: http://stackoverflow.com/comment/88011001
upvote count: 2
has comment: http://stackoverflow.com/comment/88002072

http://stackoverflow.com/a/50419909
has comment: http://stackoverflow.com/comment/87855554
score: 3
type: Answer
has body: Using split: filename = "3D_710.png" # create a list of the parts of the file name separated by "_" filename_parts = filename.split("_") # new_file is only the last part new_file = filename_parts[-1] print new_file # 710.png Full example including rename, assuming Images is relative to the directory containing our Python script: from os import listdir, rename from os.path import isfile, join, realpath, dirname dir_path = dirname(realpath(__file__)) images_path = join(dir_path, "Images") only_files = [f for f in listdir(images_path) if isfile(join(images_path, f))] for file in only_files: filename_parts = file.split("_") # new_file is only the last part new_file = filename_parts[-1] rename(join(images_path, file), join(images_path, new_file))
accepted answer of: http://stackoverflow.com/q/50419852
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50419852

http://stackoverflow.com/q/50443248
tagged with: python
tagged with: python-3.6
has title: python3: Can I get cartesian product of 'one' 3d list?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87900444
score: 0
duplicate of: http://stackoverflow.com/q/533905
linked to: http://stackoverflow.com/q/3480184
answer count: 1
has body: I have a list looks like below [['a'], ['b'], [[1], [2], [3]], ['d']] and I need to get [['a'], ['b'], [1], ['d']], [['a'], ['b'], [2], ['d']], [['a'], ['b'], [3], ['d']] I saw few posts and found itertools.product, but I think this needs multiple lists in same dimension as argument. Is there any way to get the result?
duplicate of: http://stackoverflow.com/q/3480184
type: Question
linked to: http://stackoverflow.com/q/2921847
has answer: http://stackoverflow.com/a/50443353
accepted answer: http://stackoverflow.com/a/50443353

http://stackoverflow.com/comment/87886205
comment on: http://stackoverflow.com/a/50435495
score: 0
type: Comment
has text: If you can point out the typo in a comment, then just do that. If it's too complicated to describe in a comment, feel free to write a proper answer, but be aware that you will lose any rep gained if the question gets deleted.
type: AnswerComment

http://stackoverflow.com/comment/87912070
score: 0
type: Comment
type: QuestionComment
has text: On what basis is the code to determine this desired output?
comment on: http://stackoverflow.com/q/50449454

http://stackoverflow.com/comment/87974010
type: AnswerComment
comment on: http://stackoverflow.com/a/50478456
score: 0
has text: @matttree OK, I added (untested) examples for both. There are also some great examples in the linked docs (which obviously don't fit your code as neatly, but they're tested, and well explained). Also, one more note at the end.
type: Comment

google-chrome
tags question: http://stackoverflow.com/q/50489982
tags question: http://stackoverflow.com/q/50505540
tags question: http://stackoverflow.com/q/50452087
type: Tag
tag name: google-chrome
tags question: http://stackoverflow.com/q/50404771
tags question: http://stackoverflow.com/q/50472129
tags question: http://stackoverflow.com/q/50430290
tags question: http://stackoverflow.com/q/50511059
tags question: http://stackoverflow.com/q/50443955
tags question: http://stackoverflow.com/q/50494495
tags question: http://stackoverflow.com/q/50532328

http://stackoverflow.com/comment/89098453
type: QuestionComment
comment on: http://stackoverflow.com/q/50494654
has text: I have the same problem. I'm using pywin32==221, PyQt5==5.10, Python x64 on windows 7-64.
score: 0
type: Comment

http://stackoverflow.com/comment/88089880
type: QuestionComment
score: 2
has text: You can use a combination of PyWin32 and ctypes to get an `IShellItem` for `FOLDERID_ComputerFolder`. Bind it to an `IEnumShellItems` to list the folder. For each item, check if it's a link via `GetAttributes(SFGAO_LINK)`. If it is, get the target shell item by binding to `BHID_LinkTargetItem`, and then get the file-system path via `GetDisplayName(SIGDN_FILESYSPATH)`, which should be a UNC path.
type: Comment
comment on: http://stackoverflow.com/q/50528180

http://stackoverflow.com/comment/87936102
has text: @Doctor PC: Is this what you are expecting ?
type: AnswerComment
comment on: http://stackoverflow.com/a/50434659
type: Comment
score: 0

http://stackoverflow.com/q/50440799
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100161655
downvote count: 0
has body: When I run: $ openssl version -a I get 1.0.2k as version: OpenSSL 1.0.2k 26 Jan 2017 built on: reproducible build, date unspecified platform: darwin64-x86_64-cc options: bn(64,64) rc4(ptr,int) des(idx,cisc,16,int) idea(int) blowfish(idx) compiler: cc -I. -I.. -I../include -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -arch x86_64 -O3 -DL_ENDIAN -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM OPENSSLDIR: "/usr/local/php5/ssl" But when I check the version with python: $ python -c 'import ssl; print(ssl.OPENSSL_VERSION)' I get: OpenSSL 0.9.8zg 14 July 2015 How can I link the latest openssl version? My pip version is ; pip 10.0.1 from /Library/Python/2.7/site-packages/pip (python 2.7) When I try to install some modules using PIP I get [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) error. So trying to upgrade my ssl version in python And How to make my system Openssl version is same as virtualenv version?
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/99982540
has comment: http://stackoverflow.com/comment/139516245
has comment: http://stackoverflow.com/comment/100018457
has comment: http://stackoverflow.com/comment/100018147
tagged with: openssl
tagged with: python-2.7
has title: How to link python 2.7 with latest openssl version in MAC OS?
has comment: http://stackoverflow.com/comment/100018447
has answer: http://stackoverflow.com/a/56805097
tagged with: macos
upvote count: 6
has answer: http://stackoverflow.com/a/50440829

http://stackoverflow.com/q/50503025
has body: I have packaged up a python application using python setup.py sdist bdist_wheelon an Ubuntu machine. I want to upload these files to a proxy server of Artifactory. I am using the following twine command to do it twine upload --repository-url https://apro.example.net.au/api/pypi/example-python -u username -p password dist/* --client-cert /usr/lib/ssl/certs/my_cert.pem When I run the command I am getting the following error SSLError: HTTPSConnectionPool(host='apro.example.net.au', port=443): Max retries exceeded with url: /api/pypi/example-python (Caused by SSLError(SSLError(336265225, '[SSL] PEM lib (_ssl.c:2959)'),)) I have placed my my_certs.pem into /usr/lib/ssl/certs/ and ran update-ca-certificates to make sure the certificates are up to date. When I was trying to figure out what the SSLError was I came across what line it was complaining in _ssl.c in cpython (https://github.com/python/cpython/blob/master/Modules/_ssl.c) What does SSL_TLSEXT_ERR_OK exact mean? I cannot figure out what is wrong with the certificate as it works fine with other applications I run against it.
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
upvote count: 1
tagged with: pypi
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50595432
accepted answer: http://stackoverflow.com/a/50595432
tagged with: twine
tagged with: python
has title: SSL Errors when uploading py file to proxy server via Twine
tagged with: ssl-certificate

http://stackoverflow.com/comment/87857625
score: 0
has text: @mahir, please add trailing in webapp/ in your root/urls
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50421195

http://stackoverflow.com/comment/87969823
score: 0
comment on: http://stackoverflow.com/a/50478103
type: Comment
has text: Thanks, this was exactly what I was looking for, as I was manipulating data frames and arrays !!
type: AnswerComment

http://stackoverflow.com/comment/88516918
type: AnswerComment
has text: @loco.loop True -- although I personally find scopes to be my main tool for organizing a graph. I name scopes and variables, very rarely operations. But that is a personal standpoint of course.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50459642

scipy
tags question: http://stackoverflow.com/q/50414364
tags question: http://stackoverflow.com/q/50520375
tags question: http://stackoverflow.com/q/50491326
tags question: http://stackoverflow.com/q/50437865
tags question: http://stackoverflow.com/q/50496471
tags question: http://stackoverflow.com/q/50451884
tags question: http://stackoverflow.com/q/50530158
tags question: http://stackoverflow.com/q/50506782
tags question: http://stackoverflow.com/q/50453437
tags question: http://stackoverflow.com/q/50452686
tags question: http://stackoverflow.com/q/50484358
tags question: http://stackoverflow.com/q/50514413
tags question: http://stackoverflow.com/q/50496336
tags question: http://stackoverflow.com/q/50438066
tags question: http://stackoverflow.com/q/50457773
tags question: http://stackoverflow.com/q/50459009
tags question: http://stackoverflow.com/q/50423320
tags question: http://stackoverflow.com/q/50475183
tags question: http://stackoverflow.com/q/50463929
tags question: http://stackoverflow.com/q/50517812
tags question: http://stackoverflow.com/q/50405177
tags question: http://stackoverflow.com/q/50406849
tags question: http://stackoverflow.com/q/50520215
type: Tag
tags question: http://stackoverflow.com/q/50470855
tags question: http://stackoverflow.com/q/50490240
tags question: http://stackoverflow.com/q/50452104
tags question: http://stackoverflow.com/q/50500044
tags question: http://stackoverflow.com/q/50411052
tag name: scipy
tags question: http://stackoverflow.com/q/50475732
tags question: http://stackoverflow.com/q/50394811
tags question: http://stackoverflow.com/q/50453388
tags question: http://stackoverflow.com/q/50396666
tags question: http://stackoverflow.com/q/50414900
tags question: http://stackoverflow.com/q/50531652
tags question: http://stackoverflow.com/q/50419778
tags question: http://stackoverflow.com/q/50448837
tags question: http://stackoverflow.com/q/50455246
tags question: http://stackoverflow.com/q/50517794
tags question: http://stackoverflow.com/q/50516862
tags question: http://stackoverflow.com/q/50420702
tags question: http://stackoverflow.com/q/50414144
tags question: http://stackoverflow.com/q/50471374
tags question: http://stackoverflow.com/q/50448199
tags question: http://stackoverflow.com/q/50451649
tags question: http://stackoverflow.com/q/50522488
tags question: http://stackoverflow.com/q/50441741
tags question: http://stackoverflow.com/q/50400456

http://stackoverflow.com/a/50525235
has comment: http://stackoverflow.com/comment/88066796
score: 2
has comment: http://stackoverflow.com/comment/88062913
upvote count: 2
has comment: http://stackoverflow.com/comment/88063487
has comment: http://stackoverflow.com/comment/88066981
downvote count: 0
answers question: http://stackoverflow.com/q/50483439
has comment: http://stackoverflow.com/comment/88066857
type: Answer
has body: The very first thing, the code snippet you are showing as a reference is not for your use case as I had written that code snippet for batch uploads from boto3 where you have to provide image paths in your script along with metadata for image, so the names in your code snippet are metadata.So upto what i get to understand from your question, you want files in a local folder to be uploaded and want to provide custom names before uploading , so this is how you will do that. import os import boto3 s3 = boto3.resource('s3') directory_in_str="E:\\streethack\\hold" directory = os.fsencode(directory_in_str) for file in os.listdir(directory): filename = os.fsdecode(file) if filename.endswith(".jpeg") or filename.endswith(".jpg") or filename.endswith(".png"): strg=directory_in_str+'\\'+filename print(strg) print("Enter name for your image : ") inp_val = input() strg2=inp_val+'.jpeg' file = open(strg,'rb') object = s3.Object('mausamrest','test/'+ strg2) #mausamrest is bucket object.put(Body=file,ContentType='image/jpeg',ACL='public-read') else: continue programmatically , you have to provide path of folder which is hard-coded in this example in directory_in_str variable. then , this code will iterate over each file searching for image , then it will ask for input for custom name and then it will upload your file. Moreover, you want to show these images on your website , so public_read for images have been turned on using ACL , so you can directly use s3 links to embedd images in your webpages like this one. https://s3.amazonaws.com/mausamrest/test/jkl.jpeg This above file is the one i used to test this code snippet. your images will be availbale like this. Make sure you change bucket name. :)

http://stackoverflow.com/comment/87977954
type: QuestionComment
has text: Have you looked at PDFMiner? https://github.com/euske/pdfminer This lets you parse and convert. Not totally sure if this would help you split, but I expect it does.
type: Comment
comment on: http://stackoverflow.com/q/50481346
score: 0

http://stackoverflow.com/q/50524739
tagged with: amazon-web-services
favorite count: 0
tagged with: amazon-s3
has title: Upload image to S3 python
tagged with: python
type: Question
upvote count: 5
score: 5
has answer: http://stackoverflow.com/a/50538544
has comment: http://stackoverflow.com/comment/88061528
type: UnansweredQuestion
has body: I am trying to upload an image to S3 through Python. My code looks like this: import os from PIL import Image import boto from boto.s3.key import Key def upload_to_s3(aws_access_key_id, aws_secret_access_key, file, bucket, key, callback=None, md5=None, reduced_redundancy=False, content_type=None): conn = boto.connect_s3(aws_access_key_id, aws_secret_access_key) bucket = conn.get_bucket(bucket, validate=False) k = Key(bucket) k.key = key k.set_contents_from_file(file) AWS_ACCESS_KEY = "...." AWS_ACCESS_SECRET_KEY = "....." filename = "images/image_0.jpg" file = Image.open(filename) key = "image" bucket = 'images' upload_to_s3(AWS_ACCESS_KEY, AWS_ACCESS_SECRET_KEY, file, bucket, key) I am getting this error message: S3ResponseError: S3ResponseError: 400 Bad Request <?xml version="1.0" encoding="UTF-8"?> <Code>InvalidRequest The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. 90593132BA5E6D6C ... This code is based on the tutorial from this website: http://stackabuse.com/example-upload-a-file-to-aws-s3/ I have tried k.set_contents_from_file as well as k.set_contents_from_filename, but both don't seem to work for me. The error says something about using AWS4-HMAC-SHA256, but I am not sure how to do that. Is there another way to solve this problem besides using AWS4-HMAC-SHA256? If anyone can help me out, I would really appreciate it. Thank you!
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88090685

python-module
tags question: http://stackoverflow.com/q/50391831
tags question: http://stackoverflow.com/q/50486381
type: Tag
tag name: python-module
tags question: http://stackoverflow.com/q/50398429
tags question: http://stackoverflow.com/q/50517423
tags question: http://stackoverflow.com/q/50477348

http://stackoverflow.com/comment/87807446
type: QuestionComment
has text: Can you give examples for `colorsX` and show us exactly what logic you are trying to apply?
score: 3
comment on: http://stackoverflow.com/q/50395811
type: Comment

http://stackoverflow.com/comment/87958001
type: Comment
type: QuestionComment
score: 0
has text: okay, so you have python2 installed, and you have both 2.6 and 2.7 You probably want to use 2.7, so to install `mysql` you could run `python2.7 -m pip install mysql`
comment on: http://stackoverflow.com/q/50471730

azure-storage-emulator
type: Tag
tag name: azure-storage-emulator
tags question: http://stackoverflow.com/q/50528704

http://stackoverflow.com/comment/89786658
score: 3
has text: I found decreasing momentum helped a bit with this.
comment on: http://stackoverflow.com/q/50388003
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87902711
comment on: http://stackoverflow.com/a/50444381
type: Comment
has text: Ok, solved it. I used beautiful soup to find and extract the text body in the "Normal" class div.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50446334
has comment: http://stackoverflow.com/comment/87906626
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87906537
answers question: http://stackoverflow.com/q/50446255
score: 1
type: Answer
has body: I want to dynamically create based on a parameter value that is passed to the function. You can use locals. locals()['df_'+ ABC] = pd.read.... But it's not recommended to do this. Use a dictionary instead. my_dict = {} my_dict['df_' + ABC] = pd.read....... When you want to return value the dataframe just use bracket notation. return my_dict['df_' + ABC]
has comment: http://stackoverflow.com/comment/87906193

http://stackoverflow.com/q/50461333
has answer: http://stackoverflow.com/a/50472906
tagged with: python
has comment: http://stackoverflow.com/comment/87935771
has comment: http://stackoverflow.com/comment/87935964
type: AnsweredQuestion
upvote count: 3
score: 3
has title: Finding the depth of a particular node in a tree using recursion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50461610
favorite count: 0
has comment: http://stackoverflow.com/comment/87936081
has answer: http://stackoverflow.com/a/50461610
possible better answer: http://stackoverflow.com/a/50472906
tagged with: recursion
has body: I'm currently trying to solve a problem where I return the maximum depth a number appears in a tree. For example, if a tree looks like this: 1 / \ 2 3 \ 2 My function should return 2. Yet, my function returns 0 def max_depth(t,value): if t == None: return -1 left = max_depth(t.left, value) right = max_depth(t.right, value) if t.value == value: return 1 + max(left,right) else: return max(left,right) Is my thought process wrong? I should add 1 if the current value matches the one I'm looking for (which is the parameter), and do not add 1 if they do not match. I use max() so it returns the maximum of either the left child or the right child, so I get the child with the higher depth. Is that wrong? Here is the tree class: class TN: def __init__(self,value,left=None,right=None): self.value = value self.left = left self.right = right And here is my construction of the tree: tree4 = TN(2) tree3 = TN(3, left = None, right = tree4) tree2 = TN(2) tree1 = TN(1, left = tree2, right = tree3) print(max_depth(tree1, 2)) That will print 0
has comment: http://stackoverflow.com/comment/87935941
type: Question

http://stackoverflow.com/comment/87909741
comment on: http://stackoverflow.com/q/50448018
score: 0
has text: @YakymPirozhenko I have to do several calculations like this -- this is just a demo case. So I want to, say, get the sum over weekdays, over weekends, over weeknights, and so on, but always for the same `user1-user2` pair. It's also a pretty large dataset (>10GB) with several rows and >1M `user1-user2` pairs, so if I do that, I'd be doing several groupbys over and over...
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/135531136
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/76857787
score: 0
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

http://stackoverflow.com/comment/88006860
score: 0
comment on: http://stackoverflow.com/a/50418378
type: Comment
type: AnswerComment
has text: I've my perfect data now and I don't know how to reach them with this row data = (50 + angle[np.newaxis,:]) / (10 + np.sqrt(distance[:,np.newaxis])). I would like to take my data in the array instead

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/50417731
type: Tag

http://stackoverflow.com/comment/87872307
score: 0
comment on: http://stackoverflow.com/q/50428661
type: Comment
type: QuestionComment
has text: Can you please tell us what `import sys` then `sys.modules['asyncio.tasks']` prints after you see that traceback?

http://stackoverflow.com/q/50478399
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/50477800
linked to: http://stackoverflow.com/q/50483235
tagged with: python
score: -1
has body: Followup question to This last post here about another problem installing spacy directly from source. On its website, spacy gives the option to install directly from source (pip and conda are both failing, I've had slightly more luck with this way). It gives 5 steps to enter in the command line: git clone https://github.com/explosion/spaCy cd SpaCy export PYTHONPATH=pwd pip install -r requirements.txt python setup.py build_ext --inplace I had to modify step 3 to use SET, and then it seemed to run okay. However, when I type in step 4, I get this error message: Command "c:\users\jacqu\appdata\local\programs\python\python37\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\jacqu\\AppData\\Local\\Temp\\pip-install-bo29last\\preshed\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\jacqu\AppData\Local\Temp\pip-record-wve_7ck8\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\jacqu\AppData\Local\Temp\pip-install-bo29last\preshed\ It seems to be a problem installing some part of Spacy called preshed. I have no idea what this error means or how to work around it. In the past I've tried to install the specific parts that I get this error for one at a time, but that doens't seem to work for preshed (pip install preshed also fails with the same error message). If it matters at all, Spacy has a folder on my computer, so it seems to have at least partially installed. Any and all suggestions would be appreciated - python is 3.7 and I'm using Windows 10.
has title: Installing Spacy on Python 3 with Windows 10 fails at installing Preshed
has answer: http://stackoverflow.com/a/50486874
tagged with: spacy
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87992848
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50533070
tagged with: python
has answer: http://stackoverflow.com/a/50533439
type: Question
has body: I have a column in a pandas dataframe where each cell contains a rather long string of words. These strings are from an SQL database and contain a mix of words and alphanumeric id phrases which are not English, separated by spaces. These strings can be up to the character max of SQL. This is also not a small dataframe, i have several million rows. The question is, what is the fastest way to keep only correct English words for each cell? Below is my initial method which seemingly would take days to complete based on the speed suggested from tqdm (hence the progress_apply). import pandas as pd from nltk.corpus import words from tqdm import tqdm def check_for_word(sentence): s = sentence.split(' ') for word in s: if word not in words.words(): s.remove(word) return ' '.join(s) tqdm.pandas(desc="Checking for Words in keywords") df['keywords'] = df['keywords'].progress_apply(check_for_word) Is there a method which would be significantly faster? Thanks for your help! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The answer below was very helpful and took less than a second to run (GREAT IMPROVEMENT!). In the end I had to change from nltk.corpus words to nltk.corpus wordnet, as words was not exhaustive enough of a list for my purposes. The final result ended up being: from nltk.corpus import wordnet from tqdm import tqdm def check_for_word(s): return ' '.join(w for w in str(s).split(' ') if len(wordnet.synsets(w)) &gt; 0) tqdm.pandas(desc="Checking for Words in Keywords") df['keywords'] = df['keywords'].progress_apply(check_for_word) which took 43 seconds to run.
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: performance
has title: How to quickly check strings for correct English words? - Python
has comment: http://stackoverflow.com/comment/88078303
tagged with: nltk
has comment: http://stackoverflow.com/comment/88078356
score: 1
accepted answer: http://stackoverflow.com/a/50533439

http://stackoverflow.com/comment/87952767
type: Comment
comment on: http://stackoverflow.com/a/50469308
has text: I wanted to remove the dates and times, retaining only the other data in each line
type: AnswerComment
score: 0

http://stackoverflow.com/a/50492251
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: Using list/generator comprehensions is preferable (more Pythonic) to map(): def rot_13(string): alph = 'abcdefghijklmnopqrstuwxyz' return ''.join(alph[(alph.find(i)+13) % len(alph)] for i in string)
answers question: http://stackoverflow.com/q/50492150
upvote count: 9
score: 9
accepted answer of: http://stackoverflow.com/q/50492150

http://stackoverflow.com/q/50514678
downvote count: 2
upvote count: 1
has title: file.write appends a new line automatically in python
has answer: http://stackoverflow.com/a/50515241
favorite count: 0
score: -1
type: Question
has answer: http://stackoverflow.com/a/50514724
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88041993
answer count: 2
has comment: http://stackoverflow.com/comment/88041875
has body: I am trying to append multiple words with a word in python for writing it to a file as below : out_file.write(words+'Positive') I am not using \n here. But the output turns out to be in 2 lines as below : It is awesome awesome. Positive What I am expecting is It is awesome. Positive. Please help.

windows
tags question: http://stackoverflow.com/q/50402058
tags question: http://stackoverflow.com/q/50418563
tags question: http://stackoverflow.com/q/50500127
tags question: http://stackoverflow.com/q/50533775
tags question: http://stackoverflow.com/q/50516002
tags question: http://stackoverflow.com/q/50393869
tags question: http://stackoverflow.com/q/50393145
tags question: http://stackoverflow.com/q/50510560
tags question: http://stackoverflow.com/q/50400963
tags question: http://stackoverflow.com/q/50415308
tags question: http://stackoverflow.com/q/50402092
tags question: http://stackoverflow.com/q/50440889
type: Tag
tags question: http://stackoverflow.com/q/50469868
tags question: http://stackoverflow.com/q/50399259
tags question: http://stackoverflow.com/q/50429079
tags question: http://stackoverflow.com/q/50386340
tags question: http://stackoverflow.com/q/50501820
tags question: http://stackoverflow.com/q/50440365
tags question: http://stackoverflow.com/q/50418925
tags question: http://stackoverflow.com/q/50529522
tags question: http://stackoverflow.com/q/50526074
tags question: http://stackoverflow.com/q/50535102
tags question: http://stackoverflow.com/q/50448446
tag name: windows
tags question: http://stackoverflow.com/q/50527401
tags question: http://stackoverflow.com/q/50418775
tags question: http://stackoverflow.com/q/50505179
tags question: http://stackoverflow.com/q/50416336
tags question: http://stackoverflow.com/q/50483796
tags question: http://stackoverflow.com/q/50427217
tags question: http://stackoverflow.com/q/50491740
tags question: http://stackoverflow.com/q/50416391
tags question: http://stackoverflow.com/q/50496756
tags question: http://stackoverflow.com/q/50437855
tags question: http://stackoverflow.com/q/50409001
tags question: http://stackoverflow.com/q/50419637
tags question: http://stackoverflow.com/q/50435421
tags question: http://stackoverflow.com/q/50447755
tags question: http://stackoverflow.com/q/50404891
tags question: http://stackoverflow.com/q/50528180
tags question: http://stackoverflow.com/q/50431294
tags question: http://stackoverflow.com/q/50474349
tags question: http://stackoverflow.com/q/50461995
tags question: http://stackoverflow.com/q/50493670

http://stackoverflow.com/comment/88044384
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50515694
has text: @lial_slasher What do you mean by *embedded*? You can do `arg_parser.parse(shlex.split(input_string))`

http://stackoverflow.com/q/50531919
has title: why do I get ZeroDivisionError?
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88075846
has comment: http://stackoverflow.com/comment/88075951
has body: I am trying to write python program that reads a .csv file. I have in the input file 4 columns/fields and I want to only have 2 in the output with one being a new one. This is the input I am using: MID,REP,NAME,NEPTUN 0,,"people's front of judea",GM6MRT 17,,Steve Jobs,NC3J0K ,0,Brian,RQQCFE 19,9,Pontius Pilate,BQ6IAJ 1,,N. Jesus,QDMXVF 18,,Bill Gates,D1CXLO 0,,"knights who say NI",CZN5JA ,1,"Robin, the brave",BWQ5AU 17,19,"Gelehed, the pure",BY9B8G then the output should be something like this(not full output): NEPTUN,GROWTH BQ6IAJ,-0.5263157894736842 BWQ5AU,inf BY9B8G,0.11764705882352941 RQQCFE,0 The new field called GROWTH is calculated by (REP-MID)/MID. So, I am using two lists to do that: import csv L = [] s =[] with open('input.csv', 'rb') as R: reader = csv.DictReader(R) for x in reader: if x['MID'] != '' or '0' and x['REP'] == '': Growth = -float(x['MID'])/float(x['MID']) L.append(x) s.append(Growth) elif x['MID'] != '' or '0': Growth = (float(x['REP']))-float(x['MID'])/float(x['MID']) L.append(x) s.append(Growth) elif x['MID'] and x['REP'] == '' or '0' : Growth = 0 L.append(x) s.append(Growth) else: Growth = float("inf") L.append(x) s.append(Growth) for i in range(len(s)): L[i]['GROWTH'] = i R.close() with open('output.csv', 'wb') as output: fields = ['NEPTUN', 'GROWTH'] writer = csv.DictWriter(output, fieldnames=fields, extrasaction='ignore') writer.writeheader() writer.writerows(L) output.close() Now, I am not even sure if the code is correct or does what I aim it for, because I am stuck at a ZeroDivisionError: float division by zero at the first ifcondition and I tried many ways to avoid it but I get the same error. I thought the problem is that when there are no values for MID field, I think the dictionary gives it `` value and that can't be transformed to 0 by float(). But it seems that is not the problem, but honestly I have no idea now, so that is why I am asking here. the full error: Growth = -float(x['MID'])/float(x['MID']) ZeroDivisionError: float …
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/50532043
has comment: http://stackoverflow.com/comment/88075867
answer count: 1
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/88075856
type: Question
has comment: http://stackoverflow.com/comment/88075751
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88075787
has comment: http://stackoverflow.com/comment/88075904
has comment: http://stackoverflow.com/comment/88075746
linked to: http://stackoverflow.com/q/26337003
has answer: http://stackoverflow.com/a/50532043
duplicate of: http://stackoverflow.com/q/15112125
tagged with: python

http://stackoverflow.com/a/50416331
score: 2
type: Answer
has body: Just define a lambda that ignores the argument and calls droplets(): commands = { 'create_droplet': partial(create_droplet), 'droplets': (lambda _ : droplets()) }
has comment: http://stackoverflow.com/comment/87848656
answers question: http://stackoverflow.com/q/50416254
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87848720

http://stackoverflow.com/q/50486098
answer count: 2
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/112671867
favorite count: 0
type: Question
has title: How to delete the first line of each group in pandas
has answer: http://stackoverflow.com/a/50486126
has answer: http://stackoverflow.com/a/50486273
linked to: http://stackoverflow.com/q/31226142
tagged with: python
has body: I have a dataframe like this : id values 0 1 3 1 1 6 2 1 3 3 2 7 4 2 6 5 2 3 6 2 9 And I want to delete the first line of each group based on id,the result should like this: id values 1 1 6 2 1 3 4 2 6 5 2 3 6 2 9 I tried it done by: df = df.groupby('id').agg(lambda x:x[1:]),but it doesn't work. Can someone help me?Thanks in advance
possible better answer: http://stackoverflow.com/a/50486273
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/50486126
score: 3

http://stackoverflow.com/a/50489588
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50489369
upvote count: 1
has body: Your found variable is being overwritten on each iteration of the loop. Therefore it will only be True if the last result matches. You don't actually need your found variable at all. If there are results, your results variable will have data in it and you can test for that.

http://stackoverflow.com/comment/88076516
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50531995
has text: Can you please edit your post to include the **full** error traceback? Thanks
type: QuestionComment

import
tags question: http://stackoverflow.com/q/50439309
type: Tag
tags question: http://stackoverflow.com/q/50513580
tags question: http://stackoverflow.com/q/50493214
tags question: http://stackoverflow.com/q/50439879
tags question: http://stackoverflow.com/q/50397890
tags question: http://stackoverflow.com/q/50407658
tags question: http://stackoverflow.com/q/50416710
tag name: import
tags question: http://stackoverflow.com/q/50486647
tags question: http://stackoverflow.com/q/50518168
tags question: http://stackoverflow.com/q/50414255
tags question: http://stackoverflow.com/q/50443388
tags question: http://stackoverflow.com/q/50516450
tags question: http://stackoverflow.com/q/50435100

http://stackoverflow.com/comment/87854897
has text: Does numpy seed effect pytirch?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50412235
type: Comment

http://stackoverflow.com/q/50509481
tagged with: python
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88034770
type: Question
has body: I have various pandas dataframes with up to 2000 time series in it. Obviously, a simple df.plot() doesn't really show anything useful (and takes a few minutes to plot). But at least I can easily get (and plot) a (rolling) mean. Simple example: ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) df = pd.DataFrame(np.random.randn(1000, 14), index=ts.index, columns=list('ABCDEFGHIJKLMN')) mean_df = df.mean(1) rolling_mean = mean_df.rolling(window = 60, center = True) ax = df.plot(style=':') rolling_mean.mean().plot(ax=ax) With this small example, one can probably see how the underlying data "behaves": It's pretty symmetric around zero and most of the data is between +1 and -1, quite a bit is between +1 and +2, as well as -1 and -2, with some stuff happening in the 2/3 bracket and some outliers going up (or down) to almost +(-)4. Why can one easily grasp this? Obviously, it's due to the number of lines per area, and thus the intensity or shading of the area. Becomes even clearer when I go monochrome: However, this lacks a quantification for density or number of lines. How can I turn this into something quantitative? I.e. the 2-4 bracket should have various shades of light grey, 1-2 medium greys, 0-1 dark greys, so that the mean would be placed on top of an almost black zone in the graph, so that I end up with 50 shades of grey and maybe a color bar to boot. I could probably play around with various shades of grey as a base color and see what setting different alphas does for a better visual effect, but this seems hacky. Another option would be to do something like max_df = df.max(1) and min_df = df.min(1) and then use matplotlib to fill between (plt.fill_between(df.index, min_df, max_df)) and rig some way to repeat this for various levels (i.e. 1, 2 and 3 standard deviations away from the mean) so that I would end with some kind of continuous box-plot. But I am wondering if there is a better way to do this. Also: I'm not really sure how …
has answer: http://stackoverflow.com/a/50511339
type: UnansweredQuestion
tagged with: data-visualization
has title: Plotting a large number of "lines" as shading or color intensity
tagged with: matplotlib

http://stackoverflow.com/q/50435338
possible better answer: http://stackoverflow.com/a/50435389
has answer: http://stackoverflow.com/a/50435389
has title: django categorizing model instances
type: Question
accepted answer: http://stackoverflow.com/a/50436650
has answer: http://stackoverflow.com/a/50436650
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
has body: When I run: python3 manage.py makemigrations after saving the below code, it shows error: todo.Task.status: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. I want to categorize every Task instance according to todo, complete or incomplete. This property is to be specified while creating every Task instance. The tasks are to be shown on different columns on HTML page. The code below does not work: from django.db import models STATUS_CHOICES = ('complete', 'incomplete', 'todo') class Task(models.Model): name = models.CharField(max_length = 128) due = models.DateTimeField(blank = True, null = True) status = models.CharField(max_length = 16, choices = STATUS_CHOICES) def __str__(self): return (f"{self.name}") Please Help.
score: 0
answer count: 2

http://stackoverflow.com/a/50541775
has comment: http://stackoverflow.com/comment/88095001
score: 0
has body: I got no error : python.exe temp.py -------------------------------------------------------------------------------------------------------------------------------------------------- Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 Unnamed: 5 Unnamed: 6 Unnamed: 7 0 ... NaN NaN NaN NaN NaN NaN NaN 1 ----------------------------------------------... NaN NaN NaN NaN NaN NaN NaN 2 ABC : - xxxxxxxxxxx NaN NaN NaN NaN NaN NaN NaN 3 Type :- xxxxxxxxxxx NaN NaN NaN NaN NaN NaN NaN 4 Date :- xxxxxxxxxx NaN NaN NaN NaN NaN NaN NaN 5 Till Date :- xxxxxxxxxx NaN NaN NaN NaN NaN NaN NaN 6 Report Index :- xxxxxxxxxx NaN NaN NaN NaN NaN NaN NaN 7 Report Date :- 01-Jul-2017 11:18:41 AM NaN NaN NaN NaN NaN NaN NaN 8 ----------------------------------------------... NaN NaN NaN NaN NaN NaN NaN 9 A PARTY B PARTY DATE TIME DURATION ID ID_A TYPE 10 ----------------------------------------------... NaN NaN NaN NaN NaN NaN NaN 11 XXXXXXXX XXXXXXXX 26-JAN-2017 11:51:54 1 123456788889999 - ZXC 12 XXXXXXXX XXXXXXXX 26-JAN-2017 11:52:06 1 123456788889999 - QWE 13 XXXXXXXX XXXXXXXX 26-JAN-2017 11:52:11 1 123456788889999 - RRR 14 XXXXXXXX XXXXXXXX 26-JAN-2017 11:52:12 1 123456788889999 - BGF 15 XXXXXXXX XXXXXXXX 26-JAN-2017 11:52:25 1 123456788889999 - OOO 16 XXXXXXXX XXXXXXXX 26-JAN-2017 11:53:23 1 123456788889999 - BGF 17 XXXXXXXX XXXXXXXX 26-JAN-2017 11:54:00 1 123456788889999 - NBG 18 XXXXXXXX XXXXXXXX 26-JAN-2017 11:54:38 1 123456788889999 - BGFD 19 XXXXXXXX XXXXXXXX 26-JAN-2017 11:54:39 1 123456788889999 - OIU 20 XXXXXXXX XXXXXXXX 26-JAN-2017 12:03:14 1 123456788889999 - BGF 21 XXXXXXXX XXXXXXXX 26-JAN-2017 12:07:43 1 123456788889999 - GGG 22 XXXXXXXX XXXXXXXX 26-JAN-2017 12:11:53 1 123456788889555 - VVVV 23 XXXXXXXX XXXXXXXX 26-JAN-2017 12:13:12 1 123456788889555 - VVVV 24 XXXXXXXX XXXXXXXX 26-JAN-2017 12:13:12 1 123456788889555 - VVVV 25 XXXXXXXX XXXXXXXX 26-JAN-2017 12:13:44 1 123456788889555 - VVVV 26 XXXXXXXX XXXXXXXX 26-JAN-2017 12:13:44 1 123456788889555 - VVVV 27 NaN NaN NaN NaN NaN N…
type: Answer
has comment: http://stackoverflow.com/comment/88094851
has comment: http://stackoverflow.com/comment/88161696
answers question: http://stackoverflow.com/q/50541190

http://stackoverflow.com/a/50486976
upvote count: 1
score: 1
has body: Using the ast module. import pandas as pd import ast df = pd.DataFrame(["[u'one_element']", "[u'two_elememts', u'two_elements']", "[u'three_elements', u'three_elements', u'three_elements']"]) print(df[0].apply(lambda x: ", ".join(ast.literal_eval(x)))) Output: 0 one_element 1 two_elememts, two_elements 2 three_elements, three_elements, three_elements Name: 0, dtype: object
type: Answer
answers question: http://stackoverflow.com/q/50486821
downvote count: 0

http://stackoverflow.com/a/50479958
has body: Try the same logic with pass DepotList value one by one. instead of passing list in isin(), pass value by iterating list DepotList= ['A', 'B'] result = [] for Depot in DepotList: resultByDepotName =rawdf.loc[rawdf.DepotName.isin(Depot)] list = forecast(resultByDepotName) result.append(list) result will contains forecast values Dont't reassign same dataframe variable of result rawdf.loc[rawdf.DepotName.isin(Depot)]
has comment: http://stackoverflow.com/comment/87981479
has comment: http://stackoverflow.com/comment/87982886
answers question: http://stackoverflow.com/q/50479577
score: 0
has comment: http://stackoverflow.com/comment/87981698
type: Answer

http://stackoverflow.com/q/50520029
has body: I'm not having any luck with pyPDF2 or PDFMiner. The tools always return _______________ for the textboxes even if they are filled in. Does anyone have any idea on how to extract the text within the textbox fields?
favorite count: 0
type: Question
score: 2
linked to: http://stackoverflow.com/q/26494211
has comment: http://stackoverflow.com/comment/88052845
type: UnansweredQuestion
answer count: 1
downvote count: 1
has title: How can I extract text from textboxes within a PDF in Python?
upvote count: 3
has comment: http://stackoverflow.com/comment/88052856
linked to: http://stackoverflow.com/q/34129936
has answer: http://stackoverflow.com/a/50524460
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
linked to: http://stackoverflow.com/q/15583535

http://stackoverflow.com/comment/87805185
has text: I should like to point out that using `assert` is generally only for debug purposes (assert statements are stripped out with `python -o`), but I wanted an easy way to generate a separate `Exception` type to show the usage of multiple `except:` blocks for a single `try:`
type: Comment
comment on: http://stackoverflow.com/a/50394568
type: AnswerComment
score: 0

http://stackoverflow.com/q/50433100
has body: I am using imageio with Python. It seems to have a cleaner API than PIL and consorts, so I would like to continue using imageio instead of other tools. I know how to get image size: height, width, channels = imageio.imread(filepath).shape Is there a way to get the size of an image, without needing to load it fully to memory? This should be possible, isnt't it? At least for a number of formats that (I guess) have the image size in the header?
has comment: http://stackoverflow.com/comment/110349361
downvote count: 0
has title: python imageio image size without loading image to memory
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/87880619
favorite count: 0
has comment: http://stackoverflow.com/comment/87880460
has comment: http://stackoverflow.com/comment/125580898
tagged with: python-imageio
type: Question
linked to: http://stackoverflow.com/q/15800704
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87880537
has comment: http://stackoverflow.com/comment/87880554

http://stackoverflow.com/a/50483101
answers question: http://stackoverflow.com/q/50482829
type: Answer
score: 0
has body: You find the available types there : pyspark.sql.types

http://stackoverflow.com/a/50493679
type: Answer
has body: You can use related_name or related query name for this.
answers question: http://stackoverflow.com/q/50493467
has comment: http://stackoverflow.com/comment/88001235
has comment: http://stackoverflow.com/comment/88000540
score: 0

http://stackoverflow.com/comment/88026679
has text: Is there a way to retrieve every first out of 4 lines? the first line is the name and the fourth line is the phone number.
score: 0
comment on: http://stackoverflow.com/q/50502353
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87831697
has text: My advice is not to do this. Nowhere in the library do we suggest you copy styles like this between cells.
type: QuestionComment
comment on: http://stackoverflow.com/q/50388288
type: Comment
score: 0

join
type: Tag
tags question: http://stackoverflow.com/q/50395463
tags question: http://stackoverflow.com/q/50421534
tag name: join
tags question: http://stackoverflow.com/q/50477220

http://stackoverflow.com/comment/94876321
score: 0
has text: Most of the time encoding is "Arabic(Windows-1256)"
type: AnswerComment
comment on: http://stackoverflow.com/a/54017472
type: Comment

http://stackoverflow.com/comment/88003831
score: 1
comment on: http://stackoverflow.com/q/50495478
has text: @JonasVirkutis, How about choose the option which you feel is *closest* to a good / correct solution? We usually expect correct syntax, but not necessarily code which works as desired.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50396221
type: AnsweredQuestion
upvote count: 5
tagged with: java
has title: Pycrypto AES GCM encryption and Java decryption
tagged with: pycryptodome
has answer: http://stackoverflow.com/a/50396222
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51615028
answer count: 2
tagged with: encryption
accepted answer: http://stackoverflow.com/a/50396222
score: 5
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51615028
tagged with: aes-gcm
has body: I'm using Pycryptodome (a PyCrypto fork) to create AES-GCM ciphertexts. I use the following Python code to encrypt: cek = os.urandom(16) nonce = os.urandom(12) cipher = AES.new(cek, AES.MODE_GCM, nonce=nonce, mac_len=16) ciphertext = cipher.encrypt(message) I then pass this to Java to decrypt: byte[] nonce = new byte[12]; Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv); SecretKeySpec secretKeySpec = new SecretKeySpec(cek, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(nonce); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmSpec); byte[] decBytes = mCipher.doFinal(cipherText); However, I get the following error: Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch! at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:524) at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1023) at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960) at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824) at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436) at javax.crypto.Cipher.doFinal(Cipher.java:2165)

http://stackoverflow.com/q/50438501
has answer: http://stackoverflow.com/a/50438589
answer count: 3
linked to: http://stackoverflow.com/q/11829422
has answer: http://stackoverflow.com/a/50453505
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87891468
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50438552
has title: Count number of occurrences of each unique item in list of lists
downvote count: 5
has comment: http://stackoverflow.com/comment/87921039
upvote count: 6
tagged with: python
has body: I have a list of lists like the following: listoflist = [["A", "B", "A", "C", "D"], ["Z", "A", "B", "C"], ["D", "D", "X", "Y", "Z"]] I want to find the number of sublists that each unique value in listoflist occurs in. For example, "A" shows up in two sublists, while "D" shows up in two sublists also, even though it occurs twice in listoflist[3]. How can I get a dataframe which has each unique element in one column and the frequency (number of sublists each unique element shows up in)?

sublist
tags question: http://stackoverflow.com/q/50444378
tag name: sublist
tags question: http://stackoverflow.com/q/50498879
tags question: http://stackoverflow.com/q/50434060
type: Tag

http://stackoverflow.com/a/52691471
answers question: http://stackoverflow.com/q/50417709
score: 0
has body: I don't have a definitive solution to this but here is what resolved it. First, I copied the kitti_label_map.pbtxt into the data_dir. Then I also copied create_kitti_tf_record.py into the data_dir. And now I copied(this is what made it run in the end) the name and absolute path of the kitti_label_map.pbtxt and pasted it as label_map_path I have no idea why but it worked.
type: Answer

http://stackoverflow.com/q/50539678
type: UnansweredQuestion
answer count: 1
tagged with: python
downvote count: 1
favorite count: 0
has body: What is the easiest way to print a graph in Python? i.e. I am wanting to visualize the maximum clique of a graph. My current data structures are: adjacency_matrix = [[False, True, False, ...], [True, False, True, ...], ..] adjacency_set = [[45, 2], [1, 32], ...] max_clique = [23, 143, 1, 2, 42, 12, 3, ...] # the vertices in the max clique Would I use matplotlib to do this?
linked to: http://stackoverflow.com/q/9213797
score: 2
has title: Printing graph (vertex, edge) in Python
upvote count: 3
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50539811
linked to: http://stackoverflow.com/q/75284417
type: Question
tagged with: graph-theory

http://stackoverflow.com/q/50518218
has answer: http://stackoverflow.com/a/50518393
tagged with: function
score: -5
has title: Why can't we have a variable refer to function in python?
has comment: http://stackoverflow.com/comment/88049092
has comment: http://stackoverflow.com/comment/88049063
has comment: http://stackoverflow.com/comment/88049381
has answer: http://stackoverflow.com/a/50518258
has comment: http://stackoverflow.com/comment/88049043
favorite count: 0
has answer: http://stackoverflow.com/a/50518289
possible better answer: http://stackoverflow.com/a/50518259
type: Question
accepted answer: http://stackoverflow.com/a/50518393
has answer: http://stackoverflow.com/a/50518259
has body: I am learning Javascript and just curious that we can have a variable refer to a function in JS but not in python. Everything in python is an object, and functions in JS are also objects but why do we get an error when a variable refers to a function. My assumption was that we should be able to assign a function to a variable as in JS because they are objects in both the cases. **Javascript code** var add = function(a,b){ return a+b }; console.log(add(3,5)) // prints 8 in console. whereas in python it gives an error as in the picture below.
has comment: http://stackoverflow.com/comment/88049735
answer count: 5
downvote count: 8
has comment: http://stackoverflow.com/comment/88049170
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/50518260
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88049052
upvote count: 3

http://stackoverflow.com/a/50510878
accepted answer of: http://stackoverflow.com/q/50510841
type: Answer
has body: Why not using split() ? s = "vishal.testzone.com" vishal = s.split('.', 1)[0] (edited per comment below from jpp).
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/88034030
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/50510841

http://stackoverflow.com/q/50520345
tagged with: web
downvote count: 1
favorite count: 0
type: Question
has title: I can't get my flask user registration code to work, what i'm i doing wrong?
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88053635
tagged with: python
score: -1
tagged with: flask
has answer: http://stackoverflow.com/a/50520849
has comment: http://stackoverflow.com/comment/88083298
tagged with: user-registration
has body: i started learning flask just few days ago so i know this might not be the best code you've seen so far my main goal for now is just to get my data into the db. find my code below from flask import Flask, session, redirect, url_for, escape, request, render_template from hashlib import md5 from dbConnect import connection import MySQLdb from MySQLdb import escape_string as thwart import gc app = Flask(__name__) #database conn conn = MySQLdb.connect(host="localhost", user="root", password="jccofficial", db="test") cur = conn.cursor() #registration handling @app.route('/register/', methods=["GET","POST"]) def register_page(): return render_template('register.html') try: if request.method == "POST": username = request.form['username'] email = request.form['email'] password = request.form['password'] x = cur.execute("SELECT * FROM users WHERE username = (%s)", (username)) if int(x) &gt; 0: flash("That username is already taken, please choose another") return render_template('register.html', form=form) else: cur.execute("INSERT INTO users (username,email,password,)VALUES (%s,%s,%s)", (username, email, password)) conn.commit() flash("Thanks for registering!") cur.close() conn.close() session['logged_in'] = True session['username'] = username return redirect(url_for('dashboard')) return render_template("register.html", form=form) except Exception as e: return(str(e)) I've setup and confirmed that my db is working by manually inserting data into it.However i do not know how to check that my form is actually posting the inputs.
answer count: 1
tagged with: authentication

http://stackoverflow.com/a/50437385
has comment: http://stackoverflow.com/comment/87888886
has body: Use listjobs.json api. import requests r = requests.get("http://localhost:6800/listjobs.json?project=myproject") The response is something like this {"status": "ok", "pending": [{"id": "78391cc0fcaf11e1b0090800272a6d06", "spider": "spider1"}], "running": [{"id": "422e608f9f28cef127b3d5ef93fe9399", "spider": "spider2", "start_time": "2012-09-12 10:14:03.594664"}], "finished": [{"id": "2f16646cfcaf11e1b0090800272a6d06", "spider": "spider3", "start_time": "2012-09-12 10:14:03.594664", "end_time": "2012-09-12 10:24:03.594664"}]} Here you can check if the spider is already running in the r.json()["running"] list. Source: http://scrapyd.readthedocs.io/en/stable/api.html#listjobs-json
answers question: http://stackoverflow.com/q/50437162
type: Answer
has comment: http://stackoverflow.com/comment/87888859
has comment: http://stackoverflow.com/comment/87889218
score: 0
has comment: http://stackoverflow.com/comment/87888967

http://stackoverflow.com/comment/87841728
score: 0
has text: First value entry of sorted list. So you want the minimum?
comment on: http://stackoverflow.com/q/50413012
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50485943
has comment: http://stackoverflow.com/comment/87985023
score: 0
answer count: 0
type: Question
has body: I have installed pydea package but jupyter notebook is throwing Module Not Found Error: No module named 'pydea' error I am starting out with DEA so any help would be really appreciated.
type: UnansweredQuestion
tagged with: python
has title: PyDEA package not found
has comment: http://stackoverflow.com/comment/87986544

http://stackoverflow.com/comment/87790193
score: 0
comment on: http://stackoverflow.com/q/50387231
type: Comment
type: QuestionComment
has text: I am not sure but I don't think there is anything integrated in tkinter to do this., so you may need to implement something to do that yourself and write the rtl as ltr.

http://stackoverflow.com/comment/90248260
score: 0
has text: does anyone have solution for this issue?
comment on: http://stackoverflow.com/q/50416391
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87911369
score: 0
type: QuestionComment
has text: @PatrickArtner No, it's not. `('jade')` is a string in parens, `('jade',)` is a 1-member tuple. Besides, tuples don't have `union` either. (Sets do.)
type: Comment
comment on: http://stackoverflow.com/q/50448922

http://stackoverflow.com/comment/87992627
type: QuestionComment
comment on: http://stackoverflow.com/q/50488327
score: 0
has text: Instinct says no remember it providing the 'y' coordinants so matplotlib will take pairs from temps and freq to plot.One other point are you sure it is a contour plot you want? Your example looks more like a bar plot...
type: Comment

http://stackoverflow.com/a/50514559
downvote count: 0
answers question: http://stackoverflow.com/q/50514078
has body: Using re.sub, you will need multiple regexp pattern to accomplish this. Here are the steps and the transformation applied to your string at each step. import re s = '[ A A A A A B B B B B B B B A A A A A ]' # Using a lookbehind, we remove spaces preceeded by a [ s = re.sub('(?&lt;=\[) +', '', s) # s: '[A A A A A B B B B B B B B A A A A A ]' # Using a lookahead, we remove spaces followed by a ] s = re.sub(' +(?=\])', '', s) # s: '[A A A A A B B B B B B B B A A A A A]' # Using a lookaround, we remove space not followed or preceeded by another space s = re.sub('(?&lt;! ) (?! )', '', s) # s: '[AAAAA BBBBBBBB AAAAA]' # Finally, we use str.replace to cut out half of the spaces s = s.replace(' ', ' ') print(s) # '[AAAAA BBBBBBBB AAAAA]' The above steps can be merged by using regexp union and chaining the re.sub and str.replace operations. s = re.sub('((?&lt;=\[) +)|( +(?=\]))|((?&lt;! ) (?! ))', '', s).replace(' ', ' ')
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/50530718
answers question: http://stackoverflow.com/q/50530320
type: Answer
score: 4
upvote count: 4
has body: I don't see an easy way to do so without using a dense tensor representation (tf.sparse_tensor_to_dense()). Tensorflow is however built for operations on huge matrices, so in many cases it shouldn't be a problem... A quick example: import tensorflow as tf import numpy as np X_sparse_np = np.array([ [1, 2, 1], [3, 0, 2], [3, 3, 3], [6, 1, 4], ]) b_np = np.array([1,2,3,4,5]) b = tf.constant(b_np) # Converting your input data into a SparseTensor: indices = X_sparse_np[:, :2].reshape((-1, 2)) values = X_sparse_np[:, 2] dense_shape = [7, 5] X_sparse = tf.SparseTensorValue(indices, values, dense_shape) # Performing your operation on its dense representation: res = tf.sparse_tensor_to_dense(X_sparse) * b # opt. Re-obtaining the sparse representation of your result: sparse_res = tf.SparseTensor(indices, tf.gather_nd(res, indices), dense_shape) with tf.Session() as sess: print(sess.run(res)) # [[ 0 0 0 0 0] # [ 0 0 3 0 0] # [ 0 0 0 0 0] # [ 2 0 0 12 0] # [ 0 0 0 0 0] # [ 0 0 0 0 0] # [ 0 8 0 0 0]] print(sess.run(sparse_res)) # SparseTensorValue( # indices=array([[1, 2], # [3, 0], # [3, 3], # [6, 1]]), # values=array([ 3, 2, 12, 8]), # dense_shape=array([7, 5]))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50530320
downvote count: 0

http://stackoverflow.com/comment/87923716
has text: NO, you can't use different length for input , but if you use word vectors you can for example use average of them , or use an embedding layer with one-hot vectors.
score: 0
comment on: http://stackoverflow.com/q/50455088
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87962811
score: 0
comment on: http://stackoverflow.com/q/50438182
type: QuestionComment
has text: RishuA: You have 2mins to edit a comment. Delete, repost, then delete this thread of comments.
type: Comment

http://stackoverflow.com/comment/87835565
score: 0
type: Comment
type: QuestionComment
has text: i am using nginx in front of the server, like proxy server. Any solution with nginx?
comment on: http://stackoverflow.com/q/50409865

http://stackoverflow.com/comment/87889150
comment on: http://stackoverflow.com/a/50437224
has text: @3h1Nh7YX24 is your number always going to be 3 digits? If so, Mureinik answer is the best approach
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50385070
type: Question
has body: I am using ODOO 11.0 how to return simple JSON object without JSON-RPC additional parameters Here is my odoo controller code: @http.route('/userappoint/webhook_test/',type='json', auth='public',method=['POST'], csrf=False,website=True) def webhook_test(self,**kw): response = { 'speech' : 'hello my name is shubham', 'displayText' : 'hello testing', 'source' : 'webhook' } return response And I am getting this result : { "result": { "displayText": "hello testing", "source": "webhook", "speech": "hello my name is shubham" }, "id": "6eaced3e-6b0d-4518-9710-de91eaf16dd9", "jsonrpc": "2.0" } But I need this : { "speech": "hello my name is shubham", "displayText": "hello testing", "source": "webhook" } Any help to point me in the right direction? Thanks
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64881282
has title: Change JSON-RPC RESPONSE
tagged with: python
has answer: http://stackoverflow.com/a/63876879
score: 0
answer count: 2
tagged with: odoo-11
tagged with: json-rpc

http://stackoverflow.com/q/50531183
upvote count: 2
has title: How to query MySQL database using API in python?
has comment: http://stackoverflow.com/comment/88074399
answer count: 1
accepted answer: http://stackoverflow.com/a/50531327
downvote count: 1
favorite count: 0
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88074507
tagged with: python
tagged with: mysql
has comment: http://stackoverflow.com/comment/88074466
linked to: http://stackoverflow.com/q/372885
has body: I have my data in database, and I want to build an API using python to query the database. What do I use or where do I even start ? I can connect to my database and pull the data. But I do not know how to build an API for other users to query the database
has answer: http://stackoverflow.com/a/50531327
type: AnsweredQuestion

http://stackoverflow.com/a/50526733
has body: Removing item while iterating over it leads to this kind of errors. One approach here could be to create a new list with the constraint you choose: nums = [31, 71, 91, 32, 92, 13, 73, 14, 34, 74] prims = [n for n in nums if primality(n)] # returns : [31, 71, 13, 73]
answers question: http://stackoverflow.com/q/50526625
type: Answer
score: 0

http://stackoverflow.com/a/50452716
upvote count: 2
score: 2
has body: Use: df.groupby(df['date'].dt.hour).mean() Output: Ac f I Pf R V date 0 301.78 59.97 1.4975 0.7 11.25 22.0
accepted answer of: http://stackoverflow.com/q/50452467
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50452467

http://stackoverflow.com/q/50422809
upvote count: 15
type: Question
has body: As per application requirement, I need to show all the data which is part of group by in comma separated format so the admin can take decision, I am new to Python and not sure how to do it. Sample reproducible data import pandas as pd compnaies = ['Microsoft', 'Google', 'Amazon', 'Microsoft', 'Facebook', 'Google'] products = ['OS', 'Search', 'E-comm', 'X-box', 'Social Media', 'Android'] df = pd.DataFrame({'company' : compnaies, 'product':products }) ----------------------------------------------------------------- company product 0 Microsoft OS 1 Google Search 2 Amazon E-comm 3 Microsoft X-box 4 Facebook Social Media 5 Google Android Now I getting count of company group by this code df.groupby(['company']).count() I need data in below mentioned format but not sure how to get it Desired output company count product Amazon 1 E-comm Facebook 1 Social Media Google 2 Search, Android Microsoft 2 OS, X-box
tagged with: data-cleaning
accepted answer: http://stackoverflow.com/a/50422952
tagged with: python
has answer: http://stackoverflow.com/a/50422952
has title: Pandas | Group by with all the values of the group as comma separated
score: 14
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/112321045
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/50447829
accepted answer of: http://stackoverflow.com/q/50446004
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50446004
score: 2
type: AcceptedAnswer
downvote count: 0
has body: if your date in the string follows YYYY-MM-DD or YYYY-MM-DD pattern, code to extract date field import re text = 'start_KA03MM7155_RKMS121MI4-4.21005_NEW_end, 2018-01-02 09:48:23' result = re.search('(\d{4}-\d{2}-\d{2})', text).group(0) print('result: ', result) result: 2018-01-02 then you can manipulate string to get desired output, for your case split_data = d.split('-') #split the string date_pattern = split_data[-1] + split_data[-2] + split_data[-3][-2:] print('date Pattern: ', date_pattern) date Pattern: 020118 with a small change in regex pattern you can time time_pattern = re.search('(\d{2}:\d{2}:\d{2})', a).group(0).replace(':', '') print('time_pattern: ', time_pattern) time_pattern: 094823 Brief Explanation: \d looks for digits \d{4} matches 4 digits (\d{4}-\d{2}-\d{2}) looks for a group having (4 digits)-(2 digits)-(2 digits) to know more about regex you can follow the official link

http://stackoverflow.com/comment/87939276
type: Comment
comment on: http://stackoverflow.com/a/50451829
has text: if i use that manual reshaping it raises another error; however using tf.layers.flatten seems to work, ill update the post if everything works
score: 0
type: AnswerComment

http://stackoverflow.com/a/50472846
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: According to documentation > for numpy.dtype specifies Big-Endian format. You are running your code most probably on Intel or compatible CPU which is Little-Endian. You need to convert your uint32_t field using ntohl() function: in_f.read(reinterpret_cast&lt;char*&gt;(&amp;cw), sizeof(cw)); cw.chunk_size = ntohl( cw.chunk_size ); cout &lt;&lt; cw.chunk_size &lt;&lt; endl; Details about Endianness
accepted answer of: http://stackoverflow.com/q/50472710
has comment: http://stackoverflow.com/comment/87960116
type: Answer
answers question: http://stackoverflow.com/q/50472710
score: 2

http://stackoverflow.com/comment/87817578
comment on: http://stackoverflow.com/q/50400852
score: 0
type: Comment
type: QuestionComment
has text: How does `file_path` relate to `list_fields`? On the front-end, the user specifies the type for each field, and the file is read independently? If so, you could probably use `zip` on `list_fields` and `type_field` and iterate that list.

http://stackoverflow.com/comment/87960961
comment on: http://stackoverflow.com/q/50473309
type: Comment
type: QuestionComment
has text: @zvone hrmm... I possibly agree. :-) Reading through the answers to that question now.
score: 0

http://stackoverflow.com/comment/87847250
type: AnswerComment
comment on: http://stackoverflow.com/a/50413323
score: 0
has text: The problem is that the database it's from a client, and I have only permission for read (select) I can't modify it in any aspect. I've make the changes above, but It's continues with the same error
type: Comment

http://stackoverflow.com/a/50501870
type: Answer
score: 0
has body: I resolved this due to changing a parameter name in my test, which had nothing to do with my Python test framework.
answers question: http://stackoverflow.com/q/50407349

http://stackoverflow.com/a/76667899
downvote count: 0
upvote count: 1
has body: You could instantiate the schema with partial=True to make all fields optional.
answers question: http://stackoverflow.com/q/50409345
type: Answer
score: 1

http://stackoverflow.com/q/50499728
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50499851
has comment: http://stackoverflow.com/comment/88012443
linked to: http://stackoverflow.com/q/23621833
has comment: http://stackoverflow.com/comment/88012320
type: UnansweredQuestion
tagged with: math
has title: Python 2 is_integer not returning properly
tagged with: python
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/88012379
score: 2
tagged with: python-2.7
upvote count: 3
tagged with: isinteger
has body: from fractions import Fraction counter = 0; a = int(raw_input()) b = int(raw_input()) if 1 &lt;= a &lt;= 10 ** 8: if a &lt;= b &lt;= 10 ** 8: for i in range(a, b+1): if float(i**Fraction(1,3)).is_integer() == True: counter += 1 print(i) print(str(counter)) print (str(float(64**Fraction(1,3)).is_integer())) This code returns false which results in the if statement not being run at all. Furthermore, the cube root of 64 is 4, therefore, the result should be an integer. However, in the range between 1 and 100 inclusive, 1, 8, and 27 return true for this case. Any help would be appreciated as to why the cube root of 64 is not returning true.
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/88046940
type: QuestionComment
comment on: http://stackoverflow.com/q/50515596
has text: @tdelaney, yes, this example shows the desired result
score: 0
type: Comment

http://stackoverflow.com/q/50501413
has title: I have age variable in dataset and i want to categorize the variable into "young","adult","old"
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88015184
tagged with: python
has answer: http://stackoverflow.com/a/50501538
accepted answer: http://stackoverflow.com/a/50501538
downvote count: 4
type: AnsweredQuestion
upvote count: 0
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/88015268
has body: this is the code I was trying, but couldn't make it bins = [0, 30, 60, 90] lables =["young","adult","old"] train['age'] = pd.cut(train.age,bins,labels = labels,include_lowest=True)

http://stackoverflow.com/a/50431206
has body: Your code snippet lists "https://googleapis.com/oauth/v4/token". The token endpoint is "https://googleapis.com/oauth2/v4/token".
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87882256
answers question: http://stackoverflow.com/q/50396786
type: Answer

http://stackoverflow.com/comment/87900668
has text: Possible duplicate of [Why doesn't pytz localize() produce a datetime object with tzinfo matching the tz object that localized it?](https://stackoverflow.com/questions/24359540/why-doesnt-pytz-localize-produce-a-datetime-object-with-tzinfo-matching-the-t)
comment on: http://stackoverflow.com/q/50443305
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88095252
type: Comment
has text: 28:48.3 1 44:42.2 1 37:26.1 1 53:04.4 1 35:25.2 1 56:26.8 1 37:50.0 1 31:13.0 1 31:29.9 1 34:49.3 1 26:59.5 1 48:02.3 1 42:04.8 1 44:20.8 1 37:38.7 1 56:37.9 1 40:48.2 1 39:47.7 1 Name: year, dtype: int64
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50541615

http://stackoverflow.com/a/50483133
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50476811
has body: Just for summary, your issue is resulted from the conflict between python 2.7 version you installed and the python version with Anaconda. The packages you installed should to be in the python 2.7 environment. However, spyder uses the Anaconda self-brought python environment. Command line uses system python environment which is determined by the the previous python environment variable in the path.
accepted answer of: http://stackoverflow.com/q/50476811
type: Answer
score: 0

http://stackoverflow.com/a/50498963
has comment: http://stackoverflow.com/comment/88014723
type: Answer
has comment: http://stackoverflow.com/comment/88014866
answers question: http://stackoverflow.com/q/50485865
score: 2
downvote count: 0
has body: NLTK provides the corpora of the most common English words (nltk.corpus.words.words('en')) and most common English names (nltk.corpus.names.words()). Unfortunately, the latter one would not have Sunder or Pichai, so you have to rely on the former. Unfortunately again, there are names that are also common English words (e.g., Hope), which makes the task even more challenging. You can still automate it to some extent: words = set(nltk.corpus.words.words('en')) def isname1(string): return any([w not in words for w in string.lower().split()]) def isname2(string): return all([w not in words for w in string.lower().split()]) list(map(isname1, ["Sunder Pichai", "View Profile", "Risk Management"])) #[True, False, False] list(map(isname2, ["Sunder Pichai", "View Profile", "Risk Management"])) #[False, False, False] As you can see, the second function is more aggressive and does not recognize "Sunder Pichai" as a name (because "sunder" is actually an English word).
has comment: http://stackoverflow.com/comment/88014611
upvote count: 2

http://stackoverflow.com/a/50423671
answers question: http://stackoverflow.com/q/50420066
type: Answer
has comment: http://stackoverflow.com/comment/87864021
has body: Read the official Twitter documentation : https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html And use the parameter q with from:@user and count=10 where 10 is your "n" andmax_id=id where "id" is your tweet id. And read the officiel tweepy documentation for the seach API. We can fix bugs for you but won't code for you.
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50420066

http://stackoverflow.com/comment/87972215
type: QuestionComment
comment on: http://stackoverflow.com/q/50479318
type: Comment
has text: @donkopotamus You mean because I am accessing global variables?
score: 0

boolean-logic
tags question: http://stackoverflow.com/q/50532983
tag name: boolean-logic
type: Tag

http
tags question: http://stackoverflow.com/q/50430865
tags question: http://stackoverflow.com/q/50441904
tags question: http://stackoverflow.com/q/50458709
tags question: http://stackoverflow.com/q/50511942
type: Tag
tags question: http://stackoverflow.com/q/50508556
tag name: http
tags question: http://stackoverflow.com/q/50479969
tags question: http://stackoverflow.com/q/50506842

http://stackoverflow.com/comment/87920320
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50422566
has text: I'd try combining them for now, just to work around the render issue.
score: 0

http://stackoverflow.com/a/50441934
has body: You can use for this meta's widgets option: from django import forms from second_app.models import user class NewUserForm(forms.ModelForm): class Meta: model = user fields = '__all__' widgets = { 'field_name': forms.HiddenInput(), }
type: Answer
accepted answer of: http://stackoverflow.com/q/50441663
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50441663

http://stackoverflow.com/comment/87973567
type: AnswerComment
has text: Yours works perfectly too! However, I find ikolim's way more of a "best practice". Thanks for responding!
type: Comment
comment on: http://stackoverflow.com/a/50465941
score: 0

http://stackoverflow.com/comment/90661318
comment on: http://stackoverflow.com/a/51854290
type: AnswerComment
has text: Is it possible to make the mapping dictionary without ourself if *redacted1.com* is on the first place and have *Drupal*? If it is possible, please change the code according to it. because then I will have clear picture/
score: 0
type: Comment

http://stackoverflow.com/q/50510291
has answer: http://stackoverflow.com/a/50510405
has title: Python code doesn't execute. No errors showed
accepted answer: http://stackoverflow.com/a/50510347
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50510339
has answer: http://stackoverflow.com/a/50510347
has body: I don't know what's wrong with my code. It would just not execute. Nothing happens, no errors occur. I can't figure it out. If someone can tell me what I have done wrong, please do so and I will be grateful. class Money (object): def __init__ (self, euro, cent): self.euro = euro self.cent = cent def __str__ (self): if self.cent &gt;= 100: r = self.cent / 100 self.cent = self.cent % 100 self.euro = self.euro + r return ("%d EUR &amp; %d cents") % (self.euro, self.cent) else: return ("%d EUR &amp; %d cents") % (self.euro, self.cent) def changeCent (self): #100 c = 1 E cents = self.euro * 100 self.cent = self.cent + cents return self.cent def changeSum (self, euros): #1 E = 100 c euros = self.cent / 100 self.euro = self.euro + euros return self.euro def debt (self, years, rate): value = Money() multiply = rate * years * 12 / 100 value.euro = self.euro * multiply value.cent = self.cent * multiply if value.cent &gt; 100: euro_ = value.cent / 100 value.cent = value.cent - 100 value.euro = value.euro + euro_ return value def main(): x = Money() x.euro = int(input("Type in your EURO ammount: \n")) x.cent = int(input("Type in your CENT ammount: \n")) print (x)
downvote count: 4
has comment: http://stackoverflow.com/comment/88032957
upvote count: 2
has comment: http://stackoverflow.com/comment/88032809
linked to: http://stackoverflow.com/q/17257631
has answer: http://stackoverflow.com/a/50510439
has comment: http://stackoverflow.com/comment/88032875
has comment: http://stackoverflow.com/comment/88032915
has answer: http://stackoverflow.com/a/50510342
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/17257631
has comment: http://stackoverflow.com/comment/88032866
answer count: 5
score: -2
has comment: http://stackoverflow.com/comment/88033086
possible better answer: http://stackoverflow.com/a/50510405
tagged with: python

http://stackoverflow.com/q/50404722
has body: I have 100 keywords in df1,and 10,000 articles in df2. I want to calculate how many articles contain a certain keyword. For example, there are about 20 articles contain keyword "apple". I try to use df.str.contains(),but I have to calculate every keyword. Can you tell me a efficient way? df1=pd.DataFrame(['apple','mac','pc','ios','lg'],columns=['keywords']) df2=pd.DataFrame(['apple is good for health','mac is another pc','today is sunday','Star wars pc game','ios is a system,lg is not','lg is a japan company '],columns=['article']) result: 1 artricl contain "apple" 1 article contain 'mac' 2 article contain 'pc' 1 article contain "ios" 2 article contain 'lg'
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50404789
has answer: http://stackoverflow.com/a/50404789
tagged with: python
has title: Pandas:check values in column A contained in column B
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87856154
type: AnswerComment
comment on: http://stackoverflow.com/a/50419717
has text: @chepner Thank you for additional nice solutions!
score: 0
type: Comment

http://stackoverflow.com/q/50464417
tagged with: android
tagged with: python
has body: ERROR : Not a valid TensorFlow Graph serialization: NodeDef expected inputs '' do not match 1 inputs specified; Op output:dtype; attr=value:tensor; attr=dtype:type>; NodeDef: dropout_1/cond/dropout/random_uniform/max = Const_output_shapes=[[]], dtype=DT_FLOAT, value=Tensor I'm relatively new to the world of TensorFlow. When i put my .pb model in android studio, this error popup in the logcat. Others .pb model works well, so i think there is a problem in the training code. This is the training code: from tensorflow.python.lib.io import file_io import argparse from pandas import read_csv from sklearn.preprocessing import LabelEncoder, MinMaxScaler from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, LSTM, Conv1D from keras.callbacks import TensorBoard, ModelCheckpoint from numpy import array, split import keras.backend as k import tensorflow as tf from keras.models import load_model from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model import tag_constants, signature_constants from tensorflow.python.saved_model.signature_def_utils_impl import predict_signature_def # training parameters epochs = 1 batch_size = 100 validation_split = 0.2 # model parameters dropout = 0.2 timesteps = 40 timesteps_in_future = 20 nodes_per_layer = 32 filter_length = 3 def train_model(train_file='datanormalized.csv', job_dir='', **args): parameter_string = '' + '_dropout_' + str(dropout) + '_timesteps_' + str(timesteps) + '_timesteps_in_future_' + str(timesteps_in_future) + '_nodes_per_layer_' + str( nodes_per_layer) + '_filter_length_' + str(filter_length) #load data #file_stream = file.io.FileIO(train_file, mode='r') file_stream = open(train_file,'r') dataframe = read_csv(file_stream, header=0) dataframe.fillna(0, inplace=True) dataset= dataframe.values X= dataset[:, [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]].astype(float) print(X.shape) y = dataset[:, 0] #ExerciseTyp…
has answer: http://stackoverflow.com/a/51197583
has comment: http://stackoverflow.com/comment/87942053
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: ERROR: Not a valid TensorFlow Graph serialization: NodeDef expected inputs '' do not match 1 inputs specified
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: model
has comment: http://stackoverflow.com/comment/89367436
type: UnansweredQuestion

http://stackoverflow.com/a/50399101
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50398988
upvote count: 5
has body: Consider below code where index_col=False. You can use this solution when you do not know how many columns are expected in the csv file. Better if different files have different number of columns. Refer to Docs for more information. from io import StringIO csvtext = StringIO("""a,b,c 1,2,3, 4,5,6, a,b,c, """) df = pd.read_csv(csvtext, index_col=False) df Output: a b c 0 1 2 3 1 4 5 6 2 a b c
type: Answer
answers question: http://stackoverflow.com/q/50398988
score: 5
downvote count: 0

http://stackoverflow.com/q/50464448
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
downvote count: 0
tagged with: sorting
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50464856
possible better answer: http://stackoverflow.com/a/50465163
tagged with: python
has answer: http://stackoverflow.com/a/50464856
score: 4
has answer: http://stackoverflow.com/a/50465163
has body: I am learning python and am having trouble with sorting. I feel like the key (for sorting) is too limiting and difficult to use once sorting algorithm begins getting more complicated. Here is the list I want to sort: ['A1', 'AA1', 'B3', 'B2', 'BB1', 'AZ15'] where each value is like an excel column (ie. 'BB1' &gt; 'AZ15' &gt; 'AA1' &gt; 'B3' &gt; 'B2' &gt; 'A1'). Here is the solution I came up with after reading the following guide. def cmp_cell_ids(name1, name2): def split(name): letter = '' number = '' for ch in name: if ch in '1234567890': number += ch else: letter += ch return letter, int(number) ltr1, num1 = split(name1) ltr2, num2 = split(name2) if len(ltr1) == len(ltr2): if ltr1 == ltr2: return num1 &gt; num2 else: return ltr1 &gt; ltr2 return len(ltr1) &gt; len(ltr2) def cmp_to_key(mycmp): class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return not mycmp(self.obj, other.obj) def __gt__(self, other): return mycmp(self.obj, other.obj) def __eq__(self, other): return self.obj == other.obj def __le__(self, other): if self.__eq__(other): return True return self.__lt__(other) def __ge__(self, other): if self.__eq__(other): return True return self.__gt__(other) def __ne__(self, other): return self.obj != other.obj return K key_cell_ids_cmp = cmp_to_key(cmp_cell_ids) cell_ids = ['A1','AA1','B3','B2','BB1','AZ15'] cell_ids.sort(key=key_cell_ids_cmp) print(cell_ids) Which gives the desired output ['A1', 'B2', 'B3', 'AA1', 'AZ15', 'BB1'] I am wondering if there is any easier/more pythonic implementation to this (in particular, I would love if I could get rid of that wrapper class).
has title: Simplify sort of Excel cell names in python
upvote count: 4

http://stackoverflow.com/q/50513688
tagged with: python
has comment: http://stackoverflow.com/comment/88040839
linked to: http://stackoverflow.com/q/47372181
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88040772
has comment: http://stackoverflow.com/comment/88041092
has comment: http://stackoverflow.com/comment/88040816
linked to: http://stackoverflow.com/q/21666976
has comment: http://stackoverflow.com/comment/88040781
type: Question
has title: How to show zero counts in pandas groupby for large dataframes
has body: I have a dataframe where I want to see the zero counts. It's essentially a duplicate of this question: Pandas Groupby How to Show Zero Counts in DataFrame But unfortunately the answer is not a duplicate one. Whenever I try the MultiIndex.from_product approach, I get the error: ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size. which is because I have several unique values for the groupby. I've confirmed though that the same script works for much smaller dataframes with fewer unique indices (and therefore, fewer elements in df.index.levels[i].values). Here's an idea on the dataframe that I'm working with: user1 user2 hour ------------------- Alice Bob 0 Alice Carol 1 Alice Bob 13 Bob Eve 2 to user1 user2 hour count ------------------------------- Alice Bob 0 1 Alice Bob 1 0 Alice Bob 2 0 and so on but what I get is user1 user2 hour count ------------------------------- Alice Bob 0 1 Alice Bob 13 1 Alice Carol 1 1 However, I have ~1.2M unique combinations of user1-user2, so MultiIndex.from_product doesn't work. EDIT: Here's the code I used for some dummy dataframe. It works for the dummy case, but not for the larger case: import pandas as pd df = pd.DataFrame({'id':[1,1,2,2,3,3],'hour':[0,1,0,0,1,1], 'to_count': [20,10,5,4,17,6]}) print(df) agg_df = df.groupby(['id', 'hour']).agg({'to_count': 'count'}) print(df.groupby(['id', 'hour']).agg({'to_count':'count'})) print(len(agg_df.index.levels)) levels = [agg_df.index.levels[i].values for i in range(len(agg_df.index.levels))] levels[-1] = [0,1,2] print(len(levels)) print(agg_df.index.names) new_index = pd.MultiIndex.from_product(levels, names=agg_df.index.names) # Reindex the agg_df and fill empty values with zero (NaN by default) agg_df = agg_df.reindex(new_index, fill_value=0) # Reset index agg_df = agg_df.reset_index() Is there a better way to show zero counts for groupby in large pandas dataframes?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88041260

http://stackoverflow.com/q/50477634
score: 0
has answer: http://stackoverflow.com/a/50480112
answer count: 1
tagged with: web-scraping
tagged with: request
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has title: Scraping JavaScript var from HTML using Beautiful Soup in Python
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I'm scraping a website's HTML after a "GET" request. I'm essentially trying to get a few tokens from the site. I'm using Beautiful soup since it's what I usually use but I can't seem to figure out how to get a javascript variable from the html. The tokens are in the HTML like so: &lt;script type="text/javascript"&gt; var accessToken = "WaX2wWBb9fkp+qVQf6ECq9JcOZJnCL3Y/furfevohpk="; var ivString = "d2c5708bbcc6b53c23af6d2cdab9f4ab"; var encryptedFpAccountId = "zk/5H7Iz0cNQPxPadMgvDw=="; var accessTokenCode = "0"; var nextPageName="signup-retail" I need to get what the accessToken, ivString, and encryptedFpAccountId equal. How should I go about scraping this?

http://stackoverflow.com/q/50483092
has comment: http://stackoverflow.com/comment/87979458
favorite count: 0
type: Question
tagged with: pandas
score: -2
has title: How to parse DataFrame with specific column and write it to different excel sheets
tagged with: python
accepted answer: http://stackoverflow.com/a/50523349
has comment: http://stackoverflow.com/comment/87979610
type: AnsweredQuestion
has body: I want to parse specific column in my dataframe and write to sheets in one excel file? I tried below code: for groups in z3.cats: group=z3[z3['cats']==groups] group.to_csv('group.csv',encoding='gbk') Here is the example data: cats predict [0.9, 1.0) 99% [0.1, 0.2) 30% [0.1, 0.2) 51% [0.0, 0.1) 0% [0.3, 0.4) 12% . . [0.9, 1.0) 100% I want to group [0.9,1.0) in cats2 column,and put them in one excel sheet name [0.9,1.0) , and [0.1, 0.2) in another excel sheet name [0.1, 0.2) .and make the two sheet is in one excel file.
has comment: http://stackoverflow.com/comment/87979353
has answer: http://stackoverflow.com/a/50523349
has comment: http://stackoverflow.com/comment/87979123
has comment: http://stackoverflow.com/comment/87983537
answer count: 1
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/87982292

http://stackoverflow.com/a/50412609
accepted answer of: http://stackoverflow.com/q/50410956
has comment: http://stackoverflow.com/comment/87844032
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50410956
has comment: http://stackoverflow.com/comment/87844613
has comment: http://stackoverflow.com/comment/87845638
type: Answer
has body: Change your regex to this: r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', prefix The problem is that in the original expression the \. is only part of one possible pattern in the OR operator. And you could precompile it (with re.compile), as it's used multiple times.

http://stackoverflow.com/comment/87928576
has text: Depending on the size of his array, it may be fast enough. Additionally, you can easily make it write to the array's buffer.
type: AnswerComment
comment on: http://stackoverflow.com/a/50457458
score: 0
type: Comment

http://stackoverflow.com/q/50459256
has title: Inconsistent numpy complex multiplication results
score: 0
has body: Consider the following Python code that multiplies two complex numbers: import numpy as np a = np.matrix('28534314.10478439+28534314.10478436j').astype(np.complex128) b = np.matrix('-1.39818115e+09+1.39818115e+09j').astype(np.complex128) #Verify values print(a) print(b) c=np.dot(a.getT(),b) #Verify product print(c) Now the product should be -7.979228021897728000e+16 + 48j which is correct when I run on Spyder. However, if I receive the values a and b from a sender to a receiver via MPI on an MPI4py program (I verify that they have been received correctly) the product is wrong and specifically -7.97922801e+16+28534416.j. In both cases I am using numpy 1.14.3 and Python 2.7.14. The only difference in the latter case is that prior to receiving the values I initialize the matrices with: a = np.empty_like(np.matrix([[0]*(1) for i in range(1)])).astype(np.complex128) b = np.empty_like(np.matrix([[0]*(1) for i in range(1)])).astype(np.complex128) and then the function MPI::Comm::Irecv() gives them the correct values. What is going wrong in the latter case if the a and b are correct but c is wrong? Is numpy arbitrarily setting the imaginary part since it's quite smaller than the real part of the product?
linked to: http://stackoverflow.com/q/4151128
has comment: http://stackoverflow.com/comment/87932959
has comment: http://stackoverflow.com/comment/87932791
answer count: 1
has comment: http://stackoverflow.com/comment/87931910
type: Question
has comment: http://stackoverflow.com/comment/87932333
has comment: http://stackoverflow.com/comment/87932782
has answer: http://stackoverflow.com/a/50460158
tagged with: complex-numbers
tagged with: python
tagged with: numpy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50460158

http://stackoverflow.com/a/50516328
has comment: http://stackoverflow.com/comment/88045198
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88045142
answers question: http://stackoverflow.com/q/50516253
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50516253
has body: Your _delete_job was spun off to be run while Tornado returned the 200. The _delete_job itself hadn't finished by the time you tried to get the same thing several milliseconds later

http://stackoverflow.com/q/50453574
tagged with: pandas
score: 2
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/50453672
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50453672
accepted answer: http://stackoverflow.com/a/50453636
has body: I have the following series (df): Index Information 1 [2, A, C] 2 [3, B, C] 3 [4, C, H] 4 [5, D, H] 5 [6, E, H] 6 [7, F, H] and I want a series that only extracts and stores the third value of each list : Index Information 1 [C] 2 [C] 3 [H] 4 [H] 5 [H] 6 [H] If I try df[0][2], it correctly gives the required output [C]. however, if I try df[:][2], instead of giving [C] [C] [H] [H] [H] [H] the output is 3 [4, C, H] What should be the correct syntax for this?
type: Question
has title: How to select a specific element from a list of rows in python
has answer: http://stackoverflow.com/a/50453636
answer count: 2
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87920525

http://stackoverflow.com/comment/87933555
type: AnswerComment
has text: change `return RoundtripSerializer(queryset, many=True).data` to `return RoundtripSerializer(queryset, many=True, context=self.context).data`
comment on: http://stackoverflow.com/a/50459007
score: 0
type: Comment

http://stackoverflow.com/comment/87919446
type: Comment
type: QuestionComment
has text: @MatiasCicero You are correct. Storing it in a variable does get me the output. But I didn't quite get why if I don't store it in a var, does it not return the output, even though I am using the return statement,
score: 0
comment on: http://stackoverflow.com/q/50452934

http://stackoverflow.com/comment/87852534
comment on: http://stackoverflow.com/a/50415828
type: Comment
has text: @user4412195 Did you notice this speedup even when you use Python `object` as the datatype before the multiplication? Can you tell me what you tried? Because, remember I need this kind of precision since I was thinking but `np.int64` was enough for me but it's not.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50419213
upvote count: 1
favorite count: 0
tagged with: attributes
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50419492
has title: attributes not appearing in xml2dict parse output even with xml_attribs = True
tagged with: http://stackoverflow.com/tag/xml
tagged with: xmltodict
linked to: http://stackoverflow.com/q/191536
score: 1
answer count: 1
has body: I am having a problem with python xmltodict. Following the near-consensus recommendation here, I tried xmltodict and liked it very much until I had to access attributes at the top level of my handler. I'm probably doing something wrong but it's not clear to me what. I have an xml document looking something like this <api> Mackenzie ... Joe ... <api> I parse it with this: xmltodict.parse(apiResult.body, item_depth=2, item_callback=handler, xml_attribs=True) where apiResult.body contains the xml shown above. But, in spite of the xml_attribs=True, I see no @id or @modified_dt in the output after parsing in the handler, although all the elements in the original do appear. The handler is coded as follows: def handler(_, cons): print (cons) mc = MatchChecker(cons) mc.check() return True What might I be doing wrong? I've also tried xmljson and instantly don't like it as well as xmltodict, if only I had the way around this issue. Does anyone have a solution to this problem or a package that would handle this better?
downvote count: 0

http://stackoverflow.com/q/50438450
has answer: http://stackoverflow.com/a/50438494
has title: center text with variable python3.6
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87890830
upvote count: 3
tagged with: centering
answer count: 1
tagged with: formatting
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50438494
has body: First, I am new to programming in general, so that means I'm new to python as well, so type slowly so I can keep up. I am trying to center a line of text that includes a variable that was input by a user. Something like this: age = input ("How old are you? ") print ("{: ^80}".format("You are", (age), "years old.")) I've tried as many ways as I can think of to get this to center the entire line reading . . . You are 40 years old. (Assuming, of course, the user input = 40) with no luck. What am I doing wrong? Thanks, Robert
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/87994033
has text: Your update is wrong. `local` is not a valid file system type.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50490197

http://stackoverflow.com/q/50484241
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50484305
accepted answer: http://stackoverflow.com/a/50484305
has title: Select keys with same length of value which is highest count list in dictionary
has body: I have a sorted defaultdict like: k = {'a':[3,4,5] , 'x':[5,4,11] , 'c':[1,3,4] , 'l': [2,3], 'h':[1]} What I want is to get only keys with highest or higesht equal length in value. Expected output: {'a':[3,4,5] , 'x':[5,4,11] , 'c':[1,3,4]} or [a,b,c] I have used numpy to get true values in an array and then extract it my code: z = np.array(arr) #arr variable has the size of lists i.e arr = [3,3,3,2,1] p = len(z[z == z[0]]) #To Check how many highest count is SAME and store the count in p variable print(z &gt;= z[0]) print(list(k)[0:p]) Output :- True True True False False [a,x,c] So my question is, is there any way to do this without using numpy ?
answer count: 1
type: Question
tagged with: defaultdict
type: AnsweredQuestion
score: 0
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/87938968
type: Comment
has text: What have you tried already and why didn't it work? Do you want us to solve 1. reading in data from a 'fastfile' (what is a fastafile...?) and 2. how to filter your dataframe based on the read input for you?
type: QuestionComment
comment on: http://stackoverflow.com/q/50462844
score: 0

http://stackoverflow.com/a/50495381
answers question: http://stackoverflow.com/q/50495057
has body: i'll try this a = np.array([[1,2,3,4],[5,6,7,8]]) for row in [0,1]: for column in range(4): print('a[%s][%s] = %s' % (row, column, a[row][column])) prints: a[0][0] = 1 a[0][1] = 2 a[0][2] = 3 a[0][3] = 4 a[1][0] = 5 a[1][1] = 6 a[1][2] = 7 a[1][3] = 8
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87950655
comment on: http://stackoverflow.com/a/50396953
has text: I trained a few models and evaluated them on the MS paraphrase database. The results are okay, but not extremely good (AUC around 0.7 to 0.75, EER around 0.3, average precision around 0.85). I think training with more data would be better. I will try smaller vectors but a larger training data set now. You said that alpha=0.75 is very high. I trained with alpha=0.025 and min_alpha=0.0001. Is that better? I used 100 epochs, maybe that was too much although I found a paper that uses 400 epochs (https://arxiv.org/pdf/1607.05368.pdf)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50438937
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87892297
accepted answer of: http://stackoverflow.com/q/50437251
type: Answer
has comment: http://stackoverflow.com/comment/91100288
has comment: http://stackoverflow.com/comment/87892210
has body: You're confusing $PATH and $PYTHONPATH. site-packages is for libraries, $PATH is for programs (binaries and scripts). pip installs libraries into its site-packages and scripts to the corresponding bin/ directory; e.g. if site-packages is /usr/local/lib/pythonX.Y/site-packages scripts are installed into /usr/local/bin/. pip doesn't check if /usr/local/bin/is in $PATH. Well, I agree with you — it should check and remind user to add bin/ directory to $PATH if it's not already there.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50437251

http://stackoverflow.com/comment/87963787
type: Comment
type: AnswerComment
score: 1
has text: Year, that works :) Thx a lot. So the trick was to put the mask into the transform, that was what I dit wrong. Thx a lot.
comment on: http://stackoverflow.com/a/50473487

http://stackoverflow.com/q/50509623
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50511481
has comment: http://stackoverflow.com/comment/88039019
has body: I've just started using Python, so I'm sorry if I ask for trivial things. I generated two random Gaussian distributions, and I used them to generate a 2D Gaussian distribution. What I'd like to do now is to plot a graph that represents the number of elements within a circumference of the 2D Gaussian distribution, varying the radius of the circumference (reducing it at each step). You would be so kind to help me solve the problem. Thank you for taking my post into consideration. import numpy as np import matplotlib.pyplot as plt import seaborn as sns mu1, sigma1 = 0, 0.1 # mean and standard deviation s1 = np.random.normal(mu1, sigma1, 10000) # generate N randoomly Gaussian points mu2, sigma2 = 0.8, 0.3 s2 = np.random.normal(mu2, sigma2, 10000) #ISTOGRAMMA DI DUE DISTRIBUZIONI GAUSSIANE CON DIFFERENTI SET plt.figure(1) plt.title('Histogram of a 2D-Gaussian Distribution') bins1 = plt.hist(s1, 100) bins2 = plt.hist(s2, 100) plt.show() #DISTRIBUZIONE GAUSSIANA 2D plt.figure(2) plt.title('2D-Gaussian Distribution') bins = plt.hist2d(s1, s2, 100) cb = plt.colorbar() cb.set_label('counts in bin') plt.show()
has comment: http://stackoverflow.com/comment/88037871
has comment: http://stackoverflow.com/comment/88038806
has comment: http://stackoverflow.com/comment/88038349
tagged with: python
has comment: http://stackoverflow.com/comment/88037676
has comment: http://stackoverflow.com/comment/88039204
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88036956
score: 0
accepted answer: http://stackoverflow.com/a/50511481
upvote count: 1
has comment: http://stackoverflow.com/comment/88038503
answer count: 1
downvote count: 1
has title: How to count how many particles in a 2D Gaussian distribution

http://stackoverflow.com/a/50405045
score: 3
upvote count: 5
type: Answer
has body: You can do it by In [11]: x = 5 In [12]: print("%.2f" % x) 5.00 In [13]:
downvote count: 2
answers question: http://stackoverflow.com/q/50405021

http://stackoverflow.com/a/50470859
has comment: http://stackoverflow.com/comment/87956054
has body: Have you tried something like req_obj.update(req_obj.make_response()) which will update your initial dict with the values newly yielded from your method?
has comment: http://stackoverflow.com/comment/87956354
has comment: http://stackoverflow.com/comment/87956183
type: Answer
has comment: http://stackoverflow.com/comment/98399862
has comment: http://stackoverflow.com/comment/87956002
has comment: http://stackoverflow.com/comment/97855440
score: 0
answers question: http://stackoverflow.com/q/50469948
has comment: http://stackoverflow.com/comment/87955191
has comment: http://stackoverflow.com/comment/87956272
has comment: http://stackoverflow.com/comment/87955371

http://stackoverflow.com/comment/87986676
type: Comment
comment on: http://stackoverflow.com/a/50486333
score: 0
type: AnswerComment
has text: Thanks for the quick reply. Is this available in REST API's?.

http://stackoverflow.com/comment/88053337
has text: @MikeTung I'm getting `-bash: virtualenv: command not found` when running that command + path. I'm also getting `-bash: pipenv: command not found` after trying to install pipenv with `pip install --user pipenv`.
comment on: http://stackoverflow.com/q/50510139
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50388128
has answer: http://stackoverflow.com/a/50388767
has title: Extract the only item from list in pandas
has answer: http://stackoverflow.com/a/50388425
downvote count: 0
upvote count: 1
tagged with: python
tagged with: string
possible better answer: http://stackoverflow.com/a/50388336
tagged with: series
has comment: http://stackoverflow.com/comment/87792291
has comment: http://stackoverflow.com/comment/87792434
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50388336
answer count: 3
tagged with: pandas
score: 1
has body: How do I extract the value from a list? For e.g. df = pd.DataFrame([[0, 4, 'Abc', 456, '[45.55%]'], [2, 5.2, 'abc', 5, '[34.54%]'], [0.2, 6, 'xyz', 65, '[12.21%]'], [3, 4.1, 'Xbc', 23, '[99.12%]']], columns=['start', 'end', 'name','body_mass', 'budget']) I can use the string replace function as shown below. But I am looking for a better solution. df.budget.str.replace('[', '').str.replace(']', '').str.replace('%', '').astype(float) 0 45.55 1 34.54 2 12.21 3 99.12 Name: budget, dtype: float64 There is only 1 item in the list, if that matters.
accepted answer: http://stackoverflow.com/a/50388767
favorite count: 0
type: Question

http://stackoverflow.com/comment/88041528
score: 0
comment on: http://stackoverflow.com/q/50514409
has text: Some of the inputs are not clear， take this for instance: alg__hi_min_n__7, it could mean {"alg": "hi", "min_n": 7} or {"alg": "hi_min", "n": 7}, while quite difficult to tell, right?
type: Comment
type: QuestionComment

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/50477638

http://stackoverflow.com/comment/87983653
score: 0
type: Comment
has text: Yes , first country code should be retained if it is different.
type: QuestionComment
comment on: http://stackoverflow.com/q/50484937

http://stackoverflow.com/comment/88076303
comment on: http://stackoverflow.com/a/50531774
type: Comment
type: AnswerComment
has text: I just tried it, unfortunately, it doesn't seem to work. I still get the same error of it making the html file blank.
score: 0

http://stackoverflow.com/q/50404202
linked to: http://stackoverflow.com/q/2953746
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87823826
score: -2
has answer: http://stackoverflow.com/a/50404294
duplicate of: http://stackoverflow.com/q/1779288
accepted answer: http://stackoverflow.com/a/50404331
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50404340
tagged with: single-quotes
has answer: http://stackoverflow.com/a/50404331
tagged with: int
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50404286
has comment: http://stackoverflow.com/comment/87823807
downvote count: 3
has comment: http://stackoverflow.com/comment/87824639
has answer: http://stackoverflow.com/a/50404286
has body: I have a number of type string with single quotes. e,g var = '2,000' type(var) # &lt;class 'str'&gt; I want to convert it to int. I have tried int(var) But it gives an error invalid literal for int() with base 10: '2,000'
tagged with: string
has comment: http://stackoverflow.com/comment/87845025
has title: how to convert single quotes string to number in python
answer count: 4

http://stackoverflow.com/a/53791690
has comment: http://stackoverflow.com/comment/111343888
downvote count: 0
has comment: http://stackoverflow.com/comment/111352154
answers question: http://stackoverflow.com/q/50416538
has comment: http://stackoverflow.com/comment/111361978
type: Answer
has body: Selenium considers PhantomJS as deprecated, so you need to us either Chrome or Firefox in headless mode. Here are the steps to use Chrome in headless mode: download chrome driver from https://sites.google.com/a/chromium.org/chromedriver/getting-started extract it to a folder add this folder to your PATH environment variable (if you don't do it, you will have to use webdriver.Chrome('/your/path/to/chromedriver') in the code below instead of webdriver.Chrome()) Then use it like this: from selenium import webdriver # prepare the option for the chrome driver options = webdriver.ChromeOptions() options.add_argument('headless') # start chrome browser browser = webdriver.Chrome(chrome_options=options) browser.get('http://www.google.com/xhtml') print(browser.current_url) browser.quit() More on how to use ChromeDriver For the other options: here (also here and here)
has comment: http://stackoverflow.com/comment/111390808
score: 26
upvote count: 26

http://stackoverflow.com/comment/87968976
has text: When you start modifying the matrix attributes directly you need to understand them. Numerous SO answers have suggested fast iteration on rows using `indptr` directly, but that's for calculations that don't change sparsity. When you start changing the sparsity (adding or removing nonzero values) directly you are taking risks. I have not attempted to do that myself, though I probably could debug the code.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50458453
type: Comment

http://stackoverflow.com/a/71294557
has body: First compare the images using opencv matchTemplate and crop. Ref: https://docs.opencv.org/3.4/d4/dc6/tutorial_py_template_matching.html # opencv import cv2 # read input image = cv2.imread(YOUR_IMAGE_PATH) template_to_match = cv2.imread(YOUR_REF_IMAGE_PATH) # convert it into gray imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) templateGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # compare images using matchTemplate result = cv2.matchTemplate(imageGray, templateGray, cv2.TM_CCOEFF_NORMED) cv2.normalize(result, result, 0, 1, norm_type=NORm_MINMAX) (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(result) (startX, startY) = maxLoc endX = startX + template_to_match.shape[1] endY = startY + template_to_match.shape[0] cropImg = image[startY:endY, startX:endX] cv2.imshow("cropped", cropImg) cv2.waitKey(0)
score: 0
answers question: http://stackoverflow.com/q/50522038
type: Answer

http://stackoverflow.com/comment/87862192
comment on: http://stackoverflow.com/q/50423675
score: 0
type: QuestionComment
type: Comment
has text: Yes i read the docs. But it explains one dimensional array. I couldn't understand this for 2 dimensional array.

http://stackoverflow.com/a/52967280
answers question: http://stackoverflow.com/q/50440309
score: 1
type: Answer
has body: The forgot_password_template.html is html file/template and You can check this from django.core.mail import send_mail, EmailMessage from django.template.loader import render_to_string message = render_to_string('forgot_password_template.html', {'bar': foo}) user.email_user("Send test email", message)
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/88082725
comment on: http://stackoverflow.com/a/50533680
score: 0
type: AnswerComment
has text: Do I need to retrieve and send the sessionId manually in the client-side? I was under the impression that it happens automatically. Edit: Btw, looks like you are right. After the login, a session key is assigned, but further requests arrive with no session key
type: Comment

http://stackoverflow.com/comment/87796497
has text: I think you are not setting your path right. Try using `export PATH=$PATH:/place/with/the/file` without the curly braces and the quotes
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50389926
score: 0

http://stackoverflow.com/comment/87872401
score: 0
type: AnswerComment
has text: @GregEremeev The brew installation failed because of conflicting files.
comment on: http://stackoverflow.com/a/50428732
type: Comment

http://stackoverflow.com/comment/88074582
has text: @Hennich, I don't think you waste time in doing the actual arithmetic (`0/0` is not actually calculated with sparse matrix arithmetic in `scipy`, at least in some sparse formats), but you do waste a lot of space for big matrices, and you waste *some* time in actually *producing* the dense from the result of the operation.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50530507
score: 0

http://stackoverflow.com/a/50450433
accepted answer of: http://stackoverflow.com/q/50450279
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50450279
upvote count: 3
score: 3
downvote count: 0
has body: You are here defining a dictionary, so for that you need to pass a key variable that should be string, like: Sample_FIGHT = { "player_damage": "You desperately try to stop the %s for %i damage", "enemy_damage": "%s gores you for %i damage", "player_win": "The %s collapses with a thunderous boom", "enemy_win": "You are squished" }

http://stackoverflow.com/q/50538699
tagged with: jsonb
tagged with: psycopg2
has answer: http://stackoverflow.com/a/50538702
favorite count: 0
type: Question
tagged with: postgresql
type: UnansweredQuestion
has title: SQLAlchemy/psycopg2: JSONB columns are being returned as strings instead of dicts Python
tagged with: python
has body: If I have a table with a JSONB column, using SQLAlchemy engines to run a direct "execute" query (engine.execute, session.execute, etc.) returns strings for the JSONB instead of dicts. I'm using the latest SQLAlchemy, what's going on?
tagged with: sqlalchemy
score: 2
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/q/50436798
has body: I was trying to test out selenium, and the code asks me to run a script browser = webdriver.Firefox() However, this is the problem I get. Hope the gurus of the coding world can help me. This is Python 3 on Windows 10.
tagged with: python
has title: Opening Firefox with selenium error
accepted answer: http://stackoverflow.com/a/50436826
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50436826
answer count: 1
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/87893390
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87900399
tagged with: python-3.x
upvote count: 2
linked to: http://stackoverflow.com/q/40208051
has comment: http://stackoverflow.com/comment/87887712

http://stackoverflow.com/comment/87926524
type: QuestionComment
comment on: http://stackoverflow.com/q/50455880
type: Comment
has text: searched it up but when i put in the bot token in bot.connect (TOKEN) it says takes 1 pontential argument but 2 were given. do . do bot.run then bot.connect?
score: 0

http://stackoverflow.com/q/50541286
type: Question
upvote count: 1
tagged with: python
has title: Maya python : TypeError: coercing to Unicode: need string or buffer, int found
type: AnsweredQuestion
tagged with: python-2.7
has body: I'm trying to make a little script for batch rending for maya and every time I have this error at the line for i in xrange((startFrame)+"," +(endFrame) + int(1)): : in Batch # TypeError: coercing to Unicode: need string or buffer, int found the code : def Batch(ignore): # Settings startFrame = cmds.textField (myStart, query=True, text=True) endFrame = cmds.textField (myEnd, query=True, text=True) Camera = cmds.textField (myCamera,query=True, text=True) for i in xrange((startFrame)+"," +(endFrame) + int(1)): maya.cmds.currentTime(i) mel.eval('execRmanMenuItem("Render");') editor = 'renderView' I'll be very thankful if someone could help me.
answer count: 1
has comment: http://stackoverflow.com/comment/88093861
downvote count: 0
tagged with: maya
accepted answer: http://stackoverflow.com/a/50541313
score: 1
has comment: http://stackoverflow.com/comment/88093886
favorite count: 0
has answer: http://stackoverflow.com/a/50541313

http://stackoverflow.com/q/50483576
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/102051537
linked to: http://stackoverflow.com/q/57780333
score: 5
upvote count: 5
possible better answer: http://stackoverflow.com/a/58816007
tagged with: python
has answer: http://stackoverflow.com/a/57811428
has answer: http://stackoverflow.com/a/58816007
has title: multiprocessing.Process doesn't terminate after putting requests response.content to queue
tagged with: python-multiprocessing
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/50483939
downvote count: 0
has answer: http://stackoverflow.com/a/50483939
tagged with: python-requests
has body: I'm trying to run multiple API requests in parallel with multiprocessing.Process and requests. I put urls to parse into JoinableQueue instance and put back the content to the Queue instance. I've noticed that putting response.content into the Queue somehow prevents the process from terminating. Here's simplified example with just 1 process (Python 3.5): import multiprocessing as mp import queue import requests import time class ChildProcess(mp.Process): def __init__(self, q, qout): super().__init__() self.qin = qin self.qout = qout self.daemon = True def run(self): while True: try: url = self.qin.get(block=False) r = requests.get(url, verify=False) self.qout.put(r.content) self.qin.task_done() except queue.Empty: break except requests.exceptions.RequestException as e: print(self.name, e) self.qin.task_done() print("Infinite loop terminates") if __name__ == '__main__': qin = mp.JoinableQueue() qout = mp.Queue() for _ in range(5): qin.put('http://en.wikipedia.org') w = ChildProcess(qin, qout) w.start() qin.join() time.sleep(1) print(w.name, w.is_alive()) After running the code I get: Infinite loop terminates ChildProcess-1 True Please help to understand why the process doesn't terminate after run function exits. Update: added print statement to show the loop terminates
favorite count: 0
type: Question

http://stackoverflow.com/q/50394633
score: 3
tagged with: python
linked to: http://stackoverflow.com/q/40852729
has title: Tensorflow: how to convert a frozen model to saved model
type: Question
has body: I'm trying to convert this Frozen Model ( extension .pb) from here: https://www.dropbox.com/s/bb7n78hq5owyjr0/tf_model_pb.zip?dl=0 To a Saved Model. Is it possible? Can you share the exact code to convert this pb file to saved model?
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54758707
answer count: 1
has comment: http://stackoverflow.com/comment/99258499
downvote count: 0
tagged with: tensorflow
favorite count: 0
tagged with: model
has comment: http://stackoverflow.com/comment/99286897
tagged with: python-3.x
linked to: http://stackoverflow.com/q/56340852

http://stackoverflow.com/comment/87788997
comment on: http://stackoverflow.com/q/50386340
type: Comment
has text: On Win64, there is only one ABI so WinDLL and CDLL make no difference. On Win32, variadic functions are cdecl not stdcall so WinDLL is using the wrong calling convention.
score: 2
type: QuestionComment

http://stackoverflow.com/a/50537422
type: Answer
has body: Create new dataframe Here is one way making use of update: df3 = df1[:].set_index('ID') df3['Data'].update(df2.set_index('ID')['Data']) df3.reset_index(inplace=True) Or we could use maps/dicts and reassign (Python >= 3.5) m = {**df1.set_index('ID')['Data'], **df2.set_index('ID')['Data']} df3 = df1[:].assign(Data=df1['ID'].map(m)) Python &lt; 3.5: m = df1.set_index('ID')['Data'] m.update(df2.set_index('ID')['Data']) df3 = df1[:].assign(Data=df1['ID'].map(m)) Update df1 Are you open to update the df1? In that case: df1.update(df2) Or if ID not index: m = df2.set_index('ID')['Data'] df1.loc[df1['ID'].isin(df2['ID']),'Data'] =df1['ID'].map(m) Or: df1.set_index('ID',inplace=True) df1.update(df2.set_index('ID')) df1.reset_index(inplace=True) Note: There might be something that makes more sense :) Full example: import pandas as pd data1 = '''\ ID Data Data1 1 AA BB 2 AB BF 3 AC BK 4 AD BL''' data2 = '''\ ID Data 1 AAB 3 AAL 4 MNL 5 AAP 6 MNX 8 DLP 9 POW''' df1 = pd.read_csv(pd.compat.StringIO(data1), sep='\s+') df2 = pd.read_csv(pd.compat.StringIO(data2), sep='\s+') m = {**df1.set_index('ID')['Data'], **df2.set_index('ID')['Data']} df3 = df1[:].assign(Data=df1['ID'].map(m)) print(df3) Returns: ID Data Data1 0 1 AAB BB 1 2 AB BF 2 3 AAL BK 3 4 MNL BL
accepted answer of: http://stackoverflow.com/q/50536846
upvote count: 2
type: AcceptedAnswer
score: 2
answers question: http://stackoverflow.com/q/50536846
downvote count: 0

http://stackoverflow.com/comment/87809827
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50396877
has text: `pandas` is definitely **not** efficient for holding dataframes. In fact, it just adds overhead. `pandas` works best with contiguous-memory arrays (e.g. `int`, `float`). Your best bet is to restructure your solution to avoid `pandas`.

http://stackoverflow.com/comment/102809407
type: QuestionComment
has text: @AndrewLavers Even when encoding variables, if you are expecting new categorical values for this variable to be present in the validation set / test set / production environment, you should encode all variables. Otherwise, there would be no difference between the "last value" and a new out-of-vocabulary value.
comment on: http://stackoverflow.com/q/50473381
type: Comment
score: 1

http://stackoverflow.com/q/50530496
has title: Monthly correlations of daily data between two pandas DataFrames
has body: I have two pandas DataFrames of daily data: import pandas as pd dates = pd.date_range('2016-01-01', '2018-01-01') ndays = len(dates) df1 = pd.DataFrame(np.random.rand(ndays, 3), columns=['a','b','c'], index=dates) df2 = pd.DataFrame(np.random.rand(ndays, 3), columns=['a','b','c'], index=dates) I would like to take the correlation of the values in each dataframe in non-overlapping monthly segments. The return value should be a DataFrame indexed by month, with columns ['a','b','c'], where each value is the correlation of daily values in df1 and df2 for that calendar month. I can perform this calculation looping over columns and months, but that does not sound like how a panda would do it. Is there a way to split two dataframes based on calendar month, apply a correlation between them, and combine into a single dataframe?
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50530773
type: Question
upvote count: 2
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50530773
score: 2
type: AnsweredQuestion

iterable-unpacking
type: Tag
tags question: http://stackoverflow.com/q/50430401
tag name: iterable-unpacking
tags question: http://stackoverflow.com/q/50506065

http://stackoverflow.com/q/50436596
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/95311762
has answer: http://stackoverflow.com/a/53237541
has answer: http://stackoverflow.com/a/67054522
upvote count: 22
has answer: http://stackoverflow.com/a/76232060
answer count: 5
type: UnansweredQuestion
downvote count: 0
has title: What is "add_fieldsets" for in UserAdmin in Django?
tagged with: django
has answer: http://stackoverflow.com/a/61327821
score: 22
favorite count: 0
type: Question
tagged with: user-administration
has answer: http://stackoverflow.com/a/72763977
has body: I'm following a tutorial on making a custom User for authentication purposes. The tutorial used a certain property add_fieldsets within UserAdmin. What does this mean? I can't seem to find any documentation on this. Here is the snippet: class UserAdmin(UserAdmin): """Define admin model for custom User model with no email field.""" fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ('Contact info', {'fields': ('contact_no',)}),) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'),}),) list_display = ('email', 'first_name', 'last_name', 'is_staff') search_fields = ('email', 'first_name', 'last_name') ordering = ('email',) Here is the tutorial I was following: How to use email as username for Django authentication (removing the username)

http://stackoverflow.com/comment/88004977
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50495986
has text: I see... please see my comment just above and see if you can edit your question to provide a [mcve] that helps us reproduce your issue.

http://stackoverflow.com/q/50538570
linked to: http://stackoverflow.com/q/19384532
has body: I have this dataframe: code 0 0000 1 0000 2 0123 3 0123 4 4567 I want to groupby code and count how many of each code there is in the dataframe, so it get to look like this: code count 0 0000 2 1 0123 2 2 4567 1 I was using: group=df.groupby('code').agg('count') However I wasn't getting it right. Can someone help?
has answer: http://stackoverflow.com/a/50944017
duplicate of: http://stackoverflow.com/q/19384532
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88089005
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/88089072
has title: Getting count groupby right on pandas
has comment: http://stackoverflow.com/comment/88090580
tagged with: pandas

http://stackoverflow.com/q/50494495
tagged with: selenium
has title: Can I minimize chrome window while selenium is running?
tagged with: google-chrome
downvote count: 1
favorite count: 0
type: Question
score: 5
has comment: http://stackoverflow.com/comment/88002534
has body: I have a project to get some information from website. I want to look at the process inside the chrome window, So I can't use headless browser. But sometimes I want to minimize the chrome window. But I found the selenium would go wrong after I minimize the chrome window manually, but sometimes not. When go wrong, exception element is not clickable at the point, other element will receive the click will be raised, or sometimes selenium just stop. I have searched for a long time that some people said that the chrome window should be focused on and can't be minimized by clicking '-' on the window title bar. And the alternative solution is: web.set_window_position(-2000,-2000) To make the window move out the screen. And someone says by simulating shortcuts to minimize the window. But I think it's the same as click '-' manually, am I wrong? My question is : Does selenium really requires chrome window not minimized? Why sometimes it can run selenium normally after minimized but sometimes not? If I use set_window_position(-2000,-2000) to move the window invisible, then I click the window icon on the bottom of os (I'm sorry that I don't know what it's called). Normally when clicked, the window will be minimized. So as for this chrome window, Will it be considered as minimized window and go wrong? I am really sorry for my poor English. I hope I have a clear description of my problem. Environment: python 3.6 chrome 66.0 selenium 3.11.0 windows server 2012 Edit to add code: wait.WebDriverWait(driver,100000).until(EC.visibility_of_element_located((By.ID,'commMgrCompositionMessage'))) textArea = driver.find_element_by_id('commMgrCompositionMessage') driver.execute_script("arguments[0].value="+"'"+modelStr+"';",textArea) time.sleep(1) wait.WebDriverWait(driver,10000).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'#sendemail_label'))) allSendMailLabel = driver.find_elements_by_css_selector('#sendemail') allSendMailLabel = allSendMailLabel[1] driver.execute_script("arg…
type: UnansweredQuestion
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/50494694
has comment: http://stackoverflow.com/comment/88001919
linked to: http://stackoverflow.com/q/11908249
answer count: 1

http://stackoverflow.com/q/50529508
has answer: http://stackoverflow.com/a/50530295
score: 0
tagged with: python
tagged with: regex
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88071332
answer count: 1
has title: Grab one or two words IF capitalised after a pattern and match the result with another list
has body: I need to extract unique names with titles such as Lord|Baroness|Lady|Baron from text and match it with another list. I struggle to get the right result and hope the community can help me. Thanks! import re def get_names(text): # find nobel titles and grab it with the following name match = re.compile(r'(Lord|Baroness|Lady|Baron) ([A-Z][a-z]+) ([A-Z][a-z]+)') names = list(set(match.findall(text))) # remove duplicates based on the index in tuples names_ = list(dict((v[1],v) for v in sorted(names, key=lambda names: names[0])).values()) names_lst = list(set([' '.join(map(str, name)) for name in names_])) return names_lst text = 'Baroness Firstname Surname and Baroness who is also known as Lady Anothername and Lady Surname or Lady Firstname.' names_lst = get_names(text) print(names_lst) Which now yields:['Baroness Firstname Surname'] Desired output: ['Baroness Firstname Surname', 'Lady Anothername'] but NOT Lady Surname or Lady Firstname Then I need to match the result with this list: other_names = ['Firstname Surname', 'James', 'Simon Smith'] and drop the element 'Firstname Surname' from it because it matches the first name and surname of the Baroness in 'the desired output'.
accepted answer: http://stackoverflow.com/a/50530295
type: Question

http://stackoverflow.com/comment/87904063
type: AnswerComment
has text: Note this is 1.6x faster than the solution you linked to for the sentence in question.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50444295

http://stackoverflow.com/q/50385463
answer count: 1
has comment: http://stackoverflow.com/comment/87796624
linked to: http://stackoverflow.com/q/47619545
score: 0
has comment: http://stackoverflow.com/comment/87791012
has title: Chevron linestyle in matplotlib
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87883168
tagged with: linestyle
has comment: http://stackoverflow.com/comment/87787518
has body: Is it possible to make a dashed linestyle using more complicated shapes in matplotlib (or any other python plotting library)? It's easy to make a linestyle with different spacings and combinations of dots and dashes, but I'm after something like this: I can envision a way of doing it by writing a function from scratch to take a custom chevron marker style and working out the angle to display it at and the correct spacing etc. However that seems like an overly complicated way to address the problem that will easily break down for things like different specified line widths.
type: Question
has answer: http://stackoverflow.com/a/56640299
has comment: http://stackoverflow.com/comment/87796712
type: UnansweredQuestion

http://stackoverflow.com/comment/87993197
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50490018
has text: you can try recursively search this line on entire filesystem `grep -r "python3 app.py" /`

http://stackoverflow.com/a/50536600
has body: from itertools import product, islice from time import time length = 16 def generate(start, alphabet): """ A recursive generator function which works like itertools.product but restricts the alphabet as it goes based on the letters accumulated so far. """ if len(start) == length: yield start return gcs = start.count('g') + start.count('c') if gcs &gt;= length * 0.5: alphabet = 'at' # consider the maximum number of Gs and Cs we can have in the end # if we add one more A/T now elif length - len(start) - 1 + gcs &lt; length * 0.4: alphabet = 'gc' for c in alphabet: if start.endswith(c * 3): continue for string in generate(start + c, alphabet): yield string def brute_force(): """ Straightforward method for comparison """ lower = length * 0.4 upper = length * 0.5 for s in product('atgc', repeat=length): if lower &lt;= s.count('g') + s.count('c') &lt;= upper: s = ''.join(s) if not ('aaaa' in s or 'tttt' in s or 'cccc' in s or 'gggg' in s): yield s def main(): funcs = [ lambda: generate('', 'atgc'), brute_force ] # Testing performance for func in funcs: # This needs to be big to get an accurate measure, # otherwise `brute_force` seems slower than it really is. # This is probably because of how `itertools.product` # is implemented. count = 100000000 start = time() for _ in islice(func(), count): pass print(time() - start) # Testing correctness global length length = 12 for x, y in zip(*[func() for func in funcs]): assert x == y, (x, y) main() On my machine, generate was just a bit faster than brute_force, at about 390 seconds vs 425. This was pretty much as fast as I could make them. I think the full thing would take about 2 hours. Of course, actually processing them will take much longer. The problem is that your constraints don't reduce the full set much. Here's an example of how to use this in parallel across 16 processes: from multiprocessing.pool import Pool alpha = 'atgc' def generate_worker(start): start = ''.join(start) for s in generate(start, alpha): print(s) Pool…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50519202
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50519202
score: 1

http://stackoverflow.com/q/50492194
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50492258
has answer: http://stackoverflow.com/a/50492258
has title: Python Pandas search for strings with metacharacters
type: Question
accepted answer: http://stackoverflow.com/a/50492256
tagged with: python
has answer: http://stackoverflow.com/a/50492256
has body: Currently I have a DataFrame as below: index Name Value 0 j_smith[1] 32 1 j_smith[32] 46 2 r_lee[2] 52 3 m_brent[3] 61 4 j_perry[4] 75 5 j_perry[6] 81 6 j[3] 92 7 j[4] 72 8 r[4] 63 9 m_jackson[3] 78 10 r_j[11] 98 In the dataframe, the names are formatted as 'first name initial'_'last name'[numbers] 'first name initial'[Numbers] 'first name initial'_'last name initial'[Numbers] I tried to use the pd.str.contains function to find the rows with 'j_perry' and 'j'(not item with r_j) as below: Score = DF[DF['Name'].str.contains('j_perry[\d+]|j[\d+]')] I got nothing from Score DataFrame. I think the problem is from the metacharacters: [ ]. How can I solve this problem?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50496361
has answer: http://stackoverflow.com/a/50502373
score: 0
linked to: http://stackoverflow.com/q/32982425
has body: I have something like that: wines = spark.table("dane_nowe_csv") selected = wines.select("price") Price is a double. The question is how can i convert this "selected" to valid type to use with that: clusters = KMeans.train(selected, 2, maxIterations=10, initializationMode="random") I'm trying to do that a lot of time today, I searched dozens of topics and there is always some errors and I have a feeling that there is some easy way to do this.
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/88005507
tagged with: pyspark
duplicate of: http://stackoverflow.com/q/32982425
tagged with: python
has title: Kmeans using DataFrame column
type: Question
tagged with: apache-spark-sql
type: UnansweredQuestion
answer count: 1
tagged with: apache-spark-ml

http://stackoverflow.com/comment/88030504
score: 0
comment on: http://stackoverflow.com/q/50509230
has text: If `config_file` is a dictionary object this works with `get()`. The `config_file` might be a `list` object
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88084557
type: Comment
comment on: http://stackoverflow.com/q/50535957
type: QuestionComment
has text: Also, many times they confuse the concept of thread with QThread, QThread is a handle of a native thread. the native thread is executed in run(), and if you use moveToThread you are moving that object to run(), so the constructor is not being executed in the native thread. I think that your ignorance about it is the cause of your questions.
score: 0

http://stackoverflow.com/a/52278528
has body: Pip is not bundled in the EPEL version of python 3.6 for some reason. I assume a decent amount of people (such as me) will find this page because of that. $ sudo yum install -y python36 ... $ python36 -m pip /usr/bin/python36: No module named pip So in this case, the setuptools package was the easiest solution. $ sudo yum install python36-setuptools $ sudo easy_install-3.6 pip ... $ python36 -m pip --version pip 18.0 from /usr/local/lib/python3.6/site-packages/pip-18.0-py3.6.egg/pip (python 3.6)
score: 5
downvote count: 0
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50408941

http://stackoverflow.com/comment/87962691
score: 0
has text: If you're referring to why the dtype if `datetime64[ns]` instead of `datetime64[D]` I found this other useful SO link https://stackoverflow.com/questions/31917964/python-numpy-cannot-convert-datetime64ns-to-datetime64d-to-use-with-numba
type: Comment
comment on: http://stackoverflow.com/q/50474488
type: QuestionComment

http://stackoverflow.com/q/50535619
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88185105
tagged with: python
has comment: http://stackoverflow.com/comment/88164157
score: 0
has body: How do I check that sess.run got through all data within one epoch without specifing num_epochs in slice_input_producer? I thought that using while not coord.should_stop() (see code below) should stop once it went through all data, but it never stops. It just iterates over and over. Is the only solution to set num_epochs=1 in slice_input_producer and than catch it in tf.errors.OutOfRangeError and thus I'll know that that it went through all data? batch_size = 3 input_queue = tf.train.slice_input_producer([image_filenames, label_filenames], num_epochs=None, shuffle=True) image_batch, label_batch = generate_batch(input_queue, batch_size) with tf.Session(...) as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) try: while not coord.should_stop(): images,labels = sess.run([train_image_batch, train_label_batch]) pltShow(images, labels) except tf.errors.OutOfRangeError: print('OutOfRangeError') finally: print("requesting threads to stop.") coord.request_stop() UPDATE1 I tried setting num_epochs=1 in slice_input_producer and then doing this, but it didn't help. It stops after first epoch epoch = 0 while epoch &lt; 10: try: while not coord.should_stop(): images,labels = sess.run([train_image_batch, train_label_batch]) pltShow(images, labels) except tf.errors.OutOfRangeError: print('OutOfRangeError') finally: print("requesting threads to stop.") epoch += 1
has comment: http://stackoverflow.com/comment/88083854
has comment: http://stackoverflow.com/comment/88083789
has comment: http://stackoverflow.com/comment/88083820
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88113790
has comment: http://stackoverflow.com/comment/88165290
type: Question
has title: How to check that I went through all data within one epoch?

http://stackoverflow.com/q/50472771
answer count: 1
has comment: http://stackoverflow.com/comment/87963461
has comment: http://stackoverflow.com/comment/87959213
has answer: http://stackoverflow.com/a/50473012
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87961788
has title: Reading text file with blanks spaces, values, brackets and special characters
score: 0
has body: I have a csv document that I can read to extrapolate columns, which are of the format: ' 46.0213(3) ', ' 101.2 ', ' 105.8(4) ', ' -- ', ' 117.2 or 22.25 ', ' 132.18900 ', ' -- ', ' 172.7(6)' where: Blank spaces should be stripped off when I am going to consider the number, that is the int() of the list element; the number in brackets at the end of each elements refers to the error (last digit for that value). This has to be taken and processed separately; The value -- means that no value is known for that case. Probably a NaN should be attributed in this case; The first of the two values in case the string element is x or y How do I deal with all those specific requests? I do not need a code for everything, but just a "code of conduct" and some suggestions to find out what is the best approach here. This is the code I use to read the text file: #!/usr/local/bin python import os, re, glob, csv with open('data.txt', 'r') as fp: reader = csv.reader(fp, delimiter=',', quotechar='(') column_I_want = list(zip(*reader))[4] print column_I_want EDIT: This is a sort of desired output: print values, error # [ 46.0213, 101.2, 105.8, NaN, 117.2, 132.18900, NaN, 172.7], [0.3, Nan, 0.4, NaN, NaN, NaN, 0.6]
tagged with: list
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87962551

http://stackoverflow.com/a/50388781
has comment: http://stackoverflow.com/comment/87805745
accepted answer of: http://stackoverflow.com/q/50388633
answers question: http://stackoverflow.com/q/50388633
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: We can first construct the url as a template: url_template = Template(url) then we render it with the given parameters: context = Context({'para1':para1, 'para2':para2}) our_url = url_template.render(context) then our_url is rendered correctly, and we can insert it into our real template rendering: return render(request, 'userpage.html', {'url': our_url}) So that means we get something like: def userpage(request): url_obj = Url.objects.filter(id=..not_important...)[0] url = url_obj.url para1_obj = Parameter.objects.filter(..not_important..)[0] para1 = para1_obj.para para2_obj = Parameter.objects.filter(..not_important..)[0] para2 = para2_obj.para url_template = Template(url) context = Context({'para1':para1, 'para2':para2}) our_url = url_template.render(context) return render(request, 'userpage.html', {'url': our_url}) Note that if you have a rather large table of parameters, you better construct the dictionary dynamically with: para_dict = { 'para{}'.format(para.id): para.para for para in Parameter.objects.all() }
type: Answer

http://stackoverflow.com/comment/87856124
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50420017
has text: yes I am, for now

http://stackoverflow.com/a/50523519
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88088522
score: 2
downvote count: 0
has body: you should use attribute, object is the instance of model class not dict var_a = obj.foo var_b = obj.bar result = var_a * var_b and best is create property in the declare of the model: Class MyModel(models.Model): foo = models.FloatField() bar = models.FloatField() @property def multiply_fb(self): return self.foo * self.bar and in the view: class MyView(generic.ListView): template_name = "my_item_list.html" model = MyModel def get_context_data(self, **kwargs): obj = MyModel.objects.get(pk=this_object_id) context = { 'result': obj.multiply_fb, } return context
type: Answer
answers question: http://stackoverflow.com/q/50523484
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50523484

http://stackoverflow.com/comment/88083751
type: QuestionComment
comment on: http://stackoverflow.com/q/50535832
has text: The thing is I don't know how to get key status other than from keyboard and mouse events.
type: Comment
score: 0

http://stackoverflow.com/comment/87982025
type: QuestionComment
has text: And what's preventing you from doing that?
comment on: http://stackoverflow.com/q/50484496
score: 1
type: Comment

http://stackoverflow.com/q/50520407
type: AnsweredQuestion
has title: Can get combined tuple tensor using tf.concat?
tagged with: python
accepted answer: http://stackoverflow.com/a/50520666
type: Question
has body: I'm apparently novice to tensorflow and trying to make new tensor using two existing tensors. Let's say there are two tensors t1 and t2. t1 = [1, 2, 3, 4, 5, 6] t2 = [7, 8, 9, 10, 11, 12] Is there anyway I can get new tensor t3 shaped like as following using tf.concat? t3 = [(1,7),(2,8),(3,9),(4,10),(5,11),(6,12)] So the first item in the first tensor combined with the first item in the second tensor and converted combined item as a tuple.
tagged with: tensor
score: 0
answer count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50520666

http://stackoverflow.com/a/50410814
has body: Use reindex if unique values of col1: a = df.set_index('col1').reindex(my_list)['col2'].values.tolist() print (a) [90, 70, 80] Or ordered categoricals: from pandas.api.types import CategoricalDtype cat_type = CategoricalDtype(categories=my_list, ordered=True) df['col1'] = df['col1'].astype(cat_type) df = df.sort_values('col2', ascending=False) print (df['col2'].tolist()) [90, 80, 70] df['col1'] = pd.Categorical(df['col1'], my_list, ordered=True) df = df.sort_values('col2', ascending=False) print (df['col2'].tolist()) [90, 80, 70]
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50410775
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87958601
comment on: http://stackoverflow.com/q/50472421
score: 0
has text: @MatheusBernardi, what is `out[0]`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87961471
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50473904
has text: I was trying to not use classes because I plan to rebuild this project using classes and so on because it's cleaner code. This is my second project learning python.
type: Comment

http://stackoverflow.com/comment/87889013
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50437484
type: Comment
has text: i dont have space before str(a) and s.sendmail(mml,em,a) just thats by wrong when posting

http://stackoverflow.com/q/50409345
tagged with: flask
has comment: http://stackoverflow.com/comment/87884113
upvote count: 6
has body: I am making a flask restful API, what I'm having trouble with is marshmallow-sqlalchemy, and webargs. In short here is my sqlalchemy model: class User(Model): id = Column(String, primary_key=True) name = Column(String(64), nullable=False) email = Column(String(120), nullable=False) password = Column(String(128)) creation_date = Column(DateTime, default=datetime.utcnow) and this is my schema: class UserSchema(ModelSchema): class Meta: model = User strict = True sqla_session = db.session user_schema = UserSchema() and an example of my routes using flask-classful and webargs: class UserView(FlaskView): trailing_slash = False model = User schema = user_schema @use_kwargs(schema.fields) def post(self, **kwargs): try: entity = self.model() for d in kwargs: if kwargs[d] is not missing: entity.__setattr__(d, kwargs[d]) db.session.add(entity) db.session.commit() o = self.schema.dump(entity).data return jsonify({'{}'.format(self.model.__table__.name): o}) except IntegrityError: return jsonify({'message': '{} exist in the database. choose another id' .format(self.model.__table__.name)}), 409 @use_kwargs(schema.fields) def put(self, id, **kwargs): entity = self.model.query.filter_by(id=id).first_or_404() for d in kwargs: if kwargs[d] is not missing: entity.__setattr__(d, kwargs[d]) db.session.commit() o = self.schema.dump(entity).data return jsonify({'{}'.format(self.model.__table__.name): o}) UserView.register(app) The problem: As you can see in my sqlalchemy model, some fields are not nullable, thus my marshmallow schemda marks them as required. My get, index, delete and post methods all work perfectly. But I included post for one reason: when I try to post a new user with no name for example, a 422 http code is raised because name field is required, which is something I want and it is done perfectly. BUT when editing fields with put request, I wish EVERYTHING in my schema becomes optional.. right now if I wanted to update a user, I must provide not only the id.. but ALL othe…
type: AnsweredQuestion
tagged with: webargs
answer count: 2
has comment: http://stackoverflow.com/comment/87836090
has comment: http://stackoverflow.com/comment/87883757
downvote count: 0
possible better answer: http://stackoverflow.com/a/76667899
accepted answer: http://stackoverflow.com/a/50435055
has comment: http://stackoverflow.com/comment/96188286
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/76667899
has answer: http://stackoverflow.com/a/50435055
has title: flask-marshmallow: how to mark all fields as optional only when the method is PUT
has comment: http://stackoverflow.com/comment/93338498
score: 6
tagged with: python
tagged with: marshmallow

http://stackoverflow.com/comment/87824722
type: QuestionComment
comment on: http://stackoverflow.com/q/50404640
score: 1
type: Comment
has text: Hard to say without understanding exactly what you are trying to accomplish. I have never see Enums used to keep track of any set of relationships more complicated than simple bookkeeping. Enums weren't even a language feature until Python3.4 so the language clearly wasn't designed with them as being a necessary construct, but more added for convenience. What relationships are you trying to capture exactly?

http://stackoverflow.com/q/50391185
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
has body: pptx library to edit/add content to a ppt. I am adding a chart using below code to a slide but not able to delete the existing one so both are overlapping. Actually wanted to delete existing chart before adding new chart at same place. I am using below code as per doc. chart_data = ChartData() chart_data.categories = ['East', 'West', 'Midwest'] chart_data.add_series('Series 1', (19.2, 21.4, 16.7)) x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5) zz = ninth_sld.shapes.add_chart( XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data) #ninth_slide.shapes.clear() chart1 = zz.chart chart1.replace_data(chart_data)
tagged with: python-pptx
tagged with: python
has comment: http://stackoverflow.com/comment/88287060
has title: Python-pptx Not able to remove/delete existing graph from ppt
has comment: http://stackoverflow.com/comment/101487625
answer count: 0
score: 2
upvote count: 2

http://stackoverflow.com/q/50494954
has body: I followed a tut Click me! and i get un-expected results: my code from PIL import ImageGrab, ImageOps import pyautogui import time from numpy import * class Cordinates(): replayBtn = (960,355) dinosaur = (784,375) #770x360, 770x365 def restartGame(): pyautogui.click(Cordinates.replayBtn) def pressSpace(): pyautogui.keyDown('space') time.sleep(0.05) print("Jump") pyautogui.keyUp('space') def imageGrab(): box = (Cordinates.dinosaur[0]+435, Cordinates.dinosaur[1]+25, Cordinates.dinosaur[1]+335, 10) image = ImageGrab.grab(box) grayImage = ImageOps.grayscale(image) a = array(grayImage.getcolors()) return a.sum() def main(): restartGame() while True: if imageGrab()!=1447: #pressSpace() print(imageGrab) time.sleep(0.1) time.sleep(2) main() and the print i added for debug gives me &lt;function imageGrab at 0x079CBD68&gt; What can i fix to make this work?
type: Question
tagged with: python-imaging-library
tagged with: python
has title: Game bot error (python chrome dinousor game error)
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50497114
answer count: 1
has answer: http://stackoverflow.com/a/50497114
favorite count: 0
tagged with: numpy

http://stackoverflow.com/a/50454247
type: AcceptedAnswer
has body: I found the answer! But the answer involves not using pandas, which is why I changed the title. There is an open source SAS7BDAT implementation for Apache Spark. (It's written in Scala). "This format is splittable when input is uncompressed thus can achieve high parallelism for a large SAS file.... Thanks to the splittable SasInputFormat, we are able to convert a 200GB (1.5Bn rows) .sas7bdat file to .csv files using 2000 executors in under 2 minutes." With this code, the efficient way to count the number of lines would be: from pyspark.sql import SQLContext sqlContext = SQLContext(sc) df = sqlContext.read.format("com.github.saurfang.sas.spark").load("input.sas7bdat") print("Number of rows in input.sas7bdat: {}".format(df.count()))
score: 0
accepted answer of: http://stackoverflow.com/q/50419361
type: Answer
answers question: http://stackoverflow.com/q/50419361

http://stackoverflow.com/q/50486381
tagged with: python
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/88016935
score: 0
has comment: http://stackoverflow.com/comment/87989258
answer count: 0
tagged with: openai-gym
has comment: http://stackoverflow.com/comment/87986140
tagged with: python-module
tagged with: debian
type: Question
has title: openAi gym for python linux debain
has comment: http://stackoverflow.com/comment/88018884
type: UnansweredQuestion
has body: I am having a problem with openAi gym, I install it with the command: &gt; pip install gym but when I tried to run the program called cig3.py: import gym env = gym.make('CartPole-v0') env.reset() for _ in range(1000): env.render() env.step(env.action_space.sample()) I get that message: Traceback (most recent call last): File "cig3.py", line 1, in &lt;module&gt; import gym ModuleNotFoundError: No module named 'gym' I am working in this version: Linux mgdebian 4.9.0-6-amd64 #1 SMP Debian 4.9.88-1+deb9u1 (2018-05-07) x86_64 GNU/Linux and with Python 3.6.4 does anyone know what the problem?
has comment: http://stackoverflow.com/comment/88019961

http://stackoverflow.com/q/50490494
downvote count: 0
has answer: http://stackoverflow.com/a/50490530
tagged with: python
answer count: 1
has body: I have a df with multiple headers : multicol = pd.MultiIndex.from_tuples([('France', '2017'), ('France', '2018'),('UK', '2017'), ('UK', '2018')], names = ("Country", "Year")) df = pd.DataFrame([[1, 2, 5, 8], [2, 4, 2, 9]], index=['Number', 'Volume'], columns=multicol) I want to print only the column France for 2018. How can I do that ?
score: 6
upvote count: 6
type: Question
tagged with: pandas
type: AnsweredQuestion
has title: Select a column in a multiple headers dataframe
favorite count: 0
accepted answer: http://stackoverflow.com/a/50490530

http://stackoverflow.com/comment/88060190
type: Comment
type: QuestionComment
has text: It looks, as if vowelIndex was intended to be a class, where the constructor receives the wd argument, which can then be used by all subsequent methods.
score: 0
comment on: http://stackoverflow.com/q/50523844

http://stackoverflow.com/comment/87953795
comment on: http://stackoverflow.com/a/50464603
score: 0
type: AnswerComment
type: Comment
has text: Please approve the answer

http://stackoverflow.com/comment/87887960
has text: I just know the lstm encoder decoder has to predict the same data therefore xtrain, xtrain. but I cant figure out how to define the dec_inputs. I mean cant I say the model encode the input and take this as input for the decoder ? it does not make sense for me or I do understand it at all. Besides it is important the the encoders inital state is the same with the one from the decoder. Maybe you have an example for me how to fix this ?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50436841
type: Comment

http://stackoverflow.com/comment/88050221
type: QuestionComment
has text: so creating a new ID for the last 2 occurrences? where does the 3rd value in the tuple come from? 155 etc, it seems to carry over to the new set of ID's too, but does not appear in your first list.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50518653

http://stackoverflow.com/q/50489136
has title: Python: random.seed is different but randint generate same number
has comment: http://stackoverflow.com/comment/87991579
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87992157
tagged with: python
score: -1
tagged with: python-2.7
upvote count: 0
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50490783
has comment: http://stackoverflow.com/comment/87991150
has body: I am facing a very unique issue. random.seed(123) rg = PhoneMetadata.metadata_for_region(random.choice(('US', 'FR', 'IN', 'GB'))) pl = rg.mobile.possible_length cc = rg.country_code print(''.join(str(random.randint(0, 9)) for _ in range(pl[0]))) --3982597919 random.seed(345) rg = PhoneMetadata.metadata_for_region(random.choice(('US', 'FR', 'IN', 'GB'))) pl = rg.mobile.possible_length cc = rg.country_code print(''.join(str(random.randint(0, 9)) for _ in range(pl[0]))) --3982597919 I am giving different seeds number but the output its giving me the same number. Its not happening every time but i am facing this issue randomly. Any help would be really appreciated.
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/88090022
comment on: http://stackoverflow.com/a/50539099
has text: That mismatch is fine... I'm more worried with the milliseconds and the timezone ... could you help me with that?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50428414
tagged with: apache-spark
answer count: 1
tagged with: rdd
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50428593
accepted answer: http://stackoverflow.com/a/50428593
has body: I have a dictory in python {'609232972': 4, '975151075': 4, '14247572': 4, '2987788788': 4, '3064695250': 2} how can I directly load this in rdd, without loosing the key value pair? When I load it like this usr_group = sc.parallelize(partition) print(usr_group.take(5)) I just breaks up the key value pair and gives ['609232972', '975151075', '14247572', '2987788788', '3064695250'] I am expecting the RDD to break into {'609232972': 4, '975151075': 4, '14247572': 4, '2987788788': 4, '3064695250': 2} so that I can process the key-value pair together
downvote count: 0
tagged with: pyspark
tagged with: python
tagged with: dictionary
score: 4
has title: how do I load a dict type directly to an rdd
type: AnsweredQuestion

http://stackoverflow.com/comment/87941333
comment on: http://stackoverflow.com/a/50463935
type: Comment
type: AnswerComment
has text: Its not fix. Sometimes it has `[{( ` and sometimes `[{` only. And same thing at the end of string.
score: 0

http://stackoverflow.com/a/50458577
type: Answer
has body: @cdc200, you can try the below code. Here I have used the concept of dictionary. Note» Dictionary is defined as an unordered collection of data items with unique keys. I have used OrderedDict () in place of dict() to preserve the order of keys. Check this nice little article OrderedDict in Python - GeeksforGeeks. import json from collections import OrderedDict d1 = {"id":"a", "foo":"bar", "baz":"bat"} d2 = {"id":"b", "foo":"bar", "baz":None} d3 = {"id":"a", "foo":"bar", "baz":None} d4 = {"id":"b", "foo":"bar", "baz":"bat"} l = [d1, d2, d3, d4] d = OrderedDict (); for index, item in enumerate(l): if item["id"] not in d: d[item["id"]] =item else: nones1, nones2 = 0, 0 for k in item: if item[k] is None: nones1 = nones1 + 1 if d[item["id"]][k] is None: nones2 = nones2 + 1 if nones2 &gt; nones1: d[item["id"]] = item l = [dict_item for dict_item in d.values()] print (l) """ {'foo': 'bar', 'id': 'a', 'baz': 'bat'}, {'foo': 'bar', 'id': 'b', 'baz': 'bat'}] """ # Pretty printing the above dictionary print(json.dumps(l, indent=4)) """ [ { "foo": "bar", "id": "a", "baz": "bat" }, { "foo": "bar", "id": "b", "baz": "bat" } ] """ Thanks.
answers question: http://stackoverflow.com/q/50453416
score: 0
has comment: http://stackoverflow.com/comment/87933037

http://stackoverflow.com/a/50555039
accepted answer of: http://stackoverflow.com/q/50492428
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50492428
downvote count: 1
has body: I think the selection of ul.list-unstyled in the subpage is too broad, there are too many of them with content that you don't actually want. If you really only want the phone numbers, you could directly search for the a tags where the href starts with "tel:". Problem still is that the these sites list multiple numbers this way, usually 2, where one of them is not visible. The one that's visible seems to always be undernath div.col-md-3. I tried this: def get_info(session,title,url): r = session.get(url) soup = BeautifulSoup(r.text,"lxml") for a_phone in soup.select("div.col-md-3 a[href^='tel:']"): print(title, a_phone.text) and got the following result: AK Frost (907) 563-9333 AK Fuzzy Budz (907) 644-2838 AK Joint (907) 522-5222 AK Slow Burn (907) 868-1450 Alaska Fireweed (907) 258-9333 Alaskabuds (907) 334-6420 Alaskan Leaf (907) 770-0262 Alaska's Green Light District (907) 644-2839 AM Delight (907) 229-1730 Arctic Herbery (907) 222-1466 Cannabaska (907) 375-9333 Catalyst Cannabis Company (907) 344-0668 Dankorage (907) 279-3265 Enlighten Alaska (907) 290-8559 Great Northern Cannabis (907) 929-9333 Hillside Natural Wellness (907) 868-8639 Hollyweed 907 (907) 929-3331 Raspberry Roots (907) 522-2450 Satori (907) 222-5420 The House of Green (907) 929-3105 Uncle Herb's (907) 561-4372 The Green Spot (907) 354-7044 Denali's Cannabis Cache (907) 683-2633 GOOD (907) 452-5463 Goodsinse (907) 347-7689 Grass Station 49 (907) 374-4420 Green Life Supply (907) 374-4769 One Hit Wonder (844) 420-1448 Pakalolo Supply Company (907) 479-9000 Rebel Roots (907) 455-4055 True Dank (907) 451-4516 The Herbal Cache (907) 783-0420 Denali 420 Recreationals (907) 892-9333 Glacier Valley Shoppe (907) 419-7943 Green Elephant (907) 290-8400 Rainforest Farms (907) 209-2670 The Fireweed Factory (907) 957-2670 Red Run Cannabis Company (907) 283-0800 Cannabis Corner (907) 225-4420 Rainforest Cannabis (907) 247-9333 The Stoney Moose (907) 617-8973 Chena Cannabis (907) 488-0489 The 420 (907) 772-3673 G…
type: Answer
has comment: http://stackoverflow.com/comment/88306976
upvote count: 4
score: 3

http://stackoverflow.com/comment/87969039
type: QuestionComment
has text: 1. What does happen? 2. Try printing "book[k]" instead of attempting to delete it. What gets printed?
comment on: http://stackoverflow.com/q/50477652
score: 0
type: Comment

http://stackoverflow.com/comment/88077065
has text: @BrendaMoura with what you say and your three xls files, what I have called `list_df_tratativaDois` should contain two dfs after your loop `for`, so `len(list_df_tratativaDois)` should give you 2. If not, it means that you don't go in the `else` part of the code, meaning your condition `if` is met more than one.
comment on: http://stackoverflow.com/a/50489392
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50482796
type: AnsweredQuestion
downvote count: 2
accepted answer: http://stackoverflow.com/a/50483384
upvote count: 1
tagged with: selenium
tagged with: web-scraping
has title: Unable to fetch article result from google search
favorite count: 0
has answer: http://stackoverflow.com/a/50483179
tagged with: beautifulsoup
type: Question
possible better answer: http://stackoverflow.com/a/50483179
answer count: 2
has answer: http://stackoverflow.com/a/50483384
has body: Im trying to read this link content via beautifulsoup and then trying to fetch article dates present in span.f import requests import json from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36'} from selenium import webdriver link="https://www.google.com/search?q=replican+party+announced&ie=utf-8&oe=utf-8&client=firefox-b" browser=webdriver.Firefox() browser.get(link) s=requests.get(link) soup5 =BeautifulSoup(s.content,'html.parser') Now i want to fetch all the article dates present in Apr 27, 2018 - along with their corresponding "link URL" But this code aint fetching anything for me for i in soup5.find_all("div",{"class":"g"}): print (i.find_all("span",{"class":"f"}))
tagged with: python
score: -1

http://stackoverflow.com/comment/87895562
has text: print at the very last line of the try section. also these comments are getting really long. you've got the answer to your original question, so probably asking another question will help you with that
type: Comment
comment on: http://stackoverflow.com/a/50440019
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87791630
type: Comment
comment on: http://stackoverflow.com/q/50387826
type: QuestionComment
has text: @RomanPerekhrest dct dictionary can be made key has 2d array's 1st array(like ['A','A'] or ['A','B'])'s 2nd element(which means A or B) and value has array of 2d array's 3st array(like ['W','NY'] or ['W','CF'] etc)'s 2nd element.
score: 0

http://stackoverflow.com/q/50390217
score: 0
has comment: http://stackoverflow.com/comment/87795990
tagged with: conv-neural-network
has title: How to properly represent a tic tac toe board to a cnn?
tagged with: python
tagged with: artificial-intelligence
has body: I'm figuring out how to manipulate convolutional neural networks (CNN) in python and I want to apply this kind of NN to an agent player that plays tic tac toe. I know that's weird and the problem doesn't need some elaborate and complex solutions like CNN, but I'm using this environment just to learn better and compare with the training of a MLP that I implemented. So, I'm trying to think about how to represent the board correctly as an input to the CNN. Unlike the chess board which we can think the input as 8x8x6 (8x8 as the 2d array representing the board and 6 channels which one representing the different pieces of the game), the tic tac toe is a bit more complicated for me because there are just one kind of piece. Is it possible and correct to represent the X and O as different pieces? Has anyone implemented something like this?
answer count: 0
has comment: http://stackoverflow.com/comment/87796021
type: UnansweredQuestion
tagged with: neural-network
has comment: http://stackoverflow.com/comment/87795979
tagged with: tic-tac-toe
type: Question
has comment: http://stackoverflow.com/comment/87798985

http://stackoverflow.com/q/50450654
favorite count: 0
type: Question
tagged with: opencv
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/50450988
tagged with: python
type: AnsweredQuestion
has title: Filling in Circles in OpenCV
answer count: 2
possible better answer: http://stackoverflow.com/a/50450875
has comment: http://stackoverflow.com/comment/87914780
downvote count: 0
has body: I've been struggling with this for a while. I've been trying to figure out some sort of a way in OpenCV in Python to fill in while circles in an image that's entirely black and white. To be clear this image has been tresholded using adaptive thresholding but now I have these rings which I'd like to be able to fill in. Ideally whatever algorithm is used to fill in circles should be able for both sets of pictures I included. If anyone could offer any guidance in this regard I'd greatly appreciate it. Before Algorithm: After Algorithm: Before Algorithm: After Algorithm:
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50450875
has answer: http://stackoverflow.com/a/50450988

http://stackoverflow.com/q/50387619
has body: Is there a way I can get a list of the applications that belong to a Django project itself (ignoring the apps that are installed with pip). Said with other words: can I exclude the apps that were installed with pip from settings.INSTALLED_APPS?
has answer: http://stackoverflow.com/a/50387953
tagged with: python
has title: Get own applications in Django
has comment: http://stackoverflow.com/comment/87791627
score: 2
answer count: 2
upvote count: 2
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/87790946
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87791970
has answer: http://stackoverflow.com/a/50388005
type: UnansweredQuestion

http://stackoverflow.com/q/50392372
has body: I'm trying to visualize the data with some outliers using Plotly and Python3. Outliers cause the color scale legend to look badly: there are only few high data points, but the legend looks bad: space between 2k and 10k is too big. So the question is, how to change the appearance of 'color legend' on the right (see image below), so it will show the difference between 0 to 2k mostly? Unfortunately, couldn't get an answer from this doc file Sample code (jupyter notebook): import numpy as np from plotly.offline import download_plotlyjs, init_notebook_mode, iplot from plotly.graph_objs import * init_notebook_mode() x = np.random.randn(100,1) + 3 y = np.random.randn(100,1) + 10 x = np.reshape(x, 100) y = np.reshape(y, 100) color = np.random.randint(0,1000, [100]) color[[1,3,5]] = color[[1,3,5]] + 10000 # create outliers in color var trace = Scatter( x = x, y = y, mode = 'markers', marker=dict( color = color, showscale=True, colorscale = [[0, 'rgb(166,206,227, 0.5)'], [0.05, 'rgb(31,120,180,0.5)'], [0.1, 'rgb(178,223,138,0.5)'], [0.15, 'rgb(51,160,44,0.5)'], [0.2, 'rgb(251,154,153,0.5)'], [1, 'rgb(227,26,28,0.5)'] ] ) ) fig = Figure(data=[trace]) iplot(fig) What i'm looking for:
answer count: 2
has comment: http://stackoverflow.com/comment/87830038
upvote count: 14
has comment: http://stackoverflow.com/comment/87846336
has answer: http://stackoverflow.com/a/50778339
has comment: http://stackoverflow.com/comment/87845266
downvote count: 0
favorite count: 0
type: Question
score: 14
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50778339
has comment: http://stackoverflow.com/comment/87833171
has comment: http://stackoverflow.com/comment/87832912
tagged with: plotly
possible better answer: http://stackoverflow.com/a/50451608
has title: Logarithmic color scale in plotly
tagged with: python
has answer: http://stackoverflow.com/a/50451608
tagged with: jupyter-notebook
tagged with: python-3.x

http://stackoverflow.com/comment/87881043
has text: Actually, can you try this for me? "with open(/Users/name/Dexktop/Trip.docx" as f: <newline><indent>r=f.read(20)<newline>' where <..> are the actions within the angle brackets and see if r contains anything afterewards?
comment on: http://stackoverflow.com/a/50433307
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50398397
answers question: http://stackoverflow.com/q/50398324
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: You may install packages for your Python 2.7 and 3.6 by using pip2 and pip3 respectively.

http://stackoverflow.com/comment/88042373
comment on: http://stackoverflow.com/a/50464158
type: AnswerComment
has text: Thanks a lot. Extracting the starting points from the data was a great addition.
score: 0
type: Comment

http://stackoverflow.com/q/50498073
downvote count: 1
has answer: http://stackoverflow.com/a/50498262
favorite count: 0
has comment: http://stackoverflow.com/comment/88009698
has body: I tried this code: re.findall(r"d.*?c", "dcc") to search for substrings with first letter d and last letter c. But I get output ['dc'] The correct output should be ['dc', 'dcc']. What did i do wrong?
has answer: http://stackoverflow.com/a/50498195
score: 0
has answer: http://stackoverflow.com/a/50498469
has answer: http://stackoverflow.com/a/50498167
tagged with: python
tagged with: regex
answer count: 4
has comment: http://stackoverflow.com/comment/88009161
linked to: http://stackoverflow.com/q/11430863
type: Question
has title: Regex for search specific substring
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88009246
has comment: http://stackoverflow.com/comment/88009144
upvote count: 1
duplicate of: http://stackoverflow.com/q/11430863

http://stackoverflow.com/comment/88035890
type: QuestionComment
comment on: http://stackoverflow.com/q/50511707
has text: @anishtain4: why does that matter? They are iterating over something that yields objects with `.name` attributes. It doesn't matter what type of iterable they have here.
type: Comment
score: 1

http://stackoverflow.com/comment/101296952
has text: Please, explain (even briefly) what you code does and how it answer the question. Have a look at [*How do I write a good answer?*](https://stackoverflow.com/help/how-to-answer).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/57408155

http://stackoverflow.com/q/50463520
has comment: http://stackoverflow.com/comment/87942569
duplicate of: http://stackoverflow.com/q/207000
tagged with: python
has comment: http://stackoverflow.com/comment/87940384
tagged with: class
tagged with: scope
has comment: http://stackoverflow.com/comment/87940282
answer count: 0
has body: I have a few questions regarding programming terminologies. 1)I have the following code: class Dog(object): population = 0 ## class variable--for every instance of Dog, population will be increase by 1 def __init__(self, name): self.name = name self.num_legs = 4 Dog.population += 1 ## &lt;== add 1 to Dog population def get_num_legs(self): return self.num_legs dog1 = Dog('dog1') dog2 = Dog('dog2') print(Dog.population) print(dog1.population) ## What happened?## dog1.num_legs = 2 #changes the instance property of dog1 print("Dog1 has {} legs".format(dog1.get_num_legs())) print("Dog2 has {} legs".format(dog2.get_num_legs())) Dog.num_legs = 10 #changes the class variable of Dog Class dog1 = Dog('dog1') ## An instance of class dog dog2 = Dog('dog1') print("Dog1 has {} legs".format(dog1.get_num_legs())) print("Dog2 has {} legs".format(dog2.get_num_legs())) The output to this code is 2,4,4,4, and I would think that the reason why the class variable num_legs will not ever be shown to be 10 when we do print(instance.num_legs) is we always check whether the instance has a property of num_legs before we try to read from the class variable(In this case there will always be that property). However, this is just my laymen interpretation and I'm trying to find out what's the explanation with programming terminologies. Is it something similar to the namespaces and scopes in nested functions?
score: 1
downvote count: 0
has title: Python Classes properties and namespaces
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/207000
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/50487527
has body: I found the solution, after a few tries. It seems that the WhiteNoise documentation is a little bit outdated and doesn't mention everything. I changed the line from: app.wsgi_app = WhiteNoise(app.wsgi_app, root='static/') to: app.wsgi_app = WhiteNoise(app.wsgi_app, root=os.path.join(os.path.dirname(__file__), 'static'), prefix='static/') First of all, the prefixparameter is required (not mentioned in the documentation) and furthermore the Flask app did not know how to handle the 'static/' path therefore an absolute path has to be provided.
upvote count: 4
answers question: http://stackoverflow.com/q/50485530
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/95270274
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/50485530
has comment: http://stackoverflow.com/comment/87990246
has comment: http://stackoverflow.com/comment/87990837
has comment: http://stackoverflow.com/comment/87988835
type: Answer

http://stackoverflow.com/comment/87975179
has text: just use the descriptor mat entries. E.g. match = lowest sum of squared distances from one descriptor to each of the other image would be some kind of brute force matcher.
comment on: http://stackoverflow.com/q/50472180
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88043215
has text: I solved the problem
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50411559

http://stackoverflow.com/a/50401921
accepted answer of: http://stackoverflow.com/q/50401885
type: Answer
answers question: http://stackoverflow.com/q/50401885
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
has body: Take the second column starting at the first row: In [27]: x = np.arange(1, 10).reshape(3,3) # array([[1, 2, 3], # [4, 5, 6], # [7, 8, 9]]) In [31]: x[1:,2] Out[31]: array([6, 9])

http://stackoverflow.com/comment/87971245
comment on: http://stackoverflow.com/q/50461615
has text: Hi Toby - you are correct. I have made the necessary changes. I will post now. Appreciate you helping me with this
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50495878
tagged with: tensorflow
type: Question
has title: Tensorflow taking data size ( shape ) as dynamic and thus causing errors during node densing
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has body: I am training a model that the feature shape is [3751,4] and I'd like to use reshape and layer dense function built in Tensorflow to make the output labels have the shape [1,6]. The training and testing set are very similar, the only difference is that the testing data set has less batches than training set. Now I am having two hidden layers in my model that will do something like: input_layer = tf.reshape(features["x"], [1,-1]) first_hidden_layer = tf.layers.dense(input_layer, 4, activation=tf.nn.relu) second_hidden_layer = tf.layers.dense(first_hidden_layer, 5, activation=tf.nn.relu) output_layer = tf.layers.dense(second_hidden_layer, 6, activation=tf.nn.relu) This network structure is a function that both training and evaluating phase utilize. Partial code for training is like : nn = tf.estimator.Estimator(model_fn=model_fn, params=model_params, model_dir='/tmp/nmos_self_define') train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": train_features_numpy}, y=train_labels_numpy, batch_size = 3751, num_epochs=None, shuffle=False) # Train nn.train(input_fn=train_input_fn, max_steps=5000) And testing part is like: test_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": test_features_numpy}, y=test_labels_numpy, batch_size = 3751, num_epochs= 1, shuffle=False) ev = nn.evaluate(input_fn=test_input_fn) print("Loss: %s" % ev["loss"]) print("Root Mean Squared Error: %s" % ev["rmse"]) During training, there is no problem, the function can reshape the input data and do the dense part. During the testing, however, the tensor shape of the reshape function gives something like [1,?], which is different from the training phase ([1,15004]). And this caused the tf.layers.dense functions to fail because it cannot do the dense without knowing the actual shape of the tensor. The only difference between training and testing from my perspective is the num_epochs, but that shouldn't affect the input shape right? I don't understand why Tensorflow can reshape the tensor with so…
score: 0
tagged with: deep-learning
answer count: 1
has answer: http://stackoverflow.com/a/50506600

http://stackoverflow.com/comment/88003457
comment on: http://stackoverflow.com/a/50494767
type: AnswerComment
has text: @BruceWayne It produces a list. If it was a generator, you would get append a generator to the list instead of its values. This kind of things are what is explained in the Generator Expressions vs. List Comprehension question –
score: 0
type: Comment

http://stackoverflow.com/comment/87833085
type: QuestionComment
comment on: http://stackoverflow.com/q/50406874
has text: You can't change the dtype of a structured array field inplace. You have to make a new array with a `datetime64` field, and copy data to it.
type: Comment
score: 1

http://stackoverflow.com/comment/88037658
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50512511
has text: If you're running the function from within an interpreter, it will always print the return value of the function (unless it's part of a larger statement, like an assignment). A function that doesn't explicitly return returns `None`.

static-libraries
tag name: static-libraries
tags question: http://stackoverflow.com/q/50402092
type: Tag

http://stackoverflow.com/q/50388820
answer count: 3
has answer: http://stackoverflow.com/a/50388886
possible better answer: http://stackoverflow.com/a/50388886
downvote count: 1
has answer: http://stackoverflow.com/a/50389084
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50388970
accepted answer: http://stackoverflow.com/a/50388970
has title: Python reading from txt file
has comment: http://stackoverflow.com/comment/87793219
tagged with: python
score: -1
has body: I want to pull in a bunch of names from a text file into python (v3.6.5). My text file is plain text (file.txt) and I have each name on one line Name 1 Name 2 Name 3 etc. In python, I have verified that the path works with the following code path_to_file = "D:\(my user name)\Documents\names.txt" file_object = open(path_to_file, "r") print(file_object) That returns the path to the file in the console which means it is working. Now I want to put the names into a list. So names = fileobject.read() print(names) which returns Name 1 Name 2 Name 3 etc. But it is not like a normal list (ie. ["name 1", "name 2", "name 3"] etc so if I ask it to call the second name print(names[1]) it will print a as in the second letter of the first name (remember 0 is the start of the list) How can I make it like a normal array where each name is in quotes separated by a comma with square brackets arround the outside.
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/50407439
has comment: http://stackoverflow.com/comment/87859117
type: Answer
answers question: http://stackoverflow.com/q/50403205
score: 0
has body: Edited code: def sorting(final_input): final_output=[] while 0 != len(final_input): final_output+= [min(final_input)] final_input.remove(min(final_input)) return(final_output) final_input = [] while True: user_input = input("Enter number or \"quit\": ")# if "quit"in user_input.lower():################## I only changed these lines because I feel the program is more neat like this. break final_input.append(user_input) print(final_input) print(sorting(final_input)) I moved the function to the top, so it would be defined before it’s called. In your function, you were trying tofinal_output[count]=value, to create a list. This doesn’t work in python. There are multiple “array like data structures”. Create an empty list like this: final_output=[]. You can then add to it by doing either final_output+=[value], or final_output.append(value). You can also do final_output=[value1,value2,value3] if you know what all the values are going to be when the list is created. I added speech marks around “quit” as this prevents the string from being misinterpreted as “Enter number, or quit the program”, or ‘’’“Enter number or “quit:”’’’. I also made it so that it was no longer case sensitive, or punctuation sensitive. Result: Enter number or "quit": 8 Enter number or "quit": 3 Enter number or "quit": 9 Enter number or "quit": 0 Enter number or "quit": Quit. ['8', '3', '9', '0'] ['0', '3', '8', '9'] Is this the result you wanted?
accepted answer of: http://stackoverflow.com/q/50403205
type: AcceptedAnswer

http://stackoverflow.com/q/50412892
downvote count: 0
upvote count: 1
has title: Change seqID and remove a part after a pattern
favorite count: 0
type: Question
tagged with: fasta
has answer: http://stackoverflow.com/a/50413195
type: UnansweredQuestion
tagged with: bioinformatics
has body: I actually have fasta files such: &gt;seq1:QXQXQWQ:XQWQ ACTG &gt;seq3:WCCWHWJ:WGH ATGC &gt;seq7:GCGC:G ATGACA and I would like to remove all thing after the first ":" and get: &gt;seq1 ACTG &gt;seq3 ATGC &gt;seq7 ATGACA And this with biopython if it is possible?
tagged with: python
tagged with: regex
tagged with: biopython
has comment: http://stackoverflow.com/comment/87841497
score: 1
answer count: 1

http://stackoverflow.com/comment/87859645
type: Comment
score: 0
has text: @SahilDhiman , it's not about missing `0` in curly braces, but you just forgot to close your predicate as well as your XPath, so just add `]'` -> `'//*[@title="{}"]'.format(name)`. P.S. *`'//*[@title="karam"'` This works*... I don't really think so
type: QuestionComment
comment on: http://stackoverflow.com/q/50422124

http://stackoverflow.com/a/50516213
has comment: http://stackoverflow.com/comment/88057620
has comment: http://stackoverflow.com/comment/88057736
has comment: http://stackoverflow.com/comment/88057517
has comment: http://stackoverflow.com/comment/88045541
has comment: http://stackoverflow.com/comment/88057759
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88045466
upvote count: 1
has comment: http://stackoverflow.com/comment/88045338
answers question: http://stackoverflow.com/q/50515266
has body: The problem is that you only determine if a heading needs to be printed after you get to a data line. This means that you need to retain the last heading in a variable, and print it before the first occurrence of a data line. Here is a sample implementation that retains the last line of text. If the text is followed by a line containing '—————————————————————————', it gets flagged as a heading line, otherwise it gets treated as a data line and the last heading is printed. Since you mentioned in the comments that your data originates on Windows, I have added a line to strip any trailing carriage returns from your lines. This will work just fine with files that don't have them as well: with open('tran', 'r') as f: prev_line = '' # Not strictly necessary, but avoids some warnings for line in f: line = line.rstrip('\r') if '—————————————————————————' in line: heading = prev_line elif line.startswith('tcp'): if '—————————————————————————' in prev_line: print(heading) print(prev_line) print(line) prev_line = line This will skip the newlines between sections, but you can include those with something like: elif not line and prev_line.startswith('tcp'): print(line) Here is an IDEOne Link that demos the code with @Flaming_Dorito's example.
has comment: http://stackoverflow.com/comment/88057827
has comment: http://stackoverflow.com/comment/88045710
has comment: http://stackoverflow.com/comment/88056878
score: 1
has comment: http://stackoverflow.com/comment/88054134
accepted answer of: http://stackoverflow.com/q/50515266
type: Answer

http://stackoverflow.com/q/50434855
type: Question
has title: How many unique values of quality are in this dataset?
answer count: 2
has answer: http://stackoverflow.com/a/50434877
type: UnansweredQuestion
tagged with: python
has body: I need to answer this question: How many unique values of quality are in this dataset? I tried out to answer this question with this function: df.pd.groupby('quality').unique() However, there is a mistake. What should I do?
tagged with: series
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/50434932
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/50394949
answers question: http://stackoverflow.com/q/50392949
has body: For grouping python provides itertools.groupby(), which groups sorted input by a given key function. In this case the input needs to be sorted first by org_id, then by main_cat then by number in descending order, e.g. if your data as a list looks like this: data = [ ['Career', 'school', 5, 'A'], ['Career', 'college', 3, 'A'], ['Career', 'higher', 4, 'A'], ['Job', 'Blr', 6, 'A'], ['Job', 'Hyd', 11, 'A'], ['Job', 'Chennai', 12, 'A'], ['Career', 'school', 15, 'B'], ['Career', 'college', 30, 'B'], ['Career', 'higher', 5, 'B'], ['Job', 'Blr', 5, 'B'], ['Career', 'college', 8, 'C'], ['Job', 'Chennai', 4, 'C'] ] then you'd sort it like this: data.sort(key = lambda x: (x[3], x[0], -x[2])) or by altering your sql statement to include ORDER BY main_cat, sub_cat, number DESC, then you'll aready get it in the right order from the database. Now you can use groupby to group, and islice to limit the number of results per grouped category: from itertools import groupby, islice from operator import itemgetter # already sorted data data = [ ['Career', 'school', 5, 'A'], ['Career', 'higher', 4, 'A'], ['Career', 'college', 3, 'A'], ['Job', 'Chennai', 12, 'A'], ['Job', 'Hyd', 11, 'A'], ['Job', 'Blr', 6, 'A'], ['Career', 'college', 30, 'B'], ['Career', 'school', 15, 'B'], ['Career', 'higher', 5, 'B'], ['Job', 'Blr', 5, 'B'], ['Career', 'college', 8, 'C'], ['Job', 'Chennai', 4, 'C'] ] data.sort(key = lambda x: (x[3], x[0], -x[2])) for org, by_org in groupby(data, key=itemgetter(3)): print("org:", org) for cat, by_cat in islice(groupby(by_org, key=itemgetter(0)), 2): print(" cat:", cat) for subcat, by_subcat in islice(groupby(by_cat, key=itemgetter(1)), 2): print(" subcat:", subcat, " = ", list(by_subcat)) Output: org: A cat: Career subcat: school = 'Career', 'school', 5, 'A' subcat: higher = 'Career', 'higher', 4, 'A' cat: Job subcat: Chennai = 'Job', 'Chennai', 12, 'A' subcat: Hyd = 'Job', 'Hyd', 11, 'A' org: B cat: Career subcat: college = [['Career', 'college', 30, 'B']…
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50392949

http://stackoverflow.com/comment/87878895
comment on: http://stackoverflow.com/q/50432219
type: Comment
type: QuestionComment
score: 0
has text: what gives `sr.Microphone.list_microphone_names()` ? if you see your mic, you can specify the `device_index` parameter. Check this doc : https://realpython.com/python-speech-recognition/#the-microphone-class

http://stackoverflow.com/q/50425038
has answer: http://stackoverflow.com/a/50591576
type: UnansweredQuestion
tagged with: python
tagged with: inheritance
tagged with: mongoengine
has title: Add Same fields and methods to EmbededDocument and Document class in mongoengine
tagged with: class
score: 2
upvote count: 2
tagged with: oop
downvote count: 0
has body: I want to add timestamp related fields to both EmbededDocument class inherited documents and to regular Document class inherited Documents. Since EmbededDocument and Document classes cannot be mixed in mongoengine I had to create a base class and tried to use that through multi-inheritance. This is what I have done class SikkaBase(): # Passing a callable as default created_on = DateTimeField(default=datetime.now) updated_on = DateTimeField(default=datetime.now) is_deleted = BooleanField(default=False) # Update the updated_on field for every update def update(self, *args, **kwargs): self.updated_on = datetime.now() super(SikkaBase, self).save(*args, **kwargs) # Update the created_on field for every updates def save(self, *args, **kwargs): self.updated_on = datetime.now() super(SikkaBase, self).save(*args, **kwargs) class SikkaBaseDocument(Document, SikkaBase): meta = { 'abstract': True } class SikkaEmbededBaseDocument(EmbeddedDocument, SikkaBase): meta = { 'abstract': True } This throws an error File ".../sikka_env/lib/python2.7/site-packages/mongoengine/base/metaclasses.py", line 305, in __new__ if b.__class__ == TopLevelDocumentMetaclass] AttributeError: class SikkaBase has no attribute '__class__' I am not so sure about my solution either as SikkaBase class is not related to MongoEngine in any way, not sure how relevant that is. Looking for any possible solutions. I can always copy the same code in the SikkaBaseDocument and SikkaEmbededBaseDocument class but want to avoid doing the same.
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50512524
has comment: http://stackoverflow.com/comment/88038289
has title: Python - Accurate time.sleep
has comment: http://stackoverflow.com/comment/88082401
has answer: http://stackoverflow.com/a/50514321
has comment: http://stackoverflow.com/comment/88049386
favorite count: 0
has comment: http://stackoverflow.com/comment/88040016
type: Question
has comment: http://stackoverflow.com/comment/88038614
has comment: http://stackoverflow.com/comment/88039444
has comment: http://stackoverflow.com/comment/88037470
has comment: http://stackoverflow.com/comment/88038355
answer count: 3
has body: I am working on a project which accurate timer is really crucial. I am working on python and am using timer.sleep() function. I noticed that timer.sleep() function will add additional delay because of the scheduling problem (refer to timer.sleep docs). Due to that issue, the longer my program runs, the more inaccurate the timer is. Is there any more accurate timer/ticker to sleep the program or solution for this problem? Any help would be appreciated. Cheers.
has comment: http://stackoverflow.com/comment/88037722
has comment: http://stackoverflow.com/comment/88037872
score: 10
upvote count: 10
linked to: http://stackoverflow.com/q/1211806
has comment: http://stackoverflow.com/comment/88037887
tagged with: python
has comment: http://stackoverflow.com/comment/88038693
has answer: http://stackoverflow.com/a/50513859
linked to: http://stackoverflow.com/q/13397571
tagged with: sleep
has comment: http://stackoverflow.com/comment/88039006
has answer: http://stackoverflow.com/a/50514270
has comment: http://stackoverflow.com/comment/88037980
has comment: http://stackoverflow.com/comment/88038863
has comment: http://stackoverflow.com/comment/88039383
has comment: http://stackoverflow.com/comment/88041880
has comment: http://stackoverflow.com/comment/88037517
tagged with: timer
has comment: http://stackoverflow.com/comment/88037759
downvote count: 0
has comment: http://stackoverflow.com/comment/88038004
has comment: http://stackoverflow.com/comment/88038264
type: UnansweredQuestion

http://stackoverflow.com/comment/130890945
type: AnswerComment
has text: Thank you, for some reason I needed to add many=True on my serializer even if the data I am trying to get is only 1
comment on: http://stackoverflow.com/a/50413348
type: Comment
score: 0

http://stackoverflow.com/a/50420175
answers question: http://stackoverflow.com/q/50418159
has body: So I just fixed my code to remove the manual partition of the dataframe and used groupby instead. Here's the code: for i in [2.0,1.5]: FuzzyWuzzyResults = emb.map_partitions(lambda df: df.groupby('phase').get_group(3.0)['drugs'].apply(fuzzy_match, args=(df.groupby('phase').get_group(i)['drugs'],fuzz.ratio,90)), meta=('results')).compute() Not sure whether it's accurate, but at least it's running, and that too on all CPU cores.
type: Answer
score: 0

http://stackoverflow.com/a/77387024
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50389852
score: 3
has body: Configure the type checking mode: In your settings.json file, add a new line with the following setting: "python.analysis.typeCheckingMode": "basic". The default value for this line is off, meaning the static analysis is disabled. You have two other possible values which are basic and strict. The basic mode enables basic type checking rules, while strict mode enables all type checking rules at the highest error severity

http://stackoverflow.com/q/50445428
has answer: http://stackoverflow.com/a/50446307
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87904579
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50445823
has body: I am trying to do a simple summation with column name Tangible Book Value and Earnings Per Share: df['price_asset_EPS'] = (df["Tangible Book Value"]) + (df["Earnings Per Share"]) However, the result doesn't evaluate the numbers and also the plus is missing as below 0.66-0.36 1.440.0 What I have missed in between?
score: 1
has title: Why did pandas give "0.66-0.36" when I tried to add two columns?
tagged with: python
has comment: http://stackoverflow.com/comment/87905279
type: Question
upvote count: 2
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/50476828
accepted answer of: http://stackoverflow.com/q/50476501
has comment: http://stackoverflow.com/comment/87989772
has comment: http://stackoverflow.com/comment/87983967
has comment: http://stackoverflow.com/comment/87984690
type: Answer
has comment: http://stackoverflow.com/comment/87990071
has comment: http://stackoverflow.com/comment/87983645
answers question: http://stackoverflow.com/q/50476501
has comment: http://stackoverflow.com/comment/87992274
downvote count: 0
score: 1
upvote count: 1
has body: Installation If you create a new environment, I would recommend using a new python version. Currently, I'd use python 3.6, because matplotlib does not support python 3.3 anymore. So first create a conda environment with python 3.6; I name it plotenv here: &gt; conda create --name plotenv python=3.6 Next install matplotlib to it, &gt; conda install --name plotenv matplotlib Finally install plotly to it, &gt; conda install --name plotenv -c plotly plotly Done. Console usage Don't forget to activate the environment if you want to use it via source activate plotenv (on linux) or activate plotenv (on windows). &gt; activate plotenv You may then start python (plotenv) &gt; python and import any of the installed submodules, e.g. &gt;&gt;&gt; from mpl_toolkits.axes_grid1 import ImageGrid Usage with Jupyter In case you want to use jupyter notebook with the newly created environment, you need to install it first, &gt; conda install --name plotenv ipython jupyter and then run the following inside this environment: (plotenv) &gt; python -m ipykernel install --user --name plotenv Now, starting juypter (plotenv) &gt; jupyter notebook would give you the option to create a new notebook with this environment:
type: AcceptedAnswer

http://stackoverflow.com/a/50497331
accepted answer of: http://stackoverflow.com/q/50495946
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50495946
has body: Definitely the execution of gcloud auth application-default login instead of gcloud auth login solved this 403 issue for me
type: Answer

http://stackoverflow.com/q/50406973
linked to: http://stackoverflow.com/q/11169445
upvote count: 1
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50407139
has body: I'm using Python 3.5 and win32com to iterate through an excel document rows (only from the first column) and get all the values from it, the best would be in a simple list. I tried the following implementation but there are a few problems with it: excel_app = win32com.client.Dispatch('Excel.Application') workbook = excel_app.Workbooks.Open(myfile2) worksheet = workbook.Sheets('Sheet1') data = excel_app.Range("A1:A60") print(data) for i in data: if i is not None: print(i) The problems are mainly with: "data = excel_app.Range("A1:A60")" This takes the first 60 rows, I would like to get only as many rows as there is data in the excel file, otherwise either i don't get enough data, or i get too much and i end up with a bunch of 'None' It returns a Tuple, so i can't modify it in order to remove the 'None' values if i get more data than the spreadsheet has.
has comment: http://stackoverflow.com/comment/87829923
downvote count: 0
has answer: http://stackoverflow.com/a/50407418
tagged with: python
has title: Python: Iterating through excel column and getting values with win32com
has comment: http://stackoverflow.com/comment/87829409
tagged with: excel
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87829753
accepted answer: http://stackoverflow.com/a/50407418
tagged with: win32com
score: 1
has answer: http://stackoverflow.com/a/50407139

python-curses
tag name: python-curses
tags question: http://stackoverflow.com/q/50490095
type: Tag

http://stackoverflow.com/a/50703102
accepted answer of: http://stackoverflow.com/q/50423279
has body: Docutils developers identified this as a bug and patched it. See on the docutils-users mailing list here and here @andref's answer is great, though, thanks for pointing to this package.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50423279
score: 1
type: Answer

http://stackoverflow.com/q/50465207
has comment: http://stackoverflow.com/comment/87943966
answer count: 1
upvote count: 1
has title: Python generator chaining refers to last iteration
favorite count: 0
type: Question
tagged with: iterator
has comment: http://stackoverflow.com/comment/87944060
has body: In this code: x = [0] for i in range(10): x = (a+i for a in x) print(list(x)) # [90] I'm chaining generators so that the x in one iteration uses the result of the previous x. But it seems all the x generators use the value of i in the last iteration (9). How can I make it so that each generators uses the value of i in the iteration that they're created? (So that the final result is 0 + 1 + 2 + 3 + 4 +...)
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50465563
linked to: http://stackoverflow.com/q/5190146
has comment: http://stackoverflow.com/comment/87945154
score: 1
duplicate of: http://stackoverflow.com/q/5190146

http://stackoverflow.com/q/50421508
tagged with: ssh
tagged with: python
tagged with: paramiko
type: UnansweredQuestion
tagged with: multithreading
answer count: 1
has body: I want to download files from remote server using Paramiko with multithreading. There are two solution came into my mind, but I'm not sure which is right (or better). Solution 1: Assuming that the SFTPClient.get is thread safe (But I can't find any document mentioned that), a simple one would as: from paramiko import SSHClient, AutoAddPolicy, SFTPClient from concurrent.futures import ThreadPoolExecutor from typing import List client = SSHClient() ciient.set_missing_host_key_policy(AutoAddPolicy()) client.connect( ... ) sftp = client.open_sftp() files_to_download: List[str] = ... with ThreadPoolExecutor(10) as pool: pool.map(lambda fn: sftp.get(fn, fn), files_to_download) Solution 2: There are two questions in Solution 1 Is the Paramiko's API really thread-safe? Is it efficient to download multi-files via a single connection? So here is my second solution: from paramiko import SSHClient, AutoAddPolicy, SFTPClient from concurrent.futures import ThreadPoolExecutor from threading import Lock, local from typing import List client = SSHClient() ciient.set_missing_host_key_policy(AutoAddPolicy()) client.connect( ... ) thread_local = local() thread_lock = Lock() files_to_download: List[str] = ... def download(fn: str) -&gt; None: """ thread-safe and each thread has its own SFTPClient """ if not hasattr(thread_local, 'sftp'): with thread_lock: thread_local.sftp = client.open_sftp() thread_local.sftp.get(fn, fn) with ThreadPoolExecutor(10) as pool: pool.map(download, files_to_download) Which solution is better?
downvote count: 0
linked to: http://stackoverflow.com/q/65106405
favorite count: 0
type: Question
tagged with: sftp
score: 5
has answer: http://stackoverflow.com/a/50421992
has title: Is it necessary to open a SFTPClient per one thread in Paramiko with multi-threading?
upvote count: 5

http://stackoverflow.com/q/50442298
answer count: 1
has answer: http://stackoverflow.com/a/50444761
has body: I have a real-time facial recognition program that can identify the faces of people known to me And then write the person's name on it. Now, when someone such as 'Alex' is detected, then I'll show the image I've seen for this person and close it after a few seconds, and again new people This is a piece of my code: for face_encoding in face_encodings: # match = face_recognition.compare_faces(known_face_encoding, face_encoding) # Matches=np.where(match)[0] #Checking which image is matched face_distances=face_recognition.face_distance(face_encodings, face_encoding) Matches =list(face_distances&lt;= 0.4) name="Unknown" if True in Matches: match_index = np.argmin(face_distances) name = known_person[match_index] face_names.append(name) As you can see, the name represents the people's name how i do it??please help me thank you in advance
has title: show image when person detected
type: Question
tagged with: opencv
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/50418775
has comment: http://stackoverflow.com/comment/87853160
answer count: 4
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87853082
tagged with: python
has body: I tried the answer to when this was asked previously and it didn't work, so I'm asking here. I'm very new to both windows and python, and am trying to run python from my (Windows 10) command line so that I can use pip to install a package (SpaCy). I'm not entirely sure what I'm doing wrong, but after the C:Users\myname&gt; typing C:Users\myname&gt;python leads to an invalid syntax error, saying: 'python' is not recognized as an internal or external command, operable program or batch file. I have python 2.7 installed on my computer, and it works when I use an interpreter such as Rodeo. I also get the same error when trying to use pip to install SpaCy, although when I try to install pip I get a message that pip is already installed. Is there some basic knowledge I'm just missing?
has title: command line not recognizing python despite it being on my computer
has answer: http://stackoverflow.com/a/50418835
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/50418818
has answer: http://stackoverflow.com/a/50418854
tagged with: windows
has answer: http://stackoverflow.com/a/50418831

http://stackoverflow.com/a/50387181
type: Answer
has comment: http://stackoverflow.com/comment/134508078
answers question: http://stackoverflow.com/q/50385390
has body: I realized it was just my silly mistake def __init__(self): return self.name I was using init instead of str ....but why would this one cause an error like an attribute error like that **def __str(self): return self.name** Thanks ,my bad
score: 0

http://stackoverflow.com/a/50418266
upvote count: 8
type: Answer
has body: drop_duplicates Call drop_duplicates on tuplized data: df[0].apply(tuple, 1).drop_duplicates().apply(list).to_frame() 0 0 [1, 0] 1 [0, 0] collections.OrderedDict However, I'd much prefer something that doesn't involve apply... from collections import OrderedDict pd.Series(map( list, (OrderedDict.fromkeys(map(tuple, df[0].tolist())))) ).to_frame() Or, pd.Series( list(k) for k in OrderedDict.fromkeys(map(tuple, df[0].tolist())) ).to_frame() 0 0 [1, 0] 1 [0, 0]
has comment: http://stackoverflow.com/comment/105746200
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/50418139
has comment: http://stackoverflow.com/comment/105748044

http://stackoverflow.com/q/50504425
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50504621
has body: I have bellow code, I want to get the delta days number instead of its format: now = datetime.datetime.now() com_day = now + datetime.timedelta(days=7.23) delta_days = com_day - now print(delta_days) # there gets the `7 days, 5:31:12` I want to get 7.23 instead of 7 days, 5:31:12. How to get the requirement?
has answer: http://stackoverflow.com/a/50504531
accepted answer: http://stackoverflow.com/a/50504531
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88021091
tagged with: python
has answer: http://stackoverflow.com/a/50504621
type: Question
has title: Get the delta days number instead of its format

eval
tag name: eval
tags question: http://stackoverflow.com/q/50541570
type: Tag

http://stackoverflow.com/comment/87873935
comment on: http://stackoverflow.com/q/50429243
type: QuestionComment
score: 0
has text: 403 can also mean that the view expects a logged-in user. Is that the case in your setup?
type: Comment

http://stackoverflow.com/q/50447523
has answer: http://stackoverflow.com/a/50447722
answer count: 1
tagged with: parameter-passing
type: Question
tagged with: c#
score: 0
tagged with: python
tagged with: gensim
tagged with: visual-studio-2017
has body: I am a C# programmer and new to Python. Now I am working on Python form Visual Studio 2017. I have already written a program in C# to do some text processing tasks, but now I need to accomplish my work in python as it provides advanced functions for dealing with Natural Language Processing. Specifically, I need to pass a List&lt;List&gt; parameter from my C# application to the Python application. The passed parameter will be used instead of doc_term_matrix inline 48 at the following python snippet: Another issue to be handled is the casting of the different data types, as I want to import a List&lt;List&lt;double&gt;&gt;, as shown below, from C# to be used as the parameter returned from the dictionary.doc2bow(doc) function in Python. I have no idea how to do so. So, please help me solve this issue.
has title: Passing parameters from C# application to Python application [for using in gensim] in Visual Studio 2017
type: UnansweredQuestion

http://stackoverflow.com/q/50467804
tagged with: python
has comment: http://stackoverflow.com/comment/87948704
has answer: http://stackoverflow.com/a/50468560
score: 0
has comment: http://stackoverflow.com/comment/87950005
answer count: 1
tagged with: keyword
has title: Unable to call class methods with keyword defined in robot framework
type: Question
tagged with: robotframework
has body: Hi I am trying to create my own keywords and call it from robot scripts : Below is my sample code : util.py from robot.api.deco import keyword @keyword('Add Num') def add(a,b): print "Simple method" return int(a)+int(b) class Geo : @keyword('Class Add Num') def addd(self,a,b): print "Inside class method " return int(a)+int(b) Sample.robot *** Settings *** Library util.py *** Test Cases *** TC_01 [Documentation] sample test [Tags] Sample Add Num 10 20 Class Add Num 10 2 Which I am running using pybot command - pybot sample.robot Add Num keyword is works fine , but Class Add Num gives an error : No keyword with name 'Class Add Num' found. I have tried looking into stackoverflow and official robot framework docs , but could find any relevant help . How to resolve this error , Or I need to implement it in a different way ??
has comment: http://stackoverflow.com/comment/87949957
type: UnansweredQuestion

http://stackoverflow.com/q/50463238
has answer: http://stackoverflow.com/a/74394203
score: 13
possible better answer: http://stackoverflow.com/a/51706087
has comment: http://stackoverflow.com/comment/87941328
favorite count: 0
has answer: http://stackoverflow.com/a/51706087
type: AnsweredQuestion
has body: My program in tkinter is working well when I am running it using PyCharm, when I am creating .exe file using pyinstaller, pyinstaller -i"icon.ico" -w -F script.py I have no errors. I am pasting script.exe in same folder as my script.py, and after running it I think in step where subprocess is, it is not answering, because I haveprint before subprocess line and its working. Anyone know why? This is the line with subprocess: import subprocess from subprocess import Popen, PIPE s = subprocess.Popen([EXE,files,'command'],shell=True, stdout=subprocess.PIPE) EDIT: same problem with: s = subprocess.check_output([EXE,files,'command'],shell=True, stderr=subprocess.STDOUT)
answer count: 5
has comment: http://stackoverflow.com/comment/87939694
linked to: http://stackoverflow.com/q/43593348
tagged with: python
has answer: http://stackoverflow.com/a/66682390
upvote count: 13
accepted answer: http://stackoverflow.com/a/50468088
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/50468088
tagged with: subprocess
has answer: http://stackoverflow.com/a/59012092
downvote count: 0
has title: subprocess seems not working in pyinstaller exe file

http://stackoverflow.com/comment/87856388
type: QuestionComment
has text: Also if its a small correction like that, dont downvote it. Now nobody is going to look at it and I'm gonna have to post it again
comment on: http://stackoverflow.com/q/50420359
score: 0
type: Comment

http://stackoverflow.com/comment/87866226
comment on: http://stackoverflow.com/q/50425656
type: QuestionComment
type: Comment
has text: Please place the additional information that you put in comments into your question. It seems that you want a path for any pair of nodes in the tree, so since your example tree has `6` nodes you want `6*5//2 == 15` paths. Is that correct? Also show us the data structure that you use for the binary tree--that would affect any answer.
score: 0

plotly-dash
tags question: http://stackoverflow.com/q/50466450
tags question: http://stackoverflow.com/q/50390506
type: Tag
tags question: http://stackoverflow.com/q/50497104
tag name: plotly-dash

http://stackoverflow.com/q/50420701
tagged with: python-2.7
downvote count: 0
tagged with: dht
score: 1
upvote count: 1
tagged with: tcp
has title: Server connected, but no response TCP socket programming
has comment: http://stackoverflow.com/comment/87859449
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has body: I'm implementing a circular distributed hash table, each peer knows its immediate successor and set up TCP connection with its successor, like, 1->3->4->5->8->1. User will input a 4-digit number, and we proceed it into a certain value using a hash function written by us. For example, user inputs 3456, corresponding hash value is 128. Peer 3 get the input from user, and pass the hash value to its successor(4) asking if he is greater than hash value. If not, the successor will pass the hash to its successor(5). Repeat this until it find the right peer. (Here, since 8 &lt; 128, we say peer 1 is the one we want) Now, we know peer 1 is the peer we want. Then we let peer 1 make a TCP connection with the requesting peer 3, and send 3 "FIND1,3456,3", when peer 3 get this message, it should print out "peer 1 has the value". The problem I met is, after I find peer 1 is the one I want, my peer 1 client sets up TCP connection with peer 3 server (peer 1 client said the connection is set up), but peer 3 doesn't get any message from peer 1, what's wrong with it? How should I fix it? Thanks for your patience to read these, feel free to ask if there is anything ambiguous :) #!/usr/bin/python2.7 import sys import socket import time import threading import re from collections import defaultdict successor = defaultdict(dict) peer = int(sys.argv[1]) successor[1] = int(sys.argv[2]) successor[2] = int(sys.argv[3]) serverName = 'localhost' peerPort = 50000 + int(peer) address = (serverName,peerPort) #-------------proceed input string--------------------------- def getFileNum(name): fileValid = re.match('^request ([0-9]{4})$',name) if fileValid is None: print 'invalid file!' return else: hashName = fileValid.group(1) return hashName #----------------get request input-------------------------------- def getRequestInput(clientSocketTCP): while flag == 0: fileName = raw_input() hashname = getFileNum(fileName) if hashname is not None: hashname = re.sub('^(0)*','',hashname) hashnum = int(hashnam…

http://stackoverflow.com/comment/87950338
has text: Didn't know about `isna` unclear to me apart from less typing what is different from `isnull`
score: 0
comment on: http://stackoverflow.com/a/50468516
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87913383
comment on: http://stackoverflow.com/q/50450106
has text: If you get `view returned none`, that means you never end up in a branch that would return anything else, so neither form is valid. You can try `print(form_reg.errors)` (and likewise for `form_login`) within the `post()` method to see what the error(s) are that make that happen.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50488990
answers question: http://stackoverflow.com/q/50488912
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50488912
has body: You can keep track of the original ones before declaring: orig_keys = set(globals().keys()) a = 10 b = 100 c = 1000 my_keys = set(globals().keys()) - orig_keys print(my_keys) Results in: {'orig_keys', 'a', 'c', 'b'} You can check it live here
type: AcceptedAnswer
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/50432712
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87882823
answer count: 1
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/87879677
type: UnansweredQuestion
has title: ImportError: No module named "webisite_dj"
tagged with: powershell
has comment: http://stackoverflow.com/comment/87882834
tagged with: python
has answer: http://stackoverflow.com/a/50435928
score: 0
has body: I am getting an below error while running manage.py run server. Directory: C:\Users\home\Desktop\website_dj>ls 557 manage.py PS C:\Users\home\Desktop\website_dj> python manage.py runserver ImportError: No module named 'website_dj'

http://stackoverflow.com/comment/87916174
comment on: http://stackoverflow.com/q/50451339
type: Comment
type: QuestionComment
has text: Use `text = []` at the beginning. So `text` is defined in either case where you have value or when you set an empty value.
score: 0

http://stackoverflow.com/comment/88043419
score: 0
type: Comment
type: QuestionComment
has text: I would prefer an answer where to get the template or install all the default files.
comment on: http://stackoverflow.com/q/50515109

http://stackoverflow.com/q/50538887
has body: I am trying to make a loop that can roll my dice and assign the rolled value into a list that can then be put through a dictionary to get back the values written in the dictionary. My dictionary is as follows: scores = {1:1000, 2:200, 3:300, 4:400, 5:500, 6:600} rolls = [] for i in range(5): self.rolls.append(random.randint(1,6)) my_score = 0 How do I make the values in rolls that of the ones in the dictionary and add them to my_score.
has comment: http://stackoverflow.com/comment/88089691
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50539233
tagged with: python
tagged with: dictionary
has title: How to assign values from a list to a dictionary and back into a separate list?
tagged with: list
upvote count: 1
score: 1
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50522488
tagged with: scipy
tagged with: pypy
type: Question
has comment: http://stackoverflow.com/comment/88083885
has body: I am trying to install SciPy with PyPy on Windows. I installed PyPy with the windows 32-bit zip on the website. I installed numpy using python setup.py install. I tried to install scipy with pip install scipy or related commands, I always get a "NotFoundError: no lapack/blas resources found" error. Note I cannot install with wheels because they are meant for CPython 2.7 not PyPy 2.7 How can I solve this problem, especially since most of SciPy is compatible with PyPy?
type: UnansweredQuestion
score: 0
has title: installing SciPy with PyPy on Windows
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50650658
has comment: http://stackoverflow.com/comment/88067541

http://stackoverflow.com/comment/87834570
has text: Yes, it is possible, but you won't like it: you will have to spell out each possible variation. So, for a string with 3 char limit, it would look like `^( {2}\S| \S |\S )$`. Imagine what the expression for 50 chars will look like. Certainly you may create it dynamically, but why not just use `(len(s) <= 50 || len(s) >= 0) && len(strings.TrimSpace(s)) != 0`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50409293
type: Comment

http://stackoverflow.com/a/50511709
type: AcceptedAnswer
has body: Here is one way: OUTPUT_DF = (INPUT_DF.groupby(['ID', 'DATE(MM/DD/YY)']) .apply(lambda x: sum(x.EXPOSURE * x.VALUE))) ID DATE(MM/DD/YY) MP 5/31/05 3.8 8/29/03 5.4 STA 1/31/03 2.1 8/29/03 3.4 ZT 5/31/05 8.6 6/31/05 1.2 To get it as a dataframe in the format you have posted, just add to_frame and reset_index: OUTPUT_DF = (INPUT_DF.groupby(['ID', 'DATE(MM/DD/YY)']) .apply(lambda x: sum(x.EXPOSURE * x.VALUE)) .to_frame('FINAL_VALUE') .reset_index()) &gt;&gt;&gt; OUTPUT_DF ID DATE(MM/DD/YY) FINAL_VALUE 0 MP 5/31/05 3.8 1 MP 8/29/03 5.4 2 STA 1/31/03 2.1 3 STA 8/29/03 3.4 4 ZT 5/31/05 8.6 5 ZT 6/31/05 1.2
has comment: http://stackoverflow.com/comment/88035855
answers question: http://stackoverflow.com/q/50511519
type: Answer
has comment: http://stackoverflow.com/comment/88035942
accepted answer of: http://stackoverflow.com/q/50511519
has comment: http://stackoverflow.com/comment/88036041
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88036008

http://stackoverflow.com/q/50541457
answer count: 2
has comment: http://stackoverflow.com/comment/88094415
possible better answer: http://stackoverflow.com/a/50541950
has title: Scrapy: 403 Error on all requests
has comment: http://stackoverflow.com/comment/88094497
accepted answer: http://stackoverflow.com/a/53215137
tagged with: scrapy
has comment: http://stackoverflow.com/comment/88094543
has answer: http://stackoverflow.com/a/53215137
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88094164
has answer: http://stackoverflow.com/a/50541950
has body: My scrapy crawler uses random proxies and it works on my computer. But when I run it on a vps, it return 403 error on every requests. 2018-05-26 09:43:18 [scrapy.proxies] DEBUG: Proxy user pass not found 2018-05-26 09:43:18 [scrapy.proxies] DEBUG: Using proxy &lt;http://104.237.210.29:2716&gt;, 20 proxies left 2018-05-26 09:43:19 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying &lt;GET http://www.yelp.com/&gt; (failed 1 times): 403 Forbidden 2018-05-26 09:43:19 [scrapy.proxies] DEBUG: Proxy user pass not found 2018-05-26 09:43:19 [scrapy.proxies] DEBUG: Using proxy &lt;http://104.237.210.173:5195&gt;, 20 proxies left 2018-05-26 09:43:19 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying &lt;GET http://www.yelp.com/&gt; (failed 1 times): 403 Forbidden 2018-05-26 09:43:19 [scrapy.proxies] DEBUG: Proxy user pass not found 2018-05-26 09:43:19 [scrapy.proxies] DEBUG: Using proxy &lt;http://104.237.210.93:3410&gt;, 20 proxies left 2018-05-26 09:43:19 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying &lt;GET http://www.yelp.com/&gt; (failed 1 times): 403 Forbidden I manually checked the proxies on firefox on the vps and I can access the websites without any error. This my settings, it's the same as the one on my computer: DOWNLOADER_MIDDLEWARES = { # 'monitor.middlewares.MonitorDownloaderMiddleware': 543, # Proxies 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90, 'scrapy_proxies.RandomProxy': 100, 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110, # Proxies end # Useragent 'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware': None, 'random_useragent.RandomUserAgentMiddleware': 400, # Useragent end } # Random useragent list USER_AGENT_LIST = r"C:\Users\Administrator\Desktop\useragents.txt" # Retry many times since proxies often fail RETRY_TIMES = 5 # Retry on most error codes since proxies fail for different reasons RETRY_HTTP_CODES = [500, 503, 504, 400, 403, 404, 408] # Proxy list containing entries like # http://host1:port…
tagged with: python
has comment: http://stackoverflow.com/comment/88094630
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50420211
possible better answer: http://stackoverflow.com/a/50420261
type: Question
has answer: http://stackoverflow.com/a/50420261
accepted answer: http://stackoverflow.com/a/50420274
tagged with: python
has answer: http://stackoverflow.com/a/50420274
tagged with: logging
type: AnsweredQuestion
answer count: 2
score: 3
upvote count: 3
tagged with: pep8
downvote count: 0
has body: I have a CLI script which uses the logging module to print to screen and file. Is it possible to make ouput look better when breaking long lines for PEP8 using \? logger.warning("SKIPPED File: '%s'; \ MyFunc() returned no results." % (dir_file, )) # You have to scroll to see the result --&gt; WARNING----SKIPPED File: 'test-filetypes/client-somefile.txt'; MyFunc() returned no results.
has title: Make logging output pretty when using backslash in string for Python PEP 8?
favorite count: 0

http://stackoverflow.com/a/50460441
has body: It’s because self.kwargs is set in the view function returned from .as_view and not in the base class constructor.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50457035
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50457035
score: 1

http://stackoverflow.com/comment/87871336
has text: @Ivanovitch, just the built in `sklearn.metrics.confusion_matrix()`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50428173
type: Comment

http://stackoverflow.com/q/50453941
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50454010
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50454010
tagged with: python
has body: I am ploting two graph in one graph using following code. And also i want see X-axis values on some point in graph itself. Because i am ploting two graph in one plot, so i am two values for one point. I want to see both values clearly. But when values are closer they collide each and values are not visible clearly. import matplotlib.pyplot as plt plt.rcParams.update(plt.rcParamsDefault) plt.style.use(['default']) a=[1.23,2.24,3.12,1.11,2.46] b=[1.24,2.23,3.15,1.25,2.78] xc=range(5) plt.figure(figsize=(5,5)) for x,y in zip(xc,a): plt.text(x, y, '%.2f' % y, ha='center', va= 'bottom') for x,y in zip(xc,b): plt.text(x, y, '%.2f' % y, ha='center', va= 'bottom') plt.plot(xc,a) plt.plot(xc,b) plt.xlabel('num of Epochs') plt.ylabel('loss') plt.title('train_loss vs val_loss') plt.legend(['train','val']) Please help me to code for better visualization of graph
type: AnsweredQuestion
has title: showing x-axis values at particular point clearly using matplotlin in python
score: 1

http://stackoverflow.com/comment/126601768
score: 0
type: Comment
type: QuestionComment
has text: Similar behaviour can be observed if the input data is `int`
comment on: http://stackoverflow.com/q/50484278

http://stackoverflow.com/q/50489490
has comment: http://stackoverflow.com/comment/87992987
type: Question
has body: I have a tree structure where at every node there is a list of documents (document length can vary from 5 to 500), and each document contains a number of words. I want to store in how many documents each word appears in the form of a dictionary. For example: If the document at any node A = [['b','m','n'],['b'],['g'],['o','b','g'],['b','g']] The count should be stored in each node like A.occurlist = {'b':4,'m':1,'n':1,'g':3,'o':1 I am running the below code but it is not able to incur recursion and showing error: TypeError: 'dict' object is not callable Code: def occurlist(node): wordSet = set() lis = [] next_node = [] child_nodes = node.children for child in child_nodes: next_node.append(child) lis += child.documents wordSet = set(itertools.chain.from_iterable(lis)) occurDict = {word:0 for word in wordSet} for child in child_nodes: occurlist = {} occurlist.update(copy.deepcopy(occurDict)) for doc in child.documents: for word in wordSet: if word in doc: occurlist[word] +=1 child.occurlist = occurlist print child.name print len(next_node) if next_node: for nn in next_node: if not nn.update: occurlist(nn) occurlist(Savings_Accounts) Savings_Accounts is the name of root node.
has answer: http://stackoverflow.com/a/50489630
type: UnansweredQuestion
has title: Recursion not working while traversing through the tree
tagged with: python
has comment: http://stackoverflow.com/comment/87992214
score: 0
answer count: 1

http://stackoverflow.com/comment/88034439
has text: It's not clear to me what you are trying to accomplish. Why is the script in a loop in the template?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50511034
score: 0

http://stackoverflow.com/comment/87973535
has text: Yes it will, it loops over the first set while looping over the whole of the second set for each of the first
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50480048
type: Comment

http://stackoverflow.com/q/50425247
has title: how to decide which class tag i should use to crawl data from website using scrapy
upvote count: 0
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/50425516
tagged with: scrapy
favorite count: 0
type: Question
has body: I am new to python and scrapy and i want crawl bank names from website. I am using scrapy but I am confuse about what class name to use in response.css('_______::text').extract()enter image description hereto get the name of bank. I have included screenshot of inspect of page. enter image description here
type: UnansweredQuestion
score: -2
tagged with: python

http://stackoverflow.com/a/50437257
has comment: http://stackoverflow.com/comment/87889208
has body: import pandas as pd data = [['A'], ['America'], ['2017-39', '2017-40', '2017-41', '2017-42', '2017-43'], [10.0, 6.0, 6.0, 6.0, 1.0], [5.0,7.0,8.0,9.0,1.0], ['B'], ['Britan'], ['2017-38', '2017-39', '2017-40', '2017-41', '2017-42', '2017-43', '2017-44'], [41.0, 27.0, 38.0, 36.0, 33.0, 41.0, 8.0], [40.0, 38.0, 28.0, 27.0, 23.0, 65.0, 4.0]] result = {} for letters, countries, dates, val1, val2 in zip(*[iter(data)]*5): result[tuple(letters+countries)] = pd.DataFrame({'date':dates, 'val1':val1, 'val2':val2}) result = pd.concat(result) print(result) yields date val1 val2 A America 0 2017-39 10.0 5.0 1 2017-40 6.0 7.0 2 2017-41 6.0 8.0 3 2017-42 6.0 9.0 4 2017-43 1.0 1.0 B Britan 0 2017-38 41.0 40.0 1 2017-39 27.0 38.0 2 2017-40 38.0 28.0 3 2017-41 36.0 27.0 4 2017-42 33.0 23.0 5 2017-43 41.0 65.0 6 2017-44 8.0 4.0 The main idea above is to use the "grouper idiom" zip(*[iter(data)]*5) to group the items in data in groups of 5. That way, you can use for letters, countries, dates, val1, val2 in zip(*[iter(data)]*5): to loop through 5 items of data at a time. pd.concat can accept a dict of DataFrames as input and concatenate them into a single DataFrame with a MultiIndex composed of the keys of the dict. So the for-loop is used to compose the dict of DataFrames, for letters, countries, dates, val1, val2 in zip(*[iter(data)]*5): result[tuple(letters+countries)] = pd.DataFrame({'date':dates, 'val1':val1, 'val2':val2}) and then result = pd.concat(result) produces the desired DataFrame. Not that you could drop the last level of the MultiIndex: In [91]: result.index = result.index.droplevel(level=-1) In [92]: result Out[92]: date val1 val2 A America 2017-39 10.0 5.0 America 2017-40 6.0 7.0 America 2017-41 6.0 8.0 America 2017-42 6.0 9.0 America 2017-43 1.0 1.0 B Britan 2017-38 41.0 40.0 Britan 2017-39 27.0 38.0 Britan 2017-40 38.0 28.0 Britan 2017-41 36.0 27.0 Britan 2017-42 33.0 23.0 Britan 2017-43 41.0 65.0 Britan 2017-44 8.0 4.0 but I wouldn't recommend this since it makes the …
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50437159
downvote count: 0

http://stackoverflow.com/q/50399374
tagged with: zipcode
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/16378152
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/87814980
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50399487
score: -3
tagged with: powershell
upvote count: 1
tagged with: excel
has title: Extracting city and state info out of zip codes in Excel
linked to: http://stackoverflow.com/q/16378152
has body: I need to extract city and state info out of the zip codes in my Excel sheet. I have an Excel sheet which has over 50 thousands of zip codes in a single column, I created another 2 columns next to it as City and State. Is there any easy way or any common formula to find out corresponding city and state names with these zip codes and populate them in city and state columns? Thanks..
has answer: http://stackoverflow.com/a/50399491
tagged with: scripting
tagged with: python

http://stackoverflow.com/comment/87878623
has text: Let me try to create new Django app in my system and try your code. I'll get get back to you soon. Thanks.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50431195
score: 0

http://stackoverflow.com/q/50401827
has title: pip does not upgrade after installing a specific version
tagged with: python-packaging
score: 0
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: pip
has answer: http://stackoverflow.com/a/50401946
tagged with: python
has body: $ lsb_release -a LSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch Distributor ID: CentOS Description: CentOS release 6.7 (Final) Release: 6.7 Codename: Final $ sudo yum -y erase python-pip $ ls -l /usr/bin/pip* ls: cannot access /usr/bin/pip*: No such file or directory $ sudo yum -y install python-pip Running Transaction Installing : python-pip-7.1.0-1.el6.noarch 1/1 Verifying : python-pip-7.1.0-1.el6.noarch 1/1 Installed: python-pip.noarch 0:7.1.0-1.el6 Complete! $ /usr/bin/pip --version pip 7.1.0 from /usr/lib/python2.6/site-packages (python 2.6) $ /usr/bin/pip2 --version pip 7.1.0 from /usr/lib/python2.6/site-packages (python 2.6) $ /usr/bin/pip2.6 --version pip 7.1.0 from /usr/lib/python2.6/site-packages (python 2.6) $ sudo pip2.6 install pip==9.0.3 You are using pip version 7.1.0, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. Collecting pip==9.0.3 Using cached https://files.pythonhosted.org/packages/ac/95/a05b56bb975efa78d3557efa36acaf9cf5d2fd0ee0062060493687432e03/pip-9.0.3-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 7.1.0 Uninstalling pip-7.1.0: Successfully uninstalled pip-7.1.0 Successfully installed pip-9.0.0 $ /usr/bin/pip --version pip 9.0.3 from /usr/lib/python2.6/site-packages (python 2.6) $ /usr/bin/pip2 --version pip 9.0.3 from /usr/lib/python2.6/site-packages (python 2.6) $ /usr/bin/pip2.6 --version pip 9.0.3 from /usr/lib/python2.6/site-packages (python 2.6) Why no upgrade happens below ? $ sudo pip2.6 install --upgrade pip DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6 /usr/lib/python2.6/site-packages/pip/_vendor/urllib3/util/ssl_.py:339: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) e…

http://stackoverflow.com/a/50458212
score: 0
type: Answer
has body: It appears in the first block of code that is commented, you are iterating thru the unconfirmed_users by using pop(). pop() pops off from the end of the list as in unconfirmed_users[-1]. Where in the second code block you use the for loop which starts from the beginning of the list as in unconfirmed_users[0].
answers question: http://stackoverflow.com/q/50458131

http://stackoverflow.com/q/50521481
tagged with: qualtrics
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: extract
upvote count: 2
possible better answer: http://stackoverflow.com/a/50527137
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50592434
has answer: http://stackoverflow.com/a/50592434
score: 2
has title: Qualtrics API - Certain columns change from string to number
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50527137
has body: I am downloading data from a survey that we did in Qualtrics. I found Python 3 sample code (https://api.qualtrics.com/docs/response-exports) and based my code around it. After successful download I noticed that questions that had provided a list of option for the user to select from were downloaded as numbers (I suspect the index of the answer selected). I believe the answer is simple as putting in some parameters to download the data differently but I can't seem to find it in Qualtric's API documentation. This is what the data looks like when I use this program This is what I want it to look like Here is my code with my api credentials changed: import shutil import os import requests import zipfile import json import io # Setting user Parameters apiToken = "myKey" surveyId = "mySurveyID" fileFormat = "csv" dataCenter = "az1" # Setting static parameters requestCheckProgress = 0 progressStatus = "in progress" baseUrl = "https://{0}.qualtrics.com/API/v3/responseexports/".format(dataCenter) headers = { "content-type": "application/json", "x-api-token": apiToken, } # Step 1: Creating Data Export downloadRequestUrl = baseUrl downloadRequestPayload = '{"format":"' + fileFormat + '","surveyId":"' + surveyId + '"}' downloadRequestResponse = requests.request("POST", downloadRequestUrl, data=downloadRequestPayload, headers=headers) progressId = downloadRequestResponse.json()["result"]["id"] print(downloadRequestResponse.text) #print (requests) # Step 2: Checking on Data Export Progress and waiting until export is ready while requestCheckProgress &lt; 100 and progressStatus is not "complete": requestCheckUrl = baseUrl + progressId requestCheckResponse = requests.request("GET", requestCheckUrl, headers=headers) requestCheckProgress = requestCheckResponse.json()["result"]["percentComplete"] print("Download is " + str(requestCheckProgress) + " complete") # Step 3: Downloading file requestDownloadUrl = baseUrl + progressId + '/file' requestDownload = requests.request("GET", reques…

http://stackoverflow.com/q/50537522
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50540326
has body: I have created a file parameter for my python script. My idea is read these parameters from a JSON file and then execute wherever I need. here is the sample file: { "configfiles": [ { "log": "/home/ubuntu/scripts/mtm-etl/etl-process-log", "connection":"/home/ubuntu/scripts/mtm-etl/etlconfig/mtm-connection", "query_redshift_library":"/home/ubuntu/scripts/mtm-etl/etlconfig/query_redshift_library" } ] } Ok, now I pretend to read these key, values in a for within my script to assign them to a variable then, here is my code: with open('etl-parameters','r') as userinfo: param = json.load(userinfo) for param,extraction in param.items(): if ("ETL" in param): for item in extraction: process = item['etl-process'] stored_query = item['stored-query'] elif( "configfiles" in param): for item in extraction: logfile = item['log'], connectionfile = item['connection'], query_redshift_library = item['query_redshift_library'] My issue is in the elif because for one variable is being assigned the right data type as a string but for some reason for the variables logfile and connectionfile it's assigning a tuple. I have catched up this in my debug: I appreciate your feedback thanks
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python 3 reading json values as tuple
tagged with: python
has answer: http://stackoverflow.com/a/50540326
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/50499893
downvote count: 0
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
has title: How can I set the coefficients in SVM manually?
answer count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has body: from sklearn.svm import SVC print(SVC.__doc__) Doesn't show any way to construct a SVM with set coefficients, and though there's access to coef_ it won't allow assigning to it: File "coffee.py", line 17, in &lt;module&gt; clf.coef_[0] = [1.0,1.0] ValueError: assignment destination is read-only Now naturally you can do the equivalent matrix operations as I've done in coffee.py example, but is there a general way to change specific values in general for any type of SVM?
type: UnansweredQuestion

http://stackoverflow.com/q/50392027
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I want to wrap the tf.metrics around a Sonnet module for measuring performance of each batch, and the following is the work I have done: import tensorflow as tf import sonnet as snt class Metrics(snt.AbstractModule): def __init__(self, indicator, summaries = None, name = "metrics"): super(Metrics, self).__init__(name = name) self._indicator = indicator self._summaries = summaries def _build(self, labels, logits): if self._indicator == "accuracy": metric, metric_update = tf.metrics.accuracy(labels, logits) with tf.control_dependencies([metric_update]): outputs = tf.identity(metric) elif self._indicator == "precision": metric, metric_update = tf.metrics.precision(labels, logits) with tf.control_dependencies([metric_update]): outputs = tf.identity(metric) elif self._indicator == "recall": metric, metric_update = tf.metrics.recall(labels, logits) with tf.control_dependencies([metric_update]): outputs = tf.identity(metric) elif self._indicator == "f1_score": metric_recall, metric_update_recall = tf.metrics.recall(labels, logits) metric_precision, metric_update_precision = tf.metrics.precision(labels, logits) with tf.control_dependencies([metric_update_recall, metric_update_precision]): outputs = 2.0 / (1.0 / metric_recall + 1.0 / metric_precision) else: raise ValueError("unsupported metrics") if type(self._summaries) == list: self._summaries.append(tf.summary.scalar(self._indicator, outputs)) return outputs However, when I want to test the module, the following code works: def test3(): import numpy as np labels = tf.constant([1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], tf.int32) logits = tf.constant([1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], tf.int32) metrics = Metrics("accuracy") accuracy = metrics(labels, logits) metrics2 = Metrics("f1_score") f1_score = metrics2(labels, logits) writer = tf.summary.FileWriter("utils-const", tf.get_default_graph()) with tf.Session() as sess: sess.run([tf.global_variables_…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50395387
has title: tf.constant and tf.placeholder behave differently
tagged with: sonnet

http://stackoverflow.com/q/50420066
tagged with: tweepy
downvote count: 1
has answer: http://stackoverflow.com/a/50423671
has body: Suppose that a twitter user has sent a tweet which has a specific tweet id. What is the best way to get n tweets from same user exactly before that specific tweet id using tweepy? Any help will be appreciated.
type: AnsweredQuestion
score: 0
tagged with: twitter
favorite count: 0
type: Question
has title: optimum way to get tweets before specific tweet using tweepy
answer count: 1
accepted answer: http://stackoverflow.com/a/50423671
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87978849
has text: @Cicero I checked the first 5 links in `article links.txt`; they do have the text content in the `article-wrap` class.
score: 0
comment on: http://stackoverflow.com/q/50482770
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50432219
has comment: http://stackoverflow.com/comment/87878968
has comment: http://stackoverflow.com/comment/87878895
type: UnansweredQuestion
tagged with: python
has title: Use external microphone for pyaudio
has comment: http://stackoverflow.com/comment/87888517
has comment: http://stackoverflow.com/comment/87879267
tagged with: pyaudio
has comment: http://stackoverflow.com/comment/87886774
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87898694
tagged with: speech-recognition
favorite count: 0
has comment: http://stackoverflow.com/comment/87879169
type: Question
has body: I am writing a code in python which does speech recognition using the pyaudio module. When I first ran the code I got an error saying "no default input device detected" . So I got a USB sound card and a microphone but it still gives me the same error. How do I get my code to use the usb sound card instead of my comp's inbuilt one? I have Ubuntu 16.04 and Python 3.6.5 This is my python code import speech_recognition as sr import pyaudio #I tried using import pyaudio as well r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) try: print("You said" + r.recognize_sphinx(audio)) except sr.UnknownValueError: print("Could not understand audio") except sr.RequestError as e: print("error; {0}".format(e)) PS- My mic works well with applications like Audacity, so I don't think the mic is broken this is the screenshot of the pavucontrol
tagged with: python-3.x

http://stackoverflow.com/q/50432185
tagged with: list
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/87878632
tagged with: python
type: UnansweredQuestion
score: -1
upvote count: 0
has answer: http://stackoverflow.com/a/50432280
downvote count: 1
answer count: 1
favorite count: 0
tagged with: indexing
has body: I have a pandas dataframe df column1 2 1 3 2 8 3 10 4 45 5 I wanna convert this column1 of pandas dataframe into a list x , and I also want the index to be the index of the list as well so that if i call x[2] it should return 1 I tried x = df['column1'].values But the list index got reset. I am looking for an answer, I will appreciate your time and effort to help me.
has title: deep copying the pandas dataframe into a list (including index)

http://stackoverflow.com/comment/87826659
comment on: http://stackoverflow.com/q/50405112
type: Comment
score: 0
has text: Why are your dict keys URL-encoded?
type: QuestionComment

http://stackoverflow.com/a/50401376
type: Answer
answers question: http://stackoverflow.com/q/50401236
upvote count: 2
downvote count: 0
has body: In your situation, it is better to define 3 function, one for each candidate: A = 0 B = 0 C = 0 def after_vote_A(): global A A += 1 print("Thank you for your vote.") def after_vote_B(): global B B += 1 print("Thank you for your vote.") def after_vote_C(): global C C += 1 print("Thank you for your vote.") Don’t forget to use the keyword global or else you define a local variable. An alternative is to store votes in a dict: votes = {'A': 0, 'B': 0, 'C': 0} def after_vote(letter): votes[letter] += 1 print("Thank you for your vote.") Démonstration: after_vote('A') after_vote('B') after_vote('A') after_vote('A') print(votes) You get: Thank you for your vote. Thank you for your vote. Thank you for your vote. Thank you for your vote. {'A': 3, 'B': 1, 'C': 0}
score: 2
has comment: http://stackoverflow.com/comment/87818815

http://stackoverflow.com/q/50510374
accepted answer: http://stackoverflow.com/a/50510434
tagged with: indexing
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Tuple to index using numpy
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50510434
favorite count: 0
type: Question
tagged with: numpy
has body: It drives me crazy, but I can't figure it out I have a data matrix of (10000,4) I need to select some rows where the elements of column 0 ind1=np.where( (data[:,0]&gt;55) &amp; (data[:,0]&lt;65) ) I want to keep that data only so keep_data=data[ind1,:] But keep_data is now (1,10000,4) Why is that? P.S. What i do is th efollwing keep_data=np.reshape(keep_data,(keep_data.shape[1],keep_data.shape[2]))
tagged with: arrays
tagged with: python

http://stackoverflow.com/q/50425093
has comment: http://stackoverflow.com/comment/87865461
downvote count: 0
has body: I am using Python 3.6 I can use the .format function to insert a variables value as part of a new variables value as per the below: var_1 = "First_Var" var_2 = "Second_Var_{}".format(var_1) print (var_1, var_2) This, when run, prints: First_Var Second_Var_First_Var I would like to be able to insert the value of var_1 and var_2 as values in a dict as per the below code: var_1 = "First_Var" var_2 = "Second_Var_{}".format(var_1) dict_with_inserts = {'First_Var': '{}_inserted', 'Second_Var': '{}_inserted'}.format(var_1, var_2) print (dict_with_inserts) When I run the above I get the below error: AttributeError: 'dict' object has no attribute 'format' So it seems I cant use the .format function on dicts. Is there an alternative way to do this or is it not possible to insert the value of a variable within a Python dict? Any examples or help will be much appreciated.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50432532
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87865176
has answer: http://stackoverflow.com/a/50425150
possible better answer: http://stackoverflow.com/a/50425150
has answer: http://stackoverflow.com/a/50425152
has title: Python 3.6 - Can a variable value be used as part of a key value in a Dict?
has answer: http://stackoverflow.com/a/50425161
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/50432532
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/87790568
comment on: http://stackoverflow.com/q/50387354
type: Comment
type: QuestionComment
has text: which line fails?
score: 0

http://stackoverflow.com/comment/88078014
type: Comment
has text: According to what your initials are running the GUI in another thread, that is forbidden in Qt.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50529406

http://stackoverflow.com/q/50408357
has answer: http://stackoverflow.com/a/50409973
answer count: 2
has comment: http://stackoverflow.com/comment/87832760
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87834239
has comment: http://stackoverflow.com/comment/87832277
has comment: http://stackoverflow.com/comment/87832121
tagged with: python
has answer: http://stackoverflow.com/a/50409293
favorite count: 0
tagged with: go
has comment: http://stackoverflow.com/comment/87833699
score: 0
has comment: http://stackoverflow.com/comment/87967101
has title: Limiting the regex string length for a specific pattern
has comment: http://stackoverflow.com/comment/87832446
has comment: http://stackoverflow.com/comment/87832627
tagged with: java
has body: Can anyone please suggest a regex for the below mentioned conditions. Should not allow only blank spaces(white spaces). Blank spaces are allowed only if atleast one non whitespace character is present. Any characters is allowed. Length should be limited to 50 characters. I tried this pattern .*[^ ].* from Regex pattern for "contains not only spaces". Can you please suggest how to limit this to 50 characters.
downvote count: 1
linked to: http://stackoverflow.com/q/12568451
tagged with: regex
has comment: http://stackoverflow.com/comment/87832184
has comment: http://stackoverflow.com/comment/87834320
type: Question
has comment: http://stackoverflow.com/comment/87833296

http://stackoverflow.com/comment/87875460
type: Comment
comment on: http://stackoverflow.com/a/50430268
score: 0
type: AnswerComment
has text: I tried this and doesnt worked, on my case, PC and I are integers variables.

http://stackoverflow.com/comment/87983047
comment on: http://stackoverflow.com/a/50484677
type: Comment
has text: Question: how would it look like, if it would work with standard input?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88072082
score: 0
has text: @irene Understood, very large product, i think I have something on my mind, will post once I test it.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50529751

http://stackoverflow.com/comment/87908577
has text: @TomDalton Thanks, I will try to fix it
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50447533

http://stackoverflow.com/q/50504818
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88021972
tagged with: web-crawler
has answer: http://stackoverflow.com/a/50504976
score: 0
has body: I am new to scrapy. I would like to make my web crawler for my personal experiment,that would crawl the entire Internet and store the URL of e-commerce websites to my db.I have searched all over the Google ,and found this this one and many more are almost same. But there is start_urls = ['http://brickset.com/sets/year-2016'] that I want to modify and want to add whole Internet.Is this possible ? if yes ,please guide me the right approach. Thanks in advance.
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88021866
tagged with: scrapy
downvote count: 1
has comment: http://stackoverflow.com/comment/88021906
favorite count: 0
type: Question
has title: How to make web crawler for all e-commerce websites

http://stackoverflow.com/q/50529504
linked to: http://stackoverflow.com/q/1373164
downvote count: 0
has body: I want to print out variables named a1, a2, a3, ... etc. using for loop in python. Is there a way to implement this? For example, a0 = 3 a1 = 4 a2 = 5 for i in range(3): tmps = 'a' + '%d' %i print(tmps) This will only print out a0 a1 a2 I want my code to print out 3 4 5
has answer: http://stackoverflow.com/a/50529568
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50529568
score: 2
has answer: http://stackoverflow.com/a/50529565
accepted answer: http://stackoverflow.com/a/50529565
has title: Python - Can I print out variables with consecutive numbers with for loops?
tagged with: python
linked to: http://stackoverflow.com/q/9383740
duplicate of: http://stackoverflow.com/q/1373164
favorite count: 0
type: Question
answer count: 2
tagged with: for-loop
upvote count: 2

http://stackoverflow.com/comment/88046752
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50496642
has text: Thanks so much. This works perfectly on the test data. Unfortunately, I am running into issues on the real set, largely, I believe, because of unexpected NaN's. For instance, Bob's 'dob' might be missing or a 'date_entered', and it seems to be throwing everything off.
type: AnswerComment

http://stackoverflow.com/comment/87852257
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50415828
has text: Good point; I forgot all about np.matrix`. Replacing it by `np.array` resulted in about 3x speedup. @mgus
type: Comment

http://stackoverflow.com/q/50434584
has comment: http://stackoverflow.com/comment/87901456
has title: Process 4 different video feed in opecv python
has comment: http://stackoverflow.com/comment/87901369
has body: I have CUDA 9.0 running on 1080 GPU (ubuntu 16.04), i have to process four different video feed in opencv. what is best way to multiprocess in cuda &amp; opencv ?
has comment: http://stackoverflow.com/comment/87902188
score: 0
answer count: 0
tagged with: image-processing
tagged with: object-detection
type: Question
tagged with: yolo
has comment: http://stackoverflow.com/comment/87885777
type: UnansweredQuestion
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/87901630
tagged with: python

http://stackoverflow.com/q/50536492
tagged with: keras
answer count: 0
score: 1
has body: The episodic memory module from DMN has a unique state update mechanism that is based on the attention: Equation 8 describes the gate g, the attention map, is used to compute the next state between a GRU and the previous state. My current implementation uses: class EpisodicMemory(L.Wrapper): """Episodic memory from DMN.""" def __init__(self, units, **kwargs): self.grucell = L.GRUCell(units, name=kwargs['name']+'_gru') # Internal cell super().__init__(self.grucell, **kwargs) def build(self, input_shape): """Build the layer.""" _, _, ctx_shape = input_shape self.grucell.build((ctx_shape[0],) + ctx_shape[2:]) super().build(input_shape) def call(self, inputs): """Compute new state episode.""" init_state, atts, cs = inputs # GRU pass over the facts, according to the attention mask. while_valid_index = lambda state, index: index &lt; tf.shape(cs)[1] retain = 1 - atts update_state = (lambda state, index: (atts[:,index,:] * self.grucell.call(cs[:,index,:], [state])[0] + retain[:,index,:] * state)) # Loop over context final_state, _ = tf.while_loop(while_valid_index, (lambda state, index: (update_state(state, index), index+1)), loop_vars = [init_state, 0]) return final_state def compute_output_shape(self, input_shape): """Collapse time dimension.""" return input_shape[0] and used as: # ... sim_vec = concat([s_s_c, s_m_c, ctx_state, embedded_sents, repeated_q]) sim_vec = att_dense1(sim_vec) # (?, context_size, dim) sim_vec = att_dense2(sim_vec) # (?, context_size, 1) episodic_mem = EpisodicMemory(dim, name='episodic_mem') state = episodic_mem([state, sim_vec, embedded_sents]) # ... Is there a way to implement this in Keras without binding to Tensorflow functions? Even though we can pass constants to a custom RNN cell, say the attention map, we don't know the current index of the loop inside call function.
favorite count: 0
type: Question
has title: Episodic Memory from Dynamic Memory Networks
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87868194
type: QuestionComment
has text: Just tried with 3 images, all with the same result :(
comment on: http://stackoverflow.com/q/50426629
type: Comment
score: 0

http://stackoverflow.com/comment/88084308
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50528569
has text: @alexboal If you don't mind seeing the browser actually open, you should use Selenium as was suggested by CoMartel.
type: Comment

http://stackoverflow.com/q/50474398
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50475211
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87962453
tagged with: python
has body: I am following up online course for Python basic, and got stuck with a quiz about generator: I have access to the solution, but I don't want to directly see it. I want to make output as below, without using enumerate but by using generator. I have below pre-written piece of code to start, but I cannot understand why they put start=0. Could someone help me out to have some leads ? I still want to make output myself, but dont know how should I start. Expected output: Lesson 1: Why Python Programming Lesson 2: Data Types and Operators Lesson 3: Control Flow Lesson 4: Functions Lesson 5: Scripting Code: lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"] def my_enumerate(iterable, start=0): # Implement your generator function here for i, lesson in my_enumerate(lessons, 1): print("Lesson {}: {}".format(i, lesson)) Thank you!
tagged with: generator
tagged with: iterator
downvote count: 0
has title: Python generators to generate iterators

http://stackoverflow.com/a/50421109
type: Answer
has body: You can adjust your root_to_leaf_paths() function a bit to treat it as a general dict flattener. Flatten both the schema and the data. Then the comparison is trivial. schema = { 'a' : str, 'b' : { 'c': int, 'd': int, } } data = { 'a' : 1, 'c' : 1 } def flatten(obj, path = tuple()): if isinstance(obj, dict): for k, v in obj.items(): yield from flatten(v, path + (k,)) else: yield (path, obj) fschema = dict(flatten(schema)) fdata = dict(flatten(data)) for path, exp in fschema.items(): if path in fdata: got = type(fdata[path]) if got is not exp: print(f'Incorrect type: path={path} got={got} exp={exp}') else: print(f'Missing key: path={path}')
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50420987
answers question: http://stackoverflow.com/q/50420987

http://stackoverflow.com/comment/87878123
type: Comment
has text: The reason is that "* 4" just makes 3 references to the existing sublist [[0]*3] instead of making new sublists. Therefore, essentially it only creates only 1 sublist here.
type: AnswerComment
comment on: http://stackoverflow.com/a/50431781
score: 1

timedelta
tags question: http://stackoverflow.com/q/50464135
tags question: http://stackoverflow.com/q/50478066
tags question: http://stackoverflow.com/q/50454573
type: Tag
tags question: http://stackoverflow.com/q/50443443
tags question: http://stackoverflow.com/q/50393580
tags question: http://stackoverflow.com/q/50462553
tags question: http://stackoverflow.com/q/50480517
tags question: http://stackoverflow.com/q/50455797
tag name: timedelta
tags question: http://stackoverflow.com/q/50463625

http://stackoverflow.com/a/69645821
answers question: http://stackoverflow.com/q/50532509
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50532509
has body: As stated by FHTMitchell pd.to_numeric is the better option.
score: 0

http://stackoverflow.com/comment/88077286
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50532583
has text: Megain, `numpy` works faster then simple python array.

http://stackoverflow.com/a/50541615
has comment: http://stackoverflow.com/comment/88094517
has comment: http://stackoverflow.com/comment/88094801
has body: Starting with the Series, ser: 2014 180657 2015 153837 2014 72395 2012 69708 2013 61364 2015 54117 2013 3313 2012 1076 2/8/2014 0:00 2 7/3/2014 0:00 2 1/29/2015 0:00 2 9/1/2014 0:00 2 11/22/2014 0:00 2 10/16/2014 0:00 2 dtype: int64 You can convert the index to datetime and extract the year: ser.index = pd.to_datetime(ser.index, errors='coerce').year ser 2014 180657 2015 153837 2014 72395 2012 69708 2013 61364 2015 54117 2013 3313 2012 1076 2014 2 2014 2 2015 2 2014 2 2014 2 2014 2 dtype: int64 If this introduces NaNs, you can eliminate them by ser = ser[ser.index.notnull()] ser.index = ser.index.astype('int') And if you want to group this by year, you can group on index: ser.groupby(level=0).sum() Out: 2012 70784 2013 64677 2014 253062 2015 207956 dtype: int64
has comment: http://stackoverflow.com/comment/88095304
has comment: http://stackoverflow.com/comment/88095252
has comment: http://stackoverflow.com/comment/88094602
has comment: http://stackoverflow.com/comment/88095336
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/88095123
has comment: http://stackoverflow.com/comment/88095399
upvote count: 4
has comment: http://stackoverflow.com/comment/88094928
has comment: http://stackoverflow.com/comment/88094848
has comment: http://stackoverflow.com/comment/88094495
downvote count: 0
has comment: http://stackoverflow.com/comment/88094923
answers question: http://stackoverflow.com/q/50541508

http://stackoverflow.com/comment/88001730
has text: It's also worth mentioning that vectorized string operations don't always outperform regular Python loops. Even when they do, the difference is not that much. Pandas handles labels/NaNs for you though.
score: 2
comment on: http://stackoverflow.com/a/50494389
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87817529
type: Comment
type: QuestionComment
has text: What version of Pandas are you using?
comment on: http://stackoverflow.com/q/50400843
score: 1

http://stackoverflow.com/q/50441119
has answer: http://stackoverflow.com/a/50678096
has comment: http://stackoverflow.com/comment/87896971
has comment: http://stackoverflow.com/comment/87896861
has body: Get python from Docker Hub: $ docker pull python on CoreOS. Want to use Ansible to connect it from other host, so it's necessary to launch Python on CoreOS. But how to do by this way? More details This way can run ansible with coreos: Step 1: Install python with shell script on CoreOS (It's said not good but now it can be used) How do I run python on my Vagrant vm instance that is CoreOS? Step 2: Config hosts in an ansible-playbook [coreos] core-01 [coreos:vars] ansible_ssh_user=core ansible_python_interpreter=/home/core/bin/python Step 3: Test connection $ ansible -m ping -u core -i hosts core-01 core-01 | SUCCESS =&gt; { "changed": false, "ping": "pong" } It can be used. But about Step 1, is there a way to use python container to launch it instead of using shell script to install?
favorite count: 0
type: Question
tagged with: coreos
has comment: http://stackoverflow.com/comment/87896875
has comment: http://stackoverflow.com/comment/87896790
accepted answer: http://stackoverflow.com/a/50678096
score: -3
has title: How to run Python with docker on daemon mode?
tagged with: python
linked to: http://stackoverflow.com/q/36816491
tagged with: docker
has comment: http://stackoverflow.com/comment/87929893
type: AnsweredQuestion
tagged with: ansible
upvote count: 0
has comment: http://stackoverflow.com/comment/87914466
answer count: 1
downvote count: 3
tagged with: process

http://stackoverflow.com/q/50386210
tagged with: python
type: Question
upvote count: 2
score: 2
has title: Accuracy very bad in tensorflow logistic regression
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50389541
tagged with: tensorflow
favorite count: 0
tagged with: logistic-regression
has body: I am trying to write a program that predicts if one has malignant tumor or benign tumor Dataset is from:https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Prognostic%29 This is my code and my accuracy is at about 65% which is no better than a coin flip. Any help would be appreciated import tensorflow as tf import pandas as pd import numpy as np df = pd.read_csv(r'D:\wholedesktop\logisticReal.txt') df.drop(['id'], axis=1, inplace=True) x_data = np.array(df.drop(['class'], axis=1)) x_data = x_data.astype(np.float64) y = df['class'] y.replace(2, 0, inplace=True) y.replace(4, 1, inplace=True) y_data = np.array(y) # y shape = 681,1 # x shape = 681,9 x = tf.placeholder(name='x', dtype=np.float32) y = tf.placeholder(name='y', dtype=np.float32) w = tf.Variable(dtype=np.float32, initial_value=np.random.random((9, 1))) b = tf.Variable(dtype=np.float32, initial_value=np.random.random((1, 1))) y_ = (tf.add(tf.matmul(x, w), b)) error = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_, labels=y)) goal = tf.train.GradientDescentOptimizer(0.05).minimize(error) prediction = tf.round(tf.sigmoid(y_)) correct = tf.cast(tf.equal(prediction, y), dtype=np.float64) accuracy = tf.reduce_mean(correct) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(2000): sess.run(goal, feed_dict={x: x_data, y: y_data}) print(i, sess.run(accuracy, feed_dict={x: x_data, y: y_data})) weight = sess.run(w) bias = sess.run(b) print(weight) print(bias)

http://stackoverflow.com/q/50498612
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88020860
upvote count: 2
tagged with: healpy
has comment: http://stackoverflow.com/comment/88022547
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50645308
tagged with: python
has title: Healpy mask has border
has comment: http://stackoverflow.com/comment/88034456
has comment: http://stackoverflow.com/comment/88036073
has comment: http://stackoverflow.com/comment/88035798
has comment: http://stackoverflow.com/comment/88021326
has body: I am trying to mask my healpy map for pixels that have no data, however when I apply the healpy mask with badval=-1.6375e+30, there seems to be a border around my mask. import healpy as hp import numpy as np # load the mask mask = hp.read_map('mask_nvss_S20-S1000_Ns64.fits') # degrade the mask to NSIDE = 16 mask16 = np.round(hp.ud_grade(mask, 16)) # apply it to the map masked_map = hp.ma(map1) masked_map.mask = np.logical_not(mask16) # masked map nvss_map = np.round(masked_map) Can anyone help me remove this border effect?
has comment: http://stackoverflow.com/comment/88058376
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/88021471
downvote count: 1

http://stackoverflow.com/comment/88015030
type: AnswerComment
has text: See commented out code... this would create a file called `file15.csv` for all the 15 second data and `file16.csv` for all the 16 second data.
score: 1
comment on: http://stackoverflow.com/a/50501263
type: Comment

http://stackoverflow.com/comment/88027164
comment on: http://stackoverflow.com/q/50507165
score: 0
type: Comment
has text: Thank you for comment. I just wonder that code is trained
type: QuestionComment

http://stackoverflow.com/comment/87859914
has text: Output shown above is when I reinstalled it to confirm that this package is install properly. Output of `pip freeze` is not showing this package and I wonder why if everything is perfect here. Thanks.
comment on: http://stackoverflow.com/a/50400563
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87959284
comment on: http://stackoverflow.com/a/50472474
type: Comment
type: AnswerComment
has text: NoReverseMatch at /polls/ .
score: 0

http://stackoverflow.com/comment/88053930
score: 0
has text: @zwitterion also, if you are having problem with unicode vs ascii, definitely switch to Python3, everything has been harmonized
comment on: http://stackoverflow.com/q/50520741
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88040162
comment on: http://stackoverflow.com/a/50512010
score: 0
type: AnswerComment
has text: You can use `datetime.fromtimestamp(i['Time']).strftime('%Y-%m-%d')` if you need a string output.
type: Comment

http://stackoverflow.com/a/50400060
has comment: http://stackoverflow.com/comment/97626255
has body: I think a scatter plot is perfectly suitable to create this kind of categorical bubble plot. Create the dataframe: import pandas as pd df = pd.DataFrame([[.3,.2,.4],[.1,.4,.1]], columns=list("ABC"), index=list("XY")) Option 1: unstack the DataFrame dfu = df.unstack().reset_index() dfu.columns = list("XYS") This creates a table like X Y S 0 A X 0.3 1 A Y 0.1 2 B X 0.2 3 B Y 0.4 4 C X 0.4 5 C Y 0.1 which you can plot column-wise. Since the sizes of scatters are points one would need to multiply the S column with some large number, like 5000 to get large bubbles. import matplotlib.pyplot as plt dfu["S"] *= 5000 plt.scatter(x="X", y="Y", s="S", data=dfu) plt.margins(.4) plt.show() Option 2: create grid Using e.g. numpy, one may create a grid of the dataframe's columns and index such that one may then plot a scatter of the flattened grid. Again one would need to multiply the dataframe values by some large number. import numpy as np import matplotlib.pyplot as plt x,y = np.meshgrid(df.columns, df.index) df *= 5000 plt.scatter(x=x.flatten(), y=y.flatten(), s=df.values.flatten()) plt.margins(.4) plt.show() In both cases the result would look like
upvote count: 6
type: Answer
score: 6
answers question: http://stackoverflow.com/q/50399802
has comment: http://stackoverflow.com/comment/97625393
accepted answer of: http://stackoverflow.com/q/50399802
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87847241

http://stackoverflow.com/comment/88009908
has text: It's sure possible. You may start by reading the [legend guide](https://matplotlib.org/tutorials/intermediate/legend_guide.html) and search for similar questions on SO.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50497990

colors
tags question: http://stackoverflow.com/q/50399356
tags question: http://stackoverflow.com/q/50530617
tags question: http://stackoverflow.com/q/50516127
tags question: http://stackoverflow.com/q/50445511
tags question: http://stackoverflow.com/q/50415567
tag name: colors
tags question: http://stackoverflow.com/q/50386036
type: Tag

http://stackoverflow.com/q/50470949
accepted answer: http://stackoverflow.com/a/50471009
tagged with: redis
tagged with: byte
has comment: http://stackoverflow.com/comment/87955438
has answer: http://stackoverflow.com/a/50471009
has comment: http://stackoverflow.com/comment/87955717
has body: a1 = b'\x01\x02\x41' \x41 is A and when I print str(a1), I get b'\x01\x02A' how could I get the original hex string? I want to get: \x01\x02\x41 I use this string for redis-cli --pipe. I don't want python to print the converted string for me. How could I do it? now I do like this: def convert(i:bytes): result = list() for j in i: result.append('\\x%s' % bytes([j]).hex()) return ''.join(result) It is too ugly. Is there a better way? btw. This is my redis-cli --pipe script: SET "\xda\xb8\xe6\xc0\x79\x62\xea\x06\xde\x9e\xb0\x4e\x68\xde\x0b\x62" "\x00\x42\xdc\x06\x03\x00\x00\x00" SET "\x68\xfa\xfc\x03\x36\x99\xb0\x56\xb4\x00\xaf\x61\x42\xe0\x30\x42" "\x01\x42\xdc\x06\x03\x00\x00\x00" SET "\x40\x98\xb9\x8f\xd8\x4e\x2e\x32\x40\x09\xca\xa4\x55\x52\xde\x7f" "\x02\x42\xdc\x06\x03\x00\x00\x00" SET "\xd0\x75\xdf\x46\x36\xd0\xb4\xed\xcc\xed\xd6\x27\xf7\xd9\xc5\xa5" "\x03\x42\xdc\x06\x03\x00\x00\x00" I use it this way: cat sample.redis | redis-cli --pipe
tagged with: python
has comment: http://stackoverflow.com/comment/87955332
has title: How could I convert a bytes to a whole hex string?
type: AnsweredQuestion
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/14674834
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/88034147
comment on: http://stackoverflow.com/q/50510375
type: Comment
has text: Please remove your `tkinter` tag as this question has nothing to do with tkinter or rather the problem you are having is not related to tkinter but purely a python problem.
type: QuestionComment
score: 0

http://stackoverflow.com/q/50456449
downvote count: 1
type: AnsweredQuestion
has title: How to update particular cell value in spark data frame?
accepted answer: http://stackoverflow.com/a/50460346
has answer: http://stackoverflow.com/a/50456551
has answer: http://stackoverflow.com/a/50460346
has comment: http://stackoverflow.com/comment/87927055
score: 1
possible better answer: http://stackoverflow.com/a/50456551
favorite count: 0
type: Question
has body: I have two dataframe. I need to find a value from a dataframe and update a cell for a particular row. Ex. Df1 = (a, 10), (b, 20), (c, 30) Df2 = (a, A1), (c, C1) Expected output: (A, 10, A1), (b, 20, NaN), (c, 30, C1) Please send me in the solution in details as I have just started to work with spark dataframe.
answer count: 2
tagged with: apache-spark-sql
upvote count: 2
tagged with: pyspark
tagged with: python

http://stackoverflow.com/q/50415960
answer count: 2
has answer: http://stackoverflow.com/a/50416031
possible better answer: http://stackoverflow.com/a/50416031
has body: I need to "duplicate" the elements of a DataFrame as many times as elements in a collection (let's say a list to simplify it). It might be hard to explain by words, so I will show my code: In [1]: data = {char: [] for char in 'abcd'} In [2]: n = 3 In [3]: properties = [i for i in range(1, n + 1)] In [4]: l = list(range(1, 11)) In [5]: for e in l: ...: data['a'].append(e + e) ...: data['b'].append(e * e) ...: data['c'].append(e ** e) ...: data['d'].append(1.0 / e) ...: In [6]: df = pd.DataFrame(data) In [7]: df Out[7]: a b c d 0 2 1 1 1.000000 1 4 4 4 0.500000 2 6 9 27 0.333333 3 8 16 256 0.250000 4 10 25 3125 0.200000 5 12 36 46656 0.166667 6 14 49 823543 0.142857 7 16 64 16777216 0.125000 8 18 81 387420489 0.111111 9 20 100 10000000000 0.100000 based on properties, I need to produce the following DataFrame: a b c d property 0 2 1 1 1.000000 1 1 4 4 4 0.500000 1 2 6 9 27 0.333333 1 3 8 16 256 0.250000 1 4 10 25 3125 0.200000 1 5 12 36 46656 0.166667 1 6 14 49 823543 0.142857 1 7 16 64 16777216 0.125000 1 8 18 81 387420489 0.111111 1 9 20 100 10000000000 0.100000 1 10 2 1 1 1.000000 2 11 4 4 4 0.500000 2 12 6 9 27 0.333333 2 13 8 16 256 0.250000 2 14 10 25 3125 0.200000 2 15 12 36 46656 0.166667 2 16 14 49 823543 0.142857 2 17 16 64 16777216 0.125000 2 18 18 81 387420489 0.111111 2 19 20 100 10000000000 0.100000 2 20 2 1 1 1.000000 3 21 4 4 4 0.500000 3 22 6 9 27 0.333333 3 23 8 16 256 0.250000 3 24 10 25 3125 0.200000 3 25 12 36 46656 0.166667 3 26 14 49 823543 0.142857 3 27 16 64 16777216 0.125000 3 28 18 81 387420489 0.111111 3 29 20 100 10000000000 0.100000 3 which is to repeat my data array depending on the amount of elements in properties, and adding the column property. Currently I am using two loops nested loops to achieve it as follows: new_data = {'a': [], 'b': [], c: [], d: [], 'property': []} properties = [1, 2, 3] for property_id in properties: for e in l: new_data['property'].append(property_id) new_data['a'].append(e + e) new_data['b'].append(e * e) ne…
downvote count: 0
has title: Duplicate dataframe depending on elements on a collection
upvote count: 1
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/50415999
score: 1
accepted answer: http://stackoverflow.com/a/50415999
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/87787690
score: 0
comment on: http://stackoverflow.com/q/50385390
type: Comment
type: QuestionComment
has text: Is that the only code in the Category class?? Are you overriding the __init__ method?

http://stackoverflow.com/comment/87861901
type: AnswerComment
type: Comment
has text: @Mulliganaceous if so you can just adding a `datetime.datetime(0,0,0,0,0,0)` to that `timedelta` object. what I provided is just a hint. Beautiful is better than ugly.
comment on: http://stackoverflow.com/a/50422409
score: 0

http://stackoverflow.com/a/50495837
has comment: http://stackoverflow.com/comment/89990717
accepted answer of: http://stackoverflow.com/q/50479385
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50479385
has comment: http://stackoverflow.com/comment/88165062
has comment: http://stackoverflow.com/comment/88008407
has body: First of all there are no "q", "lang", "result_type" parameters for API.user_timeline (read http://docs.tweepy.org/en/v3.5.0/api.html#API.user_timeline) So to ignore some tweets, you have to code a filter. You just can skip tweets not containing "#Gempa" like this : for Tweet in api.user_timeline(user_id=108543358): text = str(Tweet.text.encode("utf-8")) if "#Gempa" not in text: continue print ("*****" + str(n) +"*****") print ("ID: " + Tweet.id_str) ...
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50529022
has title: pandas, melt, unmelt preserve index
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/64855389
answer count: 3
tagged with: pandas
downvote count: 0
upvote count: 48
favorite count: 0
possible better answer: http://stackoverflow.com/a/64855389
type: Question
score: 48
accepted answer: http://stackoverflow.com/a/50529106
has body: I've got a table of clients (coper) and asset allocation (asset) A = [[1,2],[3,4],[5,6]] idx = ['coper1','coper2','coper3'] cols = ['asset1','asset2'] df = pd.DataFrame(A,index = idx, columns = cols) so my data look like asset1 asset2 coper1 1 2 coper2 3 4 coper3 5 6 and I want to run them through a linear optimization (i've got constraints- somtehing like sum of all of asset_i &lt;= amount_on_hand_i and sum of coper_j = price_j) so I have to turn this 2D matrix into a 1D vector. Which is easy with melt df2 = pd.melt(df,value_vars=['asset1','asset2']) But now, when I try to unmelt it, I get a 6-row array with lots of blanks! df2.pivot(columns = 'variable', values = 'value') variable asset1 asset2 0 1.0 NaN 1 3.0 NaN 2 5.0 NaN 3 NaN 2.0 4 NaN 4.0 5 NaN 6.0 Is there any way to preserve the 'coper' part of my indexing while using melt?
has answer: http://stackoverflow.com/a/63005213
tagged with: python
has answer: http://stackoverflow.com/a/50529106
tagged with: linear-programming

http://stackoverflow.com/comment/87994712
type: QuestionComment
comment on: http://stackoverflow.com/q/50490849
score: 2
has text: If you want to use float values, use `DoubleVar`, `IntVar` is for integers.
type: Comment

http://stackoverflow.com/q/50540876
favorite count: 0
tagged with: logic
has answer: http://stackoverflow.com/a/50540994
linked to: http://stackoverflow.com/q/9539921
has comment: http://stackoverflow.com/comment/88093249
has comment: http://stackoverflow.com/comment/88093222
has title: Python - optional parameters before the required ones
has body: def func(a, b, c, config) I will always need to choose one of the three(a, b, c) and the config is always required. It should work like: func(a="hello", config) and func(b="hello", config) Is possible to place optional parameters before the required ones?
tagged with: python
score: -1
type: Question
upvote count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: function
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/87806427
comment on: http://stackoverflow.com/q/50395236
score: 0
type: Comment
type: QuestionComment
has text: To check the last vowel you can try something like this: if word[-1] in vocals: word=word[:-1] sorry but I can't figure out how to post code in comments

http://stackoverflow.com/q/50461448
possible better answer: http://stackoverflow.com/a/50666515
has title: cx_oracle python iteration
tagged with: database
has answer: http://stackoverflow.com/a/50666515
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50481455
has body: I have my python script which reads an excel column row by row and returns all rows str(values). I want to write another script which will allow put these values to sql db. I've already written connect method: def db_connect(): adr = 'some_addr' uid = 'some_uid' pwd = 'pwd' port = port dsn_tns = cx_Oracle.makedsn(adr, port, SID) db = cx_Oracle.connect('username', 'pass', dsn_tns) cur = db.cursor() cur.execute('update TABLE set ROW = 666 where ANOTHER_ROW is null') db.commit() This method does an update but it sets 666 for ALL rows. How to do it by kind of iteration in sql? For example, first row of output == 1, second == 23, third == 888.
type: AnsweredQuestion
upvote count: 0
tagged with: sql
tagged with: cx-oracle
downvote count: 2
answer count: 3
accepted answer: http://stackoverflow.com/a/50470980
has answer: http://stackoverflow.com/a/50470980
favorite count: 0
tagged with: iteration
type: Question

http://stackoverflow.com/comment/87810206
score: 0
type: Comment
has text: Thanks Andersson. That was perfect.
comment on: http://stackoverflow.com/a/50396971
type: AnswerComment

http://stackoverflow.com/comment/92483064
comment on: http://stackoverflow.com/a/50438924
type: Comment
has text: `python3 -m pip uninstall pip` `sudo apt-get --reinstall install python3-pip`
type: AnswerComment
score: 0

http://stackoverflow.com/q/50494262
tagged with: visualization
has comment: http://stackoverflow.com/comment/88004370
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: event-handling
has body: I am very new to the Bokeh visualization library in Python. I have built a geographical map visualization using Bokeh and Google Maps API that allows me to see the distribution of my data for a particular location (city) in the US. I have further factorised that data by gender (using a distinct color for each gender in my dataset, male, female and unknown). What I am aiming to do now is, to render this visualization on a button click event. After going through various documentation in Bokeh, research on stack overflow and other similar sites, I have come up with the following code so far, from bokeh.plotting import figure, output_file, show from bokeh.models import * from bokeh.plotting import gmap from bokeh.io import output_notebook, curdoc from bokeh.transform import factor_cmap from bokeh.models.widgets import Panel, Tabs from bokeh.events import ButtonClick from bokeh.models import Button from bokeh.layouts import column from bokeh.events import ButtonClick import pandas as pd import numpy as np import pyodbc output_file("gmap.html") #parameters server = 'x.x.x.x\abc' db = 'abc' # Create the connection conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + db + ';Trusted_Connection=yes') map_options = GMapOptions(lat=37.686293, lng=-97.3614409, map_type="roadmap", zoom=13) p = gmap("My_Google_Maps_API_Key", map_options, title="Client_Distribution", plot_width=1000, plot_height=600) def callback(event): print ('abc') global p, map_options sql = """ with CTE AS (SELECT CR.ClientID, CR.Latitude, CR.Longtitude FROM Company C LEFT JOIN ClientRegistration CR on C.CompanyID = CR.CompanyID WHERE C.CompanyID = xxx AND (CR.Latitude IS NOT NULL AND CR.Longtitude IS NOT NULL) ) SELECT C.ClientID, C.Latitude, C.Longtitude, CL.Sex FROM CTE C LEFT JOIN Clients CL on C.ClientID = CL.ClientID """ df = pd.read_sql(sql, conn) print (df) df'Latitude','Longtitude' = df'Latitude','Longtitude'.apply(pd.to_numeric) df['Sex'] = df['Sex'].astype('str') map…
has comment: http://stackoverflow.com/comment/88006048
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Updating a Geographical Visualization in Bokeh on button click event
tagged with: python
tagged with: bokeh
tagged with: geocoding

http://stackoverflow.com/comment/88040204
score: 0
comment on: http://stackoverflow.com/q/50511413
type: QuestionComment
has text: @user32185 2G uncompressed with 16 million rows by 22 columns.
type: Comment

http://stackoverflow.com/q/50489512
tagged with: pandas
answer count: 1
has title: Python connection with Exasol - export to pandas
type: Question
type: UnansweredQuestion
tagged with: exasolution
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/50850619
has body: I have problem with export data to pandas from Exasol v.6.0.4. I can connect with Exasol but when I want to transport data to pandas DataFrame then I have error. I'm using library pyexasol. My code is following: from pyexasol import ExaConnection con = ExaConnection(dsn=dns, user=user, password=password) con.execute('OPEN SCHEMA SCHEMATEST1') #to this moment everything works correct data = con.export_to_pandas('select * from TABLETEST1') # pandas data frame per default Error: TypeError: cannot serialize '_io.FileIO' object What I've done bad? How I can export data from Exasol query to Pandas DataFrame? My libraries and version of tools: Exasol 6.0.4 Python 3.6.4 Libraries: backcall (0.1.0) bleach (2.1.3) colorama (0.3.9) decorator (4.3.0) entrypoints (0.2.3) html5lib (1.0.1) ipykernel (4.8.2) ipython (6.4.0) ipython-genutils (0.2.0) ipywidgets (7.2.1) jedi (0.12.0) Jinja2 (2.10) jsonschema (2.6.0) jupyter (1.0.0) jupyter-client (5.2.3) jupyter-console (5.2.0) jupyter-core (4.4.0) MarkupSafe (1.0) mistune (0.8.3) nbconvert (5.3.1) nbformat (4.4.0) notebook (5.5.0) numpy (1.14.3) pandas (0.23.0) pandocfilters (1.4.2) parso (0.2.1) pickleshare (0.7.4) pip (9.0.1) prompt-toolkit (1.0.15) pyasn1 (0.4.2) pyexasol (0.3.17) Pygments (2.2.0) pyodbc (4.0.23) python-dateutil (2.7.3) pytz (2018.4) pywinpty (0.5.1) pyzmq (17.0.0) qtconsole (4.3.1) rsa (3.4.2) scikit-learn (0.19.1) scipy (1.1.0) Send2Trash (1.5.0) setuptools (28.8.0) simplegeneric (0.8.1) six (1.11.0) sklearn (0.0) terminado (0.8.1) testpath (0.3.1) tornado (5.0.2) traitlets (4.3.2) wcwidth (0.1.7) webencodings (0.5.1) websocket-client (0.47.0) widgetsnbextension (3.2.1) Please help! :)
score: 0

http://stackoverflow.com/q/50425779
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87867854
favorite count: 0
tagged with: apache-spark-ml
type: Question
type: AnsweredQuestion
tagged with: apache-spark
score: 1
has comment: http://stackoverflow.com/comment/87866378
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/50427320
tagged with: python
has title: Running regression on several columns in parallel
has answer: http://stackoverflow.com/a/50427320
has comment: http://stackoverflow.com/comment/87866234
has body: I have a very wide dataframe with label columns. I want to run a logistic regression for each column independenly. I'm trying to find the most efficient way to run this in parallel. +----------+--------+--------+--------+-----+------------+ | features | label1 | label2 | label3 | ... | label30000 | +----------+--------+--------+--------+-----+------------+ My initial thought was to use ThreadPoolExecutor, get result for each column, and join: extract_prob = udf(lambda x: float(x[1]), FloatType()) def lr_for_column(argm): col_name = argm[0] test_res = argm[1] lr = LogisticRegression(featuresCol="features", labelCol=col_name, regParam=0.1) lrModel = lr.fit(tfidf) res = lrModel.transform(test_tfidf) test_res = test_res.join(res.select('id', 'probability'), on="id") test_res = test_res.withColumn(col_name, extract_prob('probability')).drop("probability") return test_res.select('id', col_name) with futures.ThreadPoolExecutor(max_workers=100) as executor: future_results = [executor.submit(lr_for_column, [colname, test_res]) for colname in list_of_label_columns] futures.wait(future_results) for future in future_results: test_res = test_res.join(future.result(), on="id") but this method is not very performant. Is there a faster way to do this?
linked to: http://stackoverflow.com/q/40865326
answer count: 1

http://stackoverflow.com/a/50419169
type: Answer
has body: list objects are not hashable because they are mutable, but tuple, on the other hand, are immutable. You can transform list values to tuple and make use of this property. Suppose you have df = pd.DataFrame({"A": [1,2,3,4], "B": ["a", "b", "c", "d"], "C": [[1,2,3], [2], [2,3,1], [4]] }) A B C 0 1 a [1, 2, 3] 1 2 b [2] 2 3 c [2, 3, 1] 3 4 d [4] Thus, you can do something like df.C.apply(sorted).transform(tuple).unique() which returns array([(1, 2, 3), (2,), (4,)], dtype=object) Thus, your code could be something like below, making use of collections.Hashable to check whether the content of the column is indeed hashable or not import collections for i in df.columns: if isinstance(df[i].iloc[0], collections.Hashable): if len(df[i].unique()) &lt; 10: df = df.drop(i, 1) else: if len(df[i].apply(sorted).transform(tuple).unique()) &lt; 10: df = df.drop(i, 1) Notice that this would also apply to other unhashable types, such as dicts &gt;&gt;&gt; df["D"] = [{"a":2}, {}, {"k":3}, {"k":3}]}) &gt;&gt;&gt; print(df.D.apply(sorted).transform(tuple).unique()) [('a',) () ('k',)]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50418645
answers question: http://stackoverflow.com/q/50418645
upvote count: 5
score: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/111715877
score: 0
type: Comment
comment on: http://stackoverflow.com/a/61172633
type: AnswerComment
has text: Having this problem as well (installing django-celery automatically uninstalling latest celery and re-installing 3.1). Did you just end up not using django-celery? The docs seem a little out of date

http://stackoverflow.com/comment/88079719
type: QuestionComment
has text: I can see you missed ` ` after ` ` in new templete
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50533746

http://stackoverflow.com/q/50534267
has comment: http://stackoverflow.com/comment/88080656
answer count: 2
has comment: http://stackoverflow.com/comment/88080691
downvote count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88080514
has answer: http://stackoverflow.com/a/50534328
has comment: http://stackoverflow.com/comment/88080507
has answer: http://stackoverflow.com/a/50534321
linked to: http://stackoverflow.com/q/432842
has comment: http://stackoverflow.com/comment/88080558
has title: Python checking if exactly one object is not None
favorite count: 0
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/88080554
type: Question
has body: I have two python objects a and b. What is the best/most-efficient/most-pythonic way to check if exactly one of these objects is None?

http://stackoverflow.com/a/50460235
score: 1
type: Answer
has body: Rearrange your code like this: os.chdir("C:\\Users\\user\\Desktop\\" +FolderName) i=1 while i &lt; 10: doc = Document() doc.add_paragraph('Title/Keyword:'+str(titles[i])); doc.add_paragraph('Research Link:'+str(link[i])); doc.add_paragraph('Target Site:'+str(keyword[i])); doc.save(str(doc_number[i])+str(essay_type[i])+' '+str(titles[i])+' '+str(writer[i])+'.docx'); i+=2
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50448598

http://stackoverflow.com/comment/87954273
type: Comment
has text: Fixed that too.
type: AnswerComment
comment on: http://stackoverflow.com/a/50470002
score: 0

http://stackoverflow.com/q/50399293
has answer: http://stackoverflow.com/a/50722722
favorite count: 0
type: Question
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50402839
tagged with: flask
has answer: http://stackoverflow.com/a/50402839
type: AnsweredQuestion
tagged with: flask-restplus
answer count: 2
has body: Developing a rest API using flask with flask_restplus. It successfully returns an image file, generated by the PIL library, but the file is corrupted and cannot be viewed. @api.route('/annotate') class Annotate(Resource): @api.representation('image/png') def post(self): file = io.BytesIO() img = Image.new('RGBA', (50, 50), (70, 0, 0, 255)) img.save(file, 'png') file.seek(0) return send_file(file, as_attachment=True, attachment_filename='annotated.png', mimetype='image/png')
tagged with: python-imaging-library
has title: Flask Restplus returns a corrupted PNG file
score: 1
accepted answer: http://stackoverflow.com/a/50722722
downvote count: 0

http://stackoverflow.com/comment/88050445
score: 0
comment on: http://stackoverflow.com/q/50518889
has text: Do you want to retrieve the value of the variable in the template or you don't know how to send it to the template? in top of that, in which view do you have that queryset?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88074485
type: Comment
type: QuestionComment
has text: @VivekKumar: I edited the post, sentiment is the polarity positive or negative, I train only on the column review
comment on: http://stackoverflow.com/q/50515740
score: 0

http://stackoverflow.com/comment/88008650
comment on: http://stackoverflow.com/q/50483439
score: 0
has text: @JohnRotenstein I am doing that in Django . Like as a admin I will upload image on admin side which will be update on s3 .
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50486419
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50483586
upvote count: 1
has body: update: if you know that the first node name is , then you can just do : $ echo " $(base -decode <file>) " | \ xmlstarlet sel -t -m '//bar/ancestor::foo' -c . It selects the ancestor named foo of the node called bar, since foo is the first xml-node, it will select the requested xml file. original answer below: Using xmlstarlet you might want to do this $ echo " $(base -decode <file>) " | \ xmlstarlet sel -t -m '//bar/ancestor::*[last()-1]' -c . This essentially selects the full xml-tree of ancestors of the node 'bar' but it will only go upto the correct depth. I added an extra head node to make the full string a valid xml file. This way you only need to print from the first node onwards. The echo would produce something like (slightly different version): <barometer /> <BBB/> <bar /> xmlstarlet will do a template selection based on the xpath //bar/ancestor::*, leading to the following set of matches <bar /> <BBB /><bar /> <BBB /><bar /> everything </ head> We are interested in the penultimate one, i.e. [last()-1] and we ask to print a copy of it -c .
type: Answer

http://stackoverflow.com/comment/88000361
score: 0
type: Comment
has text: @seuling nope. I just figured it will work if I use with `virtualenv`, that's why my `home = /root/wxr/wxr` is the same as `chdir` but why is that though? For before, it used to work without havinvg `virtualenv` so I didn't think this is the problem before until I really had no other thoughts on what is going on
type: QuestionComment
comment on: http://stackoverflow.com/q/50480388

http://stackoverflow.com/comment/87858234
score: 0
type: Comment
has text: I mean in my opinion,the dot '.' is only used for the method or function of a class.It is not like the underline '_' that can be used in the name of variable
type: AnswerComment
comment on: http://stackoverflow.com/a/50415451

http://stackoverflow.com/a/50443654
type: Answer
accepted answer of: http://stackoverflow.com/q/50443189
has body: You can map you values, sorting and then drop duplicates: df = pd.DataFrame([[1,67,'one'], [1, 89, 'three'], [2, 78, 'two'], [2, 70, 'one']], columns = ['Id', 'Score', 'Version' ]) d = {'one':1,'two':2, 'three':3} df['vers'] = df['Version'].map(d) df = df.sort_values('vers', ascending=False).drop_duplicates('Id').sort_index() Output: Id Score Version vers 1 1 89 three 3 2 2 78 two 2
answers question: http://stackoverflow.com/q/50443189
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87901295
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/50463394
tagged with: python
has body: below is example xml. I'm studying xml.etree.ElementTree module not lxml. This is test1 This is test 222222 333333 This is test I'm trying to collect all texts of BBB under CCC under AAA element. but i have no idea why it doesnt work. there is no error when it starts but texts are not collected. i wonder why this code doesn't work well. BBB_collect = ''.join(BBB.itertext()) please check below import xml.etree.ElementTree as ET import re f1 = open ("C:\\test\\Data.xml","r",encoding="utf=8") f2 = open ("C:\\test\\output.xml","wt",encoding="utf=8") doc = ET.parse("C:\\test\\Data.xml") root = doc.getroot() a = 0 try: while True : AAA = root.findall('AAA')[a] for CCC in AAA.findall('CCC'): for BBB in CCC.findall('BBB'): BBB_collect = ''.join(BBB.itertext()) print(BBB_collect) print('===============') a = a+1 except IndexError : pass Could you give ma any advice ? What's wrong with it ? Ultimately, this is my goal below. Thisistest1 This is test 222222333333 This is test
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
answer count: 2
has title: How to collect text nodes at same element level?
score: 1
accepted answer: http://stackoverflow.com/a/50466731
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50466731
possible better answer: http://stackoverflow.com/a/50465582
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87941639
has answer: http://stackoverflow.com/a/50465582

http://stackoverflow.com/comment/87948890
has text: Probably the root of your problem is that your `Temperature` list is not numeric, I think it's probably `str`. Try `type(Temperature[0])` to make sure
type: Comment
comment on: http://stackoverflow.com/q/50467885
type: QuestionComment
score: 2

http://stackoverflow.com/q/50431275
tagged with: holoviews
downvote count: 0
has answer: http://stackoverflow.com/a/52152459
linked to: http://stackoverflow.com/q/42354648
has body: Say I have these labels: hv.Labels((stops['x'], stops['y'], labels)) How do I rotate the text by n degrees? I would imagine it to be something like this: hv.Labels((stops['x'], stops['y'], labels), rotation=45) Similar to this question. It seems like the bokeh Text glyph has an angle property but I've been struggling to figure out what goes on behind the scenes.
upvote count: 3
score: 3
tagged with: python
tagged with: bokeh
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has title: Rotating text of Holoviews Label
has answer: http://stackoverflow.com/a/57646782

http://stackoverflow.com/q/50493670
type: Question
has comment: http://stackoverflow.com/comment/88011441
type: UnansweredQuestion
tagged with: windows
tagged with: python
tagged with: ms-office
has comment: http://stackoverflow.com/comment/88011484
has title: Search office documents for string python
has comment: http://stackoverflow.com/comment/88003238
score: 0
has answer: http://stackoverflow.com/a/50570435
answer count: 1
tagged with: string
has body: I've been looking for a fast and relatively easy way of searching (grep-ish) for user-defined strings in files of varying formats, i.e xlsx, docx, pptx, pdf using Python. My research has led me to believe that there might not be a convenient way of doing this, as per a single module or similar. Am I forced to use a separate module for each file type? And if so are these approriate? docx openpyxl pptx slate I also looked at forms of decompression to get to the xml-files containing actual text but it seems unwieldy. I just want to be sure that there is no simple, uniform way of handling all of these different filetypes.
tagged with: parsing

http://stackoverflow.com/a/51541369
answers question: http://stackoverflow.com/q/50456778
has comment: http://stackoverflow.com/comment/90073796
score: 0
has comment: http://stackoverflow.com/comment/90063801
type: AcceptedAnswer
has body: I decided to post an answer to my own questions, in case if someone else is looking from elasticsearch import Elasticsearch import json es = Elasticsearch([{'host': 'hostname or ip', 'port': 9200}], http_auth=('username', 'password'), maxsize=25) data = es.search(request_timeout=30, index="your_index_name", body={"your Json query string as Json format"} ) print (data)
accepted answer of: http://stackoverflow.com/q/50456778
type: Answer

http://stackoverflow.com/a/50414126
has body: If you prefer loc, you can use: In [245]: df.loc[(slice(None), 'Ai'), :] ...: Out[245]: value year name 1921 Ai 90 1922 Ai 7
type: Answer
score: 14
has comment: http://stackoverflow.com/comment/125716283
has comment: http://stackoverflow.com/comment/87844054
upvote count: 14
downvote count: 0
has comment: http://stackoverflow.com/comment/87844039
answers question: http://stackoverflow.com/q/50413993

http://stackoverflow.com/comment/88054267
comment on: http://stackoverflow.com/q/50512391
has text: @eyllanesc I want to get the data from both graph and have the clear sight on graph. if many curves in the same graph, it will be dazzled.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50386340
accepted answer: http://stackoverflow.com/a/50400774
score: 1
tagged with: windows
has answer: http://stackoverflow.com/a/50400774
has body: I'm using Python 2.7 on Windows 10-32 and Windows 10-64. I'm writing a python wrapper to a C compiled stdcall (Windows) DLL (= mydll). I have 2 versions of the DLL - 32 and 64 bit. The 64 version works great using windll.mydll. The 32 version works great using the same command for all functions on the DLL, except for variadic printf-like functions. When running mydll.myvarfunc("Hello") I get ValueError: Procedure probably called with too many arguments (4 bytes in excess) Is there a way around this that does not involve changing the C code for the variadic functions?
has title: windll ctypes call variadic c function from python 2.7 works in win64 but not in win32
tagged with: variadic-functions
has comment: http://stackoverflow.com/comment/87788997
favorite count: 0
type: Question
tagged with: ctypes
has comment: http://stackoverflow.com/comment/87788960
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: 32bit-64bit
has comment: http://stackoverflow.com/comment/87792581
has comment: http://stackoverflow.com/comment/87804483

http://stackoverflow.com/q/50480497
tagged with: python-3.x
type: UnansweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/87984613
has title: Find common sequences of words in sublists in Python
has comment: http://stackoverflow.com/comment/87984475
has comment: http://stackoverflow.com/comment/87984428
has comment: http://stackoverflow.com/comment/87985083
has comment: http://stackoverflow.com/comment/88110507
tagged with: python
upvote count: 4
has body: I have a nested list of strings: [['Start', 'двигаться', 'другая', 'сторона', 'света', 'надолго', 'скоро'], ['Start', 'двигаться', 'другая', 'сторона', 'света', 'чтобы', 'посмотреть'], ['Start', 'двигаться', 'новая', 'планета'], ['Start', 'двигаться', 'сторона', 'признание', 'суверенитет', 'израильский'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'на'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'оккупировать'], ['Start', 'двигаться', 'сторона', 'признание', 'высот', 'Голанский'], ['Start', 'двигаться', 'сторона', 'признание', 'и']] I need an algorithm to find first longest common sequence for two or more words in the list (in this case all sublists has two first common elements 'Start', 'двигаться'), make a string from them, move to next elements, find next longest common for two or more ('сторона', 'света', 'надолго' and 'сторона', 'признание' in this case) if a sublist has this common element, make next string from it. If there are no common elements, just add the rest words as a single string. And so on. If there is one element left in sequence, add it to the previous string. A single common element also does not count as a sequence. Resulting sequences can be of any length and split may start from the first element. Desires output: [['Start двигаться', 'другая сторона света', 'надолго скоро'], ['Start двигаться', 'другая сторона света', 'чтобы посмотреть'], ['Start двигаться', 'новая планета'], ['Start двигаться', 'сторона признание', 'суверенитет израильский'], ['Start двигаться', 'сторона признание', 'высот на'], ['Start двигаться', 'сторона признание', 'высот оккупировать'], ['Start двигаться', 'сторона признание', 'высот Голанский'], ['Start двигаться', 'сторона признание и']] I've checked other LCS topics but didn't find a solution.
tagged with: list
has comment: http://stackoverflow.com/comment/88110456
answer count: 0
score: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/87984030
tagged with: lcs
has comment: http://stackoverflow.com/comment/87984180
has comment: http://stackoverflow.com/comment/87984345
favorite count: 0
type: Question

http://stackoverflow.com/comment/93513022
comment on: http://stackoverflow.com/a/50389789
type: Comment
type: AnswerComment
score: 0
has text: @JoePhi - ya, your question is really data dependent issue, is possible see your json sample data?

http://stackoverflow.com/comment/87814072
type: QuestionComment
comment on: http://stackoverflow.com/q/50397835
has text: `_remove_action` is only used by `_handle_conflict_resolve`, which is used when you set the `conflict_handler` to `resolve` (as opposed to the default 'error'). It takes an `Action` object as argument, not its `dest`. The full list of `Actions` is `parser._actions`. Look at the code for `_remove_action` (it's defined in 3 classes).
score: 0
type: Comment

http://stackoverflow.com/q/50436151
tagged with: celerybeat
type: UnansweredQuestion
tagged with: python
has title: Celery Beat doesn't work with Django
has body: I configured Celery to work with Django but whenever I start Celery Beat it never gets past this stage &gt; LocalTime -&gt; 2018-05-20 16:55:50 Configuration -&gt; . broker -&gt; redis://localhost:6379// . loader -&gt; celery.loaders.app.AppLoader . scheduler -&gt; celery.beat.PersistentScheduler . db -&gt; celerybeat-schedule . logfile -&gt; [stderr]@%DEBUG . maxinterval -&gt; 5.00 minutes (300s) No tasks scheduled. I'm using Celery 4.1.0
answer count: 0
score: 1
downvote count: 0
tagged with: django
upvote count: 1
tagged with: celery
favorite count: 0
type: Question

http://stackoverflow.com/a/50402434
downvote count: 0
upvote count: 1
has body: There are multiple problems here: 1) You define a variable named list, which would clash with the keyword list. That will lead to confusing results if you later try to create a list using the keyword. 2) You stored a single dictionary inside of a list. Why not just create a dictionary, like this: dictionary = {"length": {"a": 0.05,"b": 0.04}, "id": "66"} And then you could get the data that you want with the following commands: dictionary["length"] # Gets {"a": 0.05,"b": 0.04} dictionary["id"] # Gets "66" However, since you currently have this within a list, the answer to you question is to first get element 0 from the list, and then apply the previous commands. This would look like the following: list[0]["length"] # Gets {"a": 0.05,"b": 0.04} list[0]["id"] # Gets "66"
type: Answer
has comment: http://stackoverflow.com/comment/87821227
answers question: http://stackoverflow.com/q/50402389
has comment: http://stackoverflow.com/comment/87820657
score: 1

http://stackoverflow.com/a/50483466
answers question: http://stackoverflow.com/q/50472831
has body: I got it!!!! while poking some more around StackOverflow, I stumbled over this question and the answer provided to it by the user ACV. So, all I needed to do was, in my route, to add .name at the end of actual_amount_name=form.actual_amount_name.data, like so: actual_amount_name=form.actual_amount_name.data.name This is what my web page table looks like now: And this is the output in the text file: ActualPost('actual, 'expenses' , 'Spook', '26.5' , '2018-05-22', 'God dammit' aaaargh#&amp;*^$lkjsdfho')
accepted answer of: http://stackoverflow.com/q/50472831
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/a/50513512
answers question: http://stackoverflow.com/q/50513186
type: Answer
has body: You can use re.findall and re.sub: import re s = 'eggs (spam): tomatoes' new_s = re.sub('\(\w+\):', '{}', s).format(*[f': {i}' for i in re.findall('\((.*?)\)', s)]) Output: 'eggs : spam tomatoes'
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87983569
has text: OR operation in many programming languages is usually just 1 CPU instruction. So this *may* be faster than waiting for the exception to be raised. I would prefer this method due to it's cleanliness. The other way is to encapsulate `try except` for every single variables, which leads to ugly code.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50484965
type: AnswerComment

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/50401755
tags question: http://stackoverflow.com/q/50399178
tags question: http://stackoverflow.com/q/50519237
tags question: http://stackoverflow.com/q/50524674

http://stackoverflow.com/comment/94545827
has text: i ended up with a different solution. i believe that its better to load only the logging when needed instead of the current app. https://stackoverflow.com/a/53848974/1138430
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50457858

http://stackoverflow.com/comment/88076022
comment on: http://stackoverflow.com/q/50531921
type: Comment
type: QuestionComment
has text: what if the value of `data_3` is not a single value of all the rows?
score: 0

http://stackoverflow.com/a/50529663
downvote count: 0
answers question: http://stackoverflow.com/q/50529590
has body: Using Regex. import re da = "abc.com" print(re.sub("\.com", "", da)) or print(da.replace(".com", "")) Output: abc
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/88001791
type: Comment
has text: Print out `indegree` or `outdegree` after the loop over `A`, and you will see that they contain something like `{(1, 2, 3, 4, 5): 0}` - a single entry, with everything in one tuple. You need to either remove one layer of nesting in v.txt, or loop over `A[0]` instead of `A`.
comment on: http://stackoverflow.com/q/50494385
type: QuestionComment
score: 1

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/50518309
tags question: http://stackoverflow.com/q/50490864
tags question: http://stackoverflow.com/q/50533102
tags question: http://stackoverflow.com/q/50438738
tags question: http://stackoverflow.com/q/50402992
tags question: http://stackoverflow.com/q/50536721
tags question: http://stackoverflow.com/q/50535170
tags question: http://stackoverflow.com/q/50513545
tags question: http://stackoverflow.com/q/50432506
tags question: http://stackoverflow.com/q/50423934
tags question: http://stackoverflow.com/q/50508049
tags question: http://stackoverflow.com/q/50438428
tags question: http://stackoverflow.com/q/50477280
tags question: http://stackoverflow.com/q/50453934
tags question: http://stackoverflow.com/q/50489450
tags question: http://stackoverflow.com/q/50472023
tags question: http://stackoverflow.com/q/50440696
tags question: http://stackoverflow.com/q/50481178
tags question: http://stackoverflow.com/q/50426349
tags question: http://stackoverflow.com/q/50499893
tags question: http://stackoverflow.com/q/50423310
tags question: http://stackoverflow.com/q/50539246
tags question: http://stackoverflow.com/q/50423239
tags question: http://stackoverflow.com/q/50386162
tags question: http://stackoverflow.com/q/50390337
tags question: http://stackoverflow.com/q/50515740
tags question: http://stackoverflow.com/q/50413464
tags question: http://stackoverflow.com/q/50437670
tags question: http://stackoverflow.com/q/50392795
tags question: http://stackoverflow.com/q/50454353
tags question: http://stackoverflow.com/q/50490278
tags question: http://stackoverflow.com/q/50527616
tags question: http://stackoverflow.com/q/50464643
tags question: http://stackoverflow.com/q/50474618
tags question: http://stackoverflow.com/q/50431164
tags question: http://stackoverflow.com/q/50524927
tags question: http://stackoverflow.com/q/50519035
tags question: http://stackoverflow.com/q/50526898
tags question: http://stackoverflow.com/q/50386210
tags question: http://stackoverflow.com/q/50414117
tags question: http://stackoverflow.com/q/50504770
tags question: http://stackoverflow.com/q/50531614
tags question: http://stackoverflow.com/q/50538626
tags question: http://stackoverflow.com/q/50405987
tags question: http://stackoverflow.com/q/50500181
tags question: http://stackoverflow.com/q/50518706
tags question: http://stackoverflow.com/q/50440497
tags question: http://stackoverflow.com/q/50498387
tags question: http://stackoverflow.com/q/50518591
tags question: http://stackoverflow.com/q/50517225
tags question: http://stackoverflow.com/q/50518563
tags question: http://stackoverflow.com/q/50447893
tags question: http://stackoverflow.com/q/50514783
tags question: http://stackoverflow.com/q/50540668
tags question: http://stackoverflow.com/q/50525283
tags question: http://stackoverflow.com/q/50429826
tags question: http://stackoverflow.com/q/50495878
tags question: http://stackoverflow.com/q/50385511
tags question: http://stackoverflow.com/q/50467988
tags question: http://stackoverflow.com/q/50538563
tags question: http://stackoverflow.com/q/50537971
tags question: http://stackoverflow.com/q/50388684
tags question: http://stackoverflow.com/q/50533659
tags question: http://stackoverflow.com/q/50519856
tags question: http://stackoverflow.com/q/50484946
tags question: http://stackoverflow.com/q/50479619
tags question: http://stackoverflow.com/q/50435336
tags question: http://stackoverflow.com/q/50475348
tags question: http://stackoverflow.com/q/50518758
tags question: http://stackoverflow.com/q/50455088
tags question: http://stackoverflow.com/q/50408720
tags question: http://stackoverflow.com/q/50452476
tag name: machine-learning
tags question: http://stackoverflow.com/q/50405189
tags question: http://stackoverflow.com/q/50460115
tags question: http://stackoverflow.com/q/50425700
tags question: http://stackoverflow.com/q/50434584
tags question: http://stackoverflow.com/q/50433155
tags question: http://stackoverflow.com/q/50441669

http://stackoverflow.com/q/50505329
has title: How to show images on web pages using Ajax in Flask?
has body: I am a newbie in Python Flask. Although, I have done this task multiple time in PHP/Java, somehow I am stuck here. My task is to upload the image onto server, then display the image on web page, do some processing on image and again display the processed image on client machine. To this end, I am using the code at flask-fileupload-ajax-example on Github. I am able to show the filename as well as its size correctly using ajax on the web page. But, somehow, when I try to set the src of &lt;img&gt; tag by the path of the uploaded images, it gives a 404, File not found error. Following are the relevant code snippets. In app.py @app.route('/uploadajax', methods=['POST', 'GET']) def upldfile(): if request.method == 'POST': files = request.files['file'] print(files) if files and allowed_file(files.filename): filename = secure_filename(files.filename) app.logger.info('FileName: ' + filename) print('FileName: ' + filename) updir = os.path.join(basedir, 'upload/') files.save(os.path.join(updir, filename)) file_size = os.path.getsize(os.path.join(updir, filename)) file_path = '/'.join(['upload', filename]) return jsonify(name=filename, path=file_path, size=file_size) In app.js file: $('#submit').click(function() { event.preventDefault(); var form_data = new FormData($('#uploadform')[0]); $.ajax({ type: 'POST', url: '/uploadajax', data: form_data, contentType: false, processData: false, dataType: 'json' }).done(function(data, textStatus, jqXHR){ console.log(data); console.log(textStatus); console.log(jqXHR); console.log('Success!'); $("#resultFilename").text(data['name']); // name of the file $("#resultFilesize").text(data['size']); // size of the file //my_url = "{{ url_for('upload', filename="+data['name']+" }}"; $("#image").attr('src', data['path']); // setting the src attribute of img tag $("#adv-btn").attr('value', data['name']); $("#adv-btn").show(); //get_image(data['name']) }).fail(function(data){ alert('error!'); }); }); I have also tried using url_for but it's not get…
has answer: http://stackoverflow.com/a/50507047
tagged with: ajax
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: python
tagged with: image
type: Question
accepted answer: http://stackoverflow.com/a/50507047
tagged with: upload
tagged with: flask

http://stackoverflow.com/q/50408845
downvote count: 0
has body: On my Ubutntu machine i have both python 2.7 and 3.5. I've installed pysvn according tointruction here sudo apt-get install python-svn sudo apt-get install svn-workbench Python 2.7 sees it, but not 3.5: Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pysvn Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'pysvn' &gt;&gt;&gt;
upvote count: 1
favorite count: 0
has title: Python3, no module named pysvn on Ubuntu
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/93274836
has comment: http://stackoverflow.com/comment/87833055
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87833029
answer count: 0
has comment: http://stackoverflow.com/comment/87833647
score: 1
tagged with: pysvn
has comment: http://stackoverflow.com/comment/97797010

http://stackoverflow.com/comment/87822674
has text: Happy to help. I would still recommend looking at the first couple comments in my answer, and trying to get your original attempt to work. You were close apart from a couple minor issues, and you will definitely learn more that way!
comment on: http://stackoverflow.com/a/50403579
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/a/50540950
answers question: http://stackoverflow.com/q/50540917
score: 3
upvote count: 3
type: Answer
has body: The answer to your question is in the error... missing parentheses in calling to print Python3 requires you to use parentheses when using print - i.e. print("text")
downvote count: 0

http://stackoverflow.com/q/50395475
possible better answer: http://stackoverflow.com/a/52787359
has answer: http://stackoverflow.com/a/50395828
favorite count: 0
has comment: http://stackoverflow.com/comment/87806998
has answer: http://stackoverflow.com/a/52787359
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87807556
tagged with: integral
tagged with: python
has title: Efficient way for calculating integrals?
has body: I know how to use the Monte-Carlo to calculate integrals, but I was wondering if it is possible to use the trapezium rule combined with numpy for efficiency to get the same integral, I am not sure which one is the fastest or is the latter possible? for e.g. to integrate e**-x**2 &gt; y I could use the monte-carlo method like this: import numpy as np import matplotlib.pyplot as plt X = np.random.rand(500000,2) X[:,0] = X[:,0]*4-2 J = np.where(X[:,1] &lt; np.exp(-X[:,0]**2))[0] Xp = X[:2000] Ip = [i for i in range(len(Xp)) if i in J] Inp = [i for i in range(len(Xp)) if i not in J] plt.plot(Xp[Ip,0],Xp[Ip,1], 'bd', Xp[Inp,0],Xp[Inp,1], 'rd') plt.show() And this can calculate very easily : print len(J) / 500000.0 * 4 Which gives: 1.767784 In this case it was easy but if the intervals are not specified given in like [a,b] , n, and I want to make a function then I think the method above is not really efficient, at least I think so. So , my question is can I integrate a continuous function like e.g.cos(x)/x for a determined interval like [a,b] in a function with trapezium rule? And is it better than the method i used here? Every advice is welcome.
has comment: http://stackoverflow.com/comment/87806891
tagged with: numpy
tagged with: python-2.7
answer count: 2
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/50395828

http://stackoverflow.com/q/50393741
type: UnansweredQuestion
tagged with: memory-leaks
has answer: http://stackoverflow.com/a/70440341
tagged with: python
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50401203
score: 7
upvote count: 7
has title: OpenCV Python: how to avoid cv2.imwrite() memory "leak" in py3?
favorite count: 0
has body: I am investigating a memory leak (or "bloat") in a Python (3.5.2) application using OpenCV (3.4.1, local build) on Ubuntu 16.04 (x86). The application writes images to a file very often, and it uses .imwrite() method for this purpose. I have discovered that this usage of .imwrite() causes the RAM usage to grow wild, but I cannot find the reason for this behavior. In order to debug this issue, I have prepared this simple test script: #!/usr/bin/python3 import cv2 import time img = cv2.imread("vista.jpg") idx = 0 while True: filename = "/tmp/vista_copy_" + str(idx) + ".tiff" cv2.imwrite(filename, img) idx = idx + 1 time.sleep(1) While running this script, I monitored the free RAM (samples the free memory ever 10 seconds): $ while [ 1 ] ; do grep MemFree /proc/meminfo ; sleep 10 ; done MemFree: 898024 kB MemFree: 780640 kB MemFree: 667848 kB MemFree: 545700 kB MemFree: 437196 kB MemFree: 315820 kB MemFree: 298380 kB MemFree: 298292 kB MemFree: 297448 kB MemFree: 297080 kB MemFree: 915616 kB The last sample, where the free memory returns to its initial value, was taken after I deleted the images files from target, which might suggest that this an OS issue, or maybe that the files aren't being closed properly by the program (Although I couldn't find a clue for this in the C++ source code). I find this behavior very weird, even more so because imwrite is such a basic method. Can anyone give a hand in debugging and solving this issue? Edit So apparently the memory consumption in my test script is due to the fact that /tmp is actually a RAM drive, but the problem still stands when writing to an external drive which is connected through Ethernet adapter. Update The problem reproduces when writing to a local folder on a physical drive. It seems that this is a general OS problem not related specifically to imwrite. The OS caches the files, but doesn't ever free this cache (maybe it "thinks" it has enough memory for all this caching). Executing 'echo 3 &gt; /proc/sys/vm/drop_ca…
type: Question
tagged with: python-3.x
tagged with: opencv
tagged with: linux

http://stackoverflow.com/a/50456808
accepted answer of: http://stackoverflow.com/q/50456783
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/50456783
score: 38
has body: Taken from this post: For cookies, you can use the delete_all_cookies function: driver.delete_all_cookies() For cache, there isn't a direct way to do this through Selenium. If you are trying to make sure everything is cleared at the beginning of starting a Chrome driver, or when you are done, then you don't need to do anything. Every time you initialize a webdriver, it is a brand new instance with no cache, cookies, or history. Every time you terminate the driver, all these are cleared.
type: Answer
has comment: http://stackoverflow.com/comment/110594850
upvote count: 39

http://stackoverflow.com/q/50403935
type: UnansweredQuestion
tagged with: python
has body: I have 2 python versions 2.7 and 3.6. I set my virtual environment to run on python3 # virtualenv -p python3 venv # source venv/bin/activate # pip install -r requirements.txt When I try to install modules I get following error, Collecting enum==0.4.6 (from -r requirements.txt (line 12)) Using cached https://files.pythonhosted.org/packages/0c/4e/1ea357e7783c756bb579333c1e4a026fb331371ee771f616ffedc781e531/enum-0.4.6.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/Users/ratha/projects/test711/ATGWS/venv/lib/python3.6/site-packages/setuptools/__init__.py", line 5, in <module> import distutils.core File "/Users/ratha/projects/test711/ATGWS/venv/lib/python3.6/distutils/__init__.py", line 4, in <module> import imp File "/Users/ratha/projects/test711/ATGWS/venv/lib/python3.6/imp.py", line 27, in <module> import tokenize File "/Users/ratha/projects/test711/ATGWS/venv/lib/python3.6/tokenize.py", line 33, in <module> import re File "/Users/ratha/projects/test711/ATGWS/venv/lib/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/ct/v0v5ht_n32n6c_33dw1td2fc0000gp/T/pip-install-36x_vm0b/enum/ In my code, I use following import; from enum import Enum How can I overcome this issue with python 3 version? Note : I do not have enum34 module installed #pip uninstall enum34 :Skipping enum34 as it is not installed. This answers here didnt solve my issue Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?
score: 2
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/43124775
favorite count: 0
has title: python3.6 and enum module issue in MAC OS
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50525394
type: Question
upvote count: 2

http://stackoverflow.com/comment/87853663
has text: @HectorMontes, there is a long standing ticket on trac.wxwidgets.org about that. So I don't thin it is possible right now. There was a plan to implement it with this year GSoC, but wx didn't get to the program. So unless you have an implementation and can submit a patch to the wx C++ mainline, it will probably be tried next year GSoC. Nobody currently needs this feature (Vadim included), so it stays open. Patches welcome!
comment on: http://stackoverflow.com/q/50418665
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51986982
downvote count: 0
has comment: http://stackoverflow.com/comment/101182317
upvote count: 68
score: 68
has comment: http://stackoverflow.com/comment/105623427
type: Answer
has comment: http://stackoverflow.com/comment/114951012
has comment: http://stackoverflow.com/comment/118693271
has comment: http://stackoverflow.com/comment/101164353
has body: You can use TensorFlow Lite Python interpreter to load the tflite model in a python shell, and test it with your input data. The code will be like this: import numpy as np import tensorflow as tf # Load TFLite model and allocate tensors. interpreter = tf.lite.Interpreter(model_path="converted_model.tflite") interpreter.allocate_tensors() # Get input and output tensors. input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Test model on random input data. input_shape = input_details[0]['shape'] input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() # The function `get_tensor()` returns a copy of the tensor data. # Use `tensor()` in order to get a pointer to the tensor. output_data = interpreter.get_tensor(output_details[0]['index']) print(output_data) The above code is from TensorFlow Lite official guide, for more detailed information, read this.
answers question: http://stackoverflow.com/q/50443411

http://stackoverflow.com/a/50517907
has comment: http://stackoverflow.com/comment/120678019
upvote count: 7
score: 7
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50517745
has body: all you need is set source for profile: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) location = LocationSerializer(read_only=True) profile = UserProfileSerializer(source='userprofile', read_only=True) the userprofile is name of relation of your model User by onetoone to the UserProfle, other way you can set related_name for attribute user in the UserProfle. class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) then your serializer will work fine as is.
has comment: http://stackoverflow.com/comment/88048422
type: Answer
answers question: http://stackoverflow.com/q/50517745

http://stackoverflow.com/q/50506331
has body: long =np.array(data.Longitude) lat = np.array(data.Latitude) coordinates = np.array(385) for i in range(385): coordinates[i] = np.array([lat[i], long[i]]) #x, y = kmeans2(whiten(coordinates), 3, iter = 20) #plt.scatter(coordinates[:,0], coordinates[:,1], c=y); #plt.show() I have a dataset with two columns and I wish to merge the latitude and longitude term by term to apply k means clustering after that.Please help with the array part
type: Question
has comment: http://stackoverflow.com/comment/88024782
tagged with: python
tagged with: merge
has comment: http://stackoverflow.com/comment/88025185
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: arrays
tagged with: combiners
has answer: http://stackoverflow.com/a/50506456
has title: Combining two arrays in python term by term
accepted answer: http://stackoverflow.com/a/50506456

http://stackoverflow.com/comment/87949271
has text: Can you help me understand Boolean Slicing? I am able to work with Pandas but I need some good optimizing techniques. I have just moved from R to Python. Can you suggest some good books for that? Your answer did the trick so thanks for that.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50467559
type: AnswerComment

http://stackoverflow.com/q/50386273
tagged with: python-multiprocessing
type: Question
tagged with: numpy
has body: I want to speed up a Monte Carlo Method which bases on numpy manipulation with the Multiprocessing module. I've read enter link description here and wrote a code like follows for some tasks: import func1, func2, func3, ... #some manipulations on the SAME numpy ndarray but each of then works independantly returns a independant result import multiprocessing as mp if __name__ == '__main__': with mp.Pool(processes=mp.cpu_count()) as pool: task1 = pool.Process(target=fun1, args(arg1, arg2, ...) task2 = pool.Process(target=fun2, args(arg1, arg2, ...) task3 = pool.Process(target=fun3, args(arg1, arg2, ...) ... task1.start() task2.start() task3.start() ... variable1 = task1.join() #In my case, I need to get the returns of these functions variable2 = task2.join() variable3 = task3.join() ... Like most of the tutorials. But I got a RuntimeError:An attempt has been made to start a new process before the current process has finished its bootstrapping phase. I'm really new in this field and struggling for days before I post this question here. Could somebody kindly give me some suggestions?
tagged with: python
tagged with: montecarlo
type: AnsweredQuestion
score: 0
has title: Issues when parallelize Monte Carlo method with python Multiprocessing
linked to: http://stackoverflow.com/q/24374288
answer count: 1
accepted answer: http://stackoverflow.com/a/50581158
has answer: http://stackoverflow.com/a/50581158

http://stackoverflow.com/a/50427320
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87870070
upvote count: 1
has comment: http://stackoverflow.com/comment/87870203
has comment: http://stackoverflow.com/comment/87870169
type: Answer
accepted answer of: http://stackoverflow.com/q/50425779
answers question: http://stackoverflow.com/q/50425779
has comment: http://stackoverflow.com/comment/87870033
has body: Taking into account available resources you have nothing to gain by using ThreadPoolExecutor - having 32 cores in total and 200 partitions you can process only ~16% of you data at the same time, and this fraction can become only worse, if data grows. If you want to train 30000 models and use default number of iterations (100, probably to low in practice) you Spark program will submit around 3 000 000 jobs (each iteration create a separate one), and only a fraction of each can be processed concurrently - this doesn't give much hope for improvement, unless you add more resource. Despite that there are some things you can try: Make sure that final features don't have to be recomputed. If necessary write data to persistent storage and load it back, and make sure that data passed to model is cached. Consider applying some dimensionality reduction algorithm. Number of features is 300000 not only high, but also close to number of records (500000). It is not only computationally expensive, but can also result in serious overfitting. If you decide to reduce dimensions consider sampling to further reduce size of your training data, and consequently reduce number of partitions and increase overall throughput. If there are strong linear trends in your data, there should be visible even on a smaller sample, without significant loss of precision. Consider replacing expensive pyspark.ml algorithm with a variant that doesn't require multiple jobs, for example using some combination of tools from spark-sklearn (you could create ensemble model, by fitting sklearn model on each partition). Oversubscribing cores. For example if you have 4 physical cores / node, allow 8 or 16 to account for IO wait time.

http://stackoverflow.com/comment/88034211
has text: `d = [{}]*3` creates one list with 3 pointers to it. If you change the content of one, it will also affect the others.
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/50510919

http://stackoverflow.com/comment/88102722
comment on: http://stackoverflow.com/a/50530552
type: Comment
type: AnswerComment
score: 0
has text: I am not sure what you mean by "relevant". PhantomJS does not give search results, so its output is useless.

http://stackoverflow.com/comment/88076983
has text: Rather than separately accounting for all cases where the guess is invalid, try creating a single test for whether the guess is valid.
comment on: http://stackoverflow.com/q/50532478
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87828576
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50406169
has text: I think it manybe PIP command before installing TensorFlow can be normal use, only after installation problems, probably because the new version of Python compatible with TensorFlow might be a little less, so update PIP and conda command, can fix. by command 'conda install pip'
type: Comment

http://stackoverflow.com/comment/88065441
comment on: http://stackoverflow.com/q/50526033
type: Comment
type: QuestionComment
has text: How do you want to do that? A row cannot be plotted as an image without reshaping it. And you don't give any information on how to reshape the row. You need to give us more information.
score: 0

http://stackoverflow.com/a/50417505
type: Answer
score: 0
has body: this might helpful for you. import hashlib bagel = "bagels" h = hashlib.md5() h.update(bagel.encode('utf-8')) temp = h.hexdigest() class YClass( object ): pass y= YClass() setattr( y, temp, {'greet': 'Hello'} ) print(y.__dict__)
answers question: http://stackoverflow.com/q/50417265

http://stackoverflow.com/q/50533833
tagged with: python
has title: groupBy().count.show() giving java.lang.IllegalStateException error in pyspark
has comment: http://stackoverflow.com/comment/88089617
tagged with: apache-spark
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/88079607
has comment: http://stackoverflow.com/comment/88101710
type: Question
has body: I am trying to show() results with groupBy() function on my RDD. Its giving the following error: Py4JJavaError: An error occurred while calling o14287.showString. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 3 in stage 2669.0 failed 1 times, most recent failure: Lost task 3.0 in stage 2669.0 (TID 3896, localhost, executor driver): java.lang.IllegalStateException: Input row doesn't have expected number of values required by the schema. 26 fields are required while 1 values are provided. at org.apache.spark.sql.execution.python.EvaluatePython$$anonfun$makeFromJava$15$$anonfun$apply$15.applyOrElse(EvaluatePython.scala:184) at org.apache.spark.sql.execution.python.EvaluatePython$.org$apache$spark$sql$execution$python$EvaluatePython$$nullSafeConvert(EvaluatePython.scala:208) at org.apache.spark.sql.execution.python.EvaluatePython$$anonfun$makeFromJava$15.apply(EvaluatePython.scala:180) My Pyspark Script: import pyspark from pyspark.sql import SparkSession spark=SparkSession.builder.getOrCreate() s3RDD=spark.sparkContext.textFile("file:///Users/mydir/Documents/Projects/Pyspark/MiscScripts/logfile.gz") firstLine = s3RDD.first() sparkContext.parallelize convert string into RDD parallelize = spark.sparkContext.parallelize([firstLine]) s3RDD=s3RDD.subtract(parallelize) s3RDD=s3RDD.map(lambda x: x.split('\t')) urlsDf=s3RDD.toDF() #import pyspark.sql.functions as f urlsDf.groupBy("_8").count().show()
type: UnansweredQuestion
tagged with: pyspark

http://stackoverflow.com/comment/88061168
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50524328
has text: @cswah downvoting is used to filter questions from the frontpage. The people who did so probably meant to convey 'this question is a duplicate, don't bother looking at it.' It doesn't feel good, but it's not meant to judge you, just a tool to manage this site.
type: Comment

http://stackoverflow.com/comment/88088999
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50538447
has text: actually it seems that worked
score: 0

http://stackoverflow.com/comment/88029968
score: 0
has text: You may want to call Popen on a separate thread: https://docs.python.org/3/library/threading.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50509026

http://stackoverflow.com/comment/87901894
type: Comment
has text: I updated the code at the top
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50443970

optimization
tags question: http://stackoverflow.com/q/50520375
tags question: http://stackoverflow.com/q/50413286
tags question: http://stackoverflow.com/q/50437334
tag name: optimization
tags question: http://stackoverflow.com/q/50511775
tags question: http://stackoverflow.com/q/50466050
tags question: http://stackoverflow.com/q/50452893
tags question: http://stackoverflow.com/q/50531652
tags question: http://stackoverflow.com/q/50478806
tags question: http://stackoverflow.com/q/50455246
tags question: http://stackoverflow.com/q/50448922
tags question: http://stackoverflow.com/q/50451649
tags question: http://stackoverflow.com/q/50470726
tags question: http://stackoverflow.com/q/50396404
type: Tag
tags question: http://stackoverflow.com/q/50470855

http://stackoverflow.com/q/50538330
answer count: 3
has comment: http://stackoverflow.com/comment/88088725
has comment: http://stackoverflow.com/comment/88088647
accepted answer: http://stackoverflow.com/a/50538561
has comment: http://stackoverflow.com/comment/88088664
has answer: http://stackoverflow.com/a/50538553
score: 1
downvote count: 0
tagged with: counter
has answer: http://stackoverflow.com/a/50538561
tagged with: count
upvote count: 1
tagged with: collections
has comment: http://stackoverflow.com/comment/88088641
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88088956
has comment: http://stackoverflow.com/comment/88088616
has body: I'm working on a personal project that counts instances of names mentioned in text. I know I can do it with collections.Counter() but I'm not sure how to account for aliases efficiently. So for example let's say one of the names I want to count is "Tim" but I would also like to count any nicknames he has like "Timmy" and "Timster". I have some strings saying, "Oh Tim is going to the party?", "Yeah, my boy Timmy, wouldn't miss it, he loves to party!", "Whoa, the Timster himself is going? Count me in!" Which I'd like to all count as under a variable like "Tim". I know I could simply individually count them all and then add the counts together. But I feel like there is a better way I could do it. I.E. I want my code to look more like. names = { 'Tim':{'Tim', 'Timmy', 'Timster'}, ... other names here.} # add any occurrence of Tim names to Tim and other occurrences of other names to their main name. As opposed to something like total_tim = Counter(tim) + Counter(timmy) + Counter(timster), etc.. for each name. Does anyone have any idea how I would go about doing this?
has comment: http://stackoverflow.com/comment/88088736
has answer: http://stackoverflow.com/a/50538622
has comment: http://stackoverflow.com/comment/88088659
possible better answer: http://stackoverflow.com/a/50538553
has comment: http://stackoverflow.com/comment/88088716
tagged with: python
has comment: http://stackoverflow.com/comment/88088591
has title: How to effeciently count string aliases?
has comment: http://stackoverflow.com/comment/88088775
has comment: http://stackoverflow.com/comment/88088752
tagged with: python-3.x

http://stackoverflow.com/a/50441553
score: 1
type: Answer
has body: You are continually trying to re-start the sockets, as they fall under the never ending "while" loop. Remove the "while 1" and instead make your loop at the bottom of the script. could even be if __name__ == "__main__": run_server() while 1: time.sleep(1) This way it will start your threads and then move on, in this case into a never ending sleep. Just as an example. Hope it helps.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50440975

http://stackoverflow.com/q/50386926
type: Question
has title: code visualization in django
has answer: http://stackoverflow.com/a/50387073
tagged with: python
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
upvote count: 1
tagged with: django-rest-framework
downvote count: 1
has body: I was looking at a python code visualization tool (http://www.pythontutor.com/visualize.html#mode=display) that nicely draws a model with its functions: I am interested in having something similar for django projects where models could be visualized exactly like this, instead of just one class all the models could be visualized with a nice graphic. However graphic does not mean class or any uml diagram. Any pointers how to approach this? Any existing libraries that already achieve this or if there are none, what could be important to look at to build one?
favorite count: 0

http://stackoverflow.com/comment/87824296
type: QuestionComment
comment on: http://stackoverflow.com/q/50404469
score: 0
has text: Try `isinstance`?
type: Comment

http://stackoverflow.com/a/50419892
type: Answer
has body: You can use a regular expression to search for the digits preceding the extension. import re def update_name(name): return re.search(r'\d+\..*', name).group() update_name('3D_492.png') # '492.png'
answers question: http://stackoverflow.com/q/50419852
score: 0

http://stackoverflow.com/a/50395207
downvote count: 0
type: Answer
score: 3
answers question: http://stackoverflow.com/q/50395151
upvote count: 3
has body: df.loc[] is a reference to your index, and your index is not your date column. Try: df = df.set_index('Date') If you don't want to change your index, you could also do: df[df['Date'] &gt;= '20160701']]

http://stackoverflow.com/a/50446946
has comment: http://stackoverflow.com/comment/87913312
has comment: http://stackoverflow.com/comment/87914566
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87916344
accepted answer of: http://stackoverflow.com/q/50442416
score: 3
has body: I would suggest a cleaner solution that would achieve the same result, how about: k_model.add(Embedding(num_classes, num_classes, embeddings_initializer='identity', trainable=False, name='onehot')) You are essentially embedding things, it would make more sense to use one with fixed weights. It also gives you the flexibility to make the embedding trainable in the future.
has comment: http://stackoverflow.com/comment/87915233
answers question: http://stackoverflow.com/q/50442416
type: Answer
has comment: http://stackoverflow.com/comment/87914734
has comment: http://stackoverflow.com/comment/87913370
upvote count: 3
has comment: http://stackoverflow.com/comment/87915738

http://stackoverflow.com/q/50485096
has title: Grouping object properties into new dictionary within Marshmallow schema
type: Question
has body: I am trying to serialize an object with Marshmallow in such a way that "related" properties are grouped together into a single dictionary that does not exist on the original object. My code: from marshmallow import Schema, fields, pprint import json class StatsSchema(Schema): population = fields.Int() rating = fields.Int() class AnimalSchema(Schema): name = fields.Str() features = fields.List(fields.Str()) stats = fields.Nested(StatsSchema) dog = { 'name':'dog', 'features': ['tongue', 'wet nose'], 'population': 200, 'rating': 10 } animal_schema = AnimalSchema() data, errors = animal_schema.dump(dog) print(json.dumps(data, indent=2)) Actual result: { "features": [ "tongue", "wet nose" ], "name": "dog" } Desired result: { "features": [ "tongue", "wet nose" ], "name": "dog", "stats": {"population": 500, "rating": 10} } I understand that the "stats" key is missing from the output because it is not on the original object, but I am not sure how to specify that Marshmallow should create the new "stats" key as a new dictionary using the object.
answer count: 2
has answer: http://stackoverflow.com/a/52914161
type: UnansweredQuestion
tagged with: python
tagged with: marshmallow
has answer: http://stackoverflow.com/a/50486339
score: 0

http://stackoverflow.com/q/50506358
has body: I have a postgresql(v.9.5) table called products defined using sqlalchemy core as: products = Table("products", metadata, Column("id", Integer, primary_key=True), Column("name", String, nullable=False, unique=True), Column("description", String), Column("list_price", Float), Column("xdata", JSON)) Assume the date in the table is added as follows: id | name | description | list_price | xdata ----+------------+---------------------------+------------+-------------------------------- 24 | Product323 | description of product332 | 6000 | [{"category": 1, "uom": "kg"}] Using API edit code as follows: def edit_product(product_id): if 'id' in session: exist_data = {} mkeys = [] s = select([products]).where(products.c.id == product_id) rs = g.conn.execute(s) if rs.rowcount == 1: data = request.get_json(force=True) for r in rs: exist_data = dict(r) try: print exist_data, 'exist_data' stmt = products.update().values(data).\ where(products.c.id == product_id) rs1 = g.conn.execute(stmt) return jsonify({'id': "Product details modified"}), 204 except Exception, e: print e return jsonify( {'message': "Couldn't modify details / Duplicate"}), 400 return jsonify({'message': "UNAUTHORIZED"}), 401 Assuming that I would like to modify only the "category" value in xdata column of the table, without disturbing the "uom" attribute and its value, which is the best way to achieve it? I have tried the 'for loop' to get the attributes of the existing values, then checking with the passed attribute value changes to update. I am sure there is a better way than this. Please revert with the changes required to simplify this
upvote count: 6
has title: How to update only 1 attribute of json type column in postgres table using python api code
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/50508719
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88024858
score: 6
has comment: http://stackoverflow.com/comment/88029700
favorite count: 0
type: Question
tagged with: postgresql
has comment: http://stackoverflow.com/comment/88028400
linked to: http://stackoverflow.com/q/35897834
tagged with: python

http://stackoverflow.com/q/50419159
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87854115
tagged with: python
has comment: http://stackoverflow.com/comment/87853835
has answer: http://stackoverflow.com/a/50419307
tagged with: numpy
has body: Using this code: import pandas df = pandas.DataFrame() df['id'] = list('aaabbbcccdddeee') df['gender'] = list('mmfmfmmffmfmfff') I get a DataFrame like: id gender 0 a m 1 a m 2 a f 3 b m 4 b f 5 b m 6 c m 7 c f 8 c f 9 d m 10 d f 11 d m 12 e f 13 e f 14 e f How can I split df by id and then count the number of m and f in each category so that I can get a result that looks something like: m f a 2 1 b 2 1 c 1 2 d 2 1 e 0 3
score: 0
tagged with: pandas
has title: Pandas how groupby and then count the number of unique items in each column?
linked to: http://stackoverflow.com/q/47152691
answer count: 1
duplicate of: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/87854136
has comment: http://stackoverflow.com/comment/87853972
type: Question

http://stackoverflow.com/q/50429118
tagged with: orm
answer count: 1
tagged with: django
type: Question
linked to: http://stackoverflow.com/q/3300944
has comment: http://stackoverflow.com/comment/87890346
has title: F() expressions in django keeps giving me 0
tagged with: python
has body: I am about to update approx 2-3k of records for one of my django model. I know that using the update() would help but then because I am actually using the same value in the field and change it into something else for example having a function to scrumble the existing field. I figured there is something called F() would should be able to help me out with it but somehow, it keeps saving my values as 0 into the field. I did not get any error and have no idea where to look into. this is the tutorial I read https://docs.djangoproject.com/en/1.8/ref/models/expressions/ this is my example code before I really do such batch update for the 2-3k records # I used the below, gives me 0 when I look at my db querysets_of_model = Model.objects.filter(id__in[111, 123]).update(name=F('name') + ' testing') # this gives me 0 too querysets = Model.objects.filter(id__in[111,123]) querysets.update(name=F('name') + ' testing') # without using the F(), which of course gives me `testing only` in the name field qs = Model.objects.filter(id__in[111, 123]).update(name='testing only') what I originally wanted to do is something like this qys = Model.objects.filter().update(name=scrumble_fun(F('name'))) the scrumble_fun is just a function that scrumble the existing value then return the srcumbled values and save it. But of course before doing this, I did as the first two example to just take out two queryets and do testing to make sure I am doing it right. But seems like I am not? :( Thanks in advance for any help in advance. P.S. Looping through each queryset then save() is not the way I want to do it if that is possible.
accepted answer: http://stackoverflow.com/a/50429795
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50429795
score: 0
has comment: http://stackoverflow.com/comment/87883266
tagged with: sql-update

http://stackoverflow.com/comment/87992797
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50489552
score: 1
has text: BTW, you should not use `assert` to validate data. `assert` is intended for validating the logic of your code. If you want to raise an exception on bad data, raise `ValueError`. Also, `str(user_input)` is redundant, `user_input` is already a string.

http://stackoverflow.com/comment/87995795
has text: This just twice as fast :)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50491374
score: 1

http://stackoverflow.com/q/50514176
score: 0
has comment: http://stackoverflow.com/comment/88042013
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/88042607
has body: I'm trying t create a graphic with three stacked bar graphics, like so: I actually have two questions: 1) I'm trying to use the 'position' parameter in Pandas' DataFrame, but the bars still overlap. Is there another alternative other than reducing the width of the bars? 2) The three bars have three categories in common (B, C, D, E), how can I have a legend that only contains the actual six different categories ? My DataFrame is: A B C D E F 0 0.108858 0.265929 0.537369 2.183963 1.353575 2.938775 1 0.375641 0.198720 0.266806 0.409179 0.286645 0.636405 2 1.179256 0.808986 0.171202 0.946194 0.506783 2.121366 3 1.510399 1.218619 0.307752 0.819865 1.283067 0.213556 And my test code is: import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd df = pd.DataFrame(abs(np.random.randn(4, 6)), columns=list('ABCDEF')) print(df) colors1 = ['#a50f15', '#9ecae1', '#6baed6', '#3182bd'] colors2 = ['#fb6a4a', '#9ecae1', '#6baed6', '#3182bd'] colors3 = ['#fcbba1', '#9ecae1', '#6baed6', '#3182bd'] fig, ax = plt.subplots(figsize=(8,6)) df.plot(ax=ax, y=['A', 'B', 'C', 'D'], kind='bar', stacked=True, width=0.15, color=colors1, position=0) df.plot(ax=ax, y=['E', 'B', 'C', 'D'], kind='bar', stacked=True, width=0.15, color=colors2, position=0.5) df.plot(ax=ax, y=['F', 'B', 'C', 'D'], kind='bar', stacked=True, width=0.15, color=colors3, position=1) ax.legend(ncol=3) plt.tight_layout() plt.show()
has title: How to position 3 stacked bar graphs using Pandas
type: Question
has comment: http://stackoverflow.com/comment/88046437
type: UnansweredQuestion
tagged with: matplotlib
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/50401241
score: 1
upvote count: 1
answer count: 1
favorite count: 0
tagged with: time-series
has body: How can I join two dataframe on date column with same and different frequencies as in the below example. scenario 1 fast = pd.DataFrame({ 'date': pd.to_datetime(['2018-01', '2018-02', '2018-03', '2018-04', '2018-05', '2018-06']), 'store': ['A'] * 3 + ['B'] * 3, 'sales': [3000, 2000, 1800, 1700, 1500, 1600]}) slow = pd.DataFrame({ 'date': pd.to_datetime(['2018-01', '2018-03', '2018-06']), 'temp': [45, 55, 70]}) alligned_left_fast = ? alligned_left_slow = ? same frequency, scenario 2 unaligned_df1 = pd.DataFrame({ 'date': pd.to_datetime(['2018-01', '2018-02', '2018-03', '2018-04', '2018-05', '2018-06']), 'store': ['A'] * 3 + ['B'] * 3, 'sales': [3000, 2000, 1800, 1700, 1500, 1600]}) unaligned_df2 = pd.DataFrame({ 'date': pd.to_datetime(['2018-02-11', periods=6, freq='30D']), 'temp': [105, 95, 87]}) Unaligned_merged_left_date_index=? different frequency, scenario 3 unaligned_fast_diff_freq = pd.DataFrame({ 'date': pd.to_datetime(['2018-01-12', '2018-02-10', '2018-02-16', '2018-04-28', '2018-04-29', '2018-06-11']), 'store': ['A'] * 3 + ['B'] * 3, 'sales': [3000, 2000, 1800, 1700, 1500, 1600]}) unaligned_slow_diff_freq = pd.DataFrame({ 'date': pd.to_datetime(['2018-04', '2018-05', '2018-01', '2018-06']), 'sales': [2700, 2500, 2600, 3300]}) unaligned_fast_slow= ?
type: Question
has comment: http://stackoverflow.com/comment/87847402
has comment: http://stackoverflow.com/comment/87843521
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50455293
tagged with: pandas
has title: joining two dataframe on date column in pandas
downvote count: 0

http://stackoverflow.com/q/50426773
has comment: http://stackoverflow.com/comment/87868227
score: 0
has body: Im trying to make a user list for my multiselectfield. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') users = User.objects.values_list('id','username') authorized = MultiSelectField(choices=users, null=True) but the problem is that later on in my html file i can't compare those values with a logged user id {% if latest_question_list %} &lt;ul&gt; {% for question in latest_question_list %} {% for person in question.authorized %} {% ifequal person request.user.id %} &lt;li&gt;&lt;a href="/polls/{{ question.id }}/"&gt;{{ question.question_text }}&lt;/a&gt;&lt;/li&gt; {% endifequal %} {% endfor %} &lt;/ul&gt; {% endfor %} Thanks in advance EDIT: here's my traceback calls after use only() instead of values_list(): Traceback (most recent call last): File "/home/ab/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ab/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ab/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ab/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ab/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ab/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ab/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ab/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module retu…
tagged with: python
tagged with: templates
has title: Creating list of usernames from User model in Django
type: Question
has comment: http://stackoverflow.com/comment/87868162
has comment: http://stackoverflow.com/comment/87874379
has comment: http://stackoverflow.com/comment/87869082
type: UnansweredQuestion
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/87868403
has answer: http://stackoverflow.com/a/50428917

http://stackoverflow.com/comment/87910415
has text: The problem is in `branch2`. (That is the model that is expecting 3D, the other branch expects 4D.). Is `BR_arr` supposed to be one number per image? Or a single group of 1630 numbers repeated for all images?
type: Comment
comment on: http://stackoverflow.com/q/50447015
score: 0
type: QuestionComment

http://stackoverflow.com/q/50486927
has answer: http://stackoverflow.com/a/50487191
has body: I have this variable x = 0x61626364 I want the string "dcba", converting the hex number in char, and then reverse the string. How can I do that in python?
tagged with: string
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50487063
possible better answer: http://stackoverflow.com/a/50487063
answer count: 4
has answer: http://stackoverflow.com/a/50487257
has comment: http://stackoverflow.com/comment/87986851
tagged with: hex
type: AnsweredQuestion
tagged with: python-2.7
has title: Convert hex number to char string reversed
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50487109
accepted answer: http://stackoverflow.com/a/50487109

http://stackoverflow.com/comment/87910087
type: QuestionComment
has text: @AzatIbrakov thanks just corrected. "door" would be needed as well
score: 0
comment on: http://stackoverflow.com/q/50448384
type: Comment

twitter
tags question: http://stackoverflow.com/q/50420710
tags question: http://stackoverflow.com/q/50503326
tags question: http://stackoverflow.com/q/50479385
tags question: http://stackoverflow.com/q/50478961
tag name: twitter
tags question: http://stackoverflow.com/q/50426842
tags question: http://stackoverflow.com/q/50459620
tags question: http://stackoverflow.com/q/50420066
type: Tag
tags question: http://stackoverflow.com/q/50536931
tags question: http://stackoverflow.com/q/50385200
tags question: http://stackoverflow.com/q/50417408
tags question: http://stackoverflow.com/q/50511196
tags question: http://stackoverflow.com/q/50423076
tags question: http://stackoverflow.com/q/50424196
tags question: http://stackoverflow.com/q/50387110
tags question: http://stackoverflow.com/q/50434101

http://stackoverflow.com/comment/88051718
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50519277
has text: it is actually every 3751 rows forms a meaningful input. The inputs forms something like a 3D plot (31*11*11) with the 'current' being the data stored in the coordinates. Every 3751 rows of inputs correspond to 1 set of output (with 6 columns). And yes the sequence matter.

http://stackoverflow.com/comment/87817525
score: 0
type: AnswerComment
has text: thanks for your fast answer, but i've tried between two movies that have both "movie_rank" field with NO NaN and i got always avg:nan, so weird..
comment on: http://stackoverflow.com/a/50400814
type: Comment

http://stackoverflow.com/q/50463325
tagged with: docker
has comment: http://stackoverflow.com/comment/87939977
upvote count: 1
score: 1
has body: I'm trying to run the SqlSensor locally under docker on a Windows 10 machine, it runs on Linux but get below errors when trying to run the same simple DAG locally. The reason I'm trying to set this up is so that I can develop locally and test to speed up the development cycle. Error from Airflow log: [2018-05-22 08:27:04,929] {{models.py:1428}} INFO - Executing &lt;Task(SqlSensor): limits_test&gt; on 2018-05-21 08:00:00 [2018-05-22 08:27:04,929] {{base_task_runner.py:115}} INFO - Running: ['bash', '-c', 'airflow run sql-sensor-test-dag limits_test 2018-05-21T08:00:00 --job_id 8 --raw -sd DAGS_FOLDER/sql_sensor_test.py'] [2018-05-22 08:27:05,685] {{base_task_runner.py:98}} INFO - Subtask: [2018-05-22 08:27:05,684] {{__init__.py:45}} INFO - Using executor CeleryExecutor [2018-05-22 08:27:05,749] {{base_task_runner.py:98}} INFO - Subtask: [2018-05-22 08:27:05,749] {{models.py:189}} INFO - Filling up the DagBag from /usr/local/airflow/dags/sql_sensor_test.py [2018-05-22 08:27:05,791] {{cli.py:374}} INFO - Running on host 0f8e7a60dbab [2018-05-22 08:27:05,858] {{base_task_runner.py:98}} INFO - Subtask: [2018-05-22 08:27:05,858] {{base_hook.py:80}} INFO - Using connection to: LABCHGVA-SQL295 [2018-05-22 08:27:05,888] {{base_task_runner.py:98}} INFO - Subtask: [2018-05-22 08:27:05,888] {{sensors.py:111}} INFO - Poking: SELECT max(snapshot_id) FROM limits_run [2018-05-22 08:27:05,896] {{base_task_runner.py:98}} INFO - Subtask: [2018-05-22 08:27:05,896] {{base_hook.py:80}} INFO - Using connection to: LABCHGVA-SQL295 [2018-05-22 08:27:05,924] {{models.py:1595}} ERROR - Connection to the database failed for an unknown reason. Traceback (most recent call last): File "pymssql.pyx", line 635, in pymssql.connect (pymssql.c:10734) File "_mssql.pyx", line 1902, in _mssql.connect (_mssql.c:21821) File "_mssql.pyx", line 638, in _mssql.MSSQLConnection.__init__ (_mssql.c:6594) _mssql.MSSQLDriverException: Connection to the database failed for an unknown reason. During handling of the a…
tagged with: pymssql
favorite count: 0
type: Question
has title: Apache Airflow SqlSensor MSSQL issues on Docker running on Windows 10
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: airflow
tagged with: python
has comment: http://stackoverflow.com/comment/87944775

http://stackoverflow.com/comment/87798642
has text: .T is the short form of transposing, see the documentation (https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.ndarray.T.html#numpy.ndarray.T). This requires that you use a numpy array, not a list.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50391381

http://stackoverflow.com/comment/88093233
comment on: http://stackoverflow.com/q/50540414
has text: it is better to use pyside widgets for such stuff on maya instead of the crappy cmds maya menus
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50423262
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87993267
has answer: http://stackoverflow.com/a/50470756
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87869652
downvote count: 0
has title: Web scrape weather table
has comment: http://stackoverflow.com/comment/87954711
upvote count: 1
score: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/88001843
has comment: http://stackoverflow.com/comment/87955325
tagged with: beautifulsoup
has body: I am trying to web scrape the weather data, and need to take the table and convert to csv format. But not all the entries from table have same number of columns filled. So when i take the input in this format for h in airports: for i in range(1,3): if(i==1): for j in range(1,32): url="https://www.wunderground.com/history/airport/"+str(h)+"/2018/"+str(i)+"/"+str(j)+"/DailyHistory.html?req_city=&amp;req_state=&amp;req_statename=&amp;reqdb.zip=&amp;reqdb.magic=&amp;reqdb.wmo=" www= urllib3.PoolManager() page=www.urlopen("GET",url) bs= BeautifulSoup(page.data,"lxml") x=bs.find('div',{"class":"high-res"}) for tr in x.findAll('tr'): weather.append([td for td in tr.stripped_strings]) else: for k in range(1,29): url="https://www.wunderground.com/history/airport/"+str(h)+"/2018/"+str(i)+"/"+str(k)+"/DailyHistory.html?req_city=&amp;req_state=&amp;req_statename=&amp;reqdb.zip=&amp;reqdb.magic=&amp;reqdb.wmo=" www= urllib3.PoolManager() page=www.urlopen("GET",url) bs= BeautifulSoup(page.data,"lxml") x=bs.find('div',{"class":"high-res"}) for tr in x.findAll('tr'): weather.append([td for td in tr.stripped_strings]) The out put csv file is all over the place, the comma seperated variables each are going into a new column irrespective of the headers. is there an easy way to do this and get the date in a clearer way? So i am continuously appending a list with rows of the table, irrespective of the columns. How to make sure that the data in the columns is under the right header? This iss what i used to write the data into the csv file: with open ('weather.csv','a') as file: writer=csv.writer(file) for row in weather: writer.writerow(row)
tagged with: pandas

http://stackoverflow.com/q/50450783
type: Question
has title: Is there a better way to setup a figure with different columns per row which have different heights?
type: UnansweredQuestion
tagged with: matplotlib
tagged with: figure
tagged with: python
has body: As shown below, gridspec can be used to create a grid of rows and columns with different heights (using the height_ratios argument). To then get different number of columns required for a given row (aka to set subplot extent), the indexes of the columns within the existing grid are provided to plt.subplot(). This code works OK, but I wonder if there a more concise/less "kludgy" way using gridspec or different module altogether? # Get modules in use import seaborn as sns; sns.set(color_codes=True) import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec # Setup some data to use x = range(40) y = np.random.rand(len(x)) # Set heights of rows of subpolts height_ratios = [1.5, 1, 1.5, 1.25] # Initialise a figure fig = plt.figure( ) # Set number of "fake" columns &amp; actual rows ncols = 1000 nrows = 4 ncols4row = [1,2,2,3] # Set the # of columns to spread subplots across (just set here for Q brevity) cols2use = { 2: ( (0, 450), (550, -1) ), 3: ( (0, 283), (383, 616), (716, -1) ), } # Use grid specs to setup plot with nrows with set "height ratios" G = gridspec.GridSpec(nrows, ncols, height_ratios=height_ratios ) # Now loop rows for nrow in range( nrows ): # Number of columns in row? ncol = ncols4row[nrow] # Get axes for row based on number of rows if ncol == 1 : axes = [ plt.subplot(G[nrow, :]) ] else: axes = [ plt.subplot(G[nrow, i[0]:i[-1]]) for i in cols2use[ncol] ] # Loop axes and plot up for ax in axes: ax.plot(x,y) Which gives:
has comment: http://stackoverflow.com/comment/87951323
answer count: 0
has comment: http://stackoverflow.com/comment/87923466
downvote count: 0
upvote count: 1
score: 1
tagged with: plot
favorite count: 0

http://stackoverflow.com/comment/87923301
type: QuestionComment
comment on: http://stackoverflow.com/q/50454630
has text: The trick I used without getting too fancy was I opened 'test.pln' in MS Word choose to show all invisible characters.
score: 0
type: Comment

http://stackoverflow.com/comment/87898851
type: Comment
has text: Can you please fix your indentation, and provide the full error? And show an example of your input.
type: QuestionComment
comment on: http://stackoverflow.com/q/50442423
score: 0

http://stackoverflow.com/a/50467050
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50466515
score: 3
upvote count: 3
has body: Try using np.nan Ex: import pandas as pd import numpy as np data = pd.DataFrame({"price": ["?", "Hello", "?", "World"]}) data["price"].replace('?',np.nan, inplace=True) print(data.fillna(0)) Output: price 0 0 1 Hello 2 0 3 World
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50466515

http://stackoverflow.com/comment/87972263
type: Comment
has text: @rodrigosillos How do you get the hwnd (197526)?, what is your OS?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50477815

http://stackoverflow.com/comment/88012729
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50499936
has text: Is `des-3` a typo or a language issue?

http://stackoverflow.com/q/50388088
favorite count: 0
type: Question
tagged with: mean
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23199796
tagged with: outliers
answer count: 1
downvote count: 0
upvote count: 1
has title: Dropping outliers using standard deviation and mean formula
duplicate of: http://stackoverflow.com/q/23199796
has answer: http://stackoverflow.com/a/50402568
has body: Hello everyone, I am trying to remove the outliers from my dataset. I defined the outlier boundaries using the mean-3*std and mean+3*std. Now I want to delete the values smaller than mean-3*std and delete the values bigger than mean+3*std. Could you help me writing a formula for this? I am a beginner in python. I already looked at similar questions, but this did not helped so far. Untill now I had the following: import pandas as pd print(df_OmanAirTO.mean()-3*df_OmanAirTO.std(), df_OmanAirTO.mean()+3*df_OmanAirTO.std()) resulting in: FuelFlow 2490.145718 ThrustDerateSmoothed 8.522145 CoreSpeed 93.945180 EGTHotDayMargin 9.950557 EGT 684.168701 TotalAirTemperature 11.980698 ThrustDerate -3.780215 dtype: float64 FuelFlow 4761.600157 ThrustDerateSmoothed 29.439075 CoreSpeed 101.360974 EGTHotDayMargin 90.414781 EGT 915.952163 TotalAirTemperature 43.266653 ThrustDerate 44.672861 dtype: float64 Now I want to delete the values smaller than mean-3*std and delete the values bigger than mean+3*std. How can I do this? Thank you in advance for helping me!
tagged with: pandas
score: 1
tagged with: python
tagged with: standard-deviation

http://stackoverflow.com/comment/88082565
comment on: http://stackoverflow.com/q/50534911
has text: Did you try the line I wrote above? It should work fine with your `expansions = map(generated, regexes)`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50482899
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
has body: I have done this code but the output is not like what I want def replace(s,p,n): return "".join("{}".format(p) if not i % n else char for i, char in enumerate(s,1)) print(replace("university","-",3)) the output that I get is un-ve-si-y I must get it like : uni-ver-sit-y
type: Question
has comment: http://stackoverflow.com/comment/87978787
has comment: http://stackoverflow.com/comment/87978837
has answer: http://stackoverflow.com/a/50483145
has title: Joining a string in another string
tagged with: python
possible better answer: http://stackoverflow.com/a/50483045
answer count: 4
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50483045
has answer: http://stackoverflow.com/a/50483290
accepted answer: http://stackoverflow.com/a/50482962
has answer: http://stackoverflow.com/a/50482962

http://stackoverflow.com/comment/87948212
type: AnswerComment
comment on: http://stackoverflow.com/a/50467540
has text: Why can't I use `fib[i] = fib[i-1]+fib[i-2]` ?
score: 0
type: Comment

http://stackoverflow.com/comment/88004879
score: 0
type: Comment
type: QuestionComment
has text: Sorry, I am still new at python So, it takes some time for me to revisit the question and answer. I have edited my question and by omitting this line' df = df.drop(columns=['date']) ' all seems to run smoothly.
comment on: http://stackoverflow.com/q/50458837

http://stackoverflow.com/q/50498540
has answer: http://stackoverflow.com/a/50498642
tagged with: recursion
score: 0
has title: Analyzing BST is balanced Code
answer count: 1
type: Question
tagged with: binary-search-tree
type: UnansweredQuestion
has body: I was looking at this python code to check if a Binary Search Tree is balanced. However, I was wondering if someone could explain how height = max(left_height, right_height) + 1 comes into play. How does this line of code work to calculate the height. And finally, how this is_left_balanced, left_height = TreeNode.is_balanced(cur_node.left) is_right_balanced, right_height = TreeNode.is_balanced(cur_node.right) stack recursion is working because once is_balanced(cur_node.left) is called, its called again when the second TreeNode.is_balanced(cur_node.right) is called. Im having trouble following the stack trace for this. Here is the entire code: def is_balanced(cur_node) : if (not cur_node) : height = 0 return True, height is_left_balanced, left_height = TreeNode.is_balanced(cur_node.left) is_right_balanced, right_height = TreeNode.is_balanced(cur_node.right) #To get the height of the current node, we find the maximum of the #left subtree height and the right subtree height and add 1 to it height = max(left_height, right_height) + 1 if (not is_left_balanced or not is_right_balanced): return False, height #If the difference between height of left subtree and height of #right subtree is more than 1, then the tree is unbalanced if (abs(left_height - right_height) &gt; 1): return False, height return True, height
tagged with: python

http://stackoverflow.com/q/50401588
has comment: http://stackoverflow.com/comment/87819045
has comment: http://stackoverflow.com/comment/87819188
tagged with: python
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
has comment: http://stackoverflow.com/comment/87819062
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50401640
has body: I need to obtain a list of links from a sitemap. I'm using the code below and I don't get anything back. No errors. Ultimately I would love an excel sheet with a list. import bs4 from lxml import etree #added as suggested from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://www.example.com/sitemap.xml' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(site, "lxml.xml") #added as suggested evensite = page_soup.findAll("table", {"class":"td"}) print(evensite) After changed, this is the error obtained Traceback (most recent call last): File "/Users/user/Downloads/lxml.py", line 14, in &lt;module&gt; page_soup = soup(site, "lxml.xml") File "/anaconda3/lib/python3.6/site-packages/bs4/__init__.py", line 165, in __init__ % ",".join(features)) bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml.xml. Do you need to install a parser library? [Finished in 1.3s]
has answer: http://stackoverflow.com/a/50401640
tagged with: beautifulsoup
has title: Obtaining a xml site using BeautifulSoup
type: AnsweredQuestion
score: 1

mathematical-optimization
tags question: http://stackoverflow.com/q/50515772
tags question: http://stackoverflow.com/q/50396873
tags question: http://stackoverflow.com/q/50396404
type: Tag
tag name: mathematical-optimization
tags question: http://stackoverflow.com/q/50520375

http://stackoverflow.com/a/50580684
has body: Try this code: for i in range (0,len(df.columns)): x=df.columns[i] df[df[x]&lt;0]=np.nan
type: Answer
answers question: http://stackoverflow.com/q/50538118
score: 0

http://stackoverflow.com/a/50453645
answers question: http://stackoverflow.com/q/50453231
has body: Use scp to copy from raspberry pi machine to windows machine (if you are using linux distro on raspberry pi)
type: Answer
has comment: http://stackoverflow.com/comment/87921239
has comment: http://stackoverflow.com/comment/87931365
score: 0
has comment: http://stackoverflow.com/comment/87921150

http://stackoverflow.com/comment/87867242
comment on: http://stackoverflow.com/q/50426104
has text: I was given it beforehand, so it's static
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50487815
has answer: http://stackoverflow.com/a/50488034
score: 0
has comment: http://stackoverflow.com/comment/87988755
has comment: http://stackoverflow.com/comment/87988499
answer count: 1
tagged with: selenium
tagged with: web-scraping
tagged with: scrapy
has body: I am new to the scrapping and with python in general. I have a task for myself. Actually I need to extract some data from forms. I have learned how to extract data from HTML elements, but this is little tricky for me. Task should look like this: 1. I need to login on website 2. Go to the specific URL 3. Then I need somehow to extract all data from form Problem occurs because data of next dropdown button is shown when the previous one is choose. Here is a picture showing the site look and source code next to it.
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has title: Interactive scraping data from forms on website
tagged with: python

http://stackoverflow.com/q/50477013
has comment: http://stackoverflow.com/comment/87968195
has comment: http://stackoverflow.com/comment/87971538
answer count: 1
has title: Converting a NumPy Array to cufftComplex
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/45515526
accepted answer: http://stackoverflow.com/a/50479440
has comment: http://stackoverflow.com/comment/87968362
linked to: http://stackoverflow.com/q/44415752
tagged with: python
tagged with: cufft
tagged with: cuda
has comment: http://stackoverflow.com/comment/87971016
has body: I am writing a script to perform an FFT using the GPU/CUDA based cuFFT library. CuFFT requires that input data must be in the format specified as "cufftComplex". However my input data is in the numpy.complex64 format. I am using the Python C-API to send data from python to C. How can I convert between the two formats? Currently my code looks like this: #include&lt;python2.7/Python.h&gt; #include&lt;numpy/arrayobject.h&gt; #include&lt;cufft.h&gt; void compute_BP(PyObject* inputData, pyObject* OutputData, int Nfft) { cuffthandle plan; cuFFTPlan1d(&amp;plan, Nfft, CUFFT_C2C, CUFFT_INVERSE); cuFFTExecC2C(plan, inputData, OutputData, CUFFT_INVERSE); ... } When compiling I get the following error: Error: argument of type "PyObject *" is incompatible with parameter of type "cufftComplex".
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50479440
score: 0

http://stackoverflow.com/a/50440714
score: 3
type: Answer
has body: By using np.unique x,y = np.unique(sum([list(range(x.year,y.year)) for x,y in zip(df.StartDate,df.EndDate)],[]), return_counts=True) pd.Series(dict(zip(x,y))) Out[222]: 1990 2 1991 2 1992 2 1993 2 1994 2 1995 1 1996 1 1997 1 1999 1 2000 1 2001 1 dtype: int64
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50440186

http://stackoverflow.com/comment/88150376
comment on: http://stackoverflow.com/a/50516528
has text: I'll check out how to compile for IFC4 because that's the problem I think. I updated my question to reflect the bit of progress that was made.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/71068574
type: Answer
has body: I had the same problem but I used sql expresions: expr = """CASE WHEN variable1==8 AND variable==4.1 THEN 'new_orleans' ELSE variable3 END AS variable4""" df = df.selectExpr(*,expr)
score: 0
has comment: http://stackoverflow.com/comment/125636436
answers question: http://stackoverflow.com/q/50393380

http://stackoverflow.com/q/50512696
has answer: http://stackoverflow.com/a/50512766
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
answer count: 2
has title: Add dictionary item in list to a dictionary
has comment: http://stackoverflow.com/comment/88037969
linked to: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/88037939
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50512755
has body: Hi guys I'm pretty lost with this simple problem. I have a dictionary and a list of dictionaries in python and I want to loop over the list to add each dictionary to the first dictionary but somehow it just adds the last dictionary with the solution I came up with. I'm using Python 3.6.5 This is what I've tried: res = [] dictionary = {"id": 1, "name": "Jhon"} dictionary_2 = [ {"surname": "Doe", "email": "jd@example.com"}, {"surname": "Morrison", "email": "jm@example.com"}, {"surname": "Targetson", "email": "jt@example.com"} ] for info in dictionary_2: aux_dict = dictionary aux_dict["extra"] = info res.append(aux_dict) print(res) What I expect is: [{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Doe', 'email': 'jd@example.com'}}, {'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Morrison', 'email': 'jm@example.com'}}, {'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}}] And this is what I get [{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}}, {'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}}, {'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}}] This is probably a duplicate of some other question but I can't manage to find it
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50512755
possible better answer: http://stackoverflow.com/a/50512766
score: 1
has comment: http://stackoverflow.com/comment/88037846

http://stackoverflow.com/comment/88069155
type: Comment
type: QuestionComment
score: 2
has text: I'm parsing the output of `net use`. Dirty but works on all windows.
comment on: http://stackoverflow.com/q/50528180

http://stackoverflow.com/q/50397016
has title: Python/Numpy Slicing an array every nth row
downvote count: 0
has answer: http://stackoverflow.com/a/50397108
accepted answer: http://stackoverflow.com/a/50397108
tagged with: arrays
answer count: 1
has body: I'm new to Numpy and data analysis in general and I was wondering what I had to do to/if it is possible to take a large array and splice it into smaller array. For example if I had a large 2D array like: [[ 24.47590959 148.14814815 185.11662347 377.92894936 345.78146611] [ 24.74543137 147.49262537 185.7959032 375.93984962 346.86090878] [ 23.9300286 144.6131598 182.99098769 376.08123355 356.31569571] [ 24.68922439 145.01160093 181.35654697 382.11692778 363.30608538] [ 24.16976845 142.98991921 183.0328544 355.68202027 355.74528637] [ 23.66695856 139.94821916 181.78512998 352.4539607 348.73583261] [ 23.66219845 137.08958805 181.34010336 345.84125886 347.94711204] [ 23.53356475 135.34546931 179.85611511 352.82702655 350.32404975] [ 23.46866933 136.16557734 180.261379 354.29583702 366.703337 ] [ 23.46564044 133.71665441 179.09913137 346.08063679 358.48718408] [ 23.65184484 135.34546931 178.30079344 354.79865177 352.0506953 ] [ 22.55961378 136.23050201 176.41351328 358.93754487 342.52440486] [ 22.34936528 135.92496942 177.65144786 362.84470247 344.64931932] [ 22.6072999 137.04262025 176.64723547 361.20642947 347.82608696] [ 22.2585779 133.32444504 174.77934108 357.97386791 329.97855139] [ 21.62162162 128.09017548 173.05529117 360.94567768 333.05578684] [ 21.40983782 128.44390213 178.57142857 370.64492216 328.19166393] [ 20.8040776 127.4941034 182.34865062 369.07178446 333.72267646] [ 20.83333333 127.9590531 186.06381989 386.32412594 325.99837001] [ 20.08475768 129.11555842 184.55292055 380.22813688 315.95576619] [ 19.86531318 128.86597938 186.75880101 377.71482531 309.78934325] [ 20.47564933 130.76168683 189.35807612 374.25149701 321.64683178] [ 20.25090876 127.68945924 189.5195679 391.38943249 332.55736615]] and I wanted to split the array every nth row, how would that be possible? for example every third row would be: [[ 24.47590959 148.14814815 185.11662347 377.92894936 345.78146611] [ 24.74543137 147.49262537 185.7959032 375.93984962 346.86090878] [ 23.9300286 144.613…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87810241
tagged with: python
has comment: http://stackoverflow.com/comment/87809835
linked to: http://stackoverflow.com/q/34231244
score: 2
upvote count: 2
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/q/50436134
has title: Assign value to tensor fields which satisfy condition in Tensorflow
has answer: http://stackoverflow.com/a/50439600
tagged with: python
has comment: http://stackoverflow.com/comment/87886751
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92806399
answer count: 1
tagged with: tensorflow
has body: Let me introduce the problem with the example in numpy: arr - some numpy array a, b - constants arr[arr &lt; a] = b Now, I would like to implement the same functionality but in Tensorflow where arr would be a tensor. Tensor value is not known before runtime. As you can see, the answer would yield clarification for both assigning values to specific positions inside tensors, and also performing conditioning on the tensor and retrieving indices which satisfy condition.
linked to: http://stackoverflow.com/q/39045797
accepted answer: http://stackoverflow.com/a/50439600
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87886769

string-to-datetime
tag name: string-to-datetime
type: Tag
tags question: http://stackoverflow.com/q/50437679

http://stackoverflow.com/comment/88047263
has text: Of the whole sheet of paper @bfris. Top left corner of top left barcode + top right corner of top left barcode + bottom left corner of bottom right barcode + bottom right corner of bottom right barcode = 4 points and it's enough to do a perspective correction / homography (I tried it by manually enter the coordinates and it works).
comment on: http://stackoverflow.com/q/50497945
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50414480
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50415182
has title: Reshaping the output of a logistic regression
type: UnansweredQuestion
tagged with: python
has body: I have defined a logistic regression model as a network with one layer followed by a sigmoid activation using tf.layers. The predictions come out as a 2D tensor of shape (n,1), n being the size of the batch. However, in order to calculate the loss function, I need a 1D tensor of shape n. Of course I can reshape the tensor (and that's what I currently do), but somehow it feels like there should be something more elegant to do. Is there? Code to reproduce the issue import tensorflow as tf import numpy as np data = np.random.random((20, 6)) data[:, -1] = data[:, -1] &gt; 0.5 e = tf.data.Dataset.from_tensor_slices(data).batch(2).make_one_shot_iterator().get_next() x, y_ = e[:, :-1], e[:, -1] y = tf.layers.dense(x, 1, activation=tf.nn.sigmoid) loss_wrong = - tf.reduce_mean(tf.add(tf.multiply(y_, tf.log(y)), tf.multiply((1. - y_), tf.log(1. - y)))) y2 = tf.reshape(y, [-1]) # ugly reshape I would like to get rid of loss_correct = - tf.reduce_mean(tf.add(tf.multiply(y_, tf.log(y2)), tf.multiply((1. - y_), tf.log(1. - y2)))) with tf.Session() as sess: tf.global_variables_initializer().run() a, b, b2, lw, lc = sess.run([y_, y, y2, loss_wrong, loss_correct]) print(a) # a 1D array with the real labels print(b) # a dangerous array of arrays! print(b2) # notice how nice and flat this is print(lw) # wrong when all labels are not the same print(lc) # correct (can test by hand with the data printed)
score: 0
answer count: 1

http://stackoverflow.com/comment/87880050
has text: What is the question? Can you show an example of the data? What did you try so far?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50431221

http://stackoverflow.com/q/50393170
score: -1
tagged with: rosalind
has answer: http://stackoverflow.com/a/50407971
answer count: 1
downvote count: 1
favorite count: 0
has body: I have been working on Rosalind exercises for Bioinformatics stronghold on RNA Splicing. I am currently using Python 3.6 version. It didn't tell me there is any error in my code, so I'm assuming my code is fine. However, there is no output produced, no error warning or whatsoever. Below is my code: DNA_CODON_TABLE = { 'TTT': 'F', 'CTT': 'L', 'ATT': 'I', 'GTT': 'V', 'TTC': 'F', 'CTC': 'L', 'ATC': 'I', 'GTC': 'V', 'TTA': 'L', 'CTA': 'L', 'ATA': 'I', 'GTA': 'V', 'TTG': 'L', 'CTG': 'L', 'ATG': 'M', 'GTG': 'V', 'TCT': 'S', 'CCT': 'P', 'ACT': 'T', 'GCT': 'A', 'TCC': 'S', 'CCC': 'P', 'ACC': 'T', 'GCC': 'A', 'TCA': 'S', 'CCA': 'P', 'ACA': 'T', 'GCA': 'A', 'TCG': 'S', 'CCG': 'P', 'ACG': 'T', 'GCG': 'A', 'TAT': 'Y', 'CAT': 'H', 'AAT': 'N', 'GAT': 'D', 'TAC': 'Y', 'CAC': 'H', 'AAC': 'N', 'GAC': 'D', 'TAA': '-', 'CAA': 'Q', 'AAA': 'K', 'GAA': 'E', 'TAG': '-', 'CAG': 'Q', 'AAG': 'K', 'GAG': 'E', 'TGT': 'C', 'CGT': 'R', 'AGT': 'S', 'GGT': 'G', 'TGC': 'C', 'CGC': 'R', 'AGC': 'S', 'GGC': 'G', 'TGA': '-', 'CGA': 'R', 'AGA': 'R', 'GGA': 'G', 'TGG': 'W', 'CGG': 'R', 'AGG': 'R', 'GGG': 'G' } def result(s): result = '' lines = s.split() dna = lines[0] introns = lines[1:] for intron in introns: dna = dna.replace(intron, '') for i in range(0, len(dna), 3): codon = dna[i:i+3] protein = None if codon in DNA_CODON_TABLE: protein = DNA_CODON_TABLE[codon] if protein == '-': break if protein: result += protein return ''.join(list(result)) if __name__ == "__main__": """small_dataset = ' '""" large_dataset = open('rosalind_splc.txt').read().strip() print (result(large_dataset)) This is the content in rosalind_splc.txt text file: &gt;Rosalind_3363 ATGGGGCTGAGCCCATGTCTAAATGATATCTTGGTGCATTGCAATCTAACTATTTTTTCG CAACCATGTTCCATCTGGCGCAAAATGGGCGTGTAGGGAGCTTCGCTATAGTCACTGAAG AACATTCGCAACTTACAGCTCTCGAGAGGGTACAGCTGGACGGTGTTTGTTTGGTCTAAG TCTGAGTCCAAAGTCGTTGAATGTCGAGCTAGGTTGACGTCATTCTTCGAGTTACGTCTT CATTGATTCGCGGCGGCCGCCAGCATTTGATTGTACACATCCGACGTCTTTGGCAATCTA CATAATTATATTGAGAGGGGCGCCATTACTCGAACCCATAACAAACAACTG…
has comment: http://stackoverflow.com/comment/87805667
has comment: http://stackoverflow.com/comment/87832155
type: Question
tagged with: bioinformatics
upvote count: 0
tagged with: python
has title: RNA Splicing Python (No output given)
type: UnansweredQuestion

http://stackoverflow.com/a/68046423
score: 0
has body: Check Spark home directory contained all folder and files(xml, jars etc.) otherwise install Spark. Check your JAVA_HOME and SPARK_HOME environment variable are set in your .bashrc file, try setting the below: export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/ export SPARK_HOME=/home/ubuntu-username/spark-2.4.8-bin-hadoop2.6/ Or wherever your spark is downloaded to export SPARK_HOME=/home/Downloads/spark-2.4.8-bin-hadoop2.6/ once done, save your .bash and run bash command on terminal or restart the shell and try spark-shell
answers question: http://stackoverflow.com/q/50435286
type: Answer

http://stackoverflow.com/a/50454396
score: 1
type: Answer
has body: We can reduce it to one loop, as we would make use of array-slicing and use sum ufunc to operate along the rows of the dataframe and thus in the process make it generic to cover any number of columns, like so - a = data.values t = data["timestep"].count() c = np.zeros(t) for i in range(t): c[:i+1] += (a[:i+1,1:]*a[i,1:]).sum(axis=1) Explanation 1) a[:i+1,1:] is the slice of all rows until the i+1-th row and all columns starting from the second column, i.e mux, muy and so on. 2) Similarly, for [i,1:], that's the i-th row and all columns from second column onwards. To keep it "pandas-way", simply replace a[ with data.iloc[.
accepted answer of: http://stackoverflow.com/q/50453774
has comment: http://stackoverflow.com/comment/87923915
answers question: http://stackoverflow.com/q/50453774
has comment: http://stackoverflow.com/comment/87924007
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/88057840
type: Comment
comment on: http://stackoverflow.com/a/50522890
score: 0
has text: Oh sorry, I updated my code. I followed tutorial from: https://mortoray.com/2014/03/04/http-streaming-of-command-output-in-python-flask/#comment-29298
type: AnswerComment

http://stackoverflow.com/q/50409283
type: Question
tagged with: time
tagged with: python
tagged with: lstm
has body: I am trying to implement a lstm model with data measured once a day over time at different moments of the day. For example, let's say the last input of my data set has been measured on May 16, 2018. My data is like this: Velocity Time 0 56.122 3600 1 56.114 3601 ... ... ... 3599 75.043 7199 The time is in seconds. From 3600 to 7199 means from 1:00 am to 2:00 am. Let's say the input before has been measured the day before (May 15) from 00:00 to 00:15. Velocity Time 0 6.232 0 1 6.197 1 ... ... ... 899 5.507 899 The problem is I don't know how to deal with the 'Time' feature when I am creating my LSTM model. At the moment, I have padded my data so that they all have the same shape. For example, for the input of May 15, I have now Velocity Time 0 6.232 0 1 6.197 1 ... ... ... 899 5.507 899 900 -1 -1 ... ... ... 3599 -1 -1 I assumed in the example that 1 hour was the maximum time length of the inputs. Do I need to transform the time into a categorical data ? Because I normalized my data (not seen here) with sklearn.preprocessing.MinMaxScaler (I did it before the padding). If not, do I need to scale the time ? I have 11200 inputs. Each input (X_train) has a shape of (3600, 2). There is one output for each input (it's a boolean True or False). Thanks.
accepted answer: http://stackoverflow.com/a/50409950
type: AnsweredQuestion
score: 0
has title: keras lstm time series data
has answer: http://stackoverflow.com/a/50409950
answer count: 1
tagged with: keras

http://stackoverflow.com/comment/88003697
score: 0
has text: but afterall I just need to return value of 'b' only , I need only value of 'b' that's why I just returned that , why does it prints None then?the last value that needs to be returned is b and not gcd_a(b%a,a)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50422120

http://stackoverflow.com/q/50422052
downvote count: 1
favorite count: 0
tagged with: multiprocessing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87859094
has comment: http://stackoverflow.com/comment/87859073
has body: I am trying to construct hierarchies given a dataset, where each row represents a student, the course they've taken, and some other metadata. From this dataset, i'm trying to construct an adjacency matrix and determine the hierarchies based on what classes students have taken, and the path that different students take when choosing classes. That being said, to construct this adjacency matrix, it is computationally expensive. Here is the code I have currently, which has been running for around 2 hours. uniqueStudentIds = df.Id.unique() uniqueClasses = df['Course_Title'].unique() for studentID in uniqueStudentIds: for course1 in uniqueClasses: for course2 in uniqueClasses: if (course1 != course2 and have_taken_both_courses(course1, course2, studentID)): x = vertexDict[course1] y = vertexDict[course2] # Assuming symmetry adjacency_matrix[x][y] += 1 adjacency_matrix[y][x] += 1 print(course1 + ', ' + course2) def have_taken_both_courses(course1, course2, studentID): hasTakenFirstCourse = len(df.loc[(df['Course_Title'] == course1) &amp; (df['Id'] == studentID)]) &gt; 0 if hasTakenFirstCourse: return len(df.loc[(df['Course_Title'] == course2) &amp; (df['Id'] == studentID)]) &gt; 0 else: return False Given that I have a very large dataset size, I have tried to consult online resources in parallelizing/multithreading this computationally expensive for loop. However, i'm new to python and multiprocessing, so any guidance would be greatly appreciated!
tagged with: python
has answer: http://stackoverflow.com/a/50422719
type: Question
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/87859376
tagged with: pandas
score: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50422719
has title: How to Parallelize python loop with large dataset

http://stackoverflow.com/a/70748616
answers question: http://stackoverflow.com/q/50428499
score: 0
type: Answer
has body: Summary of troy-d Answer: window='1d' means window of 1 day window=1 means window of 1 element

http://stackoverflow.com/comment/87898987
type: QuestionComment
has text: Can you post the full stack trace so we can see which line fails? Not this problem, but that should be `sp.call(["rm", "-rf", os.path.join(folder, file))`.
type: Comment
comment on: http://stackoverflow.com/q/50442423
score: 0

http://stackoverflow.com/q/50401685
type: Question
tagged with: graph
tagged with: network-programming
has answer: http://stackoverflow.com/a/50401787
upvote count: 0
has comment: http://stackoverflow.com/comment/87820389
score: -2
downvote count: 2
tagged with: traversal
tagged with: python
has body: I have an interesting python "network" challenge. Not sure what data construct to use and am hoping to learn something new from the experts! The following is a snippet from an ordered table (see SORT column) with a FROM NODE and TO NODE. This table represents a hydrologic network (watershed sequencing) from upstream to downstream. TO NODE = 0 indicates the bottom of the network. Given there can be many branches, how does one traverse a network from any given FROM NODE to TO NODE = 0 and store the list of nodes that are sequenced over? For example, starting at: HYBAS_ID (this is same as FROM NODE)= 2120523430 see &lt;---- about 2/3rd way down, the sequence of Nodes would include the following: [2120523430, 2120523020, 2120523290, 2120523280,2120523270,2120020790, 0] Table: SORT FROM NODE TO NODE 30534 2121173490 2120522070 30533 2120521930 2120521630 30532 2120522070 2120521630 30531 2120521620 2120522930 30530 2120521630 2120522930 30529 2121172200 2121173080 30528 2120522930 2120523360 30527 2120522940 2120523360 30526 2120519380 2120523170 30525 2120519520 2120523170 30524 2120523440 2120523350 30523 2120523360 2120523350 30522 2120525750 2120523430 30521 2120525490 2120523430 30520 2121173080 2120522820 30519 2120523430 2120523020 &lt;------- if you start network here 30518 2120523350 2120523020 30517 2120522820 2120523290 30516 2120523020 2120523290 &lt;------ the second node is here 30515 2120523170 2120523280 30514 2120523290 2120523280 &lt;------ third node here 30513 2120523160 2120523270 30512 2120523280 2120523270 &lt;------ fourth 30511 2120523150 2120020790 30510 2120523270 2120020790 &lt;------ fifth 30509 2120020790 0 &lt;------ End. Would a dictionary and some kind of graph structure work to traverse this network? The code may be fed a list of thousands or millions of FROM NODES to calculate the routing so efficiency is important.
has title: How to traverse an ordered "network"?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50401787
answer count: 1
has comment: http://stackoverflow.com/comment/87819248
tagged with: sequence
favorite count: 0

http://stackoverflow.com/comment/87914222
type: QuestionComment
comment on: http://stackoverflow.com/q/50450512
has text: @Kalyan - Yes, all the inputs are different
score: 0
type: Comment

http://stackoverflow.com/comment/88342417
score: 0
type: Comment
type: QuestionComment
has text: can you try doubles instead of floats and check reproducibility?
comment on: http://stackoverflow.com/q/50412235

http://stackoverflow.com/q/50521609
tagged with: scapy
has comment: http://stackoverflow.com/comment/88056275
has comment: http://stackoverflow.com/comment/88056141
tagged with: scrapy
has title: Scrapy save html element to html file
accepted answer: http://stackoverflow.com/a/50522276
type: Question
tagged with: python
answer count: 1
has body: I want to save div element class="col-md-12 blog-data" (contains images) to html file. Where should I put response.css ? I'm new to python and scrapy . import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" def start_requests(self): urls = [ 'mysite.com/articles/1', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): page = response.url.split("/")[-2] filename = 'quotes-%s.html' % page with open(filename, 'wb') as f: f.write(response.body) //I've used it here and it gave me blank html self.log('Saved file %s' % filename) Is it possible to concat custom string like this and save to html file?Please Give me some examples. Thank you. mytext="&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt; &lt;div id='mycustomelement'&gt; { ('.blog-data')response //how to get this } &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;"
has comment: http://stackoverflow.com/comment/88056349
has answer: http://stackoverflow.com/a/50522276
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88055493

http://stackoverflow.com/comment/87889612
score: 0
type: Comment
has text: Thanks but I already read this Python documentation. Please note that I'm asking why and not how to do it. So, it's more of a question about the efficiency of python programming language instead of how to code. I'd suggest people with privileges here to understand what the question is asking before rushing to subtract reputation points.
type: QuestionComment
comment on: http://stackoverflow.com/q/50436759

http://stackoverflow.com/q/50439517
has comment: http://stackoverflow.com/comment/87893366
tagged with: pandas
has body: My code intends to generate three artist recommendations for a random user. This is a user-based collaberative filtering model, but I'm hitting an error which reads TypeError: string indices must be integers, not Series which points to the line where I assign rating_c. I checked data types and cannot detect which part in that variable is registering as a Series. Does anyone see what could be the Series? Below is the df head: userArtist.head() users artist gender plays age 0 a aesop rock m 72 28.0 1 b air m 178 28.0 2 c amon tobin m 106 28.0 3 d animal collective m 203 28.0 4 e annie m 75 28.0 Code: music_mat = userArtist.pivot_table(index='artist', columns='users', values='plays').fillna(0).apply(np.sign) # user-item collaberative filtering of random user random_user = np.random.choice(userArtist.users) # Check df for values of random user random_user_rating = music_mat[random_user] # Pairwise correlation of top five similar users user_corr = music_mat.corrwith(random_user_rating)[:5] rating_c = userArtist[(userArtist.artist.isnull().values) &amp; (userArtist.users != random_user)] rating_c['similarity'] = rating_c['users'].map(user_corr.get) rating_c['sim_rating'] = rating_c.similarity * rating_c.plays recommendation = rating_c.groupby('artist').apply(lambda s: s.sim_rating.sum() / s.similarity.sum()) recommendation
tagged with: python
has comment: http://stackoverflow.com/comment/87893402
has comment: http://stackoverflow.com/comment/87893437
has title: python - returning top three artists for like users - data type error
type: Question
has answer: http://stackoverflow.com/a/50439675
score: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87893310
has comment: http://stackoverflow.com/comment/87893294
has comment: http://stackoverflow.com/comment/87894571
tagged with: collaborative-filtering

http://stackoverflow.com/comment/88204436
type: AnswerComment
comment on: http://stackoverflow.com/a/50541131
type: Comment
has text: Got you. Thanks!
score: 0

http://stackoverflow.com/a/50525039
score: 0
has comment: http://stackoverflow.com/comment/88064952
has body: If I have understood your question correctly,you can use matplotlib.pyplot.subplot for the same. you can have a look at the examples in this link for starters https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplot.html
has comment: http://stackoverflow.com/comment/88434106
has comment: http://stackoverflow.com/comment/88078280
has comment: http://stackoverflow.com/comment/88067674
has comment: http://stackoverflow.com/comment/88069048
has comment: http://stackoverflow.com/comment/88062381
answers question: http://stackoverflow.com/q/50524613
has comment: http://stackoverflow.com/comment/88065725
type: Answer
has comment: http://stackoverflow.com/comment/88066401

http://stackoverflow.com/comment/87949881
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50468303
has text: the negative lookahead `(?!`..`)` must be at the end and the negative lookbehind `(?<!`..`)` at the start otherwise word boundaries may be used
score: 0

http://stackoverflow.com/a/50400563
accepted answer of: http://stackoverflow.com/q/50391617
has comment: http://stackoverflow.com/comment/88072579
has comment: http://stackoverflow.com/comment/87864416
has comment: http://stackoverflow.com/comment/87864242
score: 2
upvote count: 2
has body: I think the problem is that the version of tables you want to install (2.4.0) is not compatible with the version of numpy you have installed. The incompatibility is due to a bug in setup.py that comes with the tables package. See the following bug report https://github.com/PyTables/PyTables/issues/601 The person that reported the bug provides a patch here: https://gist.github.com/prehensilecode/2eb790476c38299e520ce5ea40896e08 To try and fix this myself I downloaded the 2.4.0 table package (pip download tables==2.4.0) and applied the patch to setup.py I made sure I had the tables dependencies installed (numpy, numexpr and cython), and you will also need to make sure you install the necessary HDF5 files (sudo apt install libhdf5-serial-dev) then I ran: sudo python setup.py install --hdf5=/usr/lib/i386-linux-gnu/hdf5/serial/ The path to your HDF5 files may be different to mine of course. import tablesfrom a python prompt then works
answers question: http://stackoverflow.com/q/50391617
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87864719
has comment: http://stackoverflow.com/comment/87859887
has comment: http://stackoverflow.com/comment/88108978
has comment: http://stackoverflow.com/comment/88065810
has comment: http://stackoverflow.com/comment/88107139
type: Answer
has comment: http://stackoverflow.com/comment/87859914

http://stackoverflow.com/comment/88266768
score: 0
comment on: http://stackoverflow.com/q/50474000
has text: @Jack Just wondering if you figured this out, I'm having a similar problem
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50401755
has answer: http://stackoverflow.com/a/62573718
upvote count: 3
tagged with: oauth-2.0
has body: Following is the code to access a google storage bucket using the httplib2 library import json from httplib2 import Http from oauth2client.client import SignedJwtAssertionCredentials from googleapiclient.discovery import build from pprint import pprint client_email = 'my.iam.gserviceaccount.com' json_file = 'services.json' cloud_storage_bucket = 'my_bucket' files = 'reviews/reviews_myapp_201603.csv' private_key = json.loads(open(json_file).read())['private_key'] credentials = SignedJwtAssertionCredentials(client_email, private_key,'https://www.googleapis.com/auth/devstorage.read_only') storage = build('storage', 'v1', http=credentials.authorize(Http())) pprint(storage.objects().get(bucket=cloud_storage_bucket, object=files).execute()) Can someone tell me if I can make the http request using the Python Requests library here? If yes, how?
downvote count: 0
tagged with: google-api-python-client
tagged with: python-requests
favorite count: 0
type: Question
score: 3
tagged with: google-api
type: UnansweredQuestion
tagged with: python
has title: requests library with googleapiclient
answer count: 2
has answer: http://stackoverflow.com/a/50401998

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/50503912
type: Tag
tags question: http://stackoverflow.com/q/50471802

http://stackoverflow.com/q/50426417
duplicate of: http://stackoverflow.com/q/19473185
score: -5
has comment: http://stackoverflow.com/comment/87868636
has comment: http://stackoverflow.com/comment/87867407
answer count: 1
has comment: http://stackoverflow.com/comment/87867478
tagged with: python
favorite count: 0
type: Question
has body: When I was learning to code and trying to understand lines of codes given below, I am stuck :( So I really wonder why when I assign name = None, first_name = None, last_name = None, the code still prints first_name and last_name(learned from a video about python dictionary), when I set something to None, why didn't Boolean gives me a False Error or even prints out nothing? def packer(name=None, **kwargs): print(kwargs) def unpacker(first_name=None, last_name=None): if first_name and last_name: print('Hi {} {}'.format(first_name, last_name)) else: print('Hi no name!') packer(name='Elgene', num=42, spanish_inquisition=None) unpacker(**{'last_name': 'Ee', 'first_name': 'Elgene'})
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50426619
linked to: http://stackoverflow.com/q/19473185
downvote count: 5
has title: What does 'None' mean in Python?

http://stackoverflow.com/q/50468678
has title: Telepot - Telegram bot sending message every 10 minutes
upvote count: 0
type: UnansweredQuestion
tagged with: telepot
downvote count: 1
favorite count: 0
type: Question
has body: I need my bot to monitor my raspberry cpu temperature. It checks it every minute and then send an alert if > a threshold. When a message is sent I need it to not send it again for 10 minutes. I've done it but then I get a timeout error when sending the same message 10 minutes after. Can anybody help me? I did not find any help on telepot giyhub page. This is my code bot = telepot.Bot(TOKEN) bot.message_loop(handle) while 1: if ((get_cpu_temperature() &gt; 30.0) and alarm()): data = "Temperature: " + str(get_cpu_temperature()) + " 'C" bot.sendMessage(users[0],data) time.sleep(60) The alarm function just checks if 10 mins are passed. This is the error: Traceback (most recent call last): File "temp_disk_check_live.py", line 74, in &lt;module&gt; bot.sendMessage(users[0],data) File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 456, in sendMessage return self._api_request('sendMessage', _rectify(p)) File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 434, in _api_request return api.request((self._token, method, params, files), **kwargs) File "/usr/local/lib/python2.7/dist-packages/telepot/api.py", line 130, in request r = fn(*args, **kwargs) # `fn` must be thread-safe File "/home/pi/.local/lib/python2.7/site-packages/urllib3/request.py", line 148, in request_encode_body return self.urlopen(method, url, **extra_kw) File "/home/pi/.local/lib/python2.7/site-packages/urllib3/poolmanager.py", line 321, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "/home/pi/.local/lib/python2.7/site-packages/urllib3/connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "/home/pi/.local/lib/python2.7/site-packages/urllib3/util/retry.py", line 357, in increment raise six.reraise(type(error), error, _stacktrace) File "/home/pi/.local/lib/python2.7/site-packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/home/pi/.local/lib/python2.7/site-packages/urllib3/connectionpool.py", line 38…
tagged with: telegram
has comment: http://stackoverflow.com/comment/87950502
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/56073984
answer count: 2
has answer: http://stackoverflow.com/a/50468920

http://stackoverflow.com/comment/88425337
score: 0
comment on: http://stackoverflow.com/q/50526458
type: Comment
has text: I am afraid that Silent Order API is actually meant for frontends to directly POST to Cybersource, but first you need to verify it is enabled: [Enable Payer Authentication](http://apps.cybersource.com/library/documentation/dev_guides/Secure_Acceptance_SOP/html/wwhelp/wwhimpl/js/html/wwhelp.htm#href=creating_profile.05.2.html) Can you hint to the motivation you cannot use Simple Order/SOAP ?
type: QuestionComment

http://stackoverflow.com/a/50459821
answers question: http://stackoverflow.com/q/50459203
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87932937
has body: try it , it is like example but it works from bs4 import BeautifulSoup html=""" Ignore this textFind based on this text """ soup = BeautifulSoup(html, 'lxml') s = soup.find('div') for child in s.find_all('b'): child.decompose() print(s.get_text()) Output Find based on this text

http://stackoverflow.com/comment/88011789
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50460719
has text: The original code was really long, include some of tensorflow stuff. But I am certain that it is the matplotlib package that's causing the issue. The code runs without error, if I comment it out.

http://stackoverflow.com/a/50451129
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50446949
has body: Images in 'P' mode require a palette that associates each color index with an actual RGB color. Converting the image to an array loses the palette, you must restore it again. label = PIL.Image.open(dir).convert('P') p = label.getpalette() label = np.asarray(label) img = PIL.Image.fromarray(label, mode='P') img.setpalette(p) img.save('test.png')
score: 2
type: Answer
answers question: http://stackoverflow.com/q/50446949
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87854086
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50418926
type: QuestionComment
has text: @IgnacioVazquez-Abrams I just add my java code to the question

http://stackoverflow.com/a/50587645
has body: The reason you're getting that error is because you're accessing the driver attribute of self when you call the wait_for_page_to_load(self) method. That is, when you're passing in the Firefox webdriver to the method, self is referring to the Firefox webdriver, so it's trying to access the Firefox webdriver's driver attribute, which is incorrect. What you need to do is instantiate a Navigation object so that self is referring to said object and self.driver is referring to the Firefox driver you're passing in. From your code, I'd expect something like this: def before_all(context): # These 4 lines are independent of the Navigation class driver = DriverSetup.get_driver() context.actionwords = Actionwords() base_url = '' driver.get(base_url) # These 2 lines are dependent on the Navigation class # On the right, the Navigation object is instantiated # On the left, the object is initialized to the navigation_driver variable navigation_driver = AutoTools.Navigation(driver) # After, you can call your method since the object's self.driver # was instantiated in the previous line and properly refers to the Firefox webdriver navigation_driver.wait_for_page_to_load()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50535433

http://stackoverflow.com/q/50437901
tagged with: python
has title: Django multiple URL parameters that are agnostic to their order in the URL
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/87889755
type: Question
has comment: http://stackoverflow.com/comment/87889832
has body: I'm building an API which queries a database based on multiple URL filters. In this example there are two parameters which I would like to pass to my views: &lt;tid&gt; and &lt;teams&gt;. Note that in production there would be over 5 different parameters, so I'm trying to avoid brute force solutions. My intended approach was the following regular expression in urls.py url(r'(?P&lt;teams&gt;-?teams=[0-9]*)?(?P&lt;tournaments&gt;-?tid=[0-9]*)?', stats_views.game_query, name='stats_home') This RE successfully matches and passes any URL which is of the form /teams=####-tid=####, and both the teams= and the tid= parameters are optional (this is intended). The problem is that tid= always has to come AFTER the teams= part of the URL. For example if I were to enter the URL /tid=###-teams=###, the &lt;tid&gt; parameter would be passed to views with its intended value, but the &lt;teams&gt; parameter would be passed as None.
tagged with: django
upvote count: 1
tagged with: django-rest-framework
downvote count: 1
has comment: http://stackoverflow.com/comment/87891542
has answer: http://stackoverflow.com/a/50437980
accepted answer: http://stackoverflow.com/a/50437980
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87892168
answer count: 1

http://stackoverflow.com/q/50434746
score: 4
upvote count: 4
answer count: 1
downvote count: 0
tagged with: tfrecord
has answer: http://stackoverflow.com/a/55140106
tagged with: tensorflow
favorite count: 0
type: Question
has title: tensorflow TFRecord k-hot encoding
has body: I am trying to create my training dataset with the TFRecord format following this tutorial : https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/using_your_own_dataset.md for API detection. But, instead of using one hot encoding, I would like to use k-hot encoding. For example instead of having [0 0 0 1 0] labels, I can have [0 1 0 1 0] so multi-classification. I was wondering how to do that with the TFRecord format. Do I have to create two tf.train.example if I use 2-hot encoding ? (using two times the same bouding box coordinates) or is there another way ? (like using for example 'image/object/class/text': dataset_util.bytes_list_feature(classes_text), and 'image/object/class/text2': dataset_util.bytes_list_feature(classes_text2)) ?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/87986559
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50470582
has text: I am doing that in this line of code if you have seen below 'inverted = [label_encoder.inverse_transform([argmax(decoded_imgs[i, :])]) for i in range(len(decoded_imgs))]' but I got the error that I have mentioned above
score: 0

http://stackoverflow.com/q/50496835
has answer: http://stackoverflow.com/a/50499208
tagged with: azure
upvote count: 3
favorite count: 0
has body: I've successfully been using this script to sync passwords for users on our local Samba server and our Office 365. The script uses Azure SDK for Python. I would also like to update the user image/avatar for the users in Office 365 with some script that doesn't need a windows host (like powershell with 365-modules seems to do) but I'm having a hard time navigating the documentation for Azure SDK for Python.
type: Question
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: python
has title: How to change an Office 365 user avatar with Azure SDK for Python
tagged with: avatar
score: 3
linked to: http://stackoverflow.com/q/37396426
tagged with: sdk

http://stackoverflow.com/comment/87992494
has text: Unfortunately this is not it. It’s not like I cannot plot anything. It’s just not the plane that I am expecting to get.
type: Comment
comment on: http://stackoverflow.com/a/50489790
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87843521
type: QuestionComment
has text: Do you want the slow df to be joined to every element in the fast df with the same month?
comment on: http://stackoverflow.com/q/50401241
score: 0
type: Comment

http://stackoverflow.com/comment/87938004
type: Comment
has text: What error are you getting?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50462487

http://stackoverflow.com/q/50474751
downvote count: 7
has answer: http://stackoverflow.com/a/50474783
score: -7
has comment: http://stackoverflow.com/comment/87963162
type: Question
has comment: http://stackoverflow.com/comment/87963423
tagged with: regex
linked to: http://stackoverflow.com/q/2970520
has comment: http://stackoverflow.com/comment/87963116
favorite count: 0
tagged with: python-3.x
has body: I'm having fun with some challenges and one of them makes me count substrings in a string. I have a problem specifically with "banana": str = "banana" print(str.count("ana")) This should return 2 because "ana" appears two times: b a n a n a a n a a n a But str.count("ana") returns only 1. I've also tried with regexp: import re str = "banana" print(len(re.findall("ana", str))) But it also returns 1. Am I missing something? thank you!
upvote count: 0
duplicate of: http://stackoverflow.com/q/2970520
tagged with: count
duplicate of: http://stackoverflow.com/q/37980821
tagged with: python
duplicate of: http://stackoverflow.com/q/42368751
type: UnansweredQuestion
has title: Is str.count() wrong?
answer count: 1

http://stackoverflow.com/a/50414099
downvote count: 0
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87930006
has body: You have to be subscribed to the real time data. You can't ask for 1 min for 14 D, it must be at least '30 mins' You have an error in the HistDetailsHandler where you use msg.contractDetails, the msg is historical data. I don't really understand what you're doing with the wait and use of global variables. You have a valid Contract and then ask for it and then assign it back to itself and then use it for a historical data request. Just request historical data that you're sure you have a subscription for and build from there.
answers question: http://stackoverflow.com/q/50399889
score: 1

http://stackoverflow.com/comment/87962496
type: Comment
comment on: http://stackoverflow.com/q/50474344
score: 0
type: QuestionComment
has text: @CoryKramer what about concatenating arbitrary strings?

http://stackoverflow.com/comment/88026270
comment on: http://stackoverflow.com/a/50506456
has text: Hmm - I still don't quite get it, it's a numpy 2D-array, you can index it however you like. And if you're not happy with it you can still transpose it by `.T`
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50442942
tagged with: list
possible better answer: http://stackoverflow.com/a/50443106
answer count: 3
has answer: http://stackoverflow.com/a/50443135
linked to: http://stackoverflow.com/q/312443
has answer: http://stackoverflow.com/a/50443212
has title: List to Columns (One-Dimensional list, multiple columns)
tagged with: string
has body: I am trying to write a sequence to take a one dimensional list (regardless of size) and print it out in 2 columns. So far, what I have keeps returning an "Index out of range" error. Ideally, I'd like for it to print the [0] index out as the header (which I've written into the sequence already) and then for the rest of the indices to be printed out like this: - - - - - - - - - - - - - - - - - - - - - - - - - NAMES - - - - - - - - - - - - - - - - - - - - - - - - - Rudolph S. Vena U. Josef M. Efrain L. Joye A. Mee H. Joni M. Tanya E. Rachelle L. Garrett H. So far, I have seen a lot of examples of using .zip(*) and other ways of doing something similar but usually involving a 2-dimensional list which I do not have. Does anyone have any idea how this could be improved upon? spacing = '- ' * 25 data_list = [ "NAMES", "Rudolph S.", "Josef M.", "Joye A.", "Joni M.", "Rachelle L.", "Vena U.", "Efrain L.", "Mee H.", "Tanya E.", "Garrett H."] while True: fname_prompt = input("First Name: ").strip().capitalize() if fname_prompt == "List" or fname_prompt == "list" or fname_prompt == "LIST": for item, val in enumerate(data_list): if item == 0: print(spacing) print('{:&gt;27s}'.format(str(data_list[item]))) print(spacing) else: if item &lt;= len(data_list): print('{:&lt;10s}'.format(str(data_list[item]) + '{:&gt;20s}'.format(str(data_list[item +1])))) else: break
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87899869
tagged with: format
has comment: http://stackoverflow.com/comment/87899976
has answer: http://stackoverflow.com/a/50443106
tagged with: python
linked to: http://stackoverflow.com/q/9535954
accepted answer: http://stackoverflow.com/a/50443135
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/88014252
has text: Update the question with the relevant html
comment on: http://stackoverflow.com/q/50500788
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50425841
has body: Making things a bit tidier: a = input("Choose two subjects: ") a = a.split() # define the prices here prices = {'english': 100, 'science': 125, 'stem': 200, 'math': 100} # using list comprehension. What his means: # for all courses in the input, return me their value from the prices-dict # and then sum them up cost = sum(prices[course.lower()] for course in a) print(cost)
has comment: http://stackoverflow.com/comment/87866490
accepted answer of: http://stackoverflow.com/q/50425749
has comment: http://stackoverflow.com/comment/87866383
has comment: http://stackoverflow.com/comment/87888573
has comment: http://stackoverflow.com/comment/87868708
type: Answer
has comment: http://stackoverflow.com/comment/87888146
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87877397
answers question: http://stackoverflow.com/q/50425749
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87881442
has comment: http://stackoverflow.com/comment/87868702

http://stackoverflow.com/q/50397477
has comment: http://stackoverflow.com/comment/87813613
score: 1
tagged with: python
tagged with: macos
favorite count: 0
type: Question
tagged with: python-3.x
has title: (Tensorflow Flow Setup) ImportError: No module named tensorflow
has comment: http://stackoverflow.com/comment/87810836
has body: I'm not able to complete the setup instructions through the Tensorflow documentation using pip3, Python 3.6, and mac Sierra v10.12.6. Attempting to validate the install results in the following: Installing collected packages: protobuf, tensorflow Successfully installed protobuf-3.5.2.post1 tensorflow-1.8.0 You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ➜ python3.6 python Python 2.7.10 (default, Feb 7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named tensorflow &gt;&gt;&gt; import Tensorflow as tf Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named Tensorflow &gt;&gt;&gt; import tensorflow-1.8.0 as tf File "&lt;stdin&gt;", line 1 import tensorflow-1.8.0 as tf ^ SyntaxError: invalid syntax
has answer: http://stackoverflow.com/a/50397643
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87811372
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87810878
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50397643

slice
tags question: http://stackoverflow.com/q/50415516
tag name: slice
tags question: http://stackoverflow.com/q/50494224
tags question: http://stackoverflow.com/q/50523421
type: Tag
tags question: http://stackoverflow.com/q/50514097

http://stackoverflow.com/a/50391817
score: 0
answers question: http://stackoverflow.com/q/50391725
has comment: http://stackoverflow.com/comment/87799478
type: Answer
has comment: http://stackoverflow.com/comment/87805017
has body: You keep reassigning xyz, so it will be whatever you last assigned to it. Since you have one list that you want to transform into a different list, I'd use a list comprehension here: [l.find(i)+1 for i in the_input] # ^ Whatever's here is appended to a new list

http://stackoverflow.com/a/50394217
has comment: http://stackoverflow.com/comment/87804239
has comment: http://stackoverflow.com/comment/87804459
downvote count: 0
has comment: http://stackoverflow.com/comment/87805020
upvote count: 1
has comment: http://stackoverflow.com/comment/87804201
has comment: http://stackoverflow.com/comment/87804909
has comment: http://stackoverflow.com/comment/87805197
has body: max([int(x) for x in a.split()]) This will convert a into a list of ints and find the correct max. Strings are compared char by char, comparing charcodes. max(int(x) for x in a.split()) The above works too, without creating a list, as a generator variant.
has comment: http://stackoverflow.com/comment/87804281
answers question: http://stackoverflow.com/q/50394183
type: Answer
has comment: http://stackoverflow.com/comment/87805145
score: 1

http://stackoverflow.com/comment/88009665
type: Comment
comment on: http://stackoverflow.com/a/50498291
score: 0
type: AnswerComment
has text: I can read `CREATE TABLE`, and I can see the indexes that were magically generated. I can't read Django.

http://stackoverflow.com/comment/88091500
type: QuestionComment
comment on: http://stackoverflow.com/q/50539858
has text: Ok, the code runs, but I don't understand what the code is supposed to *do*. You access increasing indices in `InvoiceList` (because `var = var + 1`), but you only *add* values to `InvoiceList` if the "preorder" radiobutton is checked. One press of the button while "preorder" isn't checked will throw that IndexError.
score: 0
type: Comment

http://stackoverflow.com/q/50390408
tagged with: deadlock
answer count: 0
has title: Python multiprocessing program possible deadlock?
has body: Could some explain to me why this hangs sometimes? (This is just for learning purposes, I wouldn't sum a list like that) import multiprocessing as mp q = mp.JoinableQueue() def worker(): S = 0 while not q.empty(): S += q.get() q.task_done() print(S) procs = [] for i in range(1000): q.put(i) for i in range(2): t = mp.Process(target=worker) t.start() procs.append(t) q.join() for t in procs: t.join()
score: 1
has comment: http://stackoverflow.com/comment/87848765
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87796894
downvote count: 0
upvote count: 1
tagged with: python

qpropertyanimation
tag name: qpropertyanimation
tags question: http://stackoverflow.com/q/50398483
type: Tag

http://stackoverflow.com/q/50514973
type: Question
upvote count: 5
score: 3
has answer: http://stackoverflow.com/a/50515119
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88042501
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50515071
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88042570
tagged with: list
downvote count: 2
accepted answer: http://stackoverflow.com/a/50515119
has answer: http://stackoverflow.com/a/50515288
has body: I have searched the web but I haven't found the answer for my problem: I have a a dictionary with lists as elements and every list has a different length. For example like that: dict_with_lists[value1] = [word1, word2, word3, word4] dict_with_lists[value2] = [word1, word2, word3] My main problem is, that I want to write the list elements in to a file which should be tab-separated and if the list is finished it should write the new list in a new line. I found a solution like that: with open('fname', 'w') as file: file.writelines('\t'.join(i) + '\n' for i in nested_list) But it doesn't only separate the words with tabs but also the characters.
tagged with: file
has title: How to write list elements into a tab-separated file?
has answer: http://stackoverflow.com/a/50515475
has comment: http://stackoverflow.com/comment/88042603
possible better answer: http://stackoverflow.com/a/50515071
favorite count: 0

http://stackoverflow.com/q/50522258
upvote count: 6
has comment: http://stackoverflow.com/comment/88065970
linked to: http://stackoverflow.com/q/29615196
type: AnsweredQuestion
has title: Add multiple csv in a single csv sheet in tabs using Pandas
tagged with: pandas
has body: I have multiple csv files, lets say a.csv , b.csv . I want both a.csv and b.csv in a new c.csv . Both new csv should be in tabs inside as it is. I just want to add both csv in tabs . Is there any short way doing that in pandas. I have the below code with me but its not giving any output ,however its executing . Tried checking few posts in stackoverflow but somehow I did not got the wanted output. Please help me with some better solution. folders=next(os.walk('.'))[1] for host in folders: Path=os.path.join(os.getcwd(),host) all_files = glob.glob(os.path.join(Path, "*.csv")) df_from_each_file = (pd.read_csv(f) for f in all_files) df = pd.concat(df_from_each_file, ignore_index=True) df.to_csv('c.csv,' index=False)
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88056812
has comment: http://stackoverflow.com/comment/88066159
has comment: http://stackoverflow.com/comment/88056926
tagged with: excel
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50553557
has comment: http://stackoverflow.com/comment/88056757
has answer: http://stackoverflow.com/a/50553557
tagged with: http://stackoverflow.com/tag/csv
score: 6
has comment: http://stackoverflow.com/comment/88057973
tagged with: python

http://stackoverflow.com/a/50443864
answers question: http://stackoverflow.com/q/50437670
type: Answer
has body: Your model as it is doesn't learn at all. You are using a VGG16 pre-trained model changing top layers with new layers, for your model to learn your new classes, but later you are making all layers untrainable. This way, your new dense layers will always contain random weights, as their initialization, and your model will never learn. If you want to keep your VGG16 weights freezed and fine tune your model, you should move your freezing layers' weights code before adding your new layers, like this: #Moved here for layer in model.layers: layer.trainable = False # add flatten and two dense layers that don't appear when specifying an input_shape model.add(Flatten()) model.add(Dense(4096)) model.add(Dropout(.5)) model.add(Dense(4096)) model.add(Dropout(.5)) ... Keep in mind that your model may have better results by not freezing any layers. For this, just leave all your layers be trainable.
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87936816
downvote count: 0
has comment: http://stackoverflow.com/comment/87929753

http://stackoverflow.com/q/50433302
tagged with: backend
has comment: http://stackoverflow.com/comment/87881076
has body: Simple example of class which goes into loop class L: def __init__(self): self.data = [] self.current = 0 self.loop() def loop(self): while True: self.data.append(self.current) self.current += 1 time.sleep(2) if __name__ == '__main__': obj = L() How is it possible to access obj.current? Is it possible to create flask app, so that the loop would go in the background, so that query /get would return the obj.current? (For example I have this object connected to Telegram. /start starts the loop, /get should receive obj.current. /start however goes into infinite loop ... )
linked to: http://stackoverflow.com/q/48448453
has comment: http://stackoverflow.com/comment/87881051
answer count: 0
downvote count: 0
has title: How to query python class data while it is in loop
tagged with: loops
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87880995
favorite count: 0
tagged with: python-3.x
tagged with: object
type: Question
has comment: http://stackoverflow.com/comment/87881130
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/87876695
comment on: http://stackoverflow.com/q/50431093
score: 0
type: Comment
type: QuestionComment
has text: But doesn't Colt need to use something like this to access a dictionary within a list . list[0]['first] that is equal to the name rather first and last only. Plus my solution is wrong. Why?

http://stackoverflow.com/q/50388069
has comment: http://stackoverflow.com/comment/87792197
tagged with: wifi
has comment: http://stackoverflow.com/comment/87792035
has title: Check status if Raspberry Pi is connected to any WiFi network (Not Internet necessarily) using Python
has answer: http://stackoverflow.com/a/50388467
favorite count: 0
type: Question
tagged with: raspbian
tagged with: python-3.x
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/68903032
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/53097130
has comment: http://stackoverflow.com/comment/87791748
answer count: 4
has body: I don't want to check if it has Internet connectivity! I just want to check if it's connected to the WiFi network (I'd have already given its SSID in the WPA_supplicant file).. This network won't have Internet access.
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/55308705
has comment: http://stackoverflow.com/comment/87791725

http://stackoverflow.com/comment/87836986
score: 0
comment on: http://stackoverflow.com/a/50410579
has text: So you want data_REF? Just try to assign to variable
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50466932
has title: Difference between csv.reader and .read when importing csv file
downvote count: 1
has comment: http://stackoverflow.com/comment/87947030
favorite count: 0
type: Question
has body: What is the difference in importing csv file with reader and with .read import csv f = open("nfl.csv", 'r') data = csv.reader(f) and using read directly f = open('nfl.csv', 'r') data = f.read()
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50467111
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50467111

http://stackoverflow.com/a/50527469
has body: For better performance is best dont use groupby, better is create final dictionary and map: #get all names with 0 contains_zeros = df.loc[df['value'] == 0, 'name'].unique() print (contains_zeros) ['a' 'b'] #get first non zero values only names with 0 s = df[df['name'].isin(contains_zeros) &amp; (df['value'] != 0)].drop_duplicates('name') print (s) name value 2 a 6 #first non zero dictionary d1 = s.set_index('name')['value'].to_dict() print (d1) {'a': 6} #dictionary with all 0 in name d2 = dict.fromkeys(set(contains_zeros) - set(s['name']), np.nan) print (d2) {'b': nan} #all dictionary without 0 d3 = dict.fromkeys(set(df['name'].unique()) - set(contains_zeros), -1) print (d3) {'c': -1} #merge all together #https://stackoverflow.com/q/38987 d = {**d1, **d2, **d3} print (d) {'a': 6, 'b': nan, 'c': -1} df['calc'] = df['name'].map(d) print (df) name value calc 0 a 0 6.0 1 a 0 6.0 2 a 6 6.0 3 a 8 6.0 4 b 0 NaN 5 b 0 NaN 6 c 5 -1.0 7 c 7 -1.0 Another slowier solution with groupby: def f(x): if (x== 0).all(): return np.nan elif (x == 0).any(): return x[x != 0].iloc[0] else: return -1 df['calc'] = df.groupby('name')['value'].transform(f) print (df) name value calc 0 a 0 6.0 1 a 0 6.0 2 a 6 6.0 3 a 8 6.0 4 b 0 NaN 5 b 0 NaN 6 c 5 -1.0 7 c 7 -1.0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50527264
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50527264

http://stackoverflow.com/comment/88048634
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50517934
type: QuestionComment
has text: You probably have some issue with your target. Also, I can't see where you define it.

http://stackoverflow.com/a/50492140
score: 14
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50491984
answers question: http://stackoverflow.com/q/50491984
type: Answer
has body: One way may be to use defaultdict: from collections import defaultdict my_list = [ {'name': 'AAA', 'date': '2018-05-14', 'price': 20.0}, {'name': 'AAA', 'date': '2018-05-15', 'price': 22.0}, {'name': 'AAA', 'date': '2018-05-16', 'price': 30.0}, {'name': 'BBB', 'date': '2018-05-14', 'price': 15.0}, {'name': 'BBB', 'date': '2018-05-15', 'price': 32.0} ] tmp = defaultdict(list) for item in my_list: tmp[item['name']].append([item['date'],item['price']]) parsed_list = [{'name':k, 'data':v} for k,v in tmp.items()] print(parsed_list) Result: [{'name': 'AAA', 'data': [['2018-05-14', 20.0], ['2018-05-15', 22.0], ['2018-05-16', 30.0]]}, {'name': 'BBB', 'data': [['2018-05-14', 15.0], ['2018-05-15', 32.0]]}]
upvote count: 14

http://stackoverflow.com/comment/112162055
comment on: http://stackoverflow.com/a/50474657
score: 0
type: AnswerComment
type: Comment
has text: Not possible, I think.

http://stackoverflow.com/comment/95050649
comment on: http://stackoverflow.com/a/50433274
type: Comment
type: AnswerComment
score: 4
has text: @Mykhalio - There are other effects as well. For example, in a multi-class problem, XGBoost creates separate trees for each class, so with 3 classes and 10 boosting rounds you might get 30 trees. In summary, that parameter can't be used neither as an upper- nor as a lower- bound.

http://stackoverflow.com/q/50495463
answer count: 1
downvote count: 0
tagged with: excel
favorite count: 0
type: Question
has body: workb = xlsxwriter.Workbook('Newexcel1.xlsx') worksheet1 = workb.add_worksheet("Sheet 1") for row, row_data in enumerate(alldata): worksheet1.write_row(row + 1, 1, row_data) cell_format.set_font_color('vbRed') worksheet1.conditional_format('C2:C7', {'type': 'cell', 'criteria': '==', 'value': 'Data Matched!', 'format': cell_format}) I'm trying to write to an excel file using python. The alldata is list of lists. The problem is that i want to change the color of text in Data Matched to green and Not Matched! to red, which is not happening. The code listed above doesn't show any error but when i open the excel file it asks me to restore previous version as the new one has xml error. alldata = [['My Total', 'Data Matched!', '$824,499,658', '$824,499,658'], ['Second Total', 'Data Matched!', '$824,532,682.20', '$824,532,682.20'], ['Featured Articles', 'Data Matched!', '$391,153,610.55', '$391,153,610.55'], ['Ads Revenue', 'Data Not Matched!', '$825,513,740.17', '$825,582,419.92'], ['Company 1 Revenue', 'Data Not Matched!', '$824,765,286.03', '$824,833,965.78'], ['Company 2 Revenue', 'Data Not Matched!', '$176,767,751.61', '$239,939,801.89']]
has title: Unable to change font color in excel using python xlsxwriter
tagged with: python
accepted answer: http://stackoverflow.com/a/50496641
has answer: http://stackoverflow.com/a/50496641
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2

http://stackoverflow.com/a/55427458
answers question: http://stackoverflow.com/q/50504053
type: Answer
score: 46
has body: Replace the below line of code ax = plt.axes(axisbg='#E6E6E6') with ax = plt.axes(facecolor='#E6E6E6')
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50504053
upvote count: 46

http://stackoverflow.com/a/50532664
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88077454
has comment: http://stackoverflow.com/comment/88077512
has comment: http://stackoverflow.com/comment/88077398
has body: If you do want to use numpy: b = np.array(a)[:, 0, :] This will be faster than a comprehension. Well... I certainly thought it would be a = np.random.random((100_000, 1, 2)).tolist() %timeit np.array([x[0] for x in a]) 41.1 ms ± 304 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit np.array(a)[:, 0, :] 57.6 ms ± 1.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit x = np.array(a); x.shape = len(a), 2 58.2 ms ± 381 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) edit Oh if its a numpy array then definitely use this method. Or use .squeeze() if you're sure it's not empty.
answers question: http://stackoverflow.com/q/50532583
has comment: http://stackoverflow.com/comment/88077568
type: Answer
accepted answer of: http://stackoverflow.com/q/50532583
score: 3
upvote count: 3

http://stackoverflow.com/a/50457098
score: 1
answers question: http://stackoverflow.com/q/50455088
type: Answer
has comment: http://stackoverflow.com/comment/87941151
downvote count: 0
has comment: http://stackoverflow.com/comment/87928953
upvote count: 1
has comment: http://stackoverflow.com/comment/87960963
has body: Yes you can have different lengths; however, you need a layer that can handle varying lengths. For example, you can use an LSTM to process the sentences of varying lengths by setting input_shape=(None, vocab_size) where None indicates an unknown number of words. You still need to pad the sequences to same length, using pad_sequences in utils. Then you need to use a Masking layer to tell the LSTM that those entries are to be skipped. If you just set to -1 and not mask then you'll introduce bias based on the length of sentences in the training set.
has comment: http://stackoverflow.com/comment/87960564

http://stackoverflow.com/q/50394393
score: 0
tagged with: list
answer count: 2
has title: What is the proper way to update Python list?
has comment: http://stackoverflow.com/comment/87804765
has comment: http://stackoverflow.com/comment/87806221
has comment: http://stackoverflow.com/comment/87804927
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/87804965
has comment: http://stackoverflow.com/comment/87890747
has comment: http://stackoverflow.com/comment/87805605
type: UnansweredQuestion
has body: I tried this: listing = [] entry = [0.0]*2 entry[0] = 1.0 entry[1] = 2.0 listing.append(entry) # My first entry entry[0] = 2.0 entry[1] = 3.0 listing.append(entry) # Another entry The above does not work. The same entry pointer is retained, so updating the entry also updates the [1.0, 2.0] entry of the listing. I can get it to work with this: entry[0] = 1.0 entry[1] = 2.0 listing.append(entry) # My first entry entry = [0.0]*2 entry[0] = 2.0 entry[1] = 3.0 listing.append(entry) # Another entry entry = [0.0]*2 But that seems clunky. Is there a cleaner way of doing this? Update: (Which cuts through the chatter of the question this duplicates) The best way to do this, at least for Python 3.X users, is: listing.append(entry.copy())
has answer: http://stackoverflow.com/a/50394481
tagged with: python
has comment: http://stackoverflow.com/comment/87804882
has answer: http://stackoverflow.com/a/50394482
has comment: http://stackoverflow.com/comment/87805062
has comment: http://stackoverflow.com/comment/87804719

http://stackoverflow.com/comment/88029300
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50508701
has text: The above numpy solution should be set at the top of the script.

http://stackoverflow.com/a/54750012
answers question: http://stackoverflow.com/q/50463767
has body: According to the OCBC API documentation, it only works if the sender is an OCBC account holder. I'd assume likewise for the DBS one. To date, I am still unable to find an universal API for do
type: Answer
score: 0

http://stackoverflow.com/comment/87901954
has text: Thanks @Kasramvd, makes perfect sense.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50443781

http://stackoverflow.com/a/50423142
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50422711
type: Answer
has body: You need to install bs4 and requests first. Open cmd and write: pip install bs4 pip install requests Then here is your code. from bs4 import BeautifulSoup import requests r = requests.get('your website') source = r.content soup = BeautifulSoup(r.content, 'lxml') altlinks = [] imgalt_list = [1, 10, 13, 32, 36] for x in soup.find_all('img', alt= True): #we find all img alt names if x['alt'] in imgalt_list: #if alt name matchs with your numbers altlinks.append(x.get('src')) #adding into list print(altlinks) You can ask any part which you don't understand.

http://stackoverflow.com/comment/87893034
score: 1
type: Comment
has text: @Jayjayyy After looking into things a bit more, I can see how running through `evalf_subs` _could_ make a difference (see updated answer), but I still can't prove that this is why it _does_ make a difference here. Someone would probably need to debug (or grub through the source) a lot deeper to be sure. Is this sufficient, or do you need more?
type: AnswerComment
comment on: http://stackoverflow.com/a/50439201

http://stackoverflow.com/comment/87811398
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50397770
type: AnswerComment
has text: However, I like your detailed explanation of the parts.

http://stackoverflow.com/comment/87963056
score: 0
has text: replace @QtCore.Slot() with @QtCore.pyqtSlot() See http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html#the-pyqtslot-decorator
type: QuestionComment
comment on: http://stackoverflow.com/q/50459672
type: Comment

http://stackoverflow.com/comment/95192338
comment on: http://stackoverflow.com/a/50490037
type: Comment
type: AnswerComment
has text: @Ernie Halberg, kind sir, did you figure out how to get the sample weight working in either xgboost or lightgbm. I followed the guide on this post using the latest xgboost (0.81) and it still does what you observed - i.e. it starts at 0.5 and drops from there. Even the native API does not seem to work as intended.
score: 0

http://stackoverflow.com/q/50416391
tagged with: django
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50416659
has title: 'caching_sha2_password' plugin failing on Windows
has comment: http://stackoverflow.com/comment/90248260
tagged with: windows
linked to: http://stackoverflow.com/q/49194719
tagged with: mysql
tagged with: web
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has body: I am currently trying to create a web application with Python's Django framework, while creating the databases through MySQL. I am running Windows 10, Django 2, Python3.6, and MySQL 8. I have tried many fixes but nothing seems to work. When I try to run test cases or run the server locally, I receive the same error: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n")
duplicate of: http://stackoverflow.com/q/49194719
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51295635
downvote count: 0

http://stackoverflow.com/a/50531960
has body: You can use a nonconditional initializer, e.g. with get, to get rid of the warning: TEST = globals().get('TEST', 'test') print(TEST)
answers question: http://stackoverflow.com/q/50531898
score: 7
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50531898
upvote count: 7
has comment: http://stackoverflow.com/comment/88076577
type: Answer

http://stackoverflow.com/a/50537687
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50537636
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50537636
has body: &gt;&gt;&gt; unicodedata.normalize('NFC', 'a\u0301') 'á' &gt;&gt;&gt; unicodedata.normalize('NFC', 'a\u0301').encode('unicode-escape') b'\\xe1'

http://stackoverflow.com/q/50474790
favorite count: 0
has title: Quick way to add a key to every value in a list
type: Question
accepted answer: http://stackoverflow.com/a/50474820
has body: Let's say I have a list of elements tagsList = ['dun', 'dai', 'che'] How do I convert the above into the following? tagsDictionaries = [ { 'name': 'dun' }, { 'name': 'dai' }, { 'name': 'che' } ] I want to do this with a for loop
upvote count: 0
has answer: http://stackoverflow.com/a/50475028
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/50475450
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50475028
answer count: 3
has answer: http://stackoverflow.com/a/50474820
downvote count: 3

http://stackoverflow.com/comment/87878765
type: QuestionComment
has text: Take a look at the `str.lstrip` method. But really, it would be better to avoid using `eval`, it's just too dangerous.
comment on: http://stackoverflow.com/q/50432207
score: 0
type: Comment

http://stackoverflow.com/comment/87913852
type: Comment
comment on: http://stackoverflow.com/a/50449316
score: 0
type: AnswerComment
has text: @JanardhanReddy.Meeniga if you've fixed the issue don't forget to close the question

http://stackoverflow.com/comment/88082697
score: 0
comment on: http://stackoverflow.com/q/50535182
type: Comment
type: QuestionComment
has text: For me it even goes above the button. Odd. Seems like a bug.

http://stackoverflow.com/comment/87938642
comment on: http://stackoverflow.com/q/50461995
type: Comment
type: QuestionComment
has text: @kvmahesh can you please elaborate more on how to select env in PyCharm and how to find settings in env
score: 0

http://stackoverflow.com/comment/87983784
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50484270
score: 0
has text: Are you generating the points using `boundingRect()` because you need to use `minAreaRect()`if you want to consider rotated boxes... see 7b... https://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html

http://stackoverflow.com/comment/88008992
has text: Which query in your code is causing the error? What permissions do you have attached to the role that your code is using? (Presumably, a role attached to an EC2 instance?)
comment on: http://stackoverflow.com/q/50492748
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87806891
has text: Uhm, no, integrating 1-dimensional, nicely bounded, infinitely differentiable functions with rapidly decaying derivatives with Monte-Carlo is indeed a *very* bad idea. But where did you get the idea that trapezium rule isn't complete garbage either? There are much better methods for numerical integration. What's wrong with [`scipy.integrate`](https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html)?
comment on: http://stackoverflow.com/q/50395475
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50457907
has body: Since you wanted to keep the code you had, you can use the operator module to map an operator to a variable. So instead of setting symbol to "&lt;" or ">", you could do this (where gt is greater than and lt is less than) import operator if order == 'ascending': op = operator.gt elif order == 'descending': op = operator.lt and this if op(alist[position], alist[position + 1]): LB, UB = UB, LB alist.remove(alist[position + 1]) alist.insert(position, LB) swapmade = True
accepted answer of: http://stackoverflow.com/q/50457703
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50457703
score: 1
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/87954187

http://stackoverflow.com/q/50425774
score: 1
linked to: http://stackoverflow.com/q/23016158
favorite count: 0
type: Question
has title: wand.py strange behavior with gifs rescaling
answer count: 0
has comment: http://stackoverflow.com/comment/90935317
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90993252
has comment: http://stackoverflow.com/comment/90933570
has body: I want to make script which liquid-rescales GIFs frame by frame, but I stuck into the problem. Every time it just distorts image, and it looks like previous frame isnt disposed. I used this answer as base for my script: In [19]: with Image() as result: ...: with Image(filename='file.gif') as source: ...: for frame in source.sequence: ...: x, y = frame.width, frame.height ...: frame.liquid_rescale(x//2, y//2) ...: frame.resize(x, y) ...: result.sequence.append(frame) ...: result.save(filename='res.gif') Here is source image: http://maxlunar.insomnia247.nl/files/file.gif And my result image: http://maxlunar.insomnia247.nl/files/res.gif I'm not sure how do I fix that mess. Also I plan to do all manipulations with images in memory (I download them from URLs right into io.BytesIO object, and this is required because I plan to use it in multithreaded application, so it should be thread/process-safe). Thanks in advance.
upvote count: 1
tagged with: python
tagged with: imagemagick
tagged with: wand

http://stackoverflow.com/a/50453870
accepted answer of: http://stackoverflow.com/q/50453772
type: Answer
answers question: http://stackoverflow.com/q/50453772
has body: There is no need to define query params in URL. Below url is enough to work. path('navigator/', views.GhNavigator, name='navigator') Let you called URL http://localhost:8000/navigator/?search_term=arrow then you can get search_term by request.GET.get('search_term').
type: AcceptedAnswer
downvote count: 0
score: 9
upvote count: 9

http://stackoverflow.com/a/50427599
answers question: http://stackoverflow.com/q/50427501
has body: Not using for, but doing by hand with a while loop: n = len(a) i = 0 while i &lt; n: ... if someCondition: n = len(a) i = 0 continue i+=1 edit - if you're just appending to the end, do you really need to start over? You can just move the finish line further, by comparing i to len(a) directly, or calling n=len(a) in your loop
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/50485756
has body: Hi I am trying to insert json files into mongoDb.I have written the code and is working fine for me. import sys, json, pymongo,glob from pymongo import MongoClient from bson import json_util from multiprocessing.sharedctypes import template from json.decoder import JSONDecodeError from itertools import count connection = MongoClient('localhost',27017) db = connection.Mysample mycollection = db.Mynewsample folder = 'C:/ESRILKA/Cloud Team/Tmobile/JSON To CSV Files/JSON files/*.json' jsonFiles = glob.glob(folder) for file in jsonFiles: with open(file) as template: try: template_dct=json.load(template) result = db.Mynewsample.insert_one(template_dct) print('Inserted post id %s ' % result.inserted_id) except (ValueError, KeyError, TypeError) as e: print("Invalid json at") pass But now i would like to validate the json file before inserting.That is if the json is not valid it should show a message saying"parsing failed etc.."
has title: Python:when I try to insert JSON file into Mongodb,if the json file is not valid its throwing an error.how to catch the error
has comment: http://stackoverflow.com/comment/87984461
has comment: http://stackoverflow.com/comment/87984593
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50485951
has comment: http://stackoverflow.com/comment/87984473
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87984571
score: 1
tagged with: pymongo
accepted answer: http://stackoverflow.com/a/50485951
favorite count: 0
type: Question
tagged with: mongodb

ocr
tags question: http://stackoverflow.com/q/50494991
tag name: ocr
type: Tag

http://stackoverflow.com/a/50548698
has comment: http://stackoverflow.com/comment/89571089
has comment: http://stackoverflow.com/comment/89570833
type: Answer
has comment: http://stackoverflow.com/comment/89571015
has comment: http://stackoverflow.com/comment/89570957
score: 0
answers question: http://stackoverflow.com/q/50525752
has comment: http://stackoverflow.com/comment/89570769
has comment: http://stackoverflow.com/comment/89570917
has comment: http://stackoverflow.com/comment/89570933
has body: You can pass a case_insensitive option to your Bot when you create it. from discord.ext import commands bot = commands.Bot('!', case_insensitive=True) @bot.command(pass_context=True) async def ping(ctx): msg = 'Pong {0.author.mention}'.format(ctx.message) await bot.say(msg)

http://stackoverflow.com/comment/87846391
comment on: http://stackoverflow.com/a/50400967
type: Comment
has text: Yes, the challenge was to figure out column widths generically. I've used file formats like this before and didn't even think to mention that's what I was doing. Its useful to point it out!
score: 0
type: AnswerComment

http://stackoverflow.com/a/50387435
upvote count: 1
has comment: http://stackoverflow.com/comment/88020735
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87790511
downvote count: 1
has comment: http://stackoverflow.com/comment/88020122
answers question: http://stackoverflow.com/q/50387337
has comment: http://stackoverflow.com/comment/98537665
has comment: http://stackoverflow.com/comment/87790377
type: Answer
accepted answer of: http://stackoverflow.com/q/50387337
has body: myVar = True # default value def myFunct(): global myVar myVar= False myFunct() print(myVar) Output: False Explanation: When you want to access the global variable inside a function access that variable using "global" keyword. And then you can update that variable.
has comment: http://stackoverflow.com/comment/87790539
score: 0

http://stackoverflow.com/comment/87844033
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50414136
type: QuestionComment
has text: Please provide a minimal working example...

http://stackoverflow.com/comment/88093001
type: QuestionComment
has text: I want the user to enter in their phone number and then a text message is sent after a batch render is finished. I have the rest of the code (not shown) I just need to add a valuable for the phone number.
comment on: http://stackoverflow.com/q/50540414
score: 0
type: Comment

http://stackoverflow.com/comment/112157300
type: Comment
comment on: http://stackoverflow.com/a/50474657
type: AnswerComment
has text: Using this approach, how can I pass individual callbacks to each model?
score: 0

http://stackoverflow.com/comment/87981868
comment on: http://stackoverflow.com/q/50484358
has text: You are trying to take `modelsOne[3071]`. How many elements does `modelsOne` have?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88273639
has text: Wow thank you Diziet, this is really helpful!! I would like to be able to compare marker types in collections and lines. Is there a similar method for lines where the output is a path such as this one?
comment on: http://stackoverflow.com/a/50535806
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87801818
has text: category: AAAA rule: KW1&KW2&NOTKW3 how can from such records, build the keyword tuple you mentionned ? i'm so sorry, i'm debutant in python
type: Comment
comment on: http://stackoverflow.com/a/50389624
score: 0
type: AnswerComment

http://stackoverflow.com/a/50529963
upvote count: 2
has body: That's a concatenation of a tuple. &gt;&gt;&gt;(5,)*2 (5,5) &gt;&gt;&gt;(5,)*5 (5,5,5,5,5)
downvote count: 0
has comment: http://stackoverflow.com/comment/88074879
answers question: http://stackoverflow.com/q/50529846
has comment: http://stackoverflow.com/comment/88075173
type: Answer
score: 2

http://stackoverflow.com/a/50538283
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50535102
has body: In Windows, there are Unicode and ANSI versions of functions. The documentation indicates the filename is an LPCTSTR. For the ANSI version that is defined as LPCSTR and for Unicode it is LPCWSTR. Here's the proper way to call a Windows function. Generally you want the W version of the function. Defining .argtypes and .restype will also help with error checking. As you found, you can pass the wrong type and it will not work. With .argtypes defined, incompatible types will be caught. from ctypes import * from ctypes import wintypes as w dll = WinDLL('winmm') dll.PlaySoundW.argtypes = w.LPCWSTR,w.HMODULE,w.DWORD dll.PlaySoundW.restype = w.BOOL SND_FILENAME = 0x20000 # Call it with a Unicode string and it works. dll.PlaySoundW('sound.wav',None,SND_FILENAME) # Call it with a byte string and get an error since `.argtypes` is defined. dll.PlaySoundW(b'sound.wav',None,SND_FILENAME) Output (after sound plays): Traceback (most recent call last): File "C:\test.py", line 15, in &lt;module&gt; dll.PlaySoundW(b'sound.wav',None,SND_FILENAME) ctypes.ArgumentError: argument 1: &lt;class 'TypeError'&gt;: wrong type Or skip all that work and just use the winsound module: import winsound winsound.PlaySound('sound.wav',winsound.SND_FILENAME)
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50535102

http://stackoverflow.com/a/51317201
has body: I had the same issue, something wrong with cryptography. Try sudo pip install --upgrade cryptography
type: Answer
answers question: http://stackoverflow.com/q/50506221
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/50419432
has answer: http://stackoverflow.com/a/50419844
accepted answer: http://stackoverflow.com/a/50419844
tagged with: python
score: -1
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
downvote count: 2
has comment: http://stackoverflow.com/comment/87857234
has comment: http://stackoverflow.com/comment/87870916
upvote count: 1
has body: I have two text files which contains the data as shown below and I want to display the output in the format described in Python. I am using PyCharm IDE with Python 3.0. I also tried using the dictionary and list in Python but I was not able to get it correctly. [File1.txt] 2|Stacey|Tucker 4|Simi|Mirza 9|Naved|Singh 6|Ram|Patel 7|Joe|Pruth [File2.txt] 2|26 6|17 9|30 4|31 7|35 print output desired: 2 Tucker,Stacey 26 4 Mirza,Simi 31 9 Singh,Naved 30 6 Patel,Ram 17 7 Pruth,Joe 35 Can anybody give me a suggestion?
has title: Querying multiple text files to merge the columns and show output using Python
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87854400

http://stackoverflow.com/comment/87801044
type: Comment
comment on: http://stackoverflow.com/a/50389267
type: AnswerComment
has text: Thank's ! Didn't know that a label2 existed ! Thank's again.
score: 0

http://stackoverflow.com/comment/87921713
type: QuestionComment
type: Comment
has text: @AGNGazer I am open to keeping just the first occurrence in this case.
comment on: http://stackoverflow.com/q/50453416
score: 0

http://stackoverflow.com/comment/87944895
has text: Could you please clarify why your solution works and the code in the question doesn't?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50465905

http://stackoverflow.com/comment/87957596
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50467781
score: 0
has text: https://stackoverflow.com/users/978961/dirn you mean return statements can breaks any loop?

http://stackoverflow.com/comment/87956730
has text: @chrisz Can you please lift your negative input to question , I removed the screenshot and updated as text :) Thank You .
type: QuestionComment
comment on: http://stackoverflow.com/q/50454658
score: 0
type: Comment

http://stackoverflow.com/comment/88084371
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50535957
score: 0
has text: You're right. But I just want to understand what is going on in the background. Perhaps I could put the question a bit more general: is it okay if the `doWork()` function accesses variables that were instantiated in the main QApplication thread?

http://stackoverflow.com/q/50401550
upvote count: 1
has comment: http://stackoverflow.com/comment/87818974
favorite count: 0
has answer: http://stackoverflow.com/a/50401598
tagged with: django-models
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50404749
type: Question
has body: I've got a category field in my model which I want to remove. However it did not have null=True so (from previous experience) deleting it will cause a django.db.utils.IntegrityError: null value in column “category” violates not-null constraint error. Any way around this? Here's is the field: class Post(models.Model): ... category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1')
answer count: 2
has comment: http://stackoverflow.com/comment/87820641
has title: How to remove a non-nullable field in Django?
type: UnansweredQuestion
downvote count: 0
tagged with: django

http://stackoverflow.com/a/50435957
has comment: http://stackoverflow.com/comment/87886052
type: Answer
answers question: http://stackoverflow.com/q/50435931
has comment: http://stackoverflow.com/comment/87886184
has comment: http://stackoverflow.com/comment/87886088
has comment: http://stackoverflow.com/comment/87886033
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50435931
has body: You are making it way harder than it needs to be. Use the denominator attribute of the Fraction instance: frac = Fraction(z) if frac.denominator &gt; 2: print(z) else: print(frac) You may want to use the Fraction.limit_denominator() method to account for the imprecise nature of floats: frac = Fraction(z).limit_denominator() if frac.denominator &gt; 2: print(z) else: print(frac) Fraction.limit_denominator() finds the closest fraction to the original where the denominator is limited be below 1 million: &gt;&gt;&gt; from fractions import Fraction &gt;&gt;&gt; 2/3 0.6666666666666666 &gt;&gt;&gt; Fraction(2/3) Fraction(6004799503160661, 9007199254740992) &gt;&gt;&gt; Fraction(2/3).limit_denominator() Fraction(2, 3) Another alternative is to pass the user input straight to Fraction(); the constructor accepts both valid values for float() and strings in the form of numerator / denominator (with optional sign). This would let your users input exact fractions such as '2 / 3': z = Fraction(input()).limit_denominator() if frac.denominator &gt; 2: print(float(z)) else: print(frac)
score: 1

http://stackoverflow.com/comment/87851239
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50416446
has text: Call it with something like `button_e(button_argument, pressed_argument)`.
type: QuestionComment

http://stackoverflow.com/comment/87870455
type: Comment
comment on: http://stackoverflow.com/a/50427350
type: AnswerComment
has text: Can you also help me which tutorial is best to start with basic and advanced python?
score: 0

http://stackoverflow.com/q/50410189
downvote count: 0
accepted answer: http://stackoverflow.com/a/50410911
upvote count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/50410911
has body: I have problem understanding the output shape of the weights' matrix in Keras. I have a simple BiLSTM like the following: model = Sequential() model.add(Embedding(vocab_size, embedding_size, input_length=55, weights=[pretrained_weights])) model.add(Bidirectional(LSTM(units=embedding_size))) model.add(Dense(5926, activation='softmax')) # number of classes print(model.summary()) weights = model.layers[-1].get_weights() print(weights) print(len(weights)) print(weights[0][0].shape) print(weights[0][0]) for e in zip(model.layers[-1].trainable_weights, model.layers[-1].get_weights()): print('Param %s:\n%s' % (e[0],e[1])) model.compile(loss='categorical_crossentropy', optimizer = RMSprop(lr=0.0005), metrics=['accuracy']) model.fit(np.array(X_train), np.array(y_train), epochs=100, validation_data=(np.array(X_val), np.array(y_val))) If I print the shape of the last layers' weights, I get this: Param &lt;tf.Variable 'dense_14/kernel:0' shape=(200, 5926) dtype=float32_ref&gt;: so the shape is (200, 5926). Which is the number of neurons in my network by the number of classes. I would like to find a way to extract the weights associated with each prediction, because then I need to update the weights matrix. My test set is composed my 680 sentences, where I have 1 label per sentence. The predictions have the following shape: predictions = model.predict(np.array(X_test)) # shape predictions = (680, 5926) Is there a way to extract from the softmax layer the weights for each prediction (with shape=(680,5926)? Like: predictions = [probability_class_1, probability_class_2,......, probability_class_5926] weights = [weight_class_1, weight_class_2, ......., weight_class_5926]
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87835983
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/87836685
has title: How to extract weights from softmax layer?
tagged with: lstm
type: AnsweredQuestion
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87836675

http://stackoverflow.com/a/50481742
accepted answer of: http://stackoverflow.com/q/50481242
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: In Python 2, whenever you mix a unicode and a str in the same expression, it has to decode() the str or encode() the unicode automatically to make them work. And it does this using your default encoding, which is usually 'ascii'. So, if any of your strings aren't ASCII, you get an error like this. One place this happens is when you call format on a unicode object and pass it a str value to be formatted: &gt;&gt;&gt; u'{}'.format('abc') u'abc' &gt;&gt;&gt; u'{}'.format('abc\xe9') UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 3: ordinal not in range(128) And notice that you have a line just like this in your code. Obviously, that task.status_text() is returning a string that isn't ASCII, just like the 'abc\xe9' in my simpler example. To fix this, you either need to be careful to always use one type consistently: &gt;&gt;&gt; print '{}'.format('abc\xe9') abcé Ideally, you can configure your database interface to return unicode instead of encoded str in the first place: &gt;&gt;&gt; print u'{}'.format(u'abcé') abcé If not, you need to make the decode or encode explicit, so you can specify the right encoding: &gt;&gt;&gt; print u'{}'.format('abc\xe9'.decode('latin-1')) abcé Of course I have no idea where your status_text is coming from, so I have no idea whether it's Latin-1. (In fact, UTF-8 is probably more likely.) But you should know, or be able to look it up or otherwise find out. If you think this is a huge pain… well, that's exactly why Python 3 was invented over a decade ago. All of these problems will go away as soon as you decide to upgrade.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50481242

http://stackoverflow.com/q/50397321
tagged with: python
has answer: http://stackoverflow.com/a/50421596
has body: I am using seq2seq to train a language model on some english words not found in the dictionary. But when I train the model on a phonetic dictionary I get these warnings, then the model wont recognize the words after training because it cant recognize these letters. WARNING:tensorflow:Invalid symbol:A WARNING:tensorflow:Invalid symbol:O WARNING:tensorflow:Invalid symbol:O WARNING:tensorflow:Invalid symbol:C WARNING:tensorflow:Invalid symbol:I WARNING:tensorflow:Invalid symbol:A WARNING:tensorflow:Invalid symbol:O WARNING:tensorflow:Invalid symbol:O WARNING:tensorflow:Invalid symbol:C WARNING:tensorflow:Invalid symbol:C WARNING:tensorflow:Invalid symbol:I WARNING:tensorflow:Invalid symbol:E WARNING:tensorflow:Invalid symbol:C WARNING:tensorflow:Invalid symbol:O WARNING:tensorflow:Invalid symbol:I WARNING:tensorflow:Invalid symbol:I WARNING:tensorflow:Invalid symbol:E WARNING:tensorflow:Invalid symbol:E WARNING:tensorflow:Invalid symbol:E WARNING:tensorflow:Invalid symbol:O WARNING:tensorflow:Invalid symbol:O Any help would be appreciated Thanks in advance.
tagged with: cmusphinx
type: AnsweredQuestion
score: 0
has title: tensorflow Invalid symbol
answer count: 1
tagged with: tensorflow
tagged with: speech-recognition
type: Question
accepted answer: http://stackoverflow.com/a/50421596

http://stackoverflow.com/comment/87938858
has text: added full views, urls and traceback to the main post, btw whenever I change arguments in this function there's always something missing, mainly objects and CD
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50462306
type: Comment

http://stackoverflow.com/q/50447564
type: UnansweredQuestion
tagged with: odoo-9
tagged with: python
has body: I would like to generate an automatic report and on the first of every month send it to specific email using email template. I am thinking to use: ir.cron object for automatically calling method on the first of every month stock.location object with get_data() method for getting data mail.template object for sending data for specific user by email. I wrote get_data() method to get power_difference values from all the locations. The problem is when I am calling send_mail() method. I get my self.id variable equal to False so as I understand mail template can't be rendered. What am I doing wrong? I am getting everything I need from get_data() method but the problem is how to pass records value to mail template and send the email. get_data() method: @api.model def get_data(self): locations = self.env['stock.location'].search([('id','child_of',[361]),('usage','=','view')] records=[] location_power_changes={} for location in locations: power = location.power location.power_difference = location.last_month_power - power location.last_month_power = power location_changes['power_difference'] = location.power_difference records.append(location_power_changes) template = self.env.ref('t_stock.email_template_1') self.env['mail.template'].browse(template.id).send_mail(self.id) mail template <?xml version="1.0" encoding="UTF-8"?> T example@mail.com example1@mail.com Test T1 % if object.get_data(): % for values in object.get_data() ${values['power_difference']} % endfor % endif
has comment: http://stackoverflow.com/comment/87934129
tagged with: http://stackoverflow.com/tag/xml
upvote count: 2
score: 2
answer count: 0
downvote count: 0
tagged with: odoo-10
has title: Odoo create an automatic report and send it to specific user using email template
tagged with: jinja2
favorite count: 0
type: Question

http://stackoverflow.com/comment/87929966
type: QuestionComment
has text: What were you expecting?
score: 0
comment on: http://stackoverflow.com/q/50458200
type: Comment

http://stackoverflow.com/q/50505214
tagged with: python
has comment: http://stackoverflow.com/comment/88023864
has comment: http://stackoverflow.com/comment/88022672
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88023905
upvote count: 3
has title: argparse with multiple subparsers and positionals
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50506796
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88023956
has answer: http://stackoverflow.com/a/50506796
has body: Let's say I have a script, select_libs.py, which enables you to choose which libraries to include in some build process. When running this script I want to be able to specify the library name, branch and version. Here are some use cases. select_libs.py Use script defaults when positionals are not defined. select_libs.py opencv stable 3.4.1 select_libs.py opencv stable 3.4.1 boost development 1.67.0 So I imagine something as simple as this: import argparse branches = ["legacy", "stable", "development"] parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='lib configuration') opencv_parser = subparsers.add_parser("opencv") opencv_parser.add_argument("opencv_build", choices=branches) opencv_parser.add_argument("opencv_version", type=str) boost_parser = subparsers.add_parser("boost") boost_parser.add_argument("boost_build", choices=branches) boost_parser.add_argument("boost_version",type=str) cmd_options = parser.parse_args() The first two use cases both work, but the third: select_libs.py opencv stable 3.4.1 boost development 1.67.0 produces this error: error: unrecognized arguments: boost development 1.67.0 In my head, this should work since each parser have exactly two positional arguments, so it should know that boost is not an argument to opencv and trigger the boost parser accordingly. Clearly I'm wrong, but what have I missed and how can I make it work as intended (if possible)? My current Python version is 3.5.2.
score: 3
linked to: http://stackoverflow.com/q/48504770

http://stackoverflow.com/comment/128637478
type: AnswerComment
comment on: http://stackoverflow.com/a/57053415
has text: Adding to what @Briareos386 said, `python-certifi-win32` currently breaks `pip` if you are using Python 3.10 on Windows.
score: 2
type: Comment

http://stackoverflow.com/comment/117601398
comment on: http://stackoverflow.com/q/50492017
has text: @DucNguyen did you find a solution?
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/87980009
has text: If you take a look at rest of the output you see that the problem misn't `spacy`, but `preshed`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50483235
score: 0
type: Comment

http://stackoverflow.com/comment/88066381
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50527345
score: 0
has text: can you maybe add the error you get and please put the code sample into text instead of using screenshots

http://stackoverflow.com/comment/87833685
has text: I mean run git bisect on Django to find the change in Django that causes your test to fail.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50407780
type: Comment

http://stackoverflow.com/a/50505229
score: 0
answers question: http://stackoverflow.com/q/50483796
type: Answer
has body: Thanks for your answers. Finally, I found the problem, I was setting this env variables with running a subprocess that execute another script, when I set this env vars from the script without a subprocess, it works and the two methods works :)

http://stackoverflow.com/q/50474250
score: 0
tagged with: python-3.5
answer count: 1
has comment: http://stackoverflow.com/comment/87963167
has comment: http://stackoverflow.com/comment/87962059
has title: Returning a value from a method in python
has body: I'm coming from perl to python, and this question seems to be ungoogleable for the clutter of unrelated examples. I'm trying to make a fast lookup index for a variable length list of objects. The objects can be returned by name or number. The methods byname and bynum are throwing a syntax error at "return" What am I doing wrong here? Thanks in advance! class BookSumIndex(): bookptr = 0 BookSum = []; # object container ByName = {} # named referent to objects ByNum = {} # numerical referent to objects def addbook(self,thisbook,bookname,booknum): self.BookSum.insert(self.bookptr,BookSumObject()) namepair = {bookname:self.bookptr} numpair = {booknum:self.bookptr} self.ByName.update(namepair) self.ByNum.update(numpair) self.bookptr += 1 def byname(self,bookname): bnam = self.ByName.get(bookname) if type(bnam) != "NoneType": thisbook = self.BookSum.get[int(bnam)] return thisbook def bynum(self,booknum): bnum = self.ByNum.booknum if type(bnum) != "NoneType": thisbook = self.BookSum[self.ByNum.get[int(bnum)] return thisbook
type: Question
has answer: http://stackoverflow.com/a/50474420
has comment: http://stackoverflow.com/comment/87962062
tagged with: python
has comment: http://stackoverflow.com/comment/87962524
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50474420
has comment: http://stackoverflow.com/comment/87962392

http://stackoverflow.com/comment/87960487
type: QuestionComment
comment on: http://stackoverflow.com/q/50473224
score: 0
has text: yes, this is what i am confused as most examples show something similar(i have even mentioned a link in my question). according to me using a class here is an overkill and a simple function would be enough.but are there any cases in which i might need a class to create a factory?
type: Comment

http://stackoverflow.com/q/50436311
has body: I'm new to python and pyspark. I'm working with a code that runs on pyspark that builds a tfidfs model. However when calling the ngrams method of the famous Pattern library an UnboundLocalError is triggered. This the text data layout it's (id ,list[text]) extracted by text.map(lambda x: (x["_id"], (x["span"], x["text"]))).groupByKey().map(lambda x: (x[0], list(x[1])): [(u'en.wikipedia.org/wiki/Woodville_South,_South_Australia', [u'Campbell was born in Myrtle Bank.']), (u'en.wikipedia.org/wiki/Picket_(military)', [u'The film dealt with the story .', u"Members of the Union force."]), (u'en.wikipedia.org/wiki/320th_Troop_Carrier_Squadron', [u" The 1st Air Transport."])] This is how the idfs are formatted: Out[23]: [{'_id': u'1,800', 'idf': 7.245417283738939}, {'_id': u'Poetry', 'idf': 5.399590593240608}, {'_id': u'Bloodworth', 'idf': 7.938564464298884}, {'_id': u'Mullally', 'idf': 7.938564464298884}] Here is part of the code I'm working with: corpus = text\ .mapValues(lambda v: ngrams(v, self.max_ngram))\ """the ngrams method call """ .flatMap(lambda (target, tokens): (((target, t), 1) for t in tokens))\ .reduceByKey(add)\ .map(lambda ((target, token), count): (token, (target, count)))\ This is the Pattern library method in text.py: def ngrams(string, n=3, punctuation=PUNCTUATION, continuous=False): """ Returns a list of n-grams (tuples of n successive words) from the given string. Alternatively, you can supply a Text or Sentence object. With continuous=False, n-grams will not run over sentence markers (i.e., .!?). Punctuation marks are stripped from words. """ def strip_punctuation(s, punctuation=set(punctuation)): return [w for w in s if (isinstance(w, Word) and w.string or w) not in punctuation] if n &lt;= 0: return [] if isinstance(string, basestring): s = [strip_punctuation(s.split(" ")) for s in tokenize(string)] if isinstance(string, Sentence): s = [strip_punctuation(string)] if isinstance(string, Text): s = [strip_punctuation(s) for s in string] if continuous: …
has comment: http://stackoverflow.com/comment/87887152
score: 1
tagged with: pyspark
has answer: http://stackoverflow.com/a/50437183
tagged with: python
tagged with: text
accepted answer: http://stackoverflow.com/a/50436848
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87887994
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/50436848
upvote count: 2
has comment: http://stackoverflow.com/comment/87888099
has comment: http://stackoverflow.com/comment/87888264
downvote count: 1
favorite count: 0
type: Question
tagged with: runtime-error
possible better answer: http://stackoverflow.com/a/50437183
has title: UnboundLocalError when calling nragms method in Pattern python library

http://stackoverflow.com/q/50455033
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50455415
downvote count: 0
possible better answer: http://stackoverflow.com/a/50455684
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has body: I am itertively performing operations on a list of images (for image in directory) and need to capture mouse position upon clicking for each separate image. This is not working. I have 2 options: omit the use of cv.namedWindow()/cv.setMouseCallback() or figure out how to use them within/symbiotically with a 'for loop' iterating over images in a directory. Currently, my code is such that a black window appears alongside my images of interest. Only mouse events over that black window are captured, but I want events for the windows displaying the images to be captured. for image in images: img = cv.imread(image) cv.namedWindow("image") cv.setMouseCallback("image", click) ... cv.imshow('x',img) k = cv.waitKey(0) &amp; 0xFF if k == 27: cv.destroyAllWindows() I have tried all combinations of namedWindow and setMouseCallback in and out of the for loop and none work. Does anybody know of a solution? Thanks.
has answer: http://stackoverflow.com/a/50455684
tagged with: python
has title: Python Opencv Mouse Events in Iterated List of Images
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/50455415

http://stackoverflow.com/comment/89396493
has text: This is an actual answer to my question. It shows a way to activate a certain conda environment at the start of the container (which is interesting in itself for a newbie like me, since I thought of doing that, but found it nowhere on the interwebs). And since the missing libraries where installed in that environment, it absolutely solves the problem I've been having. Actually I like this answer even better. It seems to be the **right** way to do it and doesn't rely on manually bending environment variables in the right direction. Sorry for the misunderstandings.
score: 0
comment on: http://stackoverflow.com/a/50985477
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87970813
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50478574
score: 0
has text: This does not append the JSON file as a string with each line separated by ','. It appends each JSON text as a dict (or list, or whatever). If you then `print(tweets)`, or `outfile.write(str(tweets))`, or something like that, then it will format the list as a string, but… just don't do that.

http://stackoverflow.com/q/50412602
type: UnansweredQuestion
tagged with: python
favorite count: 0
has body: I Have Tensorflow MLP Mnist example based simple classifier, its classify face and no_face on RGB 32x32 images. Code working good and calculating classification accuracy Epoch: 0001 cost = 6.539309704 Epoch: 0002 cost = 0.868323514 Epoch: 0003 cost = 0.265693334 Optimization Finished! Accuracy network: 0.8974359 Accuracy is calculated by this code: correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) #Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print("Accuracy network:", accuracy.eval({x: data.Images_test, y: data.Labels_test})) How I can run prediction with my own image in this model? I have tryed this code: image_with_no_face_1 = cv2.imread('a.jpg').reshape(1,3072) image_with_no_face_2 = cv2.imread('b.jpg').reshape(1,3072) image_with_face = cv2.imread('c.jpg').reshape(1,3072) print("Face :", accuracy.eval({x: image_with_no_face_1, y: data.Labels_test})) print("Face :", accuracy.eval({x: image_with_no_face_2, y: data.Labels_test})) print("Face :", accuracy.eval({x: image_with_face, y: data.Labels_test})) And get this values that not right Epoch: 0002 cost = 1087.248228555 Epoch: 0003 cost = 837.800127911 Epoch: 0004 cost = 39.879899548 Epoch: 0005 cost = 461.961817526 Optimization Finished! Accuracy network: 0.8974359 Face : 0.8974359 Face : 0.8974359 Face : 0.8974359 I think I should to use tf.matmul() or similar functions instead tf.reduce_mean() but I can't find any solutions that working with this project structure.
has comment: http://stackoverflow.com/comment/87880140
has title: How to predict my test image in tensorflow MLP Mnist example
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/87858706
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/87906666
has comment: http://stackoverflow.com/comment/87880261
answer count: 0
upvote count: 1

http://stackoverflow.com/a/50510181
type: Answer
has body: You are not using the correct dict-comprehension syntax, it should be: {key, value for key in your_iterable} where, value can be some function of key or vice-versa For your case: docs = {"doc{}".format(i + 1): Finance.documents[i] for i in range(len(Finance.documents))}
answers question: http://stackoverflow.com/q/50510037
score: 0

http://stackoverflow.com/a/50522276
has comment: http://stackoverflow.com/comment/88057935
type: Answer
has comment: http://stackoverflow.com/comment/88058023
accepted answer of: http://stackoverflow.com/q/50521609
has comment: http://stackoverflow.com/comment/88057023
answers question: http://stackoverflow.com/q/50521609
has comment: http://stackoverflow.com/comment/88057407
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88057683
has body: you cannot use response.css to give styling. response object will not have a method called .css. f want to concat a css to a div, you gotta use regex and concat Or a cleaner approach would be just append mystyle.css file in the head, And write down all your styles in mystle.css. &lt;link rel="stylesheet" type="text/css" href="mystyle.css"&gt; you can do this using BeautifulSoup. from bs4 import BeautifulSoup soup = BeautifulSoup(response.body) metatag = soup.new_tag('link') metatag.attrs['rel'] = 'stylesheet' metatag.attrs['type'] = 'text/css' metatag.attrs['src'] = 'mystyle.css' soup.head.append(metatag)
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87854899
comment on: http://stackoverflow.com/a/50419595
has text: Betty Sue Johnson is going to hate this. Better to put first and last names in tuples.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/87982780
type: Comment
type: QuestionComment
has text: How could this possibly work? ``fault()`` internally uses variables that are exclusive to ``updatesetpoints()``, what variables should ``fault()`` use when called from within ``update_label()``? Suggestion: promote ``fault()`` to a "top-level" function that accepts parameters.
comment on: http://stackoverflow.com/q/50484813
score: 1

http://stackoverflow.com/a/50524407
upvote count: 1
downvote count: 1
has body: As pointed Edchum if need replace all non numeric values to 0 - first to_numeric with errors='coerce' create NaNs for not parseable values and then convert them to 0 by fillna: df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).fillna(0) If values are not substrings use DataFrame.isin or very nice answer of Haleemur Ali: df = df.mask(df.isin(['+unend','n. def.']), 0).astype(float) For substrings with define values: There are special regex char + and ., so need escape them by \: df = df.mask(df.astype(str).apply(lambda x: x.str.contains(r'(\+unend|n\. def\.)')), 0).astype(float) Or use applymap for elemnetwise check: df = df.mask(df.applymap(lambda x: (str('n. def.') in (str(x)) or (str('unend') in str(x))) ), 0).astype(float) print (df) col1 col2 col3 time 05/04/2018 05:14:52 AM 0.000 0.0 0.000 05/04/2018 05:14:57 AM 0.000 0.0 0.000 05/04/2018 05:15:02 AM 30.691 0.0 0.121 05/04/2018 05:15:07 AM 30.691 0.0 0.108 05/04/2018 05:15:12 AM 30.715 0.0 0.105
answers question: http://stackoverflow.com/q/50524343
type: Answer
accepted answer of: http://stackoverflow.com/q/50524343
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50494824
score: 1
tagged with: python
has title: How to add key binding?
has comment: http://stackoverflow.com/comment/88002890
has comment: http://stackoverflow.com/comment/88002573
has body: None of the other stackoverflow suggestions, nor any other outside documentation has shown me how to successfully bind a key to a function. Below are links I've tried (code copied and pasted) and had no luck with. I see many people suggesting focus as a reason for failure, as though the frame containing the button isn't the user's target and therefore isn't active; nothing has come from this however. Below are links I have tried: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm https://softwareengineering.stackexchange.com/questions/213935/why-use-classes-when-programming-a-tkinter-gui-in-python python tkinter how to bind key to a button http://www.java2s.com/Code/Python/GUI-Tk/SetButtontogetfocus.htm How to bind a keypress to a button in Tkinter I am running Python 3.6 in PyCharm 5.0.4. The code in the links above are what I've been using/modifying to see how it works but not a single attempt has ended with an action being carried out. The furthest I've gotten is an error message. Thanks. EDIT: code I am using below (from most recent link) from tkinter import * root = Tk() def LeftTurn(event): print('left') frame=Frame(root, width=100, height=100) frame.bind("&lt;Left&gt;", LeftTurn) #Binds the "left" key to the frame and exexutes yourFunction if "left" key was pressed frame.pack() root.geometry("640x480") root.title("Rover ") root.mainloop() I also tried this one (below) from tkinter import * root = Tk() def yourFunction(event): print('left') frame = Frame(root, width=100, height=100) frame.bind("&lt;Left&gt;",yourFunction) #Binds the "left" key to the frame and exexutes yourFunction if "left" key was pressed frame.pack() root.mainloop()
has comment: http://stackoverflow.com/comment/88002477
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/50495021
has comment: http://stackoverflow.com/comment/88002792
linked to: http://stackoverflow.com/q/20832909
linked to: http://stackoverflow.com/q/13326940
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/50495021
accepted answer: http://stackoverflow.com/a/50495267
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50495267
has comment: http://stackoverflow.com/comment/88002483

http://stackoverflow.com/a/50403865
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50403483
has comment: http://stackoverflow.com/comment/87825330
type: Answer
answers question: http://stackoverflow.com/q/50403483
has body: Html with your text: html_doc = """ The Dormouse's story The Dormouse's story 9-Day Weather Forecast General Situation: An anticyclone aloft over the northern part of the South China Sea will bring mainly fine and hot weather to the south China coast in the next few days. Under the influence of a trough of low pressure, there will be showers over southern China midweek next week. Date/Month 18/5 (Friday) Wind: South force 3. Weather: Fine and hot. Temp Range: 27 - 32 C R.H. Range: 65 - 85 Per Cent Date/Month 19/5(Saturday) Wind: South force 3. Weather: Fine and hot. Temp Range: 27 - 32 C R.H. Range: 65 - 85 Per Cent Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well. ... """ Get the tag from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc, 'html.parser') tag = soup.find(id='weather') Even though tag.string is a bs4 NavigableString it is also a Python str >>> >>> type(tag.string) <class 'bs4.element.NavigableString'> >>> isinstance(tag.string, str) True >>> 'South force 3' in tag.string True >>> No need to convert to search with a regular expression pattern = r'Date/Month.*?Per Cent' rex = re.compile(pattern, flags = re.DOTALL) for match in rex.findall(tag.string): print(match) print('**************') >>> Date/Month 18/5 (Friday) Wind: South force 3. Weather: Fine and hot. Temp Range: 27 - 32 C R.H. Range: 65 - 85 Per Cent ************** Date/Month 19/5(Saturday) Wind: South force 3. Weather: Fine and hot. Temp Range: 27 - 32 C R.H. Range: 65 - 85 Per Cent ************** >>>

http://stackoverflow.com/comment/87965984
score: 0
comment on: http://stackoverflow.com/a/50476185
type: Comment
has text: Thank you very much, that solved my first issue. I've updated my question. Any idea what might solve this issue ?
type: AnswerComment

http://stackoverflow.com/a/50435353
type: Answer
has body: Problem solved, it was because I was using a VNC instead of using the keyboard directly connected to the Raspberry Pi.
accepted answer of: http://stackoverflow.com/q/50434460
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87885734
downvote count: 0
answers question: http://stackoverflow.com/q/50434460
type: AcceptedAnswer

http://stackoverflow.com/a/50427755
has body: It is Base64, the error is the last character "\u003d" which is a UTF-16 "=", replace "\u003d"' with "=" and it decodes properly to binary. Trailing Base64 encoded "="characters are padding. Since it decode as Base64 and the trailing "=" character it sure seems to be Base64 encoded data. The Base64 decoded binary in a hex representation is: 17F54315BFED2E99425C882F3C6969A691DAC1EB6E5756B90ED58EB663B5664406375B15F2166689EC886CC0BBA638F8C21F3522BB1616639625906D9919879EEFD8FDCE2547D1175C098EDA1F21701E96FA5B3A704F52EC616E9F5958C3610F057CF127E493D873DA04CB23BA59F14C98EA7ED9127FFB4E3C90574D04A3AF126A1E950031F7B2E6AA6EF15FDC67FB85121CB9266A4D39956DA0A87E33760F98ACDCF3C5D94B6DBEDF922DF075BB0979B30F5507144EAD98D6B795F15F7A6A9F414F8632D81AD29BD4E9CFB42F59494D8D47A07EB835FDAEE314379E2753DB86A9E8D514E123A2DF083A56A2ED48B695C0C58DB977109A0A16E5E763DCBFD38462869AAED95452983BB2271A17F1BA73614C16C307C418C610D9D06BB20BED29257C867DC0F41C8B5F7AA9C8258AA4AF7B8E68955A1ACFFFC3217643F4418AF4AFC977FDC9133C92F048A0D1FFEFCE17A881305A7087E42AA99FF0AFABFFE4B53CFA1ACFDAB527CFF86E5375C349D217F7BC36786657B4E2FB03086C51129F375B2FCC21537C6A94696B9749085A74282E526375F99A23B436AED49C6664065DB37156FDF992A556A823AF5840D520B340802B75A7B6ACFD780AA4D9A8FF4736CE03246BD8C180F09C32F89E37F9AD7F6ECC824DE57766FFEAFA6CDE88DBF2195D15C88F6254F71F154053A54C2CA047EAC255590E519370C347C5E8C1B73427 To me that looks like random data which is what encrypted data looks like, if so without the decryption key you will not be able to further decrypt it. It is 512 bytes in length which is multiple of common encryption block sizes.
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50427125

byte
tags question: http://stackoverflow.com/q/50506590
tag name: byte
tags question: http://stackoverflow.com/q/50509017
tags question: http://stackoverflow.com/q/50470949
tags question: http://stackoverflow.com/q/50424310
type: Tag
tags question: http://stackoverflow.com/q/50458200

http://stackoverflow.com/q/50470672
downvote count: 1
has body: So I'm trying to install twillio but when I try to install it it throws this error: MY_DEVICE_NAME:~ MY_NAME$ pip install twillio Collecting twillio Could not find a version that satisfies the requirement twillio (from versions: ) No matching distribution found for twillio You are using pip version 10.0.0b2, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. MY_DEVICE_NAME:~ MY_NAME$ pip install --upgrade pip Collecting pip Using cached https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl matplotlib 1.3.1 requires nose, which is not installed. matplotlib 1.3.1 requires tornado, which is not installed. matplotlib 1.3.1 has requirement numpy&gt;=1.5, but you'll have numpy 1.8.0rc1 which is incompatible. Installing collected packages: pip Found existing installation: pip 10.0.0b2 Uninstalling pip-10.0.0b2: You are using pip version 10.0.0b2, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. After which I just get stuck in an infinite loop. so what should I do?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50470714
has answer: http://stackoverflow.com/a/50470714
has comment: http://stackoverflow.com/comment/87954777
tagged with: python
has title: pip is refusing to install anything
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50470718
tagged with: pip
upvote count: 1
has answer: http://stackoverflow.com/a/50470718

http://stackoverflow.com/a/50511712
upvote count: 2
has body: If you do not wish to sort your data or drop down to numpy, then a significant performance improvement may be possible by changing your user series to Categorical. Categorical data is stored effectively as integer pointers. In the below example, I see an improvement from 86ms to 59ms. This may improve further for larger datasets and where more users are repeated. df = pd.concat([df]*10000) %timeit df.groupby('user').ts.transform(pd.Series.diff) # 86.1 ms per loop %timeit df['user'].astype('category') # 23.4 ms per loop df['user'] = df['user'].astype('category') %timeit df.groupby('user').ts.transform(pd.Series.diff) # 35.7 ms per loop If you are performing multiple operations, then the one-off cost of converting to categorical can be discounted.
downvote count: 0
answers question: http://stackoverflow.com/q/50511144
has comment: http://stackoverflow.com/comment/88035932
type: Answer
score: 2

http://stackoverflow.com/q/50460462
type: AnsweredQuestion
answer count: 2
tagged with: pandas
upvote count: 2
has comment: http://stackoverflow.com/comment/87934010
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50460531
has answer: http://stackoverflow.com/a/50460531
score: 1
has body: What is a cleaner way of loading data into a dataframe. I currently have it as: df = pd.DataFrame() df['title'] = title_list df['url'] = url_list df['category'] = category_list df['traffic'] = traffic_list df['revenue'] = revenue_list df['price'] = value_list df.to_csv('test.csv', sep=",")
tagged with: python
accepted answer: http://stackoverflow.com/a/50460476
has title: Cleaner way to populate dataframe?
has answer: http://stackoverflow.com/a/50460476

http://stackoverflow.com/a/50512837
accepted answer of: http://stackoverflow.com/q/50511910
has body: A Lua script would be the most potent approach - see EVAL's documentation for more details on how to compose such scripts, and refer to SCRIPT LOAD and EVALSHA for running them. Something like the following example should fix you up: if tonumber(redis.call('TTL', KEYS[1])) &lt; 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
upvote count: 2
answers question: http://stackoverflow.com/q/50511910
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/comment/87923803
score: 0
has text: yes df1.show() and df2.show() are working just fine
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50454850

http://stackoverflow.com/a/50448545
has comment: http://stackoverflow.com/comment/87914686
accepted answer of: http://stackoverflow.com/q/50448447
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has body: Try using soup.find_all to get all p tags Ex: from bs4 import BeautifulSoup s = """ Learning Outcomes On successful completion of this unit, you will beable to: Plan for and be active in your own learning... Reflect on your knowledge of yourself.... Articulate your informed understanding of the foundations... Demonstrate information literacy skills Communicate in writing for an academic audience Prior knowledge """ soup = BeautifulSoup(s, "html.parser") for p in soup.find(id="learning-outcomes").findNext("table").find_all("p"): print(p.text) Output: Plan for and be active in your own learning... Reflect on your knowledge of yourself.... Articulate your informed understanding of the foundations... Demonstrate information literacy skills Communicate in writing for an academic audience
answers question: http://stackoverflow.com/q/50448447
type: Answer

http://stackoverflow.com/comment/88078055
type: QuestionComment
has text: @abarnert thank you, I learned something new. I was just trying to match the return type with the variable I was trying to access, hoping that would help me get the right value. So what do you think I should do?
comment on: http://stackoverflow.com/q/50517789
score: 0
type: Comment

http://stackoverflow.com/comment/87921668
score: 0
comment on: http://stackoverflow.com/q/50453591
type: QuestionComment
has text: `for z in dbmultiAZ: waiter = client.get_waiter('db_instance_available') waiter.wait( DBInstanceIdentifier=z ) response2 = client.stop_db_instance( DBInstanceIdentifier=z ) ` @krishna_mee2004 will this works for me? my apologies if i am wrong. its getting error . Not waiting until the instance get modified
type: Comment

http://stackoverflow.com/q/50510327
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91845022
tagged with: python
has comment: http://stackoverflow.com/comment/88034096
has comment: http://stackoverflow.com/comment/91844996
score: 3
answer count: 0
tagged with: pyarrow
upvote count: 3
has comment: http://stackoverflow.com/comment/96124864
has comment: http://stackoverflow.com/comment/88033026
downvote count: 0
has comment: http://stackoverflow.com/comment/88033139
favorite count: 0
has title: pyarrow.hdfs.connect can't reach my hadoop cluster
type: Question
tagged with: hadoop
has body: I am struggling with the very first steps in interfacing my functional hadoop installation with python. Here is my main node (local network). Here is what's happening when I try to reach my main node: import pyarrow as pa pa.hdfs.connect("192.168.0.37",20500) File "/usr/local/lib/python3.5/dist-packages/pyarrow/hdfs.py", line 181, in connect kerb_ticket=kerb_ticket, driver=driver) File "/usr/local/lib/python3.5/dist-packages/pyarrow/hdfs.py", line 35, in __init__ _maybe_set_hadoop_classpath() File "/usr/local/lib/python3.5/dist-packages/pyarrow/hdfs.py", line 134, in _maybe_set_hadoop_classpath classpath = subprocess.check_output([hadoop_bin, 'classpath', '--glob']) File "/usr/lib/python3.5/subprocess.py", line 626, in check_output **kwargs).stdout File "/usr/lib/python3.5/subprocess.py", line 693, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'hadoop' I am not sure to understand what I am doing wrong and I found this issue on a lot of different reports. I set my environment variables according to the documentation . Here is the end of my .bashrc export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre export HADOOP_HOME=/home/david/Apps/hadoop export CLASSPATH='$HADOOP_HOME/bin/hdfs classpath --glob' It seems like I am getting different errors when running this script directly from my main node. Does it mean that I can't use this script as a client script? Did I miss a step? Thanks.

http://stackoverflow.com/comment/88042746
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50511319
type: AnswerComment
has text: Not working, not sure why. I actually already tried that before. Now it is failing with another error than before.

http://stackoverflow.com/comment/87942658
score: 1
comment on: http://stackoverflow.com/q/50396802
type: QuestionComment
has text: Related: https://stackoverflow.com/questions/2593257/how-to-know-if-optparse-option-was-passed-in-the-command-line-or-as-a-default
type: Comment

http://stackoverflow.com/q/50538038
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50538231
upvote count: 8
has answer: http://stackoverflow.com/a/50538231
has body: I am using TF 1.8 with eager mode enabled. I cannot print the example inside the mapfunc. It when I run tf.executing_eagerly() from within the mapfunc I get "False" import os import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) tfe = tf.contrib.eager tf.enable_eager_execution() x = tf.random_uniform([16,10], -10, 0, tf.int64) print(x) DS = tf.data.Dataset.from_tensor_slices((x)) def mapfunc(ex, con): import pdb; pdb.set_trace() new_ex = ex + con print(new_ex) return new_ex DS = DS.map(lambda x: mapfunc(x, [7])) DS = DS.make_one_shot_iterator() print(DS.next()) print(new_ex) outputs: Tensor("add:0", shape=(10,), dtype=int64) Outside mapfunc, it works fine. But inside it, the passed example does not have a value, nor .numpy() attribute.
has title: TF.data.dataset.map(map_func) with Eager Mode
tagged with: python
tagged with: eager
score: 8
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/71927293
answer count: 2
has answer: http://stackoverflow.com/a/71927293
tagged with: dataset
downvote count: 0
tagged with: tensorflow

http://stackoverflow.com/q/50499758
has comment: http://stackoverflow.com/comment/88051122
linked to: http://stackoverflow.com/q/40922742
has comment: http://stackoverflow.com/comment/88016329
linked to: http://stackoverflow.com/q/8749108
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88014541
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88015418
has comment: http://stackoverflow.com/comment/88012276
favorite count: 0
tagged with: git
has title: Git Hooks not running on Windows
type: Question
has body: I have a repository which contains versioned git hooks. I have symbolic links (that are relative) inside the .git/hooks folder that point to my versioned git hooks. The git hooks are implemented in python and contain the #!/usr/bin/env python shebang line (which should be working https://docs.python.org/3/using/windows.html?#shebang-lines). As part of my versioned git hooks - I have a pre-commit file and a utils.py file on the same level which is imported in the pre-commit script. When I commit on my Mac the pre-commit successfully runs. However, when I commit on a Windows machine, my pre-commit script blows up on the line where utils.py is being imported and I have no idea why. What is going wrong, what have I missed? EDIT: This is how I am generating my symbolic links. Note that I have used this question: https://stackoverflow.com/a/28382515/2155605 to make os.symlink work on unix and windows. Also note that when this script runs I am in the .git/hooks directory. for hook in hooks_to_enable: os.chmod("../../git-hooks/" + hook, os.stat("../../git-hooks/" + hook).st_mode | 0o111) os.symlink(os.path.join("..", "..", "git-hooks", hook), hook) EDIT: I may have narrowed down the problem. When I print my module search path (sys.path) in my versioned hook, it shows the search path from the .hooks directory so all the modules that are in the versioned hooks directory cannot be imported because they are not on the path. If I manually add them it works. However, when I do this same thing on Unix, the search path contains the directory of the versioned hook - not the .git/hooks directory - which is why it's working on Unix.
linked to: http://stackoverflow.com/q/6260149
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88012304
has comment: http://stackoverflow.com/comment/88015118
has comment: http://stackoverflow.com/comment/88050110

image-processing
tags question: http://stackoverflow.com/q/50453981
tags question: http://stackoverflow.com/q/50403624
type: Tag
tags question: http://stackoverflow.com/q/50390647
tags question: http://stackoverflow.com/q/50429079
tags question: http://stackoverflow.com/q/50509570
tags question: http://stackoverflow.com/q/50444920
tags question: http://stackoverflow.com/q/50508692
tags question: http://stackoverflow.com/q/50510430
tags question: http://stackoverflow.com/q/50488667
tags question: http://stackoverflow.com/q/50397098
tags question: http://stackoverflow.com/q/50420168
tags question: http://stackoverflow.com/q/50451629
tags question: http://stackoverflow.com/q/50410666
tags question: http://stackoverflow.com/q/50508452
tags question: http://stackoverflow.com/q/50387735
tags question: http://stackoverflow.com/q/50442597
tags question: http://stackoverflow.com/q/50395617
tags question: http://stackoverflow.com/q/50390995
tags question: http://stackoverflow.com/q/50529731
tag name: image-processing
tags question: http://stackoverflow.com/q/50425700
tags question: http://stackoverflow.com/q/50385033
tags question: http://stackoverflow.com/q/50436423
tags question: http://stackoverflow.com/q/50527851
tags question: http://stackoverflow.com/q/50522038
tags question: http://stackoverflow.com/q/50434584
tags question: http://stackoverflow.com/q/50430493
tags question: http://stackoverflow.com/q/50429692
tags question: http://stackoverflow.com/q/50433482
tags question: http://stackoverflow.com/q/50495161
tags question: http://stackoverflow.com/q/50445847
tags question: http://stackoverflow.com/q/50484270

http://stackoverflow.com/a/50531327
downvote count: 1
answers question: http://stackoverflow.com/q/50531183
accepted answer of: http://stackoverflow.com/q/50531183
type: Answer
score: 0
has body: NOT a trivial solution, but worth looking into, depending on how big a project this is and what else you may want to do with Python and MySQL. Django is a framework for Python that can handle a lot of things but, most importantly, provides a very powerful interface to MySQL and other databases. One of the many add-ons for Django is Django REST Framework which is specifically designed for setting up Restful APIs using Django &amp; Python. I have used Django &amp; Django REST Framework extensively. It can take a while to get up to speed, but I think still a lot less work than if you were to take a basic connector between Python &amp; MySQL (having to code SQL statements manually) and code the API interface at a lower level (Django REST Framework isn't perfect but it takes care of a lot of the details).
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/135817515
type: QuestionComment
comment on: http://stackoverflow.com/q/50434204
score: 0
has text: Just use shell=True...
type: Comment

http://stackoverflow.com/a/50416235
has comment: http://stackoverflow.com/comment/87932589
has body: There may be other efficient way, one way may be to: Create new_df such that it keeps unique values in Column1 with first occurences. Then, in original df getting sum after grouping by Column1 and updating the value of new_df You can try as shown below: new_df = df.drop_duplicates(subset='Column1', keep='first').reset_index() del new_df['index'] # remove extra index column after reset index new_df['Value'] = df.groupby('Column1', as_index=False).sum()['Value'] print(new_df) Result: ID Value Column1 Column2 Column3 Column4 Column5 Column6 0 1 125 aa ee ii mm aaaaa bbbb 1 2 52 bb ff jj nn cccc ddddd 2 4 10 dd hh ll pp gggg hhhh Update: Checking with dataframe after edited: new_df = df.drop_duplicates(subset='C1', keep='first').reset_index() del new_df['index'] new_df['Value'] = df.groupby('C1', as_index=False).sum()['Value'] print(new_df) Result: C1 C2 C3 C4 C5 C6 ID Value 0 aa ee ii mm aaaaa bbbb 1 125 1 bb ff jj nn cccc ddddd 2 52 2 dd hh ll pp gggg hhhh 4 10
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50416036
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50416036

http://stackoverflow.com/q/50432645
has comment: http://stackoverflow.com/comment/87879541
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87879554
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50432695
upvote count: 1
downvote count: 1
has title: adding new values in a typical key in a dictionary
has answer: http://stackoverflow.com/a/50433182
favorite count: 0
type: Question
has body: how do I add value to another dictionary to the same key like below con = {'a':{'b':'c'}, b:{'d':'e'}} into con = {'a':{'b':'c', 'e':'f'}, b:{'d':'e'}}
has comment: http://stackoverflow.com/comment/87879584
type: UnansweredQuestion

http://stackoverflow.com/comment/88222989
type: AnswerComment
has text: cjonesrun, you made the purpose of each step and how they communicate with each other very clear. Thank you for your help!
type: Comment
comment on: http://stackoverflow.com/a/50501293
score: 0

http://stackoverflow.com/comment/88068503
type: AnswerComment
comment on: http://stackoverflow.com/a/50518583
score: 0
type: Comment
has text: The super call does two things. First it saves the form (this is the issue, and why you need to take it out. Essentially it is overriding your previous save procedures). The other, important thing it does is it returns an HTTP redirect to the success URL of the view. You are going to need to replace this as well: as I mentioned in the previous answer, you are going to need to use something like: return redirect(self.get_success_url()). If you do not remove (and replace) the super call, your attempt to save the post with the group and user added in will be overridden, resulting in your error.

http://stackoverflow.com/comment/87997619
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50490596
has text: In that case, if you want a definite answer, I think you need to remove usage of from your code and change what's left so it provides an [MCVE](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/q/50522534
has comment: http://stackoverflow.com/comment/88060487
favorite count: 0
has body: Is it possible to iterate the generator object in Python with asyncio? I made a simple function named hash_generator() which return a unique hash. Now I decided to benchmark the loop and I get around 8 seconds for iterating to print 100,000 hashes. Can I run this in async to be able to minimize the time? I read the documentation of it but I am confused. I want to explore async and I want to begin with this problem. import hashlib import string import random import time def hash_generator(): """Return a unique hash""" prefix = int(time.time()) suffix = (random.choice(string.ascii_letters) for i in range(10)) key = ".".join([str(prefix), str("".join(suffix))]) value = hashlib.blake2b(key.encode(), digest_size=6).hexdigest() return value.upper() """Iterating the hashes and printing the time it loaded""" hashes = (hash_generator() for i in range(100000)) time_before = time.time() [print(i) for i in hashes] time_after = time.time() difference = time_after - time_before print('Loaded in {0:.2f}sec'.format(difference)) # 40503CBA2DAE # ... # A511068F4945 # Loaded in 8.81sec EDIT 1 The random.choice() function is the main reason why the program was taking too long to run. I recreated the function below, with current time and random string from os.urandom (low collision) as values. I tried multithreading but instead of making the task to run as fast it's taking too slow. Any recommendation to refactor the code below is always welcomed. import hashlib import time import os import timeit def hash_generator(): """Return a unique hash""" prefix = str(time.time()) suffix = str(os.urandom(10)) key = "".join([prefix, suffix]) value = hashlib.blake2b(key.encode(), digest_size=6).hexdigest() return value.upper() """Iterating the hashes and printing the time it loaded""" print(timeit.timeit(hash_generator, number=100000), "sec") # 0.497149389999322 sec EDIT 2 With the help of Jack Taylor and Stackoverflowers I can see the difference by using multiprocessing over 1M iterations. I bench…
type: Question
has title: Python: How to asynchronize a for loop
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88078896
accepted answer: http://stackoverflow.com/a/50524366
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/88057655
linked to: http://stackoverflow.com/q/2957116
has comment: http://stackoverflow.com/comment/88057329
tagged with: python
has comment: http://stackoverflow.com/comment/88154493
has comment: http://stackoverflow.com/comment/88078598
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50524366
has comment: http://stackoverflow.com/comment/88057060
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: asynchronous

http://stackoverflow.com/a/61811370
type: Answer
answers question: http://stackoverflow.com/q/50535498
has body: It all depends on what your program is doing. If you program is just stringing together large operations that are implemented in C++ then cython isn't going to help you much if at all. If you are writing code that works directly on individual pixels then cython could be a big help.
score: 0

type-conversion
tags question: http://stackoverflow.com/q/50456153
tags question: http://stackoverflow.com/q/50513318
tag name: type-conversion
type: Tag
tags question: http://stackoverflow.com/q/50481366
tags question: http://stackoverflow.com/q/50512816
tags question: http://stackoverflow.com/q/50502476
tags question: http://stackoverflow.com/q/50474053
tags question: http://stackoverflow.com/q/50442657

http://stackoverflow.com/a/50497682
answers question: http://stackoverflow.com/q/50495998
upvote count: 3
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50495998
type: AcceptedAnswer
has body: matshow or imshow work with equal sized cells. They hence cannot be used here. Instead you may use pcolor or pcolormesh. This would require to supply the coordinates of the cell edges. Hence you first need to calculate those from the given width. Assuming you want them to start at 0, you may just sum them up. import matplotlib.pyplot as plt import numpy as np; np.random.seed(43) samplemat = np.random.rand(3,3) widths = np.array([.7, .2, .1]) coords = np.cumsum(np.append([0], widths)) X,Y = np.meshgrid(coords,coords) # Display matrix plt.pcolormesh(X,Y,samplemat) plt.show()
type: Answer
has comment: http://stackoverflow.com/comment/88011774

http://stackoverflow.com/comment/87792915
type: QuestionComment
comment on: http://stackoverflow.com/q/50388683
type: Comment
score: 0
has text: `00:00:00-06:00` what time does this mean?

http://stackoverflow.com/comment/88024314
score: 0
comment on: http://stackoverflow.com/q/50484813
has text: In your updated code, ``fault()`` is still a sub-function of ``updatesetpoints()``. I do not see, how adding the class ``Batterysetpts`` to the question makes any difference in regards to the issue.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88007622
has text: That's what I thought. I added a method to the "C" class to return the desired value. Seems to be the best way to do it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50495689
type: Comment

http://stackoverflow.com/a/50429861
upvote count: 0
has body: There's a decorator for that: from django.contrib.admin.views.decorators import staff_member_required @staff_member_required @hooks.register('register_settings_menu_item') def register_django_admin_menu_item(): return MenuItem(_('Site Admin'), '/django-admin', classnames='icon icon-wagtail-inverse', order=20000)
answers question: http://stackoverflow.com/q/50426295
downvote count: 1
has comment: http://stackoverflow.com/comment/87874730
has comment: http://stackoverflow.com/comment/87874941
has comment: http://stackoverflow.com/comment/87893267
has comment: http://stackoverflow.com/comment/87874993
type: Answer
score: -1

http://stackoverflow.com/comment/87876933
type: QuestionComment
comment on: http://stackoverflow.com/q/50431139
has text: I updated your title to deal with the specific scenario you have shown, because `tqdm` takes many, many parameters. If you want to change it back feel free.
score: 1
type: Comment

http://stackoverflow.com/comment/87923073
type: Comment
type: QuestionComment
score: 0
has text: if part is like - > if the key is not in dict , create it and assign value(Lets say 1) . Suppose after few iterations we got the same key with with different value , it will go to else part and there the key value should be updated like 1,2 (assuming 2 is the new value seen, 1 for the previous value). The output should write in the same line as mentioned in output screenshot.
comment on: http://stackoverflow.com/q/50454658

decode
tag name: decode
tags question: http://stackoverflow.com/q/50471654
tags question: http://stackoverflow.com/q/50527914
tags question: http://stackoverflow.com/q/50481242
tags question: http://stackoverflow.com/q/50427125
type: Tag

linear-equation
tag name: linear-equation
type: Tag
tags question: http://stackoverflow.com/q/50510558

http://stackoverflow.com/comment/87816892
has text: Yes, I want [0,0,0,0,0] - I'll edit the question
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50400456

build
tag name: build
type: Tag
tags question: http://stackoverflow.com/q/50487626
tags question: http://stackoverflow.com/q/50504270
tags question: http://stackoverflow.com/q/50396802

http://stackoverflow.com/a/50476451
downvote count: 0
answers question: http://stackoverflow.com/q/50476327
has comment: http://stackoverflow.com/comment/87966505
has comment: http://stackoverflow.com/comment/87966471
type: Answer
upvote count: 3
has body: You can try np.sort test1.assign(key=pd.DataFrame(np.sort(test1.values,axis=1)).sum(1)).merge(test2.assign(key=pd.DataFrame(np.sort(test2'id_a','id_b'.values,axis=1)).sum(1))).drop('key',1) Out[188]: id_A id_B id_a id_b value 0 Ben Julie Ben Julie 1 1 Julie Ben Ben Julie 1 2 Jack Nina Nina Jack 0 3 Jack Julie Julie Jack 1
score: 3

http://stackoverflow.com/q/50472873
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/91984148
tagged with: anaconda
score: 1
has title: No libcudnn.so.6 after installing cuDNN 6.0.0 using anaconda?
tagged with: python
has answer: http://stackoverflow.com/a/54355558
type: Question
has body: I installed CUDA 8 and cuDNN 6 in my anaconda environment using anaconda as below: conda install -c anaconda cudatoolkit==8.0 --yes conda install -c anaconda cudnn==6.0.0 --yes In the same environment, I couldn't found libcudnn.so.6 in /usr/local/cuda/lib64. $ ls /usr/local/cuda/lib64 | grep libcudnn libcudnn.so libcudnn.so.5 libcudnn.so.5.1.5 libcudnn_static.a Is this normal? My tensorflow 1.4 is complaining libcudnn.so.6 not found. I guess it is due to the anaconda cuDNN installation?
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87976940
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50481522
has text: @Sraw How can I fix it?

http://stackoverflow.com/q/50498727
has body: Can anyone let me know what mistake i'm making. Decorator import time def f1(f): a = time.time() f() b = time.time() c = b-a print("time required is", c) @f1 def f3(f2): n = [] for i in range(1000): n.append(i) print(sum(n), "for F3") f2() @f3 def f4(): n = [] for i in range(1000): n.append(i) print(sum(n), "for F4") f4 o/p: Traceback (most recent call last): File "C:/test.py", line 13, in <module> @f1 File "C:/test.py", line 7, in f1 f() TypeError: f3() missing 1 required positional argument: 'f2' Process finished with exit code 1 looking to achieve something like this: def decorator_with_args(decorator_to_enhance): def decorator_maker(*args, **kwargs): def decorator_wrapper(func): return decorator_to_enhance(func, *args, **kwargs) return decorator_wrapper return decorator_maker @decorator_with_args def decorated_decorator(func, *args, **kwargs): def wrapper(function_arg1, function_arg2): print("Decorated with {0} {1}".format(args, kwargs)) return func(function_arg1, function_arg2) return wrapper @decorated_decorator(42, 404, 1024) def decorated_function(function_arg1, function_arg2): print("Hello {0} {1}".format(function_arg1, function_arg2)) decorated_function("Universe and", "everything")
has comment: http://stackoverflow.com/comment/88010583
type: Question
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88010751
has comment: http://stackoverflow.com/comment/88010302
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/88010376
has comment: http://stackoverflow.com/comment/88010524
has comment: http://stackoverflow.com/comment/88010771
tagged with: python-3.x
has title: Issue creating decorator in Python3
accepted answer: http://stackoverflow.com/a/50499296
has answer: http://stackoverflow.com/a/50499296
score: 0
has comment: http://stackoverflow.com/comment/88010706
answer count: 1

http://stackoverflow.com/comment/96349109
comment on: http://stackoverflow.com/a/50530697
type: Comment
type: AnswerComment
has text: I think `np.take(count_vect.get_feature_names(), neg_class_prob_sorted[:10])` returns the 10 least important features.
score: 13

http://stackoverflow.com/comment/88040386
score: 0
type: AnswerComment
has text: `dropna` does **not** reset the index. It only augments the positions. You can `reindex` with the original index to get back where you were. I indirectly reindexed via the `assign` method.
comment on: http://stackoverflow.com/a/50512709
type: Comment

http://stackoverflow.com/comment/88086402
comment on: http://stackoverflow.com/q/50535832
type: Comment
type: QuestionComment
score: 0
has text: @TuğberkKaanDuman I was testing the checking of the keyRelease for shift and checking if tkinter previously recorded a keyPress on shift by tracking the keyPress as a True/False result stored in a variable. The only problem I see with doing it this way is your program will have to rebuild itself after the fact because its very unlikely you will be able to release the button at the time where it checks for the down press.

http://stackoverflow.com/q/50452598
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50452848
has answer: http://stackoverflow.com/a/50452848
has body: I just read "Make your own neural network" book. Now I am trying to create NeuralNetwork class in Python. I use sigmoid activation function. I wrote basic code and tried to test it. But my implementation didn't work properly at all. After long debugging and comparation to code from book I found out that sigmoid of very big number is 1 because Python rounds it. I use numpy.random.rand() to generate weights and this function returns only values from 0 to 1. After summing all products of weights and inputs I get very big number. I fixed this problem with numpy.random.normal() function that generates random numbers from range, (-1, 1) for example. But I have some questions. Is sigmoid good activation function? What to do if output of node is still so big and Python rounds result to 1, which is impossible for sigmoid? How can I prevent Python to rounding floats that are very close to integer Any advices for me as beginner in neural networks (books, techniques, etc).
answer count: 1
has title: Sigmoid of x is 1
type: Question
tagged with: neural-network
tagged with: python
tagged with: sigmoid
has comment: http://stackoverflow.com/comment/87918328

http://stackoverflow.com/comment/87864281
type: Comment
type: AnswerComment
has text: okok, no I mean I want to copy all files in the liste and paste them into a new one but without removing anything into the first file
comment on: http://stackoverflow.com/a/50423621
score: 0

http://stackoverflow.com/comment/87997459
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50491740
score: 0
has text: Since you have `py` installed, you can control what it does by default by setting the `PY_PYTHON` environment variable. For example, on a Windows the command line type `set PY_PYTHON=3`.

http://stackoverflow.com/comment/87869864
comment on: http://stackoverflow.com/q/50427501
score: 0
has text: @miradulo: But for that I'll need a variable to keep track of the length of my list. Is there no other way to do it?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50528211
type: Answer
has comment: http://stackoverflow.com/comment/88469551
upvote count: 2
score: 1
answers question: http://stackoverflow.com/q/50516248
downvote count: 1
has comment: http://stackoverflow.com/comment/88455243
has body: How do I find the Python version that my app is using? See the documentation: http://modwsgi.readthedocs.io/en/develop/user-guides/checking-your-installation.html#python-installation-in-use it provides you a test you can use. How do I find my mod_wsgi version? Use the mod_wsgi.version key from the WSGI environ dictionary. See reference to this in: http://modwsgi.readthedocs.io/en/develop/user-guides/assorted-tips-and-tricks.html#determining-if-running-under-mod-wsgi You can also use: import mod_wsgi print(mod_wsgi.version) How do I get my app to use my venv? Documentation on using virtual environments can be found at: http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html As it states, if your mod_wsgi uses system Python and you want to use a different Python installation or version, you cannot force it to use that other installation or version. The mod_wsgi binary must be compiled against the specific Python version you want to use. Because system mod_wsgi packages are usually ancient and not for the version of Python you want to use, you should uninstall the system mod_wsgi package and install mod_wsgi from source code against the Python version you want to use. For that the easiest install method is using pip install mod_wsgi. See: https://pypi.org/project/mod_wsgi/

http://stackoverflow.com/a/50537938
has body: You can use recursion: def cluster(d, current = []): options = [i for i in d if any(c in current for c in i)] _flattened = [i for b in options for i in b] d = list(filter(lambda x:x not in options, d)) if not options or not d: yield current+_flattened if d and not options: yield from cluster(d[1:], d[0]) elif d: yield from cluster(d, current+_flattened) for a, *b in [[[1,2],[6,4],[2,3],[5,4]], [[1,2],[3,4],[2,3],[5,4]], [[1,2],[3,4],[2,3],[5,4], [10, 11, 12], [13, 15], [4,6], [6, 8], [23,25]]]: print([list(set(i)) for i in cluster(b, a)]) Output: [[1, 2, 3], [4, 5, 6]] [[1, 2, 3, 4, 5]] [[1, 2, 3, 4, 5, 6, 8], [10, 11, 12], [13, 15], [25, 23]]
score: 0
answers question: http://stackoverflow.com/q/50537876
has comment: http://stackoverflow.com/comment/88089384
has comment: http://stackoverflow.com/comment/88088965
type: Answer

http://stackoverflow.com/comment/87829329
comment on: http://stackoverflow.com/q/50398321
type: Comment
type: QuestionComment
has text: This is now turning into an interactive debugging session, for which SO is not the right place. You should check your layer inputs and outputs, make sure you have the right `stride`, and follow the instructions that you get from the program output. This is not something we can easily help you with.
score: 0

http://stackoverflow.com/q/50448034
answer count: 1
tagged with: tensorflow
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87909702
has title: Reshuffle tensor according to other specific tensor in Tensorflow
has body: Given certain tensors a and b where b is of type uint and max(b) &lt; len(a), I would like to get a tensor c: c = a[b] This would essentially reshuffle tensor a according to order given by b.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50451418
score: 0
has answer: http://stackoverflow.com/a/50451418

http://stackoverflow.com/comment/87804365
type: Comment
type: AnswerComment
has text: Thank you @user9806664 for your answer. I was aware of immutability of Spark reading "Scala/Spark: Immutable Dataframes and Memory" titled SO post. Nevertheless, is it possible to create a new dataframe doing that substitution you mention in another form (not entering all values of each column in the row where we want to modify 1 cell)? If so, could you provide an example? I will edit my question to be more clear thanks to your answer.
score: 1
comment on: http://stackoverflow.com/a/50393559

http://stackoverflow.com/q/50388110
possible better answer: http://stackoverflow.com/a/50388621
has answer: http://stackoverflow.com/a/50388621
type: AnsweredQuestion
upvote count: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50408071
has body: I'm using django money field in storing prices, and there's this little problem in displaying the values. The USD displayed format is different from the rest of the currency. See the displayed format below. USD: $1,000 ----> This should be 1,000 USD SGD: 1,000 SGD CNY: 1,000 CNY How come that USD is using currency sign ($) while the rest uses currency code? How do i set the USD to display currency code? Thanks in advance
downvote count: 1
has title: Django money USD format is different
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50408071
tagged with: django
tagged with: django-models
tagged with: python
score: -1

http://stackoverflow.com/a/50469346
upvote count: 7
score: 7
accepted answer of: http://stackoverflow.com/q/50469182
answers question: http://stackoverflow.com/q/50469182
type: Answer
has comment: http://stackoverflow.com/comment/87956709
type: AcceptedAnswer
downvote count: 0
has body: You are not inheriting the django.contrib.auth user model, as we can see, you are doing a OneToOne relationship with the django.contrib.auth user model. So the django.contrib.auth user model are not going to be in your Profile model. You are probably going to solve this like this: queryset = Profile.objects.all().order_by('-user__date_joined')

http://stackoverflow.com/a/50502647
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50502148
type: Answer
accepted answer of: http://stackoverflow.com/q/50502148
type: AcceptedAnswer
downvote count: 0
has body: Count as follows: #!/usr/bin/env python3.6 from collections import Counter, defaultdict from pathlib import Path def main(): n = input('Enter n: ') try: n = int(n) except: print('Invalid input.') return ss = Path('streamt.txt').read_text().strip().split('\n') c = Counter([ i.strip().split(' ', 1)[0] for i in ss if i.strip().split(' ', 2)[1] not in ('RT',) ]) d = defaultdict(list) for k, v in c.most_common(): d[v].append(k) print('\n'.join([f'{k} {" ".join(v)}' for k, v in list(d.items())[:n]])) if __name__ == '__main__': main() Output: Enter n: 10 3 andrew 2 fred 1 judy john

http://stackoverflow.com/q/50386323
type: Question
type: UnansweredQuestion
tagged with: python
has title: Tensorflow Object Detection Slow when using rtsp stream
score: 14
tagged with: opencv
has answer: http://stackoverflow.com/a/50449908
has comment: http://stackoverflow.com/comment/87790524
has answer: http://stackoverflow.com/a/50548891
answer count: 3
has body: I have followed the example here: https://www.youtube.com/watch?v=MoMjIwGSFVQ and have the object detection working with a web cam. But I have switched my web cam to use an rtsp stream from an IP camera which I believe is streaming H264 and I now notice that there is about a 30 second lag in the video, plus the video is very stop start at times. Here is the python code that does the main processing: import cv2 cap = cv2.VideoCapture("rtsp://192.168.200.1:5544/stream1") # Running the tensorflow session with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: ret = True while (ret): ret,image_np = cap.read() # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8) # plt.figure(figsize=IMAGE_SIZE) # plt.imshow(image_np) cv2.imshow('image',cv2.resize(image_np,(1280,960))) if cv2.waitKey(25) &amp; 0xFF == ord('q'): cv2.destroyAllWindows() cap.release() break I am new to python and tensorflow. Should this code b…
has answer: http://stackoverflow.com/a/54185971
downvote count: 1
upvote count: 15
has comment: http://stackoverflow.com/comment/87791037
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/50403632
downvote count: 0
possible better answer: http://stackoverflow.com/a/50403761
has answer: http://stackoverflow.com/a/50403832
has answer: http://stackoverflow.com/a/50403726
accepted answer: http://stackoverflow.com/a/50403726
has answer: http://stackoverflow.com/a/50403761
favorite count: 0
type: Question
has body: I have two lists: list_1 = [100,100,50,40,40,20,10] list_2 = [5,25,50,120] I want to move the numbers/elements from list_2 to list_1 in the descending order in a nested list: [[100,100,50,40,40,20,10,5],[100,100,50,40,40,25,20,10],[100,100,50,50,40,40,20,10],[120,100,100,50,40,40,20,10]] How to achieve this using Python 3?
score: 3
upvote count: 3
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has title: How to add the elements from one list to another list in Python3?
tagged with: list
answer count: 3

http://stackoverflow.com/comment/87787666
type: QuestionComment
has text: By the time the second loop starts there aren't any lines left to read from the file, you have already read everything.
type: Comment
comment on: http://stackoverflow.com/q/50385927
score: 0

http://stackoverflow.com/comment/88033139
comment on: http://stackoverflow.com/q/50510327
has text: sudo apt-get install libhdf4-0 , yep, got it. But it does not seem to change much
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50600890
answers question: http://stackoverflow.com/q/50497136
has comment: http://stackoverflow.com/comment/88734656
has comment: http://stackoverflow.com/comment/91160336
score: 0
accepted answer of: http://stackoverflow.com/q/50497136
type: AcceptedAnswer
type: Answer
has body: I had similar issues with adding devices in a c++ tool. My work around was to create a template file containing my device and open that from the c++ code. You can try same trick using python.

http://stackoverflow.com/a/52022636
has body: If you think you need this your best move is probably to put a list into a dictionary. It's quite a bit more code to handle but it gets the job done. On the other hand, needing to ask this question is usually, but not always, a sign you're doing something wrong.
score: 0
answers question: http://stackoverflow.com/q/50470854
type: Answer

http://stackoverflow.com/comment/88062660
comment on: http://stackoverflow.com/a/50524171
score: 0
type: AnswerComment
has text: My python version is 2.7.6, it works well. Python API may be different from the version you currently use. Maybe you can read official python docs to use correct API replace the codes, then it will work.
type: Comment

python-multithreading
tags question: http://stackoverflow.com/q/50434204
tags question: http://stackoverflow.com/q/50449082
tags question: http://stackoverflow.com/q/50481007
tags question: http://stackoverflow.com/q/50540204
tags question: http://stackoverflow.com/q/50414048
tags question: http://stackoverflow.com/q/50411871
tags question: http://stackoverflow.com/q/50411854
tags question: http://stackoverflow.com/q/50486083
tag name: python-multithreading
tags question: http://stackoverflow.com/q/50387463
tags question: http://stackoverflow.com/q/50412530
type: Tag

http://stackoverflow.com/q/50540709
tagged with: python
linked to: http://stackoverflow.com/q/20762142
has comment: http://stackoverflow.com/comment/88092763
type: Question
type: UnansweredQuestion
has body: I wrote a C# library in linux with .NET Core. Now I want to use it in python. Has someone experience with this topic? Is this even possible? I tried to use import ctypes as ct lib = ct.WinDLL("PythonTest.dll") but I run in this error Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'WinDLL'
answer count: 1
tagged with: .net-core
favorite count: 0
tagged with: c#
score: 3
upvote count: 3
tagged with: linux
downvote count: 0
has title: Using .NET Core Library in Linux Python
has answer: http://stackoverflow.com/a/50540775

http://stackoverflow.com/comment/87881487
comment on: http://stackoverflow.com/q/50403464
score: 0
type: Comment
has text: Did you try to run your scripting `sudo`?
type: QuestionComment

http://stackoverflow.com/comment/88009718
score: 1
has text: after each iteration of the `for _ in range(8)`, the matrix will be shifted one to the left. That is why I left the comment `# code to update display here and sleep for a bit`
type: Comment
comment on: http://stackoverflow.com/a/50498357
type: AnswerComment

http://stackoverflow.com/a/50571605
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50431138
has body: You can use several booleans(up, right, left, down) representing if the tank is going a direction. When a key is pressed, set the boolean to true, and when it is released set the boolean false. Make a game loop using a seperate thread/while loop withimport threading and in the game loop check if one of the booleans is true. For example, if the boolean representing right is true, then the program would add to the x-coordinate of the tank.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50431138
score: 1

http://stackoverflow.com/q/50541591
answer count: 0
has title: CVXPY: Using two sets of constraints of different format returns None
tagged with: cvxpy
downvote count: 0
score: 1
upvote count: 1
has body: I am new to CVXPY. I have been trying to solve an easy feasibility problem. Here is the code: from cvxpy import * import numpy as np dim = np.shape(Bs[0])[1] X = Variable(dim) objective = Minimize(0) constraintsA = [X.T * M * X + B * X + C == 0 for M, B, C in zip(Ms, Bs, Cs)] constraintsB = [A * X - b == 0 for A, b in zip(As, bs)] constraints = constraintsA + constraintsB prob = Problem(objective, constraints) result = prob.solve() R = X.value print R Below, you can find the input matrices: Ms = [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.]]), 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.]]), 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.]])] Bs = [array([[-18., 0., 0., 18., 0., 0.]]), array([[ 0., 0., 0., 0., -36., 0.]]), array([[ 0., 0., -18., 0., 0., -18.]])] Cs = [270.0, 540.0, 810.0] As = [array([[ 0., -1., 1., 0., 0., 0.], [ 0., 0., 0., 0., -1., 1.]]), array([[-1., 1., 0., 0., 0., 0.], [ 0., 0., 0., -1., 1., 0.]]), array([[-1., 0., 1., 0., 0., 0.], [ 0., 0., 0., -1., 0., 1.]])] bs = [array([[ 0], [ 1.00000000e+01]]), array([[ 20.], [ 10.]]), array([[ -2.00000000e+01], [ 0]])] Running it only for constraintsA, the code is executed and returns back a result vector as expected. However, when considering the constraintsB set too, my result is None. Any ideas where I might have messed it up? Thanks a lot!
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88095157
type: UnansweredQuestion
tagged with: python
tagged with: constraints
has comment: http://stackoverflow.com/comment/88096131

http://stackoverflow.com/a/50429733
score: 6
type: Answer
answers question: http://stackoverflow.com/q/50429720
upvote count: 6
type: AcceptedAnswer
downvote count: 0
has body: You can either iterate over the dictionary to update it... for k in dict_: dict_[k] -= 1 ... or create a new dictionary with a dictionary comprehension. new_dict = {k: v - 1 for k, v in dict_.items()} In both cases note that I replaced your variable name by dict_ to avoid overwriting the built-in dict name.
accepted answer of: http://stackoverflow.com/q/50429720
has comment: http://stackoverflow.com/comment/87874284

http://stackoverflow.com/a/50443511
has comment: http://stackoverflow.com/comment/87903150
has comment: http://stackoverflow.com/comment/87901025
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87901580
has body: Access the element using key-value. Here your key is the attribute name. Ex: from bs4 import BeautifulSoup s = """ 0 """ soup = BeautifulSoup(s, "html.parser") print(soup.div["end"]) Output: 4269
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87903321
accepted answer of: http://stackoverflow.com/q/50443463
type: Answer
answers question: http://stackoverflow.com/q/50443463

http://stackoverflow.com/q/50460905
answer count: 1
tagged with: scrapy
downvote count: 1
has answer: http://stackoverflow.com/a/50522781
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87978291
has comment: http://stackoverflow.com/comment/87938816
accepted answer: http://stackoverflow.com/a/50522781
has comment: http://stackoverflow.com/comment/87935517
tagged with: python
linked to: http://stackoverflow.com/q/39939553
has body: I need to get all the option values from select tag CSC IT MCA BE I tried response.css('select::attr(name:Department)').extract() but not getting. I need output : ['CSC', 'IT', 'MCA', 'BE'] I am new to web scrapy please help...
tagged with: xpath
type: AnsweredQuestion
tagged with: python-3.x
has title: How can I get the select option values in scrapy using python
score: 2
upvote count: 3
duplicate of: http://stackoverflow.com/q/39939553

http://stackoverflow.com/comment/87805751
has text: Please format your code with proper indentation so we know what the actual error is. And what's the exact error message?
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50395004

http://stackoverflow.com/q/50433446
has title: Why does integer division round down in many scripting languages?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87881999
score: 49
tagged with: raku
upvote count: 51
downvote count: 2
has answer: http://stackoverflow.com/a/50433478
linked to: http://stackoverflow.com/q/32123583
has comment: http://stackoverflow.com/comment/87881256
has answer: http://stackoverflow.com/a/50438042
has body: In the languages I have tested, - (x div y ) is not equal to -x div y; I have tested // in Python, / in Ruby, div in Perl 6; C has a similar behavior. That behavior is usually according to spec, since div is usually defined as the rounding down of the result of the division, however it does not make a lot of sense from the arithmetic point of view, since it makes div behave in a different way depending on the sign, and it causes confusion such as this post on how it is done in Python. Is there some specific rationale behind this design decision, or is just div defined that way from scratch? Apparently Guido van Rossum uses a coherency argument in a blog post that explains how it is done in Python, but you can have coherency also if you choose to round up. (Inspired by this question by PMurias in the #perl6 IRC channel)
has answer: http://stackoverflow.com/a/50433683
has answer: http://stackoverflow.com/a/50436534
favorite count: 0
accepted answer: http://stackoverflow.com/a/50436534
type: Question
tagged with: ruby
has answer: http://stackoverflow.com/a/50434508
has answer: http://stackoverflow.com/a/71068378
possible better answer: http://stackoverflow.com/a/50434508
linked to: http://stackoverflow.com/q/3602827
linked to: http://stackoverflow.com/q/319880
tagged with: python
answer count: 6
tagged with: integer-division

http://stackoverflow.com/comment/87942539
type: Comment
type: QuestionComment
has text: You are reading the entire file into virtual memory. Better to read one line at a time and write each line out (changing the line ending) to a new file.
score: 1
comment on: http://stackoverflow.com/q/50464625

http://stackoverflow.com/comment/88013646
type: AnswerComment
has text: Thanks @Anton vBR. I've fixed the paste error. This works fine. I'd like to keep AA coordinates until the next coordinates appear. Even when `AA` isn't in the `Event` column. But I can go back and use a `ffill()` option easy enough.
score: 1
comment on: http://stackoverflow.com/a/50500494
type: Comment

http://stackoverflow.com/q/50537218
tagged with: file-io
type: Question
has answer: http://stackoverflow.com/a/50537305
has comment: http://stackoverflow.com/comment/88087238
tagged with: python
has body: Working on reading from, parsing data, and then overwriting new data to a text file. My problem is, writing to the file is adding invalid characters to the beginning before adding what I want it to. The error I get is: ValueError: could not convert string to float: '\x00\x0045.5' 45.5, 5.0 is the data I am trying to write to the file and each \x00 represents an invalid character added during the writing to the file process. Normally there's like 10-15 added each iteration. I can manually go into the text file and delete them, but what's the fun in that? This is my code, and the try/except is what I added to try to fix the problem- def __init__(self, power): self.name = "Dr. Strange" self.CloakOfLevitation = "I like Dr. Strange" self.EyeOfAgamotto = InfinityStones.TimeStone(5000 + power, self.name) self.win = False self.length = randint(2, 100) stats = open("Stats.txt", 'r+', encoding = 'utf-8') data = stats.read() try: avg, tries = data.split(sep = ',') avg = float(avg) tries = float(tries) except ValueError: stats.truncate(0) stats.write(data[1:]) sleep(5) stats.close() self.__init__(power) self.new_avg = avg + (self.length - avg) / tries stats.truncate(0) stats.write(str(self.new_avg) + ',' + str((tries + 1))) stats.close() The majority of this code involves recursion, self.length determines how long the recursion will last, power is just a number and isn't important for this part. sleep(5) is in there so I can stop the program while it's running before it blows up my computer. Each time it writes data to the file, it adds invalid characters (represented as \x00 in the error output). avg is supposed to be the average number of 'deaths' before the recursion is done, and tries is the number of times the program has been run. The idea of the try/except block is to attempt to convert the data in the file to integers so math can be done with them, and if it can't turn it into a character, attempt to drop the first character in the text file (supposedly an invalid chara…
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88086629
downvote count: 0
tagged with: file
score: 1
upvote count: 1
answer count: 1
has title: Reading and writing to text file adds invalid characters
accepted answer: http://stackoverflow.com/a/50537305

http://stackoverflow.com/q/50517295
has answer: http://stackoverflow.com/a/50518550
possible better answer: http://stackoverflow.com/a/50519205
accepted answer: http://stackoverflow.com/a/50537280
has body: Implementing the following logic for a feature engineering purpose. A simple approach is easy but wondering if there is a more efficient solution that anyone can think of. Ideas are appreciated if you don't feel like implementing the whole code! Take this DataFrame and dictionary import pandas as pd random_animals = pd.DataFrame( {'description':['xdogx','xcatx','xhamsterx','xdogx' ,'xhorsex','xdonkeyx','xcatx'] }) cat_dict = {'category_a':['dog','cat'] ,'category_b':['horse','donkey']} We want to create a column/feature for each string in the dictionary AND for each category. 1 if string is contained in the description column 0 otherwise. So the output for this toy example would look like: description is_dog is_cat is_horse is_donkey is_category_a is_category_b 0 xdogx 1 0 0 0 1 0 1 xcatx 0 1 0 0 1 0 2 xhamsterx 0 0 0 0 0 0 3 xdogx 1 0 0 0 1 0 4 xhorsex 0 0 1 0 0 1 5 xdonkeyx 0 0 0 1 0 1 6 xcatx 0 1 0 0 1 0 Simple approach would be iterating once for each output column required and running (for each column, just hardcoded is_dog here for simplicity) random_animals['is_dog'] = random_animals['description'].str.contains('dog')*1 There can be an arbitrary number of strings and categories in the cat_dict so I am wondering if there is a way to do this otherwise.
has answer: http://stackoverflow.com/a/50519205
has answer: http://stackoverflow.com/a/50537280
tagged with: dummy-variable
has title: Pandas create dummy features for each string in a dictionary of lists
has comment: http://stackoverflow.com/comment/88048727
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/88048459
linked to: http://stackoverflow.com/q/46786211
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/88048324
score: 0

http://stackoverflow.com/q/50488151
type: AnsweredQuestion
has body: I'm trying to scrape the number of registrants for each division in the upcoming World Brazilian Jiu Jitsu Championships using Python and Beautiful Soup. (The goal in the end is to plot the number of competitors in each division, so the name of each registrant is immaterial.) I'm able to pull some of the information I want using BeautifulSoup, but I can't seem to isolate exactly what I want. import urllib2 from bs4 import BeautifulSoup import fileinput import matplotlib page = urllib2.urlopen("https://www.ibjjfdb.com/ChampionshipResults/926/PublicRegistrations?lang=en-US").read() soup = BeautifulSoup(page,'html.parser') My original plan was to go through all the data, count the names of the people registered in each division, save it as a data set and then plot the information by weight, age, etc. I now see that there's a counter at the bottom of each division, so all I really need to do is identify the weight division and the total. Originally I tried using soup.find_all() to pull the information I wanted, but it's giving me a lot of excess. I started with trying to pull the whole table using a command I pulled from another StackOverflow question: result = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ["row"]) which gives one long string containing what I want: [ \n BLUE / Juvenile 1 / Male / Rooster \n \n \n \r\n Atos Jiu-Jitsu\r\n [...] To narrow it down, I searched for the heading that just gives the weight classes: all_divisions = [division for division in soup.find_all("h4")] which works well and gives: [ BLUE / Juvenile 1 / Male / Rooster , BLUE / Juvenile 1 / Male / Light-Feather , BLUE / Juvenile 1 / Male / Feather , BLUE / Juvenile 1 / Male / Light , [...] I want to be able divide these into their separate groups so I can plot it. How can I split this up? I tried using all_divisions[0].split() but apparently soup.find_all() returns NoneType objects instead of strings. Next, I'm trying to get the total. I can isolate the string "Total:…
tagged with: python
has answer: http://stackoverflow.com/a/50503369
has comment: http://stackoverflow.com/comment/87989815
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87989145
answer count: 1
accepted answer: http://stackoverflow.com/a/50503369
has title: Editing Strings and Scraping Data Using Python and BeautifulSoup
tagged with: beautifulsoup

http://stackoverflow.com/comment/88012958
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50500107
has text: `re.match(r'xyz:\d+ \+ \d+', 'xyz:10 + 5')`

http://stackoverflow.com/comment/87880150
score: 0
has text: Awesome, this looks neat. Thanks!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50432935

http://stackoverflow.com/a/50441300
score: 1
has comment: http://stackoverflow.com/comment/87897103
has comment: http://stackoverflow.com/comment/93493328
downvote count: 1
has comment: http://stackoverflow.com/comment/87897033
answers question: http://stackoverflow.com/q/50441128
upvote count: 2
has comment: http://stackoverflow.com/comment/87896977
type: Answer
has comment: http://stackoverflow.com/comment/87897087
has body: instead of writing %matplotlib inline add the following code from IPython import get_ipython get_ipython().run_line_magic('matplotlib', 'inline')
has comment: http://stackoverflow.com/comment/87897113

http://stackoverflow.com/comment/87902909
comment on: http://stackoverflow.com/a/50444484
type: AnswerComment
has text: can you explain a little bit?
score: 0
type: Comment

http://stackoverflow.com/a/50458281
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50458210
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: Your hashTable object appears to be an iterable of key-value pairs. First, not that your four lines of code: tempList=[] for item in hashTable: if item!=None: tempList.append(item[1]) … is equivalent to a one-liner comprehension: tempList = [item[1] for item in hashTable if item is not None] And it's trivial to turn this into a lazy iterator, instead of building a list in memory: it = (item[1] for item in hashTable if item is not None) And you can inline this directly in the max call: maxNum = max(item[1] for item in hashTable if item is not None) As a side note, notice that I used item is not None instead of item != None. You almost never want to compare to None with == or !=. The rule of thumb is: If you want any truthy value, use if item. If you want any non-None value, use if item is not None. If you want any non-None value, while specifically allowing other classes to override __eq__ and compare as equal to None, use if item != None. However, it's worth noting that if you want to build a custom hash table, you probably want it to act like a dict—or at least like a Mapping. Implementing the Mapping interface is very easy, and it means your object can duck-type as a dict. And, if you do that, you can use the same code you'd use with a dict: maxNum = max(hashTable.values())
accepted answer of: http://stackoverflow.com/q/50458210

http://stackoverflow.com/comment/88209840
comment on: http://stackoverflow.com/q/50501480
score: 0
has text: I change `df_column = df_data_sample` and run and get `ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series`. Do you use pandas `0.23.0` ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88018154
comment on: http://stackoverflow.com/q/50391464
type: Comment
type: QuestionComment
has text: nevermind, it works now as long as i do not use 'tf.train.latest_checkpoint'. Maybe I don't know the proper way to use it. BTW, above error does not occur anymore wherever I put tf.reset_default_graph, although I don't know what made the error went away.....
score: 0

http://stackoverflow.com/a/50403630
type: Answer
accepted answer of: http://stackoverflow.com/q/50402895
has body: You should retrieve the content of comboARU using get() function as follows: def callback(eventObject): print(comboARU.get())
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50402895

http://stackoverflow.com/a/50424757
score: 0
has body: import random words = ['left', 'none', 'super', 'bale'] random.shuffle(words) print(words)
answers question: http://stackoverflow.com/q/50424725
type: Answer

http://stackoverflow.com/comment/87854952
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50418202
has text: @AmiTavory Fair enough, it may not be obvious how to go about things so I've reopened the question and answered it.
score: 1

http://stackoverflow.com/comment/88044506
has text: I don't see a problem there with 2 instances, my only guess would be how you load the test model weights. If you just use `model.save` and `model.load` it also loads the config which would be identical, but can't tell without seeing the code.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50515550

http://stackoverflow.com/q/50438182
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87962686
linked to: http://stackoverflow.com/q/2963263
answer count: 5
type: UnansweredQuestion
score: 21
has answer: http://stackoverflow.com/a/50438335
has answer: http://stackoverflow.com/a/50438744
has comment: http://stackoverflow.com/comment/87962837
has comment: http://stackoverflow.com/comment/87921953
has title: User input in dialog box
tagged with: python
has comment: http://stackoverflow.com/comment/87962811
has body: Is there any library available in python for the graphical user entry input. I know about tk but I believe it takes some line of codes to do that. I am looking for the shortest solution. a = input('Enter your string here:') In place of this, I want to get a dialogue box so that user can input there. This did not serve the purpose. This only shows the dialogue box and you can't provide an input entry. import ctypes # An included library with Python install. ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
has comment: http://stackoverflow.com/comment/87890699
upvote count: 22
has comment: http://stackoverflow.com/comment/87956622
has comment: http://stackoverflow.com/comment/87962651
tagged with: tkinter
has answer: http://stackoverflow.com/a/75580484
has comment: http://stackoverflow.com/comment/87921232
has answer: http://stackoverflow.com/a/50438570
tagged with: user-interface
downvote count: 1
has answer: http://stackoverflow.com/a/67861990
has comment: http://stackoverflow.com/comment/87962762

http://stackoverflow.com/comment/88050538
type: QuestionComment
comment on: http://stackoverflow.com/q/50518913
has text: Even with your indentation fixed I don't get that.
score: 1
type: Comment

http://stackoverflow.com/q/50541662
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: -1
has body: Here is the content of the JSON file { "error": { "class": "com.attask.common.AuthenticationException", "message": "Authentication Exception: Authentication Exception: {0}" } } Here is the code where I'm trying to parse the above content. The same code works perfectly fine for parsing other JSON files. But while parsing the above mentioned content I'm getting an error "TypeError: string indices must be integers". import json fObj = open("attask1.json","r"); res = fObj.read().encode('utf-8'); fObj.close(); data = json.loads(res); for each in data['error']: WFErrorClass = each['class']; WFErrorMessage = each['message']; print WFErrorMessage; print WFErrorClass; Anyone please explain why it is happening and suggest me how to overcome this Any help is greatly appreciated. Python version is 2.7.14 Note: Indentation is perfect and no errors with spacing
has comment: http://stackoverflow.com/comment/88094600
possible better answer: http://stackoverflow.com/a/50541782
has title: json.loads TypeError: string indices must be integers
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/50541782
upvote count: 0
accepted answer: http://stackoverflow.com/a/50541846
downvote count: 1
has answer: http://stackoverflow.com/a/50541846
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88095896
type: AnsweredQuestion

http://stackoverflow.com/a/50432125
answers question: http://stackoverflow.com/q/50432033
type: Answer
has body: Try defining idx outside the while loop and incrementing it on every iteration of the for loop. Something like this: idx = 0 while next_page is not None: for company in company_links_elements: company_url = company.get_attribute("href") writer.writerow((idx, company_url)) idx += 1 time.sleep(random.randint(1, 3)) next_page.click()
score: 0

http://stackoverflow.com/a/50442379
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50442202
has body: It should be a format issue(.text vs .txt) as highlighted already. As the below steps work fine in my linux system(see screenshot) import nltk nltk.download("gutenberg") emma = nltk.corpus.gutenberg.words('austen-emma.txt')
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50442202
score: 1
upvote count: 1

http://stackoverflow.com/q/50409623
score: 0
has comment: http://stackoverflow.com/comment/87862729
answer count: 1
linked to: http://stackoverflow.com/q/50453479
tagged with: django
tagged with: scrapy
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/87862685
type: Question
has comment: http://stackoverflow.com/comment/87920238
has comment: http://stackoverflow.com/comment/87862597
has comment: http://stackoverflow.com/comment/87862829
has comment: http://stackoverflow.com/comment/87862501
accepted answer: http://stackoverflow.com/a/50453629
tagged with: python
has answer: http://stackoverflow.com/a/50453629
has comment: http://stackoverflow.com/comment/87859761
has title: 404 error when deploying Scrapy
has comment: http://stackoverflow.com/comment/87862786
tagged with: deployment
has comment: http://stackoverflow.com/comment/87862722
has comment: http://stackoverflow.com/comment/87862644
has comment: http://stackoverflow.com/comment/87861986
type: AnsweredQuestion
has body: I am trying to deploy Django+Scrapy project on Ubuntu 16.04. When I run scrapyd-deploy, as it is described in the docs, - I get: Packing version 1526639948 Deploying to project "first_scrapy" in http://my_ip/addversion.json Deploy failed (404): &lt;full HTML code of '404.html' page&gt; When I run scrapyd-deploy -l - I see: default http://my_ip My scrapy.cfg: [settings] default = first_scrapy.settings [deploy] url = http://my_ip username = root password = rootpassword project = first_scrapy What am I doing wrong? UPDATE 1: If I change in my scrapy.cfg url=http://my_ip:6800 - this still throws 404 error. Next I tried to run scrapyd in the second console and this was the first time I saw another answer - details are here. So question now is - how to run scrapyd constantly so if I close the console - it will be still working?
has comment: http://stackoverflow.com/comment/87920415

http://stackoverflow.com/a/50387912
score: 0
type: AcceptedAnswer
has body: The problem is given_list[i] &lt;= 0. First i = 0 then given_list[i] = 7 7 is not equal or less than 0, then True and False evaluates to False. That's why it doesn't show output. In this case you don't have any problem with Jupyter or Python. Your problem was your logic. Please try hard in algorithm not syntax.
accepted answer of: http://stackoverflow.com/q/50387532
answers question: http://stackoverflow.com/q/50387532
type: Answer

http://stackoverflow.com/q/50505907
favorite count: 0
tagged with: pyc
type: Question
answer count: 0
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
tagged with: security
has title: pyc files and security with passwords?
has comment: http://stackoverflow.com/comment/88024416
has body: I am in the process of tidying up my code on github by removing .pyc files. My source code reads a password from a text file outside the git drectory. However can it be extracted from .pyc files? I have no reason to suspect suspicious behaviour but is a good lesson regarding housekeeping.
score: 1
has comment: http://stackoverflow.com/comment/88029290

http://stackoverflow.com/comment/87820133
type: Comment
has text: @Fortunato Thanks for responding. The code I originally posted DOES work, which now has me more baffled. I shorted the terms to make it easier to post which somehow solved the problem. I went ahead and posted the full program above with entire traceback. I have gone over it again and again but it still produces an error when I split the functions out into a separate module.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50398429

http://stackoverflow.com/comment/88045281
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50516350
has text: so are you using a virtual environment for your project? after installing the package, you should add it to the `INSTALLED_APPS` to your `settings.py`.

http://stackoverflow.com/comment/87979285
has text: Seriously, how can you think it works if the initial input and decrypted output dont match ? Think about it. b"my message" is encrypted. once you decrypt the cipher you should get back exactly the same. otherwise the whole encryption doesnt make sense. does it ?
comment on: http://stackoverflow.com/q/50481366
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50516666
has answer: http://stackoverflow.com/a/50517039
has answer: http://stackoverflow.com/a/50516842
tagged with: python
has comment: http://stackoverflow.com/comment/88046267
tagged with: regex
has comment: http://stackoverflow.com/comment/88045989
has comment: http://stackoverflow.com/comment/88045913
type: AnsweredQuestion
score: 0
answer count: 2
has title: Match word boundary before non-alphanumerical character
has comment: http://stackoverflow.com/comment/88046011
has comment: http://stackoverflow.com/comment/88046061
type: Question
has comment: http://stackoverflow.com/comment/88046031
has comment: http://stackoverflow.com/comment/88045975
possible better answer: http://stackoverflow.com/a/50516842
accepted answer: http://stackoverflow.com/a/50517039
has comment: http://stackoverflow.com/comment/88046064
has body: I want to find words starting with a single non-alphanumerical character, say '$', in a string with re.findall Example of matching words $Python $foo $any_word123 Example of non-matching words $$Python foo foo$bar Why \b does not work If the first character were to be alphanumerical, I could do this. re.findall(r'\bA\w+', s) But this does not work for a pattern like \b\$\w+ because \b matches the empty string only between a \w and a \W. # The line below matches only the last '$baz' which is the one that should not be matched re.findall(r'\b\$\w+', '$foo $bar x$baz'). The above outputs ['$baz'], but the desired pattern should output ['$foo', '$bar']. I tried replacing \b by a positive lookbehind with pattern ^|\s, but this does not work because lookarounds must be fixed in length. What is the correct way to handle this pattern?
has comment: http://stackoverflow.com/comment/88046016
has comment: http://stackoverflow.com/comment/88046044

glsl
tags question: http://stackoverflow.com/q/50412796
type: Tag
tag name: glsl

http://stackoverflow.com/comment/87880737
comment on: http://stackoverflow.com/q/50433163
score: 0
type: Comment
has text: Please *never* post images of text. It means we have to painstakingly transcribe your code before we can try it ourselves, or—more likely—we don't bother and look at another question instead.
type: QuestionComment

http://stackoverflow.com/comment/87914566
comment on: http://stackoverflow.com/a/50446946
type: Comment
has text: Unfortunately it is part of the base [Layer](https://github.com/keras-team/keras/blob/bf1378f39d02b7d0b53ece5458f9275ac8208046/keras/engine/base_layer.py#L54) class and not explicitly mentioned in the docs.
score: 0
type: AnswerComment

http://stackoverflow.com/a/62068566
answers question: http://stackoverflow.com/q/50536250
has comment: http://stackoverflow.com/comment/123355090
type: AcceptedAnswer
downvote count: 1
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50536250
has body: I found the answer while writing up this question and figured I'd post the solution for anyone who wants to know. To set a wedge to be transparent: import matplotlib.pyplot as plt x = [1,2,3,0.4,5] alpha = 0.5 which_wedge = 4 n = plt.pie(x) n[0][which_wedge].set_alpha(alpha) If you want to only display a single wedge, use a loop: for i in range(len(n[0])): n[0][i].set_alpha(0.0) n[0][which_wedge].set_alpha(1.0) Hope this helps someone! It can probably be used for pyplot.bar() too to hide certain bars.
score: 4

http://stackoverflow.com/q/50419547
score: 0
tagged with: matrix
has comment: http://stackoverflow.com/comment/87854717
answer count: 1
has body: Originally I have a wordsearch puzzle and my goal is to find the words in it given a previous list of words. I was able to successfully find the words in the horizontal and vertical lines, but I'm having trouble find the diagonals. My main ideia is to take my input of letters and join then in a one big string and then search for the word in this string, returning the line the word belongs to, and after that I just check where it starts, and so on. For my diagonals I was planning the same, but let's say this is my input: c l i o a e a g b e a r t l s j i a u a e e q u b e u g r r c i d e p b i o s b 2 cat big Once I convert my diagonals in a joined list this is what I get: # first diagonal first_diag = ['b', 'ci', 'eio', 'euds', 'jegeb', 'aiqrp', 'eraur', 'catub', 'lgla', 'ibs', 'oe', 'a'] # second diagonal sec_diag = ['c', 'le', 'iaa', 'ogrj', 'abtie', 'elaee', 'suquc', 'augib', 'brdi', 'reo', 'ps', 'b'] From that I would take where in my original puzzle the word "cat" is in row (0) and column (0). The same for the word "big" [8][0]. Expected output: c . . . . . a . . . . . t . . . . . . . . . . . . . . g . . . i . . . b . . . . How can I do that, or is there another way to do it? tnx in advance. edit: If needed, I can post the code I have.
has comment: http://stackoverflow.com/comment/87854929
type: Question
tagged with: python-3.x
has title: Return index of original matrix that was transformed in a diagonal list - Python 3
tagged with: diagonal
tagged with: python
has answer: http://stackoverflow.com/a/50423091
accepted answer: http://stackoverflow.com/a/50423091
type: AnsweredQuestion

http://stackoverflow.com/a/50417893
answers question: http://stackoverflow.com/q/50417711
type: Answer
score: 2
upvote count: 2
has body: You're comparing a list to a string, that'll never be true Either you just need to check if that code exists in the filter if QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1, sr_datareduce_summary_code= "Z07126").exists(): or if you need to keep the values_list, assign it to a variable and use in with values_list('sr_datareduce_summary_code', flat=True) if 'Z07126' in my_query_list:
downvote count: 0
has comment: http://stackoverflow.com/comment/87852146

http://stackoverflow.com/a/50422254
score: 1
has body: Try: name="karam" WebDriverWait(browser,10).until(EC.presence_of_element_located((By.XPATH,'//*[@title="{0}"]'.format(name)))
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50422124
answers question: http://stackoverflow.com/q/50422124
type: Answer

http://stackoverflow.com/q/50480760
accepted answer: http://stackoverflow.com/a/50480818
downvote count: 0
has answer: http://stackoverflow.com/a/50480818
possible better answer: http://stackoverflow.com/a/50480890
has body: I have a dataframe as below picture shown, how to effectively get all value with ":" in the cell and create a new dataframe? For instance, "cnt:1" shall be converted to "1"; "ack:dsn:113" shall be converted to "113", etc.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87975255
has comment: http://stackoverflow.com/comment/87975189
has comment: http://stackoverflow.com/comment/87975056
tagged with: python
has answer: http://stackoverflow.com/a/50480890
type: AnsweredQuestion
answer count: 2
has title: How to reshape dataframe with pandas
tagged with: pandas
has comment: http://stackoverflow.com/comment/87974677
score: 2
upvote count: 2

http://stackoverflow.com/comment/88034305
has text: Can this not be tackled with some form of regular expression?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50510875
score: 0

http://stackoverflow.com/q/50536502
downvote count: 0
has body: Stack: Google App Engine Flexible Python 2.7 I cannot seem to write info messages using the python logging module after configuring it to use stackdriver. In my main function for my service I have: from paste import httpserver import google.cloud.logging client = google.cloud.logging.Client('my-project-id') client.setup_logging(logging.INFO) logging.getLogger().setLevel(logging.INFO) logging.info('in main - info') httpserver.serve(app, host='127.0.0.1', port='8080') But I do not see the text 'in main - info' in my stackdriver logs. I also have the following code that responds to a request for the main page of my app: class MainPage(webapp2.RequestHandler): def get(self): logging.info('in MainPage - info') logging.error('in MainPage - error') print('in MainPage - print') self.response.write('nothing to see.') This code returns 'noting to see' to the browser, and writes 'in MainPage - error' to the stackdriver logs via stderr, as well as 'in MainPage - print' to the stackdriver logs via stdout. however, 'in MainPage - info' does not appear anywhere in the stackdriver logs. It is as if setting the log level of the logger has no effect and it is stuck at ERROR. I've tried many variations of this and searched for examples but am coming up empty. I am sure there must be something I am missing regarding the use of stackdriver logging - I'm hoping someone can point me to an example that successfully writes info log messages to stackdriver using python 2.7 and google app engine flexible. Thanks in advance!
upvote count: 1
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88747845
tagged with: google-cloud-stackdriver
type: UnansweredQuestion
tagged with: google-app-engine
has title: Can't write logging.info messages to stackdriver using google app engine flexible
tagged with: python
tagged with: python-2.7
answer count: 0
tagged with: app-engine-flexible

http://stackoverflow.com/comment/87927926
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50456945
has text: I am simply asking how to iterate through each unique ID and output that ID as an array with multiple rows that can be plotted. I have tried iterating using np.nditer. It didn't work, it only spit out the rows of ID data. I am not asking for you to code for me. Instead of closing it, could you send me to a similar question? I have looked for 6+ hours and I haven't found code that iterates and collect values for unique outputs.

http://stackoverflow.com/comment/88469551
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50528211
has text: You could also just ``pip install mod_wsgi`` then run ``mod_wsgi-express start-server`` with your Flask app and proxy it to it. So don't run it in your main Apache. The Flask builtin development server should not be used for production sites.
type: Comment

http://stackoverflow.com/comment/88024558
has text: Wow, thank you!... I've tried your suggestions: 2) I've added tf.nn.relu activation to the dense layers, i've also incremented to 4 the hidden layer size 3) The loss function uses the output of the last dense layer, not the softmax output 4) I'm now feeding in batches of 1000 samples. 5) I'm normalizing the input. layer1 = tf.layers.dense(X / 5 - 1, 4) The result are looking good... 97.45% accuracy.
comment on: http://stackoverflow.com/a/50497139
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88001807
has text: Sorry, negociadoraA = tratativaUm
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50489392

http://stackoverflow.com/comment/87980908
type: QuestionComment
comment on: http://stackoverflow.com/q/50483587
score: 3
has text: Have you googled your error message? https://stackoverflow.com/a/35016330/8881141 It seems you have strings, not float/integers in your dataframe.
type: Comment

http://stackoverflow.com/comment/87993899
type: Comment
type: QuestionComment
has text: but, `def export(param):` don't need to be with `self` ? `def export(self, paras):`
comment on: http://stackoverflow.com/q/50490410
score: 0

http://stackoverflow.com/q/50398634
type: UnansweredQuestion
has title: Django Crispy Forms add HTML Attributes
tagged with: lastpass
tagged with: django
tagged with: python
has body: My goal is to have LastPass ignore all input forms on my site. I am using crispy forms and showing all form fields with only this in my HTML: However, I want to edit some of the HTML attributes of all input elements created by this form WITHOUT writing each one individually. LastPass recommends that I use data-lpignore="true" in my HTML input tags. I tried to implement that in my form tags, but that didn't work (yes, I know, form != input). : &lt;form action="{{ action }}" method="post" class="no-ajax" data-lpignore="true"&gt; {% csrf_token %} &lt;input type="submit" name="submit" value="Save" class="btn btn-primary btn-lg" /&gt; &lt;/form&gt; This didn't work. I also tried including the following in SETTINGS.py: CRISPY_CLASS_CONVERTERS = {'data-lpignore': 'true'} Which is supposed to add data-lpignore="true" to my crispy form input tags according to crispy forms' documentation, but this didn't work. Am I stuck doing individual input lines or is there a better solution?
has answer: http://stackoverflow.com/a/50402685
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: forms
favorite count: 0
type: Question

http://stackoverflow.com/a/50465216
has comment: http://stackoverflow.com/comment/87943717
answers question: http://stackoverflow.com/q/50465188
has comment: http://stackoverflow.com/comment/87944405
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87944544
has comment: http://stackoverflow.com/comment/87944440
has comment: http://stackoverflow.com/comment/87944062
score: 3
has comment: http://stackoverflow.com/comment/87943936
has comment: http://stackoverflow.com/comment/87943999
accepted answer of: http://stackoverflow.com/q/50465188
has comment: http://stackoverflow.com/comment/87943923
type: Answer
has body: You can use numpy.setdiff1d if inputs are lists of columns names for Series and for new columns names assign: s = pd.Series(0, index=np.setdiff1d(dataframe1_columns, dataframe2_columns)) print (s) old2 0 old3 0 old4 0 old6 0 dtype: int64 df = dataframe2.assign(**s) print (df) adult adultold old old1 old2 old3 old4 old6 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 4 1 0 0 0 0 0 0 0 5 1 0 0 0 0 0 0 0 6 0 0 0 1 0 0 0 0 7 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 10 0 0 0 0 0 0 0 0

http://stackoverflow.com/q/50401028
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
has title: Problems regarding Python if statement
has comment: http://stackoverflow.com/comment/87817998
has answer: http://stackoverflow.com/a/50401047
has body: I am running Python 3.6.4 with Anaconda and Spyder. Does anyone know why the following is happening? When I execute the following code python prints "yes" which it is obviously wrong. import numpy as np a = 0 c = np.ones(150) b = np.ones(10) if a &lt; len(c) &amp; len(b) &lt; 3: print('yes') While when I made a slight modification the condition is not satisfied and python does not print anything a = 0 c = np.ones(152) b = np.ones(10) if a &lt; len(c) &amp; len(b) &lt; 3: print('yes') Furthermore if I change "&amp;" with "and" everything is working as expected.
accepted answer: http://stackoverflow.com/a/50401047
has comment: http://stackoverflow.com/comment/87818092
has comment: http://stackoverflow.com/comment/87818002
linked to: http://stackoverflow.com/q/3845018
tagged with: python
has comment: http://stackoverflow.com/comment/87817944
duplicate of: http://stackoverflow.com/q/3845018
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87818064
possible better answer: http://stackoverflow.com/a/50401068
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/87817947
has comment: http://stackoverflow.com/comment/87820608
has comment: http://stackoverflow.com/comment/87817886
tagged with: if-statement
has comment: http://stackoverflow.com/comment/87817881
has answer: http://stackoverflow.com/a/50401068
duplicate of: http://stackoverflow.com/q/41390988

http://stackoverflow.com/q/50456031
tagged with: pybinding
tagged with: c++
has comment: http://stackoverflow.com/comment/87926032
tagged with: boost
downvote count: 0
answer count: 1
has title: Assign value to a class member variable in python from c++ with boost python
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87928478
tagged with: boost-python
has answer: http://stackoverflow.com/a/50461397
has body: I have a C++ class that is exposed to python with boost python framework. struct Var { Var(std::string name) : name(name), value() {} std::string const name; float value; }; BOOST_PYTHON_MODULE(hello) { class_&lt;Var&gt;("Var", init&lt;std::string&gt;()) .def_readonly("name", &amp;Var::name) .def_readwrite("value", &amp;Var::value); ; } Below is the python script using this class: x = hello.Var("hello") def print_func(): print(x.value) Is it possible to access the object x inside C++ code and assign the value member variable a value in c++ that is printed when print_func() is executed in the python script ?
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87925708
has comment: http://stackoverflow.com/comment/87926200
tagged with: python

http://stackoverflow.com/q/50486963
downvote count: 2
has comment: http://stackoverflow.com/comment/87986714
answer count: 1
has comment: http://stackoverflow.com/comment/87986850
has body: I have a list in python 3.6.5 which goes as follows a_list = [['name1', 5, 6, 3, 7], ['name3', 2, 6, 3, 6], ['name3', 2, 10, 8, 5]] So it's basically name, score1, score2 etc. I want to add up the scores and rank they names highest to lowest So far, I have a_list.sort(a_list, key=lambda x: x[not sure what to put here], reverse=True) I need a way of adding up the numbers in the list without affecting the str field. How can I achieve this?
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50486984
has title: Python sort 2D list
has answer: http://stackoverflow.com/a/50486984
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/q/50518333
type: UnansweredQuestion
tagged with: python
has body: I have the following function that generates a double Gaussian. def Model(wavelength_array, width): """Returns the model Parameters: wavelength_array: Full wavelength array. This is a constant width: width of the Gaussians. This varies. """ Gaussian = lambda x, mean, std: np.exp(-((x[:, np.newaxis] - mean)/std)**2) separation = (3729.875-3727.092)/2 lambda0 = wavelength_array[:,(len(wavelength_array[0])+1)//2] models = [] for i,j in enumerate(wavelength_array): models.append(Gaussian(j, lambda0[i]-separation, width) + \ Gaussian(j, lambda0[i]+separation, width)) models = np.asarray(models) return models The wavelength_array is an array of arrays, and width is an array, e.g.: wavelength_array = [[4500, 4502, 4504, 4506] [4502, 4504, 4506, 4508]] width = np.arange(.1, .5, .1) I would like to loop over every array in wavelength_array and every element in width. Naively, that would mean a double loop. However, I recently learned about broadcasting and have been able to broadcast the width portion of the code. Unfortunately, I still have a loop left that is looping over wavelength_array and I am unsure how I can also broadcast over this variable. If you have any suggestions and/or feedback on how I can vectorize this function completely and speed it up, I would greatly appreciate it.
tagged with: array-broadcasting
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50519180
has title: Broadcasting Multiple Arrays

http://stackoverflow.com/comment/88081144
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50533838
has text: Fantastic, just what I was looking for and even sorted out how to do the plotting. I was thinking that I would have to take the maximum value in each column and plot that. But this does it all in one go. It is a pity that I cannot post the plot here in the comment. I think that this is also the answer to this question: https://stackoverflow.com/questions/35461477/how-to-plot-a-gaussian-function-on-python.

http://stackoverflow.com/q/50504795
tagged with: string
score: 1
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50504877
tagged with: regex
has title: Python- Regular express without order
has answer: http://stackoverflow.com/a/50504877
type: AnsweredQuestion
has body: I want to extract for example 2 entities from a sentence. eg: str1 = 'i am tom and i have a car' I want to extract the word 'tom' or 'jack' as name if exist. I also want to extract the word 'car' or 'bike' as property if exist Now I can simply write 2 regular expressions: re.search(r"(?P&lt;name&gt;tom|jack)", s).group('name') re.search(r"(?P&lt;property&gt;car|bike)", s).group('property') But I wonder if I can combine these two together. The problem is I could not know the order of both name and property. So the following code re.search(r"(?P&lt;name&gt;tom|jim).*(?P&lt;property&gt;car|bike)", s) does not work for : 'str2 = i have a car and i am tom' I tried to simply combine two order situation re.search(r"(((?P&lt;name&gt;tom|jack).*(?P&lt;property&gt;car|bike))|((?P&lt;property&gt;car|bike).*(?P&lt;name&gt;tom|jack)))", s2) it gives me "redefinition of group name" error unless I changed to re.search(r"(((?P&lt;name&gt;tom|jack).*(?P&lt;property&gt;car|bike))|((?P&lt;property2&gt;car|bike).*(?P&lt;name2&gt;tom|jack)))", s2) Question How can i write a regular express to extract tom/jack as name and car/bike as property without considering the order? Moreover I don't want to simply list all the possible orders because it might be too many situations if i want to extract n kinds of entities.
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50532582
has body: Ignoring all the other issues I can see with your code, here is a simple MCVE example of how to load a dictionary from a file into your program with values being placed in the entry field. Please use my below example when formulating future questions as the below example shows a Minimal, Complete, and Verifiable example. The bare minimum to reproduce an issue or behavior related to your question. As you can see I do not include things like the title or various other functions or variables that are unrelated to the specific questions. My example will use a couple class attributes to hold the dictionary and to hold a list used for creating the different fields. I use a list in this way because I can get the index information easy and use that to programmatically produce the correct labels and entry fields in the correct rows and columns. By producing this list we can also use it to store new values and save them to a file but that is an answer for another question if you are unable to work it out. Here is my example dictionary: {"Age":"30", "Name":"Mike", "Job":"Network Engineer"} Here is my code: Keep in mind you will need to use your own file path to your dictionary file. import tkinter as tk import json class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.button_frame = tk.Frame(self) self.button_frame.grid(row=0, column=0) self.data_frame = tk.Frame(self) self.data_frame.grid(row=0, column=2) self.loaded_dict = {} self.data_list = [] tk.Button(self.button_frame, text="Load dictionary data", command=self.load_dict).grid(row=0, column=0) def load_dict(self): self.loaded_dict = {} with open(".path/to/dict_file.txt", "r") as f: self.loaded_dict = json.load(f) if self.loaded_dict != {}: for key, value in self.loaded_dict.items(): self.data_list.append([tk.Label(self.data_frame, text=key), tk.Entry(self.data_frame), value]) for ndex, item in enumerate(self.data_list): item[0].grid(row=ndex, column=0) item[1].grid(row=ndex, column=1) item[1].insert(0, item[2])…
has comment: http://stackoverflow.com/comment/88077316
has comment: http://stackoverflow.com/comment/88077870
has comment: http://stackoverflow.com/comment/88077699
has comment: http://stackoverflow.com/comment/88077384
accepted answer of: http://stackoverflow.com/q/50531031
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88078157
type: Answer
has comment: http://stackoverflow.com/comment/88077341
answers question: http://stackoverflow.com/q/50531031
score: 0

http://stackoverflow.com/comment/87890558
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50438292
type: Comment
has text: OpenCV version 3.4.1

http://stackoverflow.com/a/50489778
upvote count: 1
has body: The problem is on this line: model_instance.dress_image1.save(thumb_io, model_instance.format, quality=60 ) You probably want this: model_instance.dress_image1.save(thumb_io, model_instance.dress_image1.format, quality=60 )
accepted answer of: http://stackoverflow.com/q/50489294
type: Answer
has comment: http://stackoverflow.com/comment/87993110
answers question: http://stackoverflow.com/q/50489294
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87992634
downvote count: 0
has comment: http://stackoverflow.com/comment/88021671

http://stackoverflow.com/q/50481939
tagged with: python
has comment: http://stackoverflow.com/comment/87977164
has comment: http://stackoverflow.com/comment/87977808
has comment: http://stackoverflow.com/comment/87977373
has comment: http://stackoverflow.com/comment/87982267
tagged with: command
type: Question
score: 0
has title: I want to copy a .wav file from my current system to linux server using python
type: UnansweredQuestion
upvote count: 1
has body: Any one have idea then please suggest, This is how I'm doing now. bt not working. Here I'm trying to copy my newtext.wav file to server location. def copyToServer(): success = os.system("scp D:/AMRITESH/ContractMonitoring/newtext.wav root@xxx.xxx.x.xxx:/usr/share/asterisk/sounds") if (success != True): print(success) print "Connection Error" else: print "Connection Established"
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88004492
tagged with: copy
favorite count: 0
tagged with: scp
has comment: http://stackoverflow.com/comment/87977456
has comment: http://stackoverflow.com/comment/87977756
has comment: http://stackoverflow.com/comment/88004487
has comment: http://stackoverflow.com/comment/87977138
has comment: http://stackoverflow.com/comment/87976880
has answer: http://stackoverflow.com/a/50495949
tagged with: ssh

http://stackoverflow.com/comment/87949126
score: 0
comment on: http://stackoverflow.com/q/50467544
type: QuestionComment
has text: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
type: Comment

http://stackoverflow.com/comment/88073683
type: Comment
type: QuestionComment
has text: @khelwood to make sure his code will be un-debuggable
comment on: http://stackoverflow.com/q/50530834
score: 1

http://stackoverflow.com/q/50468778
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50484910
has title: MFA authentication using Python boto for DynamoDb
tagged with: boto
score: 2
upvote count: 2
tagged with: python-2.7
answer count: 2
tagged with: multi-factor-authentication
has body: I've a old code which looks like something below boto.dynamodb2.connect_to_region( region_name=AWS_REGION, aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=SECRET_ACCESS_KEY) My organization has mandated MFA authentication recently. So this code gives me boto.exception.JSONResponseError: JSONResponseError: 400 Bad Request {u'Message': u'User: arn:aws:iam::123123123123:user/mike.ross is not authorized to perform: dynamodb:Scan on resource: arn:aws:dynamodb:us-west-2:123123123:table/MyTable with an explicit deny', u'__type': u'com.amazon.coral.service#AccessDeniedException'} I tried to search Internet for code examples which use MFA authentication but so far I'm unsuccessful. So far, I tried to add session_token parameter but it did not recognize the parameter. Then I tried removing all the parameters from the connect_to_region method and exported follwing environment variables with appropriate values AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN Then I got boto.exception.JSONResponseError: JSONResponseError: 400 Bad Request {u'message': u'The security token included in the request is invalid.', u'__type': u'com.amazon.coral.service#UnrecognizedClientException'} How do I change this code to use MFA authentication?
tagged with: amazon-dynamodb
downvote count: 0
has answer: http://stackoverflow.com/a/50471336
favorite count: 0

http://stackoverflow.com/comment/87904224
score: 0
type: AnswerComment
has text: Here I don't want INFO logs to get notified by SNS. Only ERROR logs should get notified by SNS.
comment on: http://stackoverflow.com/a/50445010
type: Comment

http://stackoverflow.com/q/50485225
tagged with: urllib2
has answer: http://stackoverflow.com/a/50485611
type: UnansweredQuestion
has title: Correct way to handle exception on Python2.6
tagged with: python
tagged with: python-2.6
score: 0
has body: I had an Python script that running continuously. If there any new file on directory then the python will open url using urllib2 to do some request on specific ip. here are the code encoded_string = base64.b64encode(image_file.read()) values = dumps({ 'image_data':encoded_string, 'requestCode':'111' }) headers = {"Content-Type": "application/json"} request = Request("http:/xx.xxx.xx.xxx/api/carplate_service",data=values, headers=headers) response = urlopen(request, timeout=60) The code are working well but on random time, let say usually happened on 1-2 AM then I got this error: &lt;class 'urllib2.URLError'&gt; - &lt;urlopen error [Errno 110] Connection timed out&gt; I had an exception on that function on this bellow : try: ip = sys.argv[1] histId = int(sys.argv[2]) handler = ModHandler() wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch('./' + ip + '/', pyinotify.IN_CLOSE_WRITE) notifier.loop() except BaseException as e: with open("error.log", "a") as text_file: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] text_file.write( time.strftime("%Y-%m-%d %H:%M:%S") + " [" + str(exc_tb.tb_lineno) + " - " + fname + "] : " + str(exc_type) + " - " + str(e) + "\n") text_file.close(); The exception not working well because application cannot continue if there are some error like above. My question are how to make program still continue even the exception throw? I'm using python2.6 Thanks
has comment: http://stackoverflow.com/comment/87983527
answer count: 1
type: Question

http://stackoverflow.com/q/50502669
tagged with: flask-wtforms
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: What field do you think is suitable for asking for someone's height, preferably in the format: ft' inches? I thought about decimal or integer fields, but asking for someone's height in inches or cm seems unintuitive and confusing. Should I use a string field? If so, how do I verify that the input is in the format of something like 5'6 or 6'0? Thank you.
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/50503085
downvote count: 1
score: -1
type: Question
upvote count: 0
has title: What Field to Use for Height?

http://stackoverflow.com/a/50482629
has body: Change list_new.extend(str(email)) To: list_new.append(str(email)) append adds its argument as a single element to the end of a list. The length of the list itself will increase by one. extend iterates over its argument adding each element to the list, extending the list. This post might help you.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50482527
score: 2
answers question: http://stackoverflow.com/q/50482527
upvote count: 2

http://stackoverflow.com/comment/87871204
type: Comment
has text: Manually screwing with your site-packages is going to give you even more problems down the line.
type: AnswerComment
comment on: http://stackoverflow.com/a/50419988
score: 0

http://stackoverflow.com/comment/87854998
type: AnswerComment
has text: Just because something is "fast enough", does not make it good practice, or something you should be recommending to those trying to learn pandas. Just because driving 10 mph under the speed limit is usually "fast enough" to not get pulled over for driving too slowly, doesn't mean it's the right thing to do.
type: Comment
comment on: http://stackoverflow.com/a/50419584
score: 0

http://stackoverflow.com/q/50474244
type: Question
has comment: http://stackoverflow.com/comment/88389202
tagged with: plotly
has answer: http://stackoverflow.com/a/50692021
accepted answer: http://stackoverflow.com/a/50692021
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
has body: Example code: from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go import numpy as np N = 30 random_x = np.random.randn(N) random_y = np.random.randn(N) # Create a trace trace = go.Scatter( x = random_x, y = random_y, mode = 'markers' ) data = [trace] # Plot and embed in ipython notebook! iplot(data, filename='basic-scatter') [ ] How do I get a copy of the x,y data, or the indices from the selection?
has comment: http://stackoverflow.com/comment/89061210
has comment: http://stackoverflow.com/comment/88232209
has title: How do I get data from selected points in an offline plotly python jupyter notebook?
answer count: 1
score: 6
upvote count: 7
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87928772
comment on: http://stackoverflow.com/q/50457604
type: Comment
type: QuestionComment
has text: The posted code should work, are you sure it breaks at your place? What's the exact error (with stack trace) that you get?
score: 0

http://stackoverflow.com/q/50512188
score: 19
type: AnsweredQuestion
upvote count: 19
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50512268
accepted answer: http://stackoverflow.com/a/50512709
has title: Unpack dictionary from Pandas Column
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50512709
has body: I have a dataframe that has one of the columns as a dictionary. I want to unpack it into multiple columns (i.e. code, amount are separate columns in the below Raw column format). The following code used to work with pandas v0.22, now (0.23) giving an index error: pd.DataFrame.from_records(df.col_name.fillna(pd.Series([{'code':'not applicable'}], index=df.index)).values.tolist()) ValueError: Length of passed values is 1, index implies x I searched google/stack overflow for hours and none of the other solutions previously presented work anymore. Raw column format: dict_codes 0 {'code': 'xx', 'amount': '10.00',... 1 {'code': 'yy', 'amount': '20.00'... 2 {'code': 'bb', 'amount': '30.00'... 3 {'code': 'aa', 'amount': '40.00'... 10 {'code': 'zz', 'amount': '50.00'... 11 NaN 12 NaN 13 NaN Does anyone have any suggestions? Thanks
downvote count: 0
has answer: http://stackoverflow.com/a/50512268
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/88016744
has text: Thanks a lot, I finally got it to work. This Answer is correct along with the other answer.
comment on: http://stackoverflow.com/a/50501907
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50529071
type: Question
has answer: http://stackoverflow.com/a/50529388
tagged with: python
type: UnansweredQuestion
score: -1
has body: I am creating a todo app with python and Django and I have a delete button that I want to delete tasks out of a task list but I am very new to this and I have no idea how to make the delete button actually delete lol. I would really appreciate some help. thanks in advance.
upvote count: 0
tagged with: button
tagged with: django
has comment: http://stackoverflow.com/comment/88069855
has comment: http://stackoverflow.com/comment/88069915
has title: how to make a delete button work. im using python, django, and bootstrap for the delete button
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/88005825
score: 0
comment on: http://stackoverflow.com/a/50495635
type: Comment
type: AnswerComment
has text: Is there a possibility to find overlapping strings?

http://stackoverflow.com/comment/88077527
type: Comment
type: QuestionComment
has text: Did you consider removing the `print(count)`? It seems excessive to print a million line to the console.
score: 0
comment on: http://stackoverflow.com/q/50532332

http://stackoverflow.com/q/50401691
has answer: http://stackoverflow.com/a/50402385
accepted answer: http://stackoverflow.com/a/50402385
favorite count: 0
type: AnsweredQuestion
has title: How can I find how many days has an AWS IAM user been inactive/idle for with boto3?
possible better answer: http://stackoverflow.com/a/58328300
has answer: http://stackoverflow.com/a/58328300
tagged with: aws-sdk
tagged with: python
upvote count: 4
tagged with: boto3
score: 4
tagged with: amazon-iam
type: Question
answer count: 2
downvote count: 0
has body: I would like to enforce a user lockout if that user has not logged in with username and password in aws account. How can I poll for user activity, when he/she was last active on his/her account?
tagged with: amazon-web-services

http://stackoverflow.com/a/50457168
score: 2
has body: Here's a suggestion on how to solve the problem; however I don't affirm this is the best approach, and it's certainly not the only one. Main idea Your problem can be modelised as a weighted minimum set cover problem. Good news, this is a well known optimization problem: It is easy to find algorithm descriptions for approximate solutions A quick search on the web shows many implementations of approximation algorithms in Python. Bad news, this is a NP-hard optimization problem: If you need an exact solution: algorithms will work only for "small" sized problems in a reasonable amount of time(in your case: size of the problem &lt;=> number of "1" cells). Approximate (a.k.a greedy) algorithms are trade-off between computation requirements, and a risk do deliver far from optimal solutions in certain cases. Note that the following part does not prove that your problem is NP-hard. The general minimum set cover problem is NP-hard. In your case the subsets have several properties that might help to design a better algorithm. I have no idea how though. Translating into a cover set problem Let's define some sets: U: the set of "1" cells (requiring Wifi). P(U): the power set of U (the set of subsets of U). P: the set of cells on which you can place a router (not sure if P=U in your original post). T: the set of router type (3 values in your case). R+: positive Real number (used to describe prices). Let's define a function (pseudo Python): # Domain of definition : T,P --&gt; R+,P(U) # This function takes a router type and a position, and returns # a tuple containing: # - the price of a router of the given type. # - the subset of U containing all the position covered by a router # of the given type placed at the given position. def weighted_subset(routerType, position): pass # TODO: implementation Now, we define a last set, as the image of the function we've just described: S=weighted_subset(T,P). Each element of this set is a subset of U, weighted by a price in R+. With all this …
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50452893
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50452893
downvote count: 0
type: Answer

http://stackoverflow.com/a/50526198
answers question: http://stackoverflow.com/q/50525733
has body: Try this: from PIL import Image from io import BytesIO import numpy as np import asyncio import concurrent.futures import requests def get_image_shape(path): try: img = Image.open(BytesIO(requests.get(path).content)) arr = np.array(img, dtype = np.uint8) return arr.shape except: return (0,0,0) async def main(url_list): loop = asyncio.get_event_loop() futures = [ loop.run_in_executor( None, get_image_shape, url ) for url in url_list] return [response for response in await asyncio.gather(*futures)] loop = asyncio.get_event_loop() response = loop.run_until_complete(main(url_list))
has comment: http://stackoverflow.com/comment/88065864
has comment: http://stackoverflow.com/comment/115954228
has comment: http://stackoverflow.com/comment/88089582
type: Answer
has comment: http://stackoverflow.com/comment/88081898
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50525733
downvote count: 0
has comment: http://stackoverflow.com/comment/88085867
type: AcceptedAnswer

http://stackoverflow.com/comment/87799465
type: QuestionComment
score: 8
has text: Your list is INVALID.
comment on: http://stackoverflow.com/q/50391949
type: Comment

http://stackoverflow.com/comment/95016838
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50436534
type: AnswerComment
has text: @PeterCordes: Actually "truncation" only describes rounding towards zero in sign-magnitude representations, such as IEEE-754 floating point. In two's complement representation, truncation is effectively rounding towards negative infinity, and *that* is what you get from the simple expedient of shifting in copies of the sign bit at the most-significant end. In particular, if 0xFFFF is -1, then 0xFFFE is -2.

http://stackoverflow.com/q/50454954
tagged with: outlook
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/119501902
answer count: 1
downvote count: 1
has body: I'm looking to access Microsoft exchange account via python. Access the mail Read the inbox Without using smtp. Any suggestions on how it can be done
favorite count: 0
has title: Access a Microsoft Exchange account via Python
has answer: http://stackoverflow.com/a/50455433
linked to: http://stackoverflow.com/q/288546
has comment: http://stackoverflow.com/comment/87923730
tagged with: python
score: -1
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87954946
has text: If you're going to remove *all* blank lines, you can use `lines = lines.filter(lambda line: line not in ['\n', '\r'])`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50460057
type: Comment

http://stackoverflow.com/q/50416379
type: Question
tagged with: stanford-nlp
type: UnansweredQuestion
tagged with: python
has title: How can I recover from a CoreNLP Timeout, and continue to process requests?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50459905
has body: I started my Standford NLP server (CoreNLP v 3.91, stanford-corenlp-full-2018-02-27.zip) on Ubuntu 16.04 with this command: java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000 And after some time, if I throw too large of a sentence at it, it blows up. java.util.concurrent.TimeoutException at java.util.concurrent.FutureTask.get(FutureTask.java:205) at edu.stanford.nlp.pipeline.StanfordCoreNLPServer$CoreNLPHandler.handle (StanfordCoreNLPServer.java:866) [pool-1-thread-6] INFO CoreNLP - [/127.0.0.1:34048] API call w/annotators tokenize,ssplit,pos,parse,depparse But if you ask any feminist directly (and I have, one of my best friends is a woman's studies major and we have had MANY heated passionate arguments; i've spoken to her friends too), they will fully say that modern feminism is about having the choice, and while they completely disagree with women who take this choice, it is still their choice to make. java.util.concurrent.TimeoutException at java.util.concurrent.FutureTask.get(FutureTask.java:205) at edu.stanford.nlp.pipeline.StanfordCoreNLPServer$CoreNLPHandler.handle(StanfordCoreNLPServer.java:866) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79) at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:82) at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:675) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79) at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:647) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) [Thread-0] INFO CoreNLP - CoreNLP Server is shutting down. Unfortunately this kills my server. I have my python script catch the exception caused by the server timeout, but how can I pass it, and continue using the server. I am…

http://stackoverflow.com/q/50465966
has title: Re-using zip iterator in python 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/50466182
tagged with: python
accepted answer: http://stackoverflow.com/a/50466346
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25336726
answer count: 3
has comment: http://stackoverflow.com/comment/87945809
duplicate of: http://stackoverflow.com/q/25336726
has answer: http://stackoverflow.com/a/50466182
has answer: http://stackoverflow.com/a/50466060
has body: I have the zip object: L_RANGES = zip(range(10, 20), range(11, 21)) First call of L_RANGES is ok: print(type(L_RANGES)) for a, b in L_RANGES: print(a, b) Output: &lt;class 'zip'&gt; 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 Bu the next calls do not display anything. Is there any way to maintain or reset that. So far I can just convert it to the list: L_RANGES = list(zip(range(10, 20), range(11, 21)))
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50466346
tagged with: iterator
score: 8
upvote count: 8

http://stackoverflow.com/comment/115954228
has text: Catching all exceptions and suppressing them is very risky, any unexpected exceptions that occur in your try block will also be suppressed and make it hard to find new errors. If you catch the specific exception you expect it limits that risk. Also, there are several actions in the try block, if the exception is expected from just one of them then only keep that in the try and move the rest to earlier or an else block. If you can't do these things you can at least log the exception at the error level so you still have the exception info when it occurs.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50526198

http://stackoverflow.com/comment/87795912
type: Comment
has text: I'm in window10 environment and my code in infinite loop. Same problem in your solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/50390017
score: 0

http://stackoverflow.com/comment/87871341
type: Comment
comment on: http://stackoverflow.com/q/50427228
score: 0
has text: Thank you very much, I fixed this and now, it's working. Great, I'll remember it for further use of classes and objects!
type: QuestionComment

http://stackoverflow.com/q/50436634
answer count: 1
downvote count: 0
upvote count: 1
has body: I'm using fetch_lfw_people from sklearn to get the faces to recognize and but when I trat to reshape II get this error ValueError: cannot reshape array of size 6744500 into shape (574,1,64,47) but for the data that I have It seems like the correct parameters ,is the image size that says the doc doc I know 574*1*64*47 is not 6744500 but is the data that I have lfw_people = fetch_lfw_people(min_faces_per_person=200, resize=1) X = lfw_people.data y = lfw_people.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25) X_train = X_train.reshape(X_train.shape[0], 1, 64, 47).astype('float32') X_test = X_test.reshape(X_test.shape[0], 1, 64, 47).astype('float32')
favorite count: 0
type: Question
has title: ValueError: cannot reshape array of size 6744500 into shape (574,1,64,47)
accepted answer: http://stackoverflow.com/a/50436743
has answer: http://stackoverflow.com/a/50436743
tagged with: scikit-learn
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/87931884
comment on: http://stackoverflow.com/a/50459205
type: AnswerComment
score: 0
type: Comment
has text: It's possible that the data I provided is not fully representative of my "actual" data but I keep getting the wrong results from these formulas. There's some strange summing going on which produce higher values than they should.

http://stackoverflow.com/a/50414742
has body: From scipy argrelextrema from scipy.signal import argrelextrema df.iloc[argrelextrema(df.x_cor.values, np.greater)] Out[981]: x_cor y_cor 893.400024 41 893.599976 40 894.000000 44 894.299988 88 894.599976 180
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87845994
has comment: http://stackoverflow.com/comment/87845296
has comment: http://stackoverflow.com/comment/87846259
type: Answer
answers question: http://stackoverflow.com/q/50414625
downvote count: 0
has comment: http://stackoverflow.com/comment/87845564
has comment: http://stackoverflow.com/comment/87845344
accepted answer of: http://stackoverflow.com/q/50414625
type: AcceptedAnswer

http://stackoverflow.com/q/50458723
tagged with: python
accepted answer: http://stackoverflow.com/a/50458785
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50458785
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Python How to send tuple data (signature) through socket
has body: I want to send signature &amp; verify in Server(signature) but receive the following error: TypeError: send() argument 1 must be string or buffer, not tuple How do I send a tuple? Or is there an alternative way? Client from Crypto.PublicKey import RSA from Crypto import Random import socket import hashlib random_generator = Random.new().read private_key = RSA.generate(1024, random_generator) pri_key_str=private_key.exportKey() pri_key_str ="""-----BEGIN RSA PRIVATE KEY----- blah balh~ -----END RSA PRIVATE KEY-----""" pri_key = RSA.importKey(pri_key_str) filename = 'a.txt' blocksize = 65536 def hashvalue(filename): #hash value hash = hashlib.sha256() with open(filename, "rb")as f: for block in iter(lambda: f.read(blocksize), b""): hash.update(block) return hash.hexdigest() print hashvalue(filename) signature = pri_key.sign(hashvalue(filename),'') print signature public_key = private_key.publickey() pub_key_str = public_key.exportKey() pub_key_str="""-----BEGIN PUBLIC KEY----- blah blah~ -----END PUBLIC KEY-----""" pub_key=RSA.importKey(pub_key_str) #create public key if pub_key.verify(hashvalue(filename),signature): print ("The signature is authentic") else: print ("The signature is not authentic") HOST = '127.0.0.1' PORT = 7777 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST, PORT)) client.send(hashvalue(filename)) client.send(signature ) Server from Crypto.PublicKey import RSA import socket pub_key_str="""-----BEGIN PUBLIC KEY----- blah blah~ -----END PUBLIC KEY-----""" pub_key=RSA.importKey(pub_key_str) #create public_key HOST= '127.0.0.1' PORT = 7777 server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind((HOST, PORT)) server.listen(10) client, addr = server.accept() hashv=client.recv(1024) print "receive data ( hash ) : " ,hashv signature=client.recv(1024) print "recv signature (type : str)" ,signature if pub_key.verify(hashv,a): print ("The signature is authentic") else: print ("The signature is not authentic") Error!…

http://stackoverflow.com/comment/87993111
has text: Yes, it does, unless you did a modification to the settings (disable cache option under dev tools > network)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50489982
type: QuestionComment

http://stackoverflow.com/comment/87880158
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50430883
type: AnswerComment
has text: is the python request from another server? Why do you need an API if not. You need to send a post request with form data that contains the json representation of your ProductSerializer (should be a ModelSerializer else you need to manually create the object when receiving the data)

http://stackoverflow.com/a/50419018
accepted answer of: http://stackoverflow.com/q/50418903
has comment: http://stackoverflow.com/comment/87888941
score: 5
type: AcceptedAnswer
downvote count: 0
has body: Floating point arithmetic error Your error is due to float arithmetic error. Here is what happens when you input a value such as 0.26. change = 0.26 change -= 0.25 change -= 0.01 print (change) # 8.673617379884035e-18 Since the last value of change is above 0 but below 0.01, you enter an infinite loop. How to fix it One way to fix this is to rely on exact arithmetic by using int instead of float to represent discrete values such as currencies. This means making your base unit the cent instead of the dollar. change_map = { 'quarter' : 0, 'dime' : 0, 'nickel' : 0, 'penny' : 0 } def calculator(change): while change &gt; 0: if change &gt;= 25: change -= 25 change_map['quarter'] += 1 elif change &gt;= 10: change -= 10 change_map['dime'] += 1 elif change &gt;= 5: change -= 5 change_map['nickel'] += 1 else: change -= 1 change_map['penny'] += 1 print ("You need the following: ") print (change_map) change = raw_input("Please enter amount of change: ") # Here we convert the decimal value input by the user to cents change = int(float(change) * 100) calculator(change) Example: Please enter amount of change: 0.26 You need the following: {'quarter': 1, 'dime': 0, 'nickel': 0, 'penny': 1} Improvements On a side note, you can improve your solution by using a dict of values and names for coins. In particular, this allows you to extend your program by updating the dict instead of having to add a new if-statement. Here is an example that adds in the possibility to return a dollar as change. value_map = { 100: 'dollar', 25: 'quarter', 10: 'dime', 5: 'nickel', 1: 'penny' } def calculator(change): change_map = {} for value in sorted(value_map, reverse=True): coin = value_map[value] change_map[coin], change = divmod(change, value) print ("You need the following: ") print (change_map) change = raw_input("Please enter amount of change: ") change = int(float(change) * 100) calculator(change)
has comment: http://stackoverflow.com/comment/87853658
upvote count: 5
answers question: http://stackoverflow.com/q/50418903
type: Answer

http://stackoverflow.com/comment/88002432
type: QuestionComment
has text: what steps are you using to install? pip? conda?
type: Comment
comment on: http://stackoverflow.com/q/50494746
score: 0

http://stackoverflow.com/q/50452025
tagged with: celery
favorite count: 0
tagged with: redis
tagged with: python
tagged with: daemon
type: Question
has title: Custom Celery Task class does not work properly
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/50454171
has body: I am struggling to get Celery work. I am new to Python in general and obviously to Celery and I am trying to get basic example work. I would like to run a background task which should preserve it's state as long as it is alive. So I try to implement basic example of incrementing an integer variable when called from client script. I am working on Raspberry Pi with raspbian image. Here is my worker task code: from celery import Task, registry, Celery import celery celery = Celery('tasks', broker='redis://localhost:6379',backend='redis://localhost:6379') class MyTask(celery.Task): a = 0 def __init__(self): self.a = 0 def increment(self, x): self.a += x return self.a @property def a(self): return a @celery.task(Base=MyTask) def mytask(x): mytask.increment(x) return mytask.a And this is the calling script: from tasks import mytask result = mytask.delay(2) print result.get(timeout=1) Which yields following error: [2018-05-21 15:08:23,889: DEBUG/MainProcess] TaskPool: Apply &lt;function _fast_trace_task at 0x7610cdf0&gt; (args:('tasks.mytask', '3ae83225-faee-4dc0-a6c1-1a7e7e5eaca2', {'origin': 'gen27381@raspberrypi', 'lang': 'py', 'task': 'tasks.mytask', 'group': None, 'root_id': '3ae83225-faee-4dc0-a6c1-1a7e7e5eaca2', u'delivery_info': {u'priority': 0, u'redelivered': None, u'routing_key': 'celery', u'exchange': u''}, 'expires': None, u'correlation_id': '3ae83225-faee-4dc0-a6c1-1a7e7e5eaca2', 'retries': 0, 'timelimit': [None, None], 'argsrepr': '(2,)', 'eta': None, 'parent_id': None, u'reply_to': 'fdebe38f-7353-3ef2-920b-74f76a294ff7', 'id': '3ae83225-faee-4dc0-a6c1-1a7e7e5eaca2', 'kwargsrepr': '{}'}, '[[2], {}, {"chord": null, "callbacks": null, "errbacks": null, "chain": null}]', 'application/json', 'utf-8') kwargs:{}) [2018-05-21 15:08:23,894: DEBUG/MainProcess] Task accepted: tasks2.mytask[3ae83225-faee-4dc0-a6c1-1a7e7e5eaca2] pid:27366 Traceback (most recent call last): File "test2.py", line 4, in &lt;module&gt; print result.get(timeout=1) File "/usr/local/lib/python…
type: UnansweredQuestion
answer count: 1
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/50527694
score: 0
has body: Try boto3 library from Amazon, its has all the functions your would like to do S3, GET/POST/PUT/DELETE/LIST. PUT Example-- # Upload a new file data = open('test.jpg', 'rb') s3.Bucket('my-bucket').put_object(Key='test.jpg', Body=data)
type: Answer
answers question: http://stackoverflow.com/q/50527604

http://stackoverflow.com/comment/87980959
type: Comment
type: QuestionComment
has text: @Gábor: I don't understand why you think the embedded newlines prevent you from searching for the keyword you're looking for. Can you please show the code that you've written to decode the base64 data?
comment on: http://stackoverflow.com/q/50483586
score: 1

http://stackoverflow.com/q/50530100
has answer: http://stackoverflow.com/a/50530181
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50530181
has body: I need to ask how to use keras predict from keras functional api. I need to write multivariate LSTM model with multioutput. I have written such model: inp = Input((train_X.shape[1],train_X.shape[2])) x = LSTM(192,return_sequences=True)(inp) x = Dropout(0.5)(x) x = Flatten()(x) out1 = Dense(1,activation='softsign')(x) out2 = Dense(1,activation='softsign')(x) model = Model(inputs =inp,outputs= (out1,out2)) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(train_X,[y1,y2]) ypred = model.predict([pred_X,pred_Y]) What I want (expect) is ypred returning two time series,but it gives me error: ValueError: Error when checking model : the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 2 arrays: It is expecting one array as predict argument, but with only one array it will return one predicted time series. What I need to correct to get prediction of two feautures? My data have 6 columns,first two I'm trying to predict,others are features. Dimensions of my data are: train_X.shape= (24576, 192, 6) pred_X.shape= (672, 192, 6) pred_Y.shape= (672, 192, 6) y1.shape = (24576,1) y2.shape = (24576,1)
has title: Keras lstm multi output model predict two features (time series)
tagged with: python
tagged with: keras
tagged with: lstm
type: AnsweredQuestion

http://stackoverflow.com/comment/88031317
comment on: http://stackoverflow.com/q/50508048
type: Comment
type: QuestionComment
has text: You can start `nvprof` before running your CUDA or Python code, then run your CUDA or Python code to completion/termination, then get the profiling information from `nvprof` after that. It's covered in the documentation and described in the comments [here](https://stackoverflow.com/questions/50403436/profiling-arbitrary-cuda-applications). But no, it does not behave like an instantaneous monitor like `top`.
score: 0

http://stackoverflow.com/comment/87892034
score: 0
comment on: http://stackoverflow.com/q/50438920
has text: I don't know. Python is not statically typed. Does it mean anything at all in Python? I think it's just type coercion / conversion, but some people name it "casting", because it looks syntactically similar to type casting from statically typed languages.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87927408
comment on: http://stackoverflow.com/a/50456906
type: Comment
type: AnswerComment
score: 0
has text: Still I'm getting the error Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named google

http://stackoverflow.com/comment/87925254
type: QuestionComment
has text: what have you tried so far?
comment on: http://stackoverflow.com/q/50455880
score: 1
type: Comment

http://stackoverflow.com/q/50527135
has body: Say I have a dictionary: data = { "user" : { "properties" : ["i1", "i2"] } } And the following string: txt = "The user has properties {user[properties]}" I want to have: txt.format(**data) to equal: The user has properties i1, i2 I believe to achieve this, I could subclass the formatter used by str.format but I am unfortunately unsure how to proceed. I rarely subclass standard Python classes. Note that writing {user[properties][0]}, {user[properties][1]} is not an ideal option for me here. I don't know how many items are in the list so I would need to do a regex to identify matches, then find the relevant value in data and replace the matched text with {user[properties][0]}, {user[properties][1]}. str.format takes care of all the indexing from the string's value so it is very practical.
has title: str.format a list by joining its values
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51475138
type: Question
has answer: http://stackoverflow.com/a/50527216
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/50455998
score: 0
answers question: http://stackoverflow.com/q/50455713
has body: Warning: Don't try this at home at work. It is ugly. I'll give you three ways to do it. A Class Decorator def get_me_some_attributes(): return {'a': 1, 'b': 2} def add_attributes_to_class(attributes): def decorate_class(cls): for name, value in attributes.items(): setattr(cls, name, value) return cls return decorate_class @add_attributes_to_class(get_me_some_attributes()) class A: pass Test it: &gt;&gt;&gt; A.a 1 &gt;&gt;&gt; A.b 2 A Direct Call of the Metaclass Constructor &gt;&gt;&gt; B = type('B', (object,), get_me_some_attributes()) &gt;&gt;&gt; B &lt;class '__main__.B'&gt; &gt;&gt;&gt; B.a 1 &gt;&gt;&gt; B.b 2 &gt;&gt;&gt; A Custom Metaclass class MySpecialMeta(type): def __new__(cls, name, bases, namespace): SPECIAL_STUFF = namespace.pop('SPECIAL_STUFF', {}) namespace.update(SPECIAL_STUFF) return super().__new__(cls, name, bases, namespace) class C(metaclass=MySpecialMeta): SPECIAL_STUFF = get_me_some_attributes() Test it: &gt;&gt;&gt; C &lt;class '__main__.C'&gt; &gt;&gt;&gt; C.a 1 &gt;&gt;&gt; C.b 2
type: Answer

http://stackoverflow.com/a/50435935
score: 0
answers question: http://stackoverflow.com/q/50420306
type: Answer
has body: Canopy 1.5.2 is the last version available for 32-bit Mac OS X. Canopy 1.5.5 is the last version available for 32-bit Linux. https://support.enthought.com/hc/en-us/articles/204754434-Last-32-bit-Canopy-Versions-Mac-OS-X-Canopy-1-5-2-and-Linux-Canopy-1-5-5-

http://stackoverflow.com/comment/88073740
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50530893
score: 0
has text: Are you saying, that PyMongo complains when you omit `'user_ratings.Bob': 3`?

http://stackoverflow.com/comment/88052685
comment on: http://stackoverflow.com/a/50518171
type: Comment
type: AnswerComment
has text: pardon my question, but why does the "normal" Python function work then?
score: 0

http://stackoverflow.com/comment/88046610
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50517004
has text: This is a really strong candidate for datetimes and timedeltas. You'll get all sorts of benefits like leap-year support, time zones, etc.

http://stackoverflow.com/q/50500873
has body: I am trying to build a simple histogram. For some reason, my bars are behaving abnormally. As you can see in this picture, my bar over "3" is moved to the right side. I am not sure what caused it. I did align='mid' but it did not fix it. This is the code that I used to create it: def createBarChart(colName): df[colName].hist(align='mid') plt.title(str(colName)) RUNS = [1,2,3,4,5] plt.xticks(RUNS) plt.show() for column in colName: createBarChart(column) And this is what I got: bar is not centered over 3 To recreate my data: df = pd.DataFrame(np.random.randint(1,6,size=(100, 4)), columns=list('ABCD')) Thank you for your help! P/s: idk if this info is relevant, but I am using seaborn-whitegrid style. I tried to recreate a plot with sample data and it's still showing up. Is it a bug? hist created using random data
score: 4
type: Question
tagged with: matplotlib
has title: python bar chart not centered
has answer: http://stackoverflow.com/a/50500907
upvote count: 4
has answer: http://stackoverflow.com/a/50517062
favorite count: 0
answer count: 2
downvote count: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/88003769
has text: I understood your solution but Whats going wrong in my code setup. Whats the problem or reason that my code setup even after iterating through all the boxes prints only the first quote?
score: 0
comment on: http://stackoverflow.com/a/50414849
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88100231
score: 0
type: AnswerComment
has text: @PauloMattos Is this better?
type: Comment
comment on: http://stackoverflow.com/a/50539811

http://stackoverflow.com/a/50536400
upvote count: 1
has body: Replace #break the code when else statement is true with import sys; sys.exit(0). If they answer 'yes', it will simply continue to name = input().
score: 1
answers question: http://stackoverflow.com/q/50536336
type: Answer
accepted answer of: http://stackoverflow.com/q/50536336
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88084948
downvote count: 0

http://stackoverflow.com/comment/87970376
has text: If you need complete control of the terminal like that, you're likely going to be stuck with either `curses` (built-in module for complete terminal control), or maybe `prompt_toolkit` (third party package for writing custom terminals; used by `ipython` and others). Trying to do what you asked for (undo a newline already on `stdout`) is as hard in Python [as it is in C/C++](https://stackoverflow.com/q/4531000/364696) (though as [an answer there](https://stackoverflow.com/a/4531057/364696) notes, on some terminals, ANSI escape sequences could be used, it's just not portable).
score: 0
comment on: http://stackoverflow.com/q/50478393
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50440017
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50393079
has body: My question is how to define the manhattan norm when we use CUDA, what are the modifications to be made inside the def manhattan According to the documentation, the manhattan distance metric is the summation between two vectors of the absolute values of the elementwise differences. One problem you are likely running into is one of memory space. If we assume that the output of the distance metric (i.e. the matrix elements) is expressed as an ordinary python quantity, this will probably occupy 8 bytes of memory. For the stated dimension (60326), this means the matrix would occupy 60326*60326*8 bytes, which is almost 30GB. Even if we assume that you are only storing half of that, and even if we assume a 32-bit sum of absolute differences, this will still be over 7GB of storage needed. When I tried to run such a test using the sckit-learn method, I had trouble, even on a machine that had 128GB of system memory: # cat t5.py import numpy as np import random from scipy.spatial import distance from sklearn.metrics.pairwise import pairwise_distances vector_length = 416 num_signatures = 60000 sig_pattern = np.array([0,1,2,3], dtype=np.float32).reshape(4,1) signatures = np.tile(sig_pattern,(num_signatures, vector_length//sig_pattern.shape[1])) E = pairwise_distances(signatures, metric = 'manhattan', n_jobs = -1) print(E[:8,:8]) # time python t5.py Traceback (most recent call last): File "t5.py", line 17, in &lt;module&gt; E = pairwise_distances(signatures, metric = 'manhattan', n_jobs = -1) File "/root/anaconda2/lib/python2.7/site-packages/sklearn/metrics/pairwise.py", line 1247, in pairwise_distances return _parallel_pairwise(X, Y, func, n_jobs, **kwds) File "/root/anaconda2/lib/python2.7/site-packages/sklearn/metrics/pairwise.py", line 1096, in _parallel_pairwise for s in gen_even_slices(Y.shape[0], n_jobs)) File "/root/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 789, in __call__ self.retrieve() File "/root/anaconda2/lib/python2.7/site-p…
score: 1
answers question: http://stackoverflow.com/q/50393079

http://stackoverflow.com/q/50426615
answer count: 1
tagged with: mysql
has answer: http://stackoverflow.com/a/50426702
type: Question
has comment: http://stackoverflow.com/comment/87868295
has title: How do I input data from Python FLASK to a database?
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: flask
has body: I've got the below Python code: @restServer.route("/sendData", methods=['POST']) def client(): ID = request.form.get('ID') name = request.form.get('name') postcode = request.form.get('postcode') dateofbirth = request.form.get('dateofbirth') balance = request.form.get('balance') description = request.form.get('description') insert_stmt = ( "INSERT INTO clients (ID, name, postcode, dateofbirth, balance, description) " "VALUES (%s, %s, %s, %s, %s, %s)" ) data = (ID, name, postcode, dateofbirth, balance, description) cursor.execute(insert_stmt, data) conn.commit() print("Did we do it?") return jsonify(data) I've also got the below HTML code: ID of your Avenger: Name of your Avenger: Post Code of your Avenger: Date of Birth of your Avenger: Bank balance of your Avenger: Description of your Avenger: Submit And finally the below Javascript code: function nameInput() { var words = document.getElementById("ID", "name", "postcode", "dateofbirth", "balance", "description" ).value; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { var json = JSON.parse(this.responseText); document.getElementById("nameInputReturn").innerHTML = json.name; } } xhttp.open("POST", "http://127.0.0.1:5000/sendData", true); xhttp.setRequestHeader("Content-type", "application/x-www-form- urlencoded"); xhttp.send(words); } I'm trying to make it so you can input data into the form and then it will upload that data into the database. I've figured out how to input data that I specify in the code, by simply changing the parts variables inside the data = (ID, name, postcode, dateofbirth, balance, description) line. Currently, the submit button is clicked but the database just adds a line which has NULL for every column. I'm quite new to Flask, so any help is appreciated!
score: 0
tagged with: database

http://stackoverflow.com/q/50485466
tagged with: dataframe
tagged with: python
score: 4
type: AnsweredQuestion
has body: I have a dataframe: df- A B C D E 0 V 10 5 18 20 1 W 9 18 11 13 2 X 8 7 12 5 3 Y 7 9 7 8 4 Z 6 5 3 90 I want to add a column 'Result' which should return 1 if the value in column 'E' is greater than the values in B, C &amp; D columns else return 0. Output should be: A B C D E Result 0 V 10 5 18 20 1 1 W 9 18 11 13 0 2 X 8 7 12 5 0 3 Y 7 9 7 8 0 4 Z 6 5 3 90 1 For few columns, i would use logic like : if(and(E&gt;B,E&gt;C,E&gt;D),1,0), But I have to compare around 20 columns (from B to U) with column name 'V'. Additionally, the dataframe has around 100 thousand rows. I am using df['Result']=np.where((df.ix[:,1:20])&lt;df['V']).all(1),1,0) And it gives a Memory error.
tagged with: pandas
tagged with: compare
downvote count: 0
answer count: 1
has title: compare multiple columns of pandas dataframe with one column
favorite count: 0
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50485875
linked to: http://stackoverflow.com/q/15891038
has answer: http://stackoverflow.com/a/50485875
has comment: http://stackoverflow.com/comment/87985157

http://stackoverflow.com/q/50538626
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/19054923
has comment: http://stackoverflow.com/comment/88093725
has body: My problem is that I have 3 features, but I only want to plot a 2D graphic while using 2 features at a time and show all the possible combinations. The problem is that I did classifier.fit(X_train, Y_train) so it expects to be trained with 3 features, not just 2. X_train is the size (70, 3) which is (n_samples, n_features). So far I tweaked the original code to add z_min and z_max, since I do need to have this third feature that I need to be able to use classifier.predict(). The error I get at the plt.contourf instruction is Input z must be a 2D array. import matplotlib as pl import matplotlib.colors as colors import matplotlib.cm as cmx x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1 y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1 z_min, z_max = X_train[:, 2].min() - 1, X_train[:, 2].max() + 1 xx, yy, zz = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1), np.arange(z_min, z_max, 0.1)) fig, ax = plt.subplots() # here "model" is your model's prediction (classification) function Z = classifier.predict(np.c_[np.c_[xx.ravel(), yy.ravel()], zz.ravel()]) # Put the result into a color plot Z = Z.reshape(len(Z.shape), 2) plt.contourf(xx, yy, Z, cmap=pl.cm.Paired) plt.axis('off') # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) print(z.shape) = (4612640,) print(xx.shape) = (20, 454, 508) How can I plot a 2D array + train with 3 features but only plot 2 features and keep the right shape for my array Z ? How can I get Z to the right size? What I tried so far: I read scikit-learn example with the iris dataset I want something like this, bus instead I have 2 features and I can only predict 2 values, not 3 like the example. Kaggle link 1 Retrieve Decision Boundary Lines (x,y coordinate format) from SKlearn Decision Tree plot decision boundary matplotlib But again all the examples I'm seeing, they are only training with 2 features so they are good to go from my understanding, they are not fa…
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has title: Plot the decision surface of a classification decision tree with 3 features on a 2D plot
score: 2
has answer: http://stackoverflow.com/a/50540679
linked to: http://stackoverflow.com/q/43929400
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87816471
comment on: http://stackoverflow.com/q/50400227
score: 1
type: QuestionComment
has text: What happened when you ran the code? That should give you some insight as to whether or not you can do this. However, neither of your conditions will *ever* be `True`, because `input()` reads in a string, and you are comparing to an integer, and I'm guessing that is the real problem you are having.
type: Comment

http://stackoverflow.com/comment/87906490
type: AnswerComment
has text: @rkoofoo you mean 5 seconds for each of the 10 images per name?
type: Comment
comment on: http://stackoverflow.com/a/50444761
score: 0

http://stackoverflow.com/a/50488363
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50488300
upvote count: 3
downvote count: 0
has body: Your second version creates a new empty new_a list every time it encounters an element less than 5, thereby effectively deleting all the previous entries. A more efficient way to do this would be using a list comprehension &gt;&gt;&gt; [i for i in a if i &lt; 5] [1, 1, 2, 3]

http://stackoverflow.com/q/50497125
score: 0
has comment: http://stackoverflow.com/comment/88011163
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/50499202
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88007194
answer count: 1
has body: I am trying to send an image to ocr.space using their api with python. Here is my code. The code runs without errors but doesn't print anything. Why? How can I make it print?? import requests import json def ocr_space_file(filename, overlay=False, api_key='helloworld', language='eng'): """ OCR.space API request with local file. Python3.5 - not tested on 2.7 :param filename: Your file path &amp; name. :param overlay: Is OCR.space overlay required in your response. Defaults to False. :param api_key: 2fe3ae129e88957 Defaults to 'helloworld'. :param language: Language code to be used in OCR. List of available language codes can be found on https://ocr.space/OCRAPI Defaults to 'en'. :return: Result in JSON format. """ payload = {'isOverlayRequired': overlay, 'apikey': api_key, 'language': language, } with open(filename, 'rb') as f: r = requests.post('https://api.ocr.space/parse/image', files={filename: f}, data=payload, ) return r.content.decode() def ocr_space_url(url, overlay=False, api_key='helloworld', language='eng'): """ OCR.space API request with remote file. Python3.5 - not tested on 2.7 :param url: Image url. :param overlay: Is OCR.space overlay required in your response. Defaults to False. :param api_key: 2fe3ae129e88957 Defaults to 'helloworld'. :param language: Language code to be used in OCR. List of available language codes can be found on https://ocr.space/OCRAPI Defaults to 'en'. :return: Result in JSON format. """ payload = {'url': url, 'isOverlayRequired': overlay, 'apikey': api_key, 'language': language, } m = r.content.decode() jsonstr = json.loads(m) print (jsonstr["ParsedResults"][0]["ParsedText"]) ocr_space_file(filename='example_image.png', language='eng') Here is a pastebin to my code.
has title: OCR Space API Python Not Printing Text

http://stackoverflow.com/q/50508338
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50508722
has comment: http://stackoverflow.com/comment/88030549
has body: I'm new to coding and I'm trying to create a link using Django (if possible) that sends the user to three different urls with equal probability of being to redirected to each one. Thus there is only one button to select but it can have three different results. I would like the link to simply be a bootstrap nav bar button. So far I have the following code that works just fine for a single basic html (surprise.html) url that I created: Relevant code in: Views: def surprise(request): return render(request, 'sitepages/surprise.html') Templates: Surprise urls.py: url(r'^surprise/', sitepages.views.surprise, name="surprise"), So this will redirect to a basic internal html page. But I was wondering if it's possible to add another href to the template code? Perhaps a new model would be necessary? I was thinking of using random.choice with three different urls in the list but it seems they need to be in str type and this is beyond me. Any suggestions or tips would be greatly appreciated. Thank You!
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50508722
has comment: http://stackoverflow.com/comment/88074468
has title: Django - Creating a link that maps to multiple different pages?
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/97995258
comment on: http://stackoverflow.com/a/50529235
has text: How to not hardcode the column 'B' but loop through the current column where a string match was found?
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50522146
possible better answer: http://stackoverflow.com/a/50522252
answer count: 2
has answer: http://stackoverflow.com/a/50522252
downvote count: 0
accepted answer: http://stackoverflow.com/a/50522179
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50522179
type: AnsweredQuestion
has body: I have a dict in pandas dataframe column, the input is, import pandas as pd df = pd.DataFrame([{'A': {'k1': 10}}, {'A': {'k2': 20, 'k3': 30}}, {'A': {'k4': 15}}]) df A 0 {u'k1': 10} 1 {u'k3': 30, u'k2': 20} 2 {u'k4': 15} I would like to split the keys and values of dict in column 'A' to new columns and split to rows(depends on number of keys in the dict), basically output should look like, keys values 0 k1 10 1 k3 30 2 k2 20 3 k4 15
tagged with: pandas
score: 1
has title: Pandas column dict split to new column and rows
favorite count: 0
type: Question

http://stackoverflow.com/a/50505129
answers question: http://stackoverflow.com/q/50504808
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50504808
has comment: http://stackoverflow.com/comment/88022462
type: AcceptedAnswer
downvote count: 0
has body: its possible to write a decorator to do what you seek: decorators are functions that accept a function as the first argument and arguments as next arguments. Then a different function is returned, or the arguments are modified in some way before being applied to the input-function. Here we can modify the arguments to lower case if they are instances of str and leave unaltered otherwise using comprehensions: def tolower(f, *args, **kwargs): def newfun(*args, **kwargs): as_ = [a.lower() if isinstance(a, str) else a for a in args] kws_ = {k: (v.lower() if isinstance(v, str) else v) for k,v in kwargs.items()} return f(*as_, **kws_) return newfun @tolower def print_lower(x, y, z): print(x) print(y) print(z) print_lower('A', 'B', 1) # outputs a b 1
score: 5

http://stackoverflow.com/a/50410960
has body: Only string object have the method split. If your tuple object (oi?) is a tuple of string may be you want to: "".join(oi) # ('a', 'b', 'c') =&gt; 'abc'
type: Answer
answers question: http://stackoverflow.com/q/50410862
score: 0

hubspot
type: Tag
tags question: http://stackoverflow.com/q/50398812
tag name: hubspot

http://stackoverflow.com/q/50417376
has title: How to list keys and count with dictionary of dictionaries
has comment: http://stackoverflow.com/comment/87854403
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50417593
has answer: http://stackoverflow.com/a/50417467
possible better answer: http://stackoverflow.com/a/50417467
answer count: 3
has comment: http://stackoverflow.com/comment/87850484
linked to: http://stackoverflow.com/q/2212433
score: 1
has body: I'm fairly new to Python and I'm struggling with nested dictionaries. Consider this dictionary of dictionaries: dict=[{'Item 1': {'A': 106, 'B': 77, 'C': 46, 'D': 36}, 'Item 2': {'E': 1141, 'F': 1065, 'G': 1020}}] I would like to list the keys and then the count of the nested dictionary keys. So like this: Item 1: 4 Item 2: 3 Thank you!
has answer: http://stackoverflow.com/a/50417472
accepted answer: http://stackoverflow.com/a/50417472
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87850531
has comment: http://stackoverflow.com/comment/87850585
downvote count: 0
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87850482

http://stackoverflow.com/a/65529469
upvote count: 2
has body: When you write the output on a file with out_file = open("output.txt","w") out_file.write(latex(diff(u(x,y,z),x))) out_file.close() They will look like you want them.
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50447737

http://stackoverflow.com/comment/87957926
type: Comment
has text: Thank you! Yes, I decided to append the lists instead of concatenating. I then used vstack to stack them all into an array and transposed it.
type: AnswerComment
comment on: http://stackoverflow.com/a/50457257
score: 0

http://stackoverflow.com/a/50422193
answers question: http://stackoverflow.com/q/50421236
downvote count: 0
score: 1
upvote count: 1
has body: import random sides = input("Sides") if isinstance(sides, str) and sides.isdigit(): sides = int(sides) # Ensure value to be greater than lower range i.e 1 else a traceback if sides &gt; 1: custom = random.randrange(1, sides) #see here
type: Answer

http://stackoverflow.com/comment/123220950
comment on: http://stackoverflow.com/a/50422952
has text: df=df.reset_index()
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/87986616
score: 0
comment on: http://stackoverflow.com/a/50485368
has text: Hey @AnubhavSarangi, I have edited answer with python code. Can you check it?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87989445
score: 0
type: Comment
has text: @MelDev so, in this case, you want to have a `list` of dictionaries for `properties`'s value, right? those two dictionaries have single keys, named `zookeeperStorageSize` and `cpu` respectively.
type: AnswerComment
comment on: http://stackoverflow.com/a/50486615

http://stackoverflow.com/a/50529488
score: 0
answers question: http://stackoverflow.com/q/50529336
has body: What about a global exception hook? def exception_hook(exctype, value, trace): # some exception handling logic here. sys.__excepthook__(exctype, value, trace) sys.excepthook = exception_hook
has comment: http://stackoverflow.com/comment/88070622
type: Answer

http://stackoverflow.com/comment/87880797
score: 0
has text: Translation mistake, thanks.
comment on: http://stackoverflow.com/q/50425623
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87887722
comment on: http://stackoverflow.com/a/50432859
score: 1
has text: @Sneftel Indeed, the general rule allows and even encourages to use exceptions, so this remark in the answer is wrong. However, I don't think this rule applies to this specific case. Here you have straighforward condition that is more readable (and shorter) to check directly.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50510409
answers question: http://stackoverflow.com/q/50509949
type: Answer
has body: Use a templating language such as Jinja or Chameleon. You could return a dictionary and interact with the dictionary on the template. Klein's docs describe how to use Twisted templates. Templates You can also make easy use of twisted.web.templates by returning anything that implements twisted.web.template.IRenderable such as twisted.web.template.Element in which case the template will be rendered and the result will be sent as the response body. from twisted.web.template import Element, XMLString, renderer from klein import run, route class HelloElement(Element): loader = XMLString(( ' Hello, ! ')) def __init__(self, name): self._name = name @renderer def name(self, request, tag): return self._name @route('/hello/<string:name>') def home(request, name='world'): return HelloElement(name) run("localhost", 8080) and this, which shows you exactly what you are asking for. To quote the first few paragraphs: HTML templating is the process of transforming a template document (one which describes style and structure, but does not itself include any content) into some HTML output which includes information about objects in your application. There are many, many libraries for doing this in Python: to name a few, jinja2 , django templates , and clearsilver . You can easily use any of these libraries in your Twisted Web application, either by running them as WSGI applications or by calling your preferred templating system’s APIs to produce their output as strings, and then writing those strings to Request.write . Before we begin explaining how to use it, I’d like to stress that you don’t need to use Twisted’s templating system if you prefer some other way to generate HTML. Use it if it suits your personal style or your application, but feel free to use other things. Twisted includes templating for its own use, because the twisted.web server needs to produce HTML in various places, and we didn’t want to add another large dependency for that. Twisted is not in any way incompatible…
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50526480
tagged with: pipenv
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50675268
has body: I develop a cli tool with Python for in-house use. I would like to introduce pipenv to my project to manage "dependencies of dependencies". It is because I encountered a bug due to a difference between production environment and development environment. However, MY cli tool is installed as a package.(httpie and ansible takes this strategy). So, I have to specify all dependencies in setup.py. How should I import "dependencies of dependencies" in Pipfile.lock to setup.py? (or should take other method?)
tagged with: python
score: 0
has title: Deploy CLI tool as package
answer count: 1
has comment: http://stackoverflow.com/comment/88363060
type: Question

http://stackoverflow.com/q/50387354
has comment: http://stackoverflow.com/comment/87790568
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87790581
has comment: http://stackoverflow.com/comment/87791618
tagged with: pyspark
answer count: 1
has comment: http://stackoverflow.com/comment/87795446
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87790658
has comment: http://stackoverflow.com/comment/87795470
has title: Facing Py4JJavaError on executing PySpark Code
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87790897
tagged with: apache-spark
score: 1
upvote count: 1
has body: I'm trying to execute my first PySpark code in PyCharm IDE ,and facing the following exception. from pyspark import SparkContext def example(): sc = SparkContext('local') words = sc.parallelize(["scala", "java", "hadoop", "spark", "akka"]) print(sc.getConf().getAll()) return words.count() print(example()) and Printed the following data. [('spark.master', 'local'), ('spark.rdd.compress', 'True'), ('spark.serializer.objectStreamReset', '100'), ('spark.driver.port', '59627'), ('spark.executor.id', 'driver'), ('spark.submit.deployMode', 'client'), ('spark.app.id', 'local-1526547201037'), ('spark.driver.host', 'LAPTOP-DDRRK6SB'), ('spark.ui.showConsoleProgress', 'true'), ('spark.app.name', 'pyspark-shell')] and the following exception. py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe. : java.lang.IllegalArgumentException Sorry for my English, Expecting what's wrong with the code.
has comment: http://stackoverflow.com/comment/87791771
has answer: http://stackoverflow.com/a/50398489
accepted answer: http://stackoverflow.com/a/50398489
has comment: http://stackoverflow.com/comment/87791813
favorite count: 0
type: Question

http://stackoverflow.com/a/50401522
has body: We need to improve the docs here, but see this example for how to get the request object into the 500 template: https://docs.sentry.io/clients/python/integrations/django/#message-references
accepted answer of: http://stackoverflow.com/q/50401494
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50401494
has comment: http://stackoverflow.com/comment/87819365
has comment: http://stackoverflow.com/comment/87818962
type: Answer

http://stackoverflow.com/q/50438904
has comment: http://stackoverflow.com/comment/87891997
downvote count: 1
has body: import socket import sys # creating socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'www.google.com' port = "80" x = "GET / HTTP/1.1\r\nHost : "+ host + "\n\n" s.connect((host, port) s.send(request.encode()) # the line has error invalid syntax response = s.recv(4096) print (response)
has comment: http://stackoverflow.com/comment/87891894
has title: Python (qpython) socket programming
has comment: http://stackoverflow.com/comment/87891921
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50439296
has comment: http://stackoverflow.com/comment/87892740
tagged with: sockets
has answer: http://stackoverflow.com/a/50439113
tagged with: python
score: -1
upvote count: 0
tagged with: qpython3
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/87983643
type: Comment
type: QuestionComment
has text: @Paul Right. DBScan, has a not option for the max size of clusters. I'm not sure how to do a workaround.
score: 0
comment on: http://stackoverflow.com/q/50483601

http://stackoverflow.com/a/69411028
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50511905
type: Answer
has body: So I am running windows 10, python3.9.x, using aws sqs as the broker, just finished updating some files: settings.py ### ### For celery tasks! ### from kombu.utils.url import safequote import urllib.parse AWS_ACCESS_KEY_ID = 'my aws_access_key_id for a user' AWS_SECRET_ACCESS_KEY = 'my aws_secret_access_key for a user' BROKER_URL = 'sqs://%s:%s@' % (urllib.parse.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.parse.quote(AWS_SECRET_ACCESS_KEY, safe='')) BROKER_TRANSPORT = 'sqs' BROKER_TRANSPORT_OPTIONS = { 'canves-celery-queue': { 'access_key_id': safequote(AWS_ACCESS_KEY_ID), 'secret_access_key': safequote(AWS_SECRET_ACCESS_KEY), 'region': 'us-east-1' } } CELERY_DEFAULT_QUEUE = 'celery<-project-queue>' CELERY_QUEUES = { CELERY_DEFAULT_QUEUE: { 'exchange': CELERY_DEFAULT_QUEUE, 'binding_key': CELERY_DEFAULT_QUEUE, } } ### ### End celery tasks ### celery_tasks.py (referred to in the tutorial as celery.py - renamed because apparently that caused some other programmers some errors): from __future__ import absolute_import import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<project>.settings') # 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 = Celery('<project>', include=['<project>.tasks']) app.config_from_object('django.conf:settings') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print("debug_task was fired!") print(f'Request: {self.request!r}') if __name__ == '__main__': app.start() tasks.py (this is in the same directory as the settings.py - also referrenced in celery_tasks.py) from __future__ import absolute_import from .celery_tasks import app import time @app.task(ignore_result=True) def sleep(x, y): print("Sleeping for: " + str(x …
score: 1

pygal
tags question: http://stackoverflow.com/q/50535956
type: Tag
tag name: pygal

http://stackoverflow.com/q/50449628
has title: How to remove 0% from pie chart
tagged with: pandas
tagged with: pie-chart
downvote count: 0
has answer: http://stackoverflow.com/a/50449718
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has body: I am working with text data to find the sentiment analysis. I have a data frame of sentiment score of each sentence. Using this data i am creating a pie chart but it shows the 0% in the graph. I am not able to understand the meaning of this 0%. Here is my data frame df1: score Negative 100.0 Neutral 0.0 Positive 0.0 and here is my code for creating a pie chart: import matplotlib.pyplot as plt import os plt.figure(figsize=(4,3)) df1.plot(kind='pie', autopct='%1.1f%%', subplots=True,startangle=90, legend = False, fontsize=14) plt.axis('off') plt.show() and here is my output plot: How can I remove this 0% from my plot?
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/55341445
answer count: 2

http://stackoverflow.com/comment/87844380
comment on: http://stackoverflow.com/q/50402758
type: QuestionComment
score: 2
has text: Getting 100% accuracy should be a red flag. That's not an indication of a great model, it's an indication of a horrible over-fit model. I would guess you have a 'data leak.' I bet there is a column in your training data that indicates what your output class should be. You may even be leaving the target variable as a column in X. Or it may be a more subtle leak.
type: Comment

http://stackoverflow.com/comment/87993639
type: Comment
type: QuestionComment
has text: So if I write something like 'Hello World', and make some modifications, will it cache that? What kind of a page will I have to build?
score: 0
comment on: http://stackoverflow.com/q/50489982

http://stackoverflow.com/q/50400227
has comment: http://stackoverflow.com/comment/87816568
has comment: http://stackoverflow.com/comment/87816598
type: Question
score: 2
has comment: http://stackoverflow.com/comment/87816609
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87816795
has title: Python: Have a function call another function with the argument already input
has comment: http://stackoverflow.com/comment/87816742
has comment: http://stackoverflow.com/comment/87816611
downvote count: 0
accepted answer: http://stackoverflow.com/a/50400372
has comment: http://stackoverflow.com/comment/87816600
favorite count: 0
has answer: http://stackoverflow.com/a/50400372
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50400344
has comment: http://stackoverflow.com/comment/87816471
has answer: http://stackoverflow.com/a/50400344
has body: Is it possible to have a function that calls another function with the argument already input? I'm working on a project and have simplified the problem to the code below. I want to call the function "test_2" and have the input equal y then use the input as the argument for "test_1". Is this allowed with python's rules or is there another way around this problem? def test_1(X): if x == 1: print("string") def test_2(): y = input() if y == 1: test_1(y)
tagged with: python

http://stackoverflow.com/q/50478331
tagged with: python
accepted answer: http://stackoverflow.com/a/50478421
tagged with: apply
has answer: http://stackoverflow.com/a/50478421
has comment: http://stackoverflow.com/comment/87970381
possible better answer: http://stackoverflow.com/a/50478418
has comment: http://stackoverflow.com/comment/88008872
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50478418
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has title: Custom transform '%' and '>' in numeric expressions in string columns, throughout a dataframe
has body: I've got several columns with '%' and '>' and I want to get rid of this and turn the columns into numbers. Here's how it looks like: +----+-------------+--------+ | | xRelegation | xChamp | +----+-------------+--------+ | 11 | 12% | &lt;1% | | 12 | 20% | &lt;1% | | 13 | 27% | &lt;1% | | 14 | 85% | &lt;1% | | 15 | 91% | &lt;1% | +----+-------------+--------+ So I tried building this function so I could use on all columns that have these characters: def get_prob(row): for i in df[row]: prob = 0 i = i.replace('%','') if i == '&lt;1': prob = 0.001 elif i == '&gt;99': prob = 99.99 else: prob = pd.to_numeric(i)/100 return prob However, I tried computing this : df.apply(get_prob("xChamp"), axis=1) It did not work.
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/50478459
has comment: http://stackoverflow.com/comment/87970289
has comment: http://stackoverflow.com/comment/87971062

http://stackoverflow.com/a/50575371
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: collaboratory is a research platform. It does not have a server component and neither should you rely on it for any production related task. See FAQs here Probably not directly relevant but perhaps still helpful is that Jupyter notebooks are not the way to go if you want to deploy a model. A bit of development work to pipe the data in and out would be required. Ignore it if you already know this.
answers question: http://stackoverflow.com/q/50510132
type: Answer
accepted answer of: http://stackoverflow.com/q/50510132

http://stackoverflow.com/a/50546516
type: Answer
answers question: http://stackoverflow.com/q/50518388
score: 0
accepted answer of: http://stackoverflow.com/q/50518388
type: AcceptedAnswer
has body: It turned out to be a problem not in the views or models files, but in the template. My form was sending the data to my regular 'new post' CreateView, so that's why my form_valid() method was never called and the Group was never inserted.

http://stackoverflow.com/comment/88072540
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50530289
has text: fyi, `.get()`, the way you use it, does the exact same thing as `[]`, you can just do `document['person']['scores']['SCORE_3']['@score']` instead.
type: Comment

http://stackoverflow.com/comment/136855298
score: 0
has text: As a Pylance developer mentioned here: https://github.com/microsoft/pylance-release/issues/3300#issuecomment-1406947296, this is one of the most possible errors and solutions. Thanks!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/70679570

http://stackoverflow.com/comment/87983025
comment on: http://stackoverflow.com/q/50471654
has text: You’re just opening the file using the wrong/unspecified encoding.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50405704
answers question: http://stackoverflow.com/q/50405509
has body: You can find the earliest offset for the beginning of the specified time interval and rewind to this offset. However, it is difficult to understand where the end of the interval is as the records with the earliest timestamps may arrive later. So you can consume the records from the start of the interval until you find the records with timestamps later than the endTime plus some more records to catch the late messages. The code for the rewinding to the startTime is: public void rewind(DateTime time) { Set&lt;TopicPartition&gt; assignments = consumer.assignment(); Map&lt;TopicPartition, Long&gt; query = new HashMap&lt;&gt;(); for (TopicPartition topicPartition : assignments) { query.put(topicPartition, time.getMillis()); } Map&lt;TopicPartition, OffsetAndTimestamp&gt; result = consumer.offsetsForTimes(query); result.entrySet().stream().forEach(entry -&gt; consumer.seek(entry.getKey(), Optional.ofNullable(entry.getValue()).map(OffsetAndTimestamp::offset).orElse(new Long(0)))); }
upvote count: 4
downvote count: 0
score: 4
type: Answer

http://stackoverflow.com/a/59968232
downvote count: 0
score: 1
upvote count: 1
has body: I would have done it this way, hope this helps def right_justify(s, total_length = 70): return ' ' * (total_length - len(s)) + s right_justify('Monty')
answers question: http://stackoverflow.com/q/50437906
type: Answer

http://stackoverflow.com/a/50418549
has comment: http://stackoverflow.com/comment/87852650
answers question: http://stackoverflow.com/q/50418496
downvote count: 0
upvote count: 1
score: 1
has body: You can use re.findall: import re with open('test_text.txt', 'w') as f1, open('my_file_edit.txt') as f: fields = [re.findall('^\w+', i.strip('\n'))[0] for i in f] f1.write('\n'.join(fields))
type: Answer

http://stackoverflow.com/comment/88055023
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50420693
has text: @Mykhailo Lisovyi, I looked at the various suggestions in the links you sent. It seemed like a lot of what I have seen and tried, though I haven't tried every single suggestion. This module seems different that all others I have installed, in that it seems to have a dozen or more potential install processes, only one of which may work on any given system. Is there a reason you know that xgboost does not install as seamlessly and painlessly as so many other packages?
score: 0

http://stackoverflow.com/comment/87911598
type: AnswerComment
comment on: http://stackoverflow.com/a/50449140
score: 0
type: Comment
has text: Sorry, maybe I didn't explain myself well. I see the figure as you see but I want to get it in a new and different window, not inside the console

http://stackoverflow.com/comment/101495608
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/57242329
type: Comment
has text: I modified my answer accordingly.

http://stackoverflow.com/comment/88061677
has text: ok, I see. Well, I guess I need to switch to MultiIndex DF now. cheers
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50524843

http://stackoverflow.com/comment/87808452
score: 0
has text: @ChristianDean my problem was with aliases, adapting this solution to Python3 works: https://stackoverflow.com/a/38268153/41977
comment on: http://stackoverflow.com/q/50395556
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50398358
has body: Hello I have unit test that are running fine when I run on console but when packaged with docker fail with the following error import nmslib ImportError: dlopen: cannot load any more object with static TLS I googled for this and they say to get rid of it you have to order your imports I have tried all the possible orders but still get the error I have the following imports import nmslib import numpy as np import time, math_utils, os, urllib, tables, math from math import cos, sin, acos, asin from sklearn.neighbors import NearestNeighbors from sklearn.neighbors import LSHForest from sklearn.preprocessing import normalize Any idea how to get rid of this error?
tagged with: unit-testing
favorite count: 0
type: Question
tagged with: docker
type: AnsweredQuestion
has title: import error when unit testing flask application with nmslib
tagged with: python
accepted answer: http://stackoverflow.com/a/50699478
has answer: http://stackoverflow.com/a/50699478
score: 2
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87827228
score: 0
comment on: http://stackoverflow.com/a/50406004
type: Comment
has text: unfortunately not :(
type: AnswerComment

http://stackoverflow.com/q/50528331
has body: It is possible to make multiple calls to a function in python using joblib. from joblib import Parallel, delayed def normal(x): print "Normal", x return x**2 if __name__ == '__main__': results = Parallel(n_jobs=2)(delayed(normal)(x) for x in range(20)) print results Gives: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361] However, what I really want is to call a class function on a list of class instances in parallel. The function simply stores a class variable. Then later I will access this variable. from joblib import Parallel, delayed class A(object): def __init__(self, x): self.x = x def p(self): self.y = self.x**2 if __name__ == '__main__': runs = [A(x) for x in range(20)] Parallel(n_jobs=4)(delayed(run.p() for run in runs)) for run in runs: print run.y This gives an error: Traceback (most recent call last): File "", line 1, in runfile('G:/My Drive/CODE/stackoverflow/parallel_classfunc/parallel_classfunc.py', wdir='G:/My Drive/CODE/stackoverflow/parallel_classfunc') File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 86, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "G:/My Drive/CODE/stackoverflow/parallel_classfunc/parallel_classfunc.py", line 12, in Parallel(n_jobs=4)(delayed(run.p() for run in runs)) File "C:\ProgramData\Anaconda2\lib\site-packages\joblib\parallel.py", line 183, in delayed pickle.dumps(function) File "C:\ProgramData\Anaconda2\lib\copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.name TypeError: can't pickle generator objects How is it possible to use joblib with classes like this? Or is there a better approach?
possible better answer: http://stackoverflow.com/a/70463378
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/70463378
tagged with: parallel-processing
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50704372
score: 2
has answer: http://stackoverflow.com/a/50704372
tagged with: joblib
favorite count: 0
type: Question
has title: Parallel class function calls using python joblib
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/88080691
type: QuestionComment
comment on: http://stackoverflow.com/q/50534267
has text: booleans are integers. `True == 1`, `False == 0`. that's written in stone
score: 1
type: Comment

http://stackoverflow.com/a/50393878
has body: in the above example, c and d should be the same No. You should be careful here. c and d are different ops in a computational graph. Comparing them with == is pointless, they are always different objects. What you're really looking for is tf.equal to determine if the tensor values are the same element-wise and tf.cond to organize an if statement in a computational graph. It would look something like this: result = tf.cond(tf.equal(c, d), lambda: tf.ones((1, 100)), lambda: tf.zeros((1, 100))) Also, note that reassignment of a python variable that points to an op (c in this case) does not change the op in the graph.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50393536
has comment: http://stackoverflow.com/comment/87804092
type: Answer

http://stackoverflow.com/comment/87906426
score: 0
has text: What if there is an odd number of words in the string? And why is `data` a list?
comment on: http://stackoverflow.com/q/50446393
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87876935
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50431137
has text: When, I tried django 1.11 version, it worked fine with url(), but not working with path() in 2.0.
type: Comment

http://stackoverflow.com/q/50404469
tagged with: python
accepted answer: http://stackoverflow.com/a/50404505
has answer: http://stackoverflow.com/a/50404505
duplicate of: http://stackoverflow.com/q/152580
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87824296
has title: how to get the python type of variable correctly?
answer count: 1
has body: I cant get the type? I am using python3. print(type(base64_type)) # output: &lt;class 'bytes'&gt; if type(base64_type) is 'bytes': print('wow') else: print ('Why are we not working')
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/87824321
linked to: http://stackoverflow.com/q/152580

http://stackoverflow.com/a/56501411
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50389852
has body: I had this issue for a while now. I tried a lot of solutions from stack but none worked. Uninstalling all the extensions did the trick for me.
type: Answer

http://stackoverflow.com/comment/87899126
type: Comment
type: QuestionComment
has text: Also, just catching `Exception` looses important information. You could use the traceback module, `traceback.print_exc()` to get more info.
comment on: http://stackoverflow.com/q/50442423
score: 1

http://stackoverflow.com/a/50460346
accepted answer of: http://stackoverflow.com/q/50456449
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50456449
has body: You can use below code: val d1 = Array(("a", "10"), ("b", "20"), ("c", "30")) val rdd1= sc.parallelize(d1) val df1 = rdd1.toDF("key","val") val d2 = Array(("a", "A1"), ("c", "C1")) val rdd2 = sc.parallelize(d2) val df2 = rdd2.toDF("key","div") val res = df1.join(df2,Seq("key"),"left_outer") res.show()
score: 0
type: Answer

http://stackoverflow.com/a/50387869
score: 0
has comment: http://stackoverflow.com/comment/87797463
has body: I think you can follow this link If you want to "those variables in the set of choices to be linked to a textinput", it will be use forms.ChoiceField in forms.Form. it will be nicely if you posting your code, the better we may know what you want.
type: Answer
answers question: http://stackoverflow.com/q/50386736

http://stackoverflow.com/comment/87924325
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50440024
has text: Thank you so much! I didn't realize that there was a difference between cars['US':'US'] and cars.loc['US']. Thanks to you, I'll never forget from now on.
type: AnswerComment

http://stackoverflow.com/comment/88061050
comment on: http://stackoverflow.com/q/50524541
type: Comment
type: QuestionComment
has text: If this behavior surprises you, you **must** watch [facts and myths about Python names and values](https://www.youtube.com/watch?v=_AEJHKGk9ns).
score: 0

http://stackoverflow.com/a/50431166
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50431093
type: Answer
has body: Let's build upon what you have done: In python, sequences are iterable with a for loop. When you don't need the index, don't count it: def extract_full_name(names): firstname = [] lastname = [] for item in names: firstname.append(item['first']) for item in names: lastname.append(item['last']) return list(zip(firstname,lastname)) To simply generate a list out of another one, you may use a list comprehension: def extract_full_name(names): firstname = [item['first'] for item in names] lastname = [item['last'] for item in names] return list(zip(firstname,lastname)) Since you iterate twice the same sequence we could also avoid the zip by combining as we go: def extract_full_name(names): return [(item['first'], item['last']) for item in names] Now, let's fix the mistake in your output: you output each full name as a 2-tuple containing two strings (the first name and the last name). Let's format them into a full name instead: def extract_full_name(names): return ['{} {}'.format(item['first'], item['last']) for item in names] That version is pretty much the one that confuses you, but it uses a list comprehension instead of map. [bonus] Since we use format, we could also use its rich syntax to access item's entries: def extract_full_name(names): return ['{name[first]} {name[last]}'.format(name=item) for item in names]
score: 1

http://stackoverflow.com/q/50474640
linked to: http://stackoverflow.com/q/2759067
has comment: http://stackoverflow.com/comment/87968088
has comment: http://stackoverflow.com/comment/87965788
score: 1
has body: Looking to change the file extension from .txt to .csv import os, shutil for filename in os.listdir(directory): # if the last four characters are “.txt” (ignoring case) # (converting to lowercase will include files ending in “.TXT”, etc) if filename.lower().endswidth(“.txt”): # generate a new filename using everything before the “.txt”, plus “.csv” newfilename = filename[:-4] + “.csv” shutil.move(filename, newfilename)
has answer: http://stackoverflow.com/a/50477268
type: Question
upvote count: 2
answer count: 1
duplicate of: http://stackoverflow.com/q/2759067
tagged with: python
has title: I want to rename all the .txt files on a dir to .csv using Python 3
accepted answer: http://stackoverflow.com/a/50477268
downvote count: 1
has comment: http://stackoverflow.com/comment/87967301
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/88002881
has text: @Lemayzeur how can I do that? I am so newbie at Linux and deployment :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50493132
score: 0

http://stackoverflow.com/comment/88024240
comment on: http://stackoverflow.com/q/50503899
type: Comment
type: QuestionComment
score: 0
has text: that's obvious, I did not say to clean it, but you must clean it as you did. in the same method, set it with `self.focus = True`after clean, for more information read: https://stackoverflow.com/questions/33176228/automatic-focus-of-textinput-kivy

http://stackoverflow.com/a/50505969
type: Answer
answers question: http://stackoverflow.com/q/50505787
score: 2
has body: You can use slice assignment to expand on the left-hand side and assign your x list directly to the indices of h, e.g.: h = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = [20, 21] lbp = 2 ubp = 4 h[4 + lbp:4 + ubp] = x # or better yet h[4 + lbp:4 + lbp + len(x)] = x print(h) # [1, 2, 3, 4, 5, 6, 20, 21, 9, 10] I'm not really sure why are you adding 4 to the indexes in your loop nor what lbp and ubp are supposed to mean, tho. Keep in mind that when you select a range like this, the list you're assigning to the range has to be of the same length as the range.
accepted answer of: http://stackoverflow.com/q/50505787
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88024372

http://stackoverflow.com/q/50448018
tagged with: filter
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87909660
has answer: http://stackoverflow.com/a/50448261
has title: Apply function to a filtered group after groupby
tagged with: python
has body: I know there are tons of groupby-filter questions about pandas, but I've gone through a number of them and they don't have what I need. Anyway here's what I have for the dataframe df: user1 user2 date quantity ----------------------------- Alice Bob 2018-05-21 100 Alice Bob 2018-05-19 20 Alice Carol 2018-01-01 1000 Bob Carol 2018-02-01 100 I want to calculate a function (let's say some function func) of the quantity for a given user1-user2 pair for weekdays only. So far what I have are: df['day'] = df['date'].dt.weekday df.groupby(['user1','user2']).filter(lambda x: (x.day &lt; 5).any() ) But I don't get what I expect. Apparently, what the filter does is to select only those pairs where at least one day entry is &lt; 5. What I need though, are all rows where the day column is less than 5 for one particular user1-user2 pair.
accepted answer: http://stackoverflow.com/a/50448261
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87909741

http://stackoverflow.com/q/50537527
tagged with: python
has body: My goal is to group n records by 4, say for example: 0-3 4-7 8-11 etc. find max() value of each group of 4 based on one column among other columns, and create a new dataset or csv file. The max() operation would be performed on one column, while the other columns remain as they are. Based on the research I have made here (Stackoverflow), I have tried to customize and apply the following solution on this site on my dataset, but it wasn't giving me my expectations: # Group by every 4 row until the len(dataset) groups = dataset.groupby(pd.cut(dataset.index, range(0,len(dataset),3)) needataset = groups.max() I'm getting results similar to the following: Column 1 Column 2 ... Column n 0. (0,3] 1. (3,6] The targeted column for the max() operation did not also produce the expected result. I will appreciate any guide to tackling the problem.
type: Question
has answer: http://stackoverflow.com/a/50537837
type: UnansweredQuestion
has title: How to group records with Pandas cut()?
answer count: 1
score: 0
tagged with: pandas

http://stackoverflow.com/a/50534480
type: Answer
has comment: http://stackoverflow.com/comment/88089365
score: 0
has body: You've not really provided enough information to know exactly, but it is likely that the GFile thingy is opening the file specified by path. If that is correct, then the error is likely along the following lines: GFile is probably opening the file in "text mode". The definition of "text" is that the bytes in the file have to be converted into "text" using some rules. You have not specified what those rules are, so GFile is applying a default, which appears to be "utf-8". For reference, the Python docs talk about what the standard library does. However, the content of the file is not "utf-8" compatible. Since the file at least contains the byte 0xbb, that does not look like vanilla text. Are you sure the file contains text? At any rate, it is hard to speculate on a fix without you providing more details on the exact form of the content of the file, and the arguments available on GFile. BTW, I notice that 0xbb is part of a BOM, though not the first character. Some applications on Windows do use BOMs at the start of text files. So if you think it is text, perhaps it is text preceded by a BOM? There are other answers on SO that might help in such cases.
answers question: http://stackoverflow.com/q/50533139
has comment: http://stackoverflow.com/comment/88094909

http://stackoverflow.com/comment/88003749
type: Comment
score: 0
type: QuestionComment
has text: I just wanted to know that at the end only the ''if" case will work so I'm returning that , won't it suffice?
comment on: http://stackoverflow.com/q/50421958

http://stackoverflow.com/comment/87959260
type: QuestionComment
comment on: http://stackoverflow.com/q/50472775
has text: Possible duplicate of [numpy concatenate two arrays vertically](https://stackoverflow.com/questions/21887754/numpy-concatenate-two-arrays-vertically)
score: 1
type: Comment

http://stackoverflow.com/comment/87850714
comment on: http://stackoverflow.com/q/50415516
score: 0
has text: @mkrieger1 I think that's the simplest way to do it.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50468161
upvote count: 1
has comment: http://stackoverflow.com/comment/87952875
downvote count: 0
answers question: http://stackoverflow.com/q/50467478
has body: def fibo(num): i =2 fib = [1, 2] while fib[-1] &lt; int(num): fib.append(fib[i-1]+fib[i-2]) #fib = fib[i-1] + fib[i-2] i+= 1 return fib result=fibo(9) print(result) I think the error occurs when overwriting the list.
score: 1
type: Answer

http://stackoverflow.com/q/50399127
downvote count: 0
has body: Looking at this github I'd like to be able to install datatable. I do run a fedora 26 distro that runs python3.6 statquant  ~  python3 Python 3.6.4 (default, Mar 13 2018, 18:16:01) [GCC 7.3.1 20180130 (Red Hat 7.3.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. When I try to install it I get: statquant  ~  pip install https://s3.amazonaws.com/h2o-release/datatable/stable/datatable-0.3.2/datatable-0.3.2-cp36-cp36m-linux_x86_64.whl datatable-0.3.2-cp36-cp36m-linux_x86_64.whl is not a supported wheel on this platform. Is this expected ? I am totally new to python
score: 4
tagged with: py-datatable
has title: How can I install data.table on my fedora distro
answer count: 1
tagged with: python
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50399934
type: UnansweredQuestion

http://stackoverflow.com/comment/87920006
comment on: http://stackoverflow.com/q/50452625
score: 0
type: Comment
type: QuestionComment
has text: @Claire i edited the code please help me i tried it with many code and changes but i didn't get success on python code and even i don't know much more about it. Really today i touched it first time in my life.

http://stackoverflow.com/q/50480517
tagged with: timedelta
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50480577
upvote count: 1
score: 1
tagged with: python
has title: How to take difference of several Timestamp series in a dataframe in Pandas?
has body: I want to obtain the timedelta interval between several timestamp columns in a dataframe. Also, several entries are NaN. Original DF: 0 1 2 3 4 5 0 date1 date2 NaN NaN NaN NaN 1 date3 date4 date5 date6 date7 date8 Desired Output: 0 1 2 3 4 0 date2-date1 NaN NaN NaN NaN 1 date4-date3 date5-date4 date6-date5 date7-date6 date8-date7
favorite count: 0
type: Question
tagged with: time-series
downvote count: 0
has answer: http://stackoverflow.com/a/50480577
answer count: 1

http://stackoverflow.com/comment/87923221
score: 0
type: Comment
type: QuestionComment
has text: @AntonvBR, thanks, so once I deactivate the environment and try activating it again, the library will not need to be installed again?
comment on: http://stackoverflow.com/q/50454804

http://stackoverflow.com/comment/87832819
comment on: http://stackoverflow.com/a/50389182
type: Comment
score: 0
type: AnswerComment
has text: `list_count="hi","I","am new \n to this" ` this is not the required thing

http://stackoverflow.com/a/50391964
accepted answer of: http://stackoverflow.com/q/50391555
has comment: http://stackoverflow.com/comment/87800482
has body: I found the answer: scplot.norm(x) will give me the normalized value per number. So to get the color for the number 9 I need to to cma = scplot.get_cmap() cma(scplot.norm(9)) Thanks.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50391555
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/87892168
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50437901
has text: Maybe my wording is misleading: I want order not to matter (i.e. order agnostic parameters). Hence the mandatory order is the problem. Otherwise the original RegEx works. In any case I think my initial approach was fundamentally mistaken and the accepted answer proposed a much cleaner implementation.
type: Comment

http://stackoverflow.com/comment/87934985
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50454576
has text: @ShubhamSejpal I'm not sure. The code prints the tags in soup alright here, with or without the commented line. Here's a demo for printing out the Web Page HTML source `result_html`: https://imgur.com/a/5Jaf8Yh You can manipulate the soup (soup form of `result_html`), to extract information and further handle it as you wish.
type: Comment

http://stackoverflow.com/a/50522632
has body: try this : self.main_window.title("MPG Calculator") by adding the .title command you can change the name of a page. I couldn't test your GUI so perhaps its a different page that has to be changed but it works via the same principe. since I couldn't test your GUI I haven't got a solution for your other problem.
accepted answer of: http://stackoverflow.com/q/50520301
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/50520301
type: Answer

http://stackoverflow.com/a/50413391
answers question: http://stackoverflow.com/q/50399803
type: Answer
has body: So here is a solutiono that is now working here - This may help someone else... import xml.etree.ElementTree as ET from lxml import etree def find_child(node, with_ref, with_safetyreportid): """Recursively find a node with given ref""" for element in list(node): if element.tag == with_ref and element.attrib['safetyreportid'] == with_safetyreportid: return element elif list(element): sub_result = find_child(element, with_ref, with_safetyreportid) if sub_result is not None: return sub_result return None def replace_node(from_tree, to_tree, node_ref, with_safetyreportid): """Replace node with given node_ref in the to_tree with the same ref from the from_tree""" from_node = find_child(from_tree.getroot(), node_ref, with_safetyreportid) to_node = find_child(to_tree.getroot(), node_ref, with_safetyreportid) #Find where to substitute the from_node into the to_tree to_parent, to_index = get_node_parent_info(to_tree, to_node) #Replace to_node with from_node to_parent.remove(to_node) to_parent.insert(to_index, from_node) def get_node_parent_info(tree, node): """Return tuple of (parent, index) where: parent = node of parent within tree index = index of node under parent""" parent_map = {c:p for p in tree.iter() for c in p} parent = parent_map[node] return parent, list(parent).index(node) destinationFile = etree.parse("ExampleDestination.xml") sourceFile = etree.parse("ExampleSource.xml") from_tree = ET.ElementTree(file='ExampleSource.xml') to_tree = ET.ElementTree(file='ExampleDestination.xml') safety_dest_ref = destinationFile.xpath("//concmed") safety_sour_ref = sourceFile.xpath("//concmed") for each_source_concmed in safety_sour_ref: xpath_source_concmed = each_source_concmed.xpath(".") pat_ref_source = xpath_source_concmed[0].attrib['safetyreportid'] print(pat_ref_source) replace_node(from_tree, to_tree, 'concmed', pat_ref_source) to_tree.write('ouput.xml')
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50399803

http://stackoverflow.com/q/50387749
score: 1
has body: I am trying to train a regression model of a dummy function with 3 variables with fully connected neural nets in Keras and I always get a training loss much higher than the validation loss. I split the data set in 2/3 for training and 1/3 for validation. I have tried lots of different things: changing the architecture adding more neurons using regularization using different batch sizes Still the training error is one order of magnitude higer than the validation error: Epoch 5995/6000 4020/4020 [==============================] - 0s 78us/step - loss: 1.2446e-04 - mean_squared_error: 1.2446e-04 - val_loss: 1.3953e-05 - val_mean_squared_error: 1.3953e-05 Epoch 5996/6000 4020/4020 [==============================] - 0s 98us/step - loss: 1.2549e-04 - mean_squared_error: 1.2549e-04 - val_loss: 1.5730e-05 - val_mean_squared_error: 1.5730e-05 Epoch 5997/6000 4020/4020 [==============================] - 0s 105us/step - loss: 1.2500e-04 - mean_squared_error: 1.2500e-04 - val_loss: 1.4372e-05 - val_mean_squared_error: 1.4372e-05 Epoch 5998/6000 4020/4020 [==============================] - 0s 96us/step - loss: 1.2500e-04 - mean_squared_error: 1.2500e-04 - val_loss: 1.4151e-05 - val_mean_squared_error: 1.4151e-05 Epoch 5999/6000 4020/4020 [==============================] - 0s 80us/step - loss: 1.2487e-04 - mean_squared_error: 1.2487e-04 - val_loss: 1.4342e-05 - val_mean_squared_error: 1.4342e-05 Epoch 6000/6000 4020/4020 [==============================] - 0s 79us/step - loss: 1.2494e-04 - mean_squared_error: 1.2494e-04 - val_loss: 1.4769e-05 - val_mean_squared_error: 1.4769e-05 This makes no sense, please help! Edit: this is the full code I have 6000 training examples # -*- coding: utf-8 -*- """ Created on Mon Feb 26 13:40:03 2018 @author: Michele """ #from keras.datasets import reuters import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, LSTM from keras import optimizers import matplotlib.pyplot as plt import os import pylab from keras.c…
tagged with: keras
has comment: http://stackoverflow.com/comment/87793089
downvote count: 1
tagged with: tensorflow
favorite count: 0
has title: Training loss higher than validation loss
type: Question
has answer: http://stackoverflow.com/a/50389731
has comment: http://stackoverflow.com/comment/87792905
has answer: http://stackoverflow.com/a/50392084
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87791192
has comment: http://stackoverflow.com/comment/87795390
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/87791867
has answer: http://stackoverflow.com/a/69624507

http://stackoverflow.com/q/50495946
tagged with: google-cloud-storage
favorite count: 0
tagged with: python-3.x
type: Question
downvote count: 0
upvote count: 1
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/50497331
type: AnsweredQuestion
has title: Cant get access to google bucket Invalid string value: 'noAcl:'. Allowed values: [full, noacl]
has answer: http://stackoverflow.com/a/50497331
has body: I have created google cloud virtual image first. I have such code: &gt;&gt;&gt; from google.cloud import storage &gt;&gt;&gt; from io import BytesIO &gt;&gt;&gt; client = storage.Client() &gt;&gt;&gt; bucket = client.get_bucket('landsst') However I get such error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/iashrapov/anaconda3/lib/python3.6/site-packages/google/cloud/storage/client.py", line 177, in get_buc ket bucket.reload(client=self) File "/home/iashrapov/anaconda3/lib/python3.6/site-packages/google/cloud/storage/_helpers.py", line 108, in reloa d _target_object=self) File "/home/iashrapov/anaconda3/lib/python3.6/site-packages/google/cloud/_http.py", line 293, in api_request raise exceptions.from_http_response(response) google.api_core.exceptions.Forbidden: 403 GET https://www.googleapis.com/storage/v1/b/lanst?projection=noAcl : 606507140911-compute@developer.gserviceaccount.com does not have storage.buckets.get access to landsbyconst. With such JSON as output: { "error": { "errors": [ { "domain": "global", "reason": "invalidParameter", "message": "Invalid string value: 'noAcl:'. Allowed values: [full, noacl]", "locationType": "parameter", "location": "projection" } ], "code": 400, "message": "Invalid string value: 'noAcl:'. Allowed values: [full, noacl]" } } What am I doing wrong? PS. Running same code through local PC returns error: DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credential and re-run the application. For more information, please see So initially I dont have permission error or not, hmm? upd. I can connect to the bucket created on my own
score: 1

http://stackoverflow.com/a/50517142
has body: Yes you can. Please check out the Boto3 S3 reference (http://boto3.readthedocs.io/en/latest/guide/s3.html#s3-guide): Here's a little bit to get you started: import boto3 s3 = boto3.resource('s3') your_bucket = s3.Bucket('name_of_your_bucket') for item_in_bucket in your_bucket.objects.all(): # do stuff A few things to keep in mind: make sure that the role the lambda function is running under has access to S3 make sure you increase your lambda timeout configuration (5 minutes max) so that you will have enough time to clean all the objects within the bucket. if you are exceeding 5 minutes you could look into using AWS State Machines with Step Functions with modular lambda operations to clean and store the files.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50516321
answers question: http://stackoverflow.com/q/50516321
type: Answer
score: 0

http://stackoverflow.com/comment/88019675
type: Comment
type: QuestionComment
has text: can you share screenshot when Pointer is on (0)NumberPicker[200,372][328,732]
score: 0
comment on: http://stackoverflow.com/q/50464584

http://stackoverflow.com/q/50390471
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87797740
has title: python checkbutton appearance does not update after setting to 1
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50390880
favorite count: 0
type: Question
has body: I have a class with a member self.checkbutton (using the TkInter CheckButton), created in the init function with: self.checkbutton = Checkbutton(self.frame, variable=self.value, command=self.get_entry_and_execute, onvalue="1", offvalue="0") Now, instead of clicking on the checkbutton in my frame, I want to set it in my code. So, from somewhere in my code, I call setvalue("1") calling this function: def setvalue(self, value): if (value == "1"): print "SELECTING CHECKBUTTON" self.checkbutton.select() # self.checkbutton.set(value=1) Now, when I do this, actually, I can see that the associated "self.get_entry_and_execute" function is called and it even changes some background color. But, the checkbutton remains unchecked (i.e. an empty field without the "V" symbol). Weirly, when I add the command self.checkbutton.set(value=1) , the code complains: AttributeError: Checkbutton instance has no attribute 'set' but now the checkbutton does get checked! I am assuming that because of this error, python puts the checkbutton in the correct state (=1) even though the "set" function does not exist. My question is: how can I correctly make python put the "V" inside the checkbutton box? (I.e, something like a "redraw" function).
tagged with: python

http://stackoverflow.com/comment/87964478
has text: The timestamps are the problem, but this way they are also awkward, the timestamp string needs further parsing.
type: AnswerComment
comment on: http://stackoverflow.com/a/50475467
score: 0
type: Comment

http://stackoverflow.com/comment/87811734
type: Comment
type: QuestionComment
score: 0
has text: 1) No, it's not the method at all, formally speaking, it's just link to some function which will be called completely out of scope of the class, so should be considered as data from class standpoint. 2) Yes, just supress error 3) Python 2.7, if it works in 3.0 it's ok, i'll just leave workaround for 2.7 and that's all.
comment on: http://stackoverflow.com/q/50397904

http://stackoverflow.com/comment/93477524
type: QuestionComment
has text: https://stackoverflow.com/questions/14177744/how-does-perspective-transformation-work-in-pil this will solve your problem.
score: 0
comment on: http://stackoverflow.com/q/50509570
type: Comment

http://stackoverflow.com/q/50533072
has answer: http://stackoverflow.com/a/50533349
possible better answer: http://stackoverflow.com/a/50533349
has comment: http://stackoverflow.com/comment/88078509
has comment: http://stackoverflow.com/comment/88078091
has comment: http://stackoverflow.com/comment/88078297
tagged with: python
has answer: http://stackoverflow.com/a/50533219
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/88078663
has body: I was trying some questions from hackerrank and came across this question https://www.hackerrank.com/challenges/list-comprehensions/problem I tried this solution if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) L = [] SL = [] for i in range(0, x + 1): for j in range(0, y + 1): for k in range(0, z + 1): if i + j + k != n: SL[:] = [] SL.append(i) SL.append(j) SL.append(k) print(SL) L.append(SL) print(L) although SL had the right solution I can't append SL to the main list L for some reason, and apparently L.append(SL) overwrites the list L each time it it executed as it prints the last value of SL. Why does it happen? I tried using extend, but instead of making it a list of lists, it was created as just a list of integers. EDIT: Thank you all for the explanations!
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88078409
has title: Why does append overwrite the list?
has comment: http://stackoverflow.com/comment/88078240
accepted answer: http://stackoverflow.com/a/50533219
has comment: http://stackoverflow.com/comment/88078421
type: Question

http://stackoverflow.com/a/50415999
has comment: http://stackoverflow.com/comment/87848107
has comment: http://stackoverflow.com/comment/87847692
upvote count: 3
has comment: http://stackoverflow.com/comment/87848160
has comment: http://stackoverflow.com/comment/87847658
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50415960
has body: concat Are you looking to concat df with itself? df = pd.concat( [df] * len(properties), ignore_index=True ).assign(property=np.repeat(properties, len(df))) reindex + tile df = df.reindex(np.tile(df.index, len(properties))).assign( property=np.repeat(properties, len(df)) )
accepted answer of: http://stackoverflow.com/q/50415960
has comment: http://stackoverflow.com/comment/87847642
has comment: http://stackoverflow.com/comment/87848428
has comment: http://stackoverflow.com/comment/87848115
type: Answer
has comment: http://stackoverflow.com/comment/87848221
has comment: http://stackoverflow.com/comment/87848051
score: 3
has comment: http://stackoverflow.com/comment/87848244

http://stackoverflow.com/comment/87959799
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50438556
type: AnswerComment
has text: Ok so i put your code, it works, i understand it but i have the same problem that i had before, i think our code was similar but yours is smaller. When i take for example F1W ( coordonate are [1][3]) i move it to [6][8], then it shows that i can't move there because there is a piece there. There are no piece on the way and i move P4W before. It only works if i move it to the third line, then i can move to [6][8]

http://stackoverflow.com/comment/88036991
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50511460
has text: I tried some other cases, how do you see this code?(Updated)
type: Comment

http://stackoverflow.com/comment/87929305
has text: Is the scroll down list a JavaScript object?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50457828

http://stackoverflow.com/a/55773513
downvote count: 1
answers question: http://stackoverflow.com/q/50470933
has body: Readline expects \001 and \002 as markers around invisible characters: import readline # gnureadline 6.3.8 START = '\001\033[91m\033[1m\002' END = '\001\033[0m\002' response = raw_input(START + 'Enter text: ' + END) With ANSI escape sequences prefixed with \001 and suffixed with \002, GNU readline will know that these characters should be excluded when determining the length of the prompt string.
upvote count: 5
type: Answer
score: 4

http://stackoverflow.com/a/60533250
type: Answer
answers question: http://stackoverflow.com/q/50461779
upvote count: 7
downvote count: 1
has body: I'm using ubuntu 18.04 and had the same issue here. In my case, this works fine. Hope that works for you! sudo apt-get install firefox-geckodriver
score: 6

http://stackoverflow.com/a/50453383
has body: random.choice doesn't take multiple arguments; it takes a single sequence from which to choose a value. leftchoice = random.choice([True, False]) The random module defines a class, Random, that encapsulates a random number generator. You make an instance, with an optional seed to initialize it, then call its methods to get various random values. gen = random.Random(2382948) x = gen.choice([True, False]) This is great for testing, as you can create reproducible random sequences by using the same seed. However, in general use, you may not care about the seed and be happy with some default seed (here, a value based on a value returned by os.urandom). To facilitate that use case, the random module creates a module-level instance of Random when it is imported: _inst = Random() and creates a bunch of module-level aliases to that instance's methods: ... choice = _inst.choice So random.choice, rather than being a function that takes one sequence argument, is really a bound method whose underlying unbound method takes two arguments (an instance and a sequence), and thus just needs one more. (Remember that _inst.choice([True, False]) resolves to Random.choice(_inst, [True, False])`.) The error message you see is for random.choice(True, False) is due to the fact that you are effectively trying to call Random.choice, defined as def choice(self, seq): ... as _inst.choice(True, False) or (Random.choice(_inst, True, False)), and it should be clear now that you have one argument too many.
type: Answer
has comment: http://stackoverflow.com/comment/87920072
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50453373

http://stackoverflow.com/comment/88048127
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50517777
has text: Can you post a small sample of your input dataframe, and a desired output?
score: 0

http://stackoverflow.com/comment/88066041
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50526291
has text: I used for loop, but then I realized that I need while since (as you can see) I need to make forward jumps by increment the Index by more than 1.
type: Comment

http://stackoverflow.com/comment/88080239
score: 0
type: Comment
has text: @TedKleinBergman Here is a link to a gif of the problem https://imgur.com/a/z43v0Y3. As you can see, not all of the buttons are loading in during the first few screens, and once I get past that, different sprites load in every time I toggle the inventory. Sorry I didn't include any code, I'm dumb. I'll add that really quick.
type: QuestionComment
comment on: http://stackoverflow.com/q/50533105

http://stackoverflow.com/q/50469757
tagged with: keras
has comment: http://stackoverflow.com/comment/87954089
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87954127
tagged with: python
has title: Keras: Method on_batch_end() is slow but I have no callbacks?
has comment: http://stackoverflow.com/comment/94859407
has answer: http://stackoverflow.com/a/59887400
answer count: 2
score: 7
has comment: http://stackoverflow.com/comment/87954691
has comment: http://stackoverflow.com/comment/87954283
has comment: http://stackoverflow.com/comment/87954587
downvote count: 0
has answer: http://stackoverflow.com/a/56171672
has body: Keras just warned me: UserWarning: Method on_batch_end() is slow compared to the batch update (0.988304). Check your callbacks. I have no callbacks in my keras script, but I am using DataGenerator (keras.utils.Sequence). Could this be a problem? For the DataGenerator, I have implemented __init__(), __len__(), __getitem()__, and on_epoch_end methods. For on_epoch_end, I have: def on_epoch_end(self): """ This method will be called between every epoch, so we can shuffle the indexes here. """ self.indexes = np.arange(len(self.image_names)) if self.shuffle: np.random.shuffle(self.indexes) The complete callstack is as below: Using TensorFlow backend. /var/lib/condor/execute/slot1/dir_30551/anaconda/envs/cellimage/lib/python3.6/site-packages/skimage/transform/_warps.py:84: UserWarning: The default mode, 'constant', will be changed to 'reflect' in skimage 0.15. warn("The default mode, 'constant', will be changed to 'reflect' in " /var/lib/condor/execute/slot1/dir_30551/anaconda/envs/cellimage/lib/python3.6/site-packages/keras/callbacks.py:120: UserWarning: Method on_batch_end() is slow compared to the batch update (0.586719). Check your callbacks. % delta_t_median) /var/lib/condor/execute/slot1/dir_30551/anaconda/envs/cellimage/lib/python3.6/site-packages/keras/callbacks.py:120: UserWarning: Method on_batch_end() is slow compared to the batch update (0.988304). Check your callbacks. % delta_t_median)
upvote count: 7

http://stackoverflow.com/q/50529820
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88071540
has comment: http://stackoverflow.com/comment/88074611
tagged with: python
has comment: http://stackoverflow.com/comment/88071542
has answer: http://stackoverflow.com/a/50538709
has answer: http://stackoverflow.com/a/50538730
has title: Issue writing to file
has comment: http://stackoverflow.com/comment/88071642
score: 0
tagged with: tkinter
answer count: 3
has comment: http://stackoverflow.com/comment/88071541
tagged with: http://stackoverflow.com/tag/html
has body: I am having problems with writing to my HTML file. I want to be able to make my code place what I have written in HTML, but my code will only do it when I do not have any While/If statements in this definition. If I do have Whiles/Ifs, my HTML file will simply just become blank. I have no idea why this happens, and I can't seem to find a workaround. Is there any way to use Whiles/Ifs without making my code delete everything in my file, and instead make it write what I want to in there? def invoice_creator_window(): global total_cost, total_cost_list, list_of_items, invoice_created invoice_created = Toplevel() invoice_created.focus_set() invoice_created.resizable(width = True, height = False) invoice_created.title("Invoice Created") invoice_created.geometry("300x300") invoice_created.geometry("+400+400") invoice_created.configure(bg = "limegreen") currentDisplay = 10 print(total_cost, total_cost_list, list_of_items) done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.") invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window) # done.grid(row = 1, column = 1, padx = 7.5, pady = space_between) invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between) # This section is for the invoice creation with HTML. html_formatting_start = """ Games R Us - Invoice Games R Us - Invoice Document """ counter = 0 while len(list_of_items) > 0: global html_formatting_mid print(counter) html_formatting_mid = (""" = len(list_of_items) - 1: return else: counter += 1 html_formatting_end = """ In Total: $""" + str(total_cost) +""" AUD Information Grabbed from These Links: Steam's New Releases [LIVE] - Steam's Top Sellers [LIVE] - Umart's Headphones [PRE-DOWNLOADED] - Umart's Microphones [PRE-DOWNLOADED] """ invoice_creation = open(invoice_file, "w") invoice_creation.write(html_formatting_start) invoice_creation.write(html_formatting_mid) invoice_creation.wri…
has comment: http://stackoverflow.com/comment/88071551
has answer: http://stackoverflow.com/a/50531774

http://stackoverflow.com/a/50427119
answers question: http://stackoverflow.com/q/50426844
has body: for me this works: from datetime import datetime from dateutil import tz def convert(date, from_zone = 'UTC', to_zone='America/New_York'): from_zone = tz.gettz(from_zone) to_zone = tz.gettz(to_zone) date = date.replace(tzinfo=from_zone) central = date.astimezone(to_zone) return date s = "Sat, 19 May 2018 16:32:56 +0000" d = datetime.strptime(s, '%a, %d %B %Y %H:%M:%S +%f') d = convert(d)
type: Answer
score: 0

http://stackoverflow.com/comment/87910044
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50448384
has text: what about single `'door'`?

http://stackoverflow.com/a/50509063
answers question: http://stackoverflow.com/q/50507990
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: side note: def interpolate(poly_1, poly_2): return map(lambda p, q: (p[0] + t*(q[0]-p[0]), p[1] + t*(q[1]-p[1])), poly_1, poly_2) does the same job. way faster

http://stackoverflow.com/q/50452684
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50452762
tagged with: python
upvote count: 2
tagged with: list
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/50452775
downvote count: 1
has title: Split a list inside a list
tagged with: string
has body: Say that I have this list List=[[‘this’ ],[‘is’],[‘a’],[‘sentence’]] And I want to split the inside lists so the output look like this List=[[‘t’,’h’,’i’,’s’],[‘i’,’s’],[‘a’],[‘s’,’e’,’n’,’t’,’e’,’n’,’c’,’e’]] I tried print([j for i in list for j in i ]) but the output came as [‘this’,’is’,’a’,’sentence ‘]
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50452752

http://stackoverflow.com/comment/87967214
type: Comment
has text: `os.chdir()` doesn't return you a list of files, it just changes directory. After that, you need `list=glob.glob('*.jpg')`
score: 0
comment on: http://stackoverflow.com/q/50476084
type: QuestionComment

http://stackoverflow.com/a/50512920
accepted answer of: http://stackoverflow.com/q/50512804
answers question: http://stackoverflow.com/q/50512804
score: 10
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/88038994
downvote count: 0
type: AcceptedAnswer
has body: I think you patch it at the wrong level. The get_context_data is used by the get function to render it. As a result, the get_context_data object has no control about what is done with the result, in order to construct a server response, You can however patch the get(..) function like: class ExtendedView(DetailView): """A base view for displaying a single object.""" def get(self, request, *args, **kwargs): self.object = self.get_object() data = self.get_context_data(object=self.object) if self.request.GET: data__ = JsonForm(request.GET) if data__.is_valid(): json = data__.cleaned_data['json'] if json == 'true': return JsonResponse({'data': data}) return self.render_to_response(data) The same holds for post, put, and other requests. If we take a look at the DetailView source code we see: class BaseDetailView(SingleObjectMixin, View): """A base view for displaying a single object.""" def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) Hence the get(..) calls the get_context_data(..) function. But it does not immediately returns the result, it wraps it into a rendered response.

http://stackoverflow.com/a/50451628
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50451456
type: Answer
answers question: http://stackoverflow.com/q/50451456
has body: Your placeholder a is defined as being of type float32 but [5, 8] contain int values. run_graph([2., 8.]) or run_graph(np.array([5, 8], dtype=np.float32)) should work.
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87985879
type: Comment
type: QuestionComment
score: 0
has text: @PM2Ring so what is the reason of this error?I thought this is the reason.
comment on: http://stackoverflow.com/q/50486478

http://stackoverflow.com/comment/91546057
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50483783
has text: Comming back to this because its been a tremendous help for quite some time, can I somehow get an extended list of bq ls -j --all? Or is it possible to only see the FAILURE jobs?
score: 0

http://stackoverflow.com/a/50538847
score: 1
upvote count: 1
type: Answer
has body: Your project setup is alright. I renamed the directories just for clarity in this example, but the structure is the same as yours: repo_dir/ project_package/ __init__.py process.py config.py # Declare your project in a setup.py file, so that # it will be installable, both by users and by you. setup.py When you have a module that wants to import from another module in the same project, the best approach is to use relative imports. For example: # In process.py from .config import name ... While working on the code on your dev box, do your work in a Python virtualenv, and pip install your project in "editable" mode. # From the root of your repo: pip install -e . With that approach, you'll never need to muck around with sys.path -- which is almost always the wrong approach.
has comment: http://stackoverflow.com/comment/88101495
answers question: http://stackoverflow.com/q/50538235
downvote count: 0
has comment: http://stackoverflow.com/comment/88102065

http://stackoverflow.com/q/50390081
tagged with: pandas
has answer: http://stackoverflow.com/a/50390128
tagged with: python
tagged with: numpy
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/50390119
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50390119
has comment: http://stackoverflow.com/comment/87795596
downvote count: 0
favorite count: 0
type: Question
has title: How to remove Semicolon from array in python?
possible better answer: http://stackoverflow.com/a/50390128
has body: I'm reading a csv file through pandas in python and the last column also includes ; how can i remove it. if i use delimiter as ; it does not work. Example : 0 -0.22693644; 1 -0.22602014; 2 0.37201694; 3 -0.27763826; 4 -0.5549711; Name: Z-Axis, dtype: object
has answer: http://stackoverflow.com/a/50390241

http://stackoverflow.com/q/50460211
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23596009
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50918468
has comment: http://stackoverflow.com/comment/87934530
tagged with: python
score: 1
has body: I have two scripts I am actively using for a programming class. My code is commented nicely and my teacher prefers outside resources since there are many different solutions. Getting to the actual problem though, I need to create a server with a socket (which works) and then allow another computer to connect to it using a separate script (which also works). The problem is after the connection is made. I want the two to be able to send messages back and forth. The way it sends has to be in byte form with how I have it set up but the byte returned is impossible to read. I can decode it but I want it to be conveniently located in the Command Prompt with everything else. I attempt to import the main script (Connection.py) into the secondary script (Client.py) but then it runs the main script. Is there any way I can prevent it from running? Here is my main script (the one creating the server) #Import socket and base64# import socket import base64 #Creating variable for continuous activity# neverland = True #Create socket object# s = socket.socket() print ("Socket created") #Just for debugging purposes# #Choose port number for connection# port = 29759 #Used a random number generator to get this port# #Bind to the port# s.bind((' ', port)) print ("Currently using port #%s" %(port)) #Just for debugging purposes# #Make socket listen for connections# s.listen(5) print ("Currently waiting on a connection...") #Just for debugging purposes# #Loop for establishing a connection and sending a message# while neverland == True: #Establish a connection# c, addr = s.accept() print ("Got a connection from ", addr) #Just for debugging purposes# #Sending custom messages to the client (as a byte)# usermessage = input("Enter your message here: ") usermessage = base64.b64encode(bytes(usermessage, "utf-8")) c.send(usermessage) #End the connection# c.close() And here is my secondary script (the one that connects to the main one) #Import socket module# import socket import Connection #Create a …
answer count: 1
downvote count: 0
has title: How to use a variable from one python script in another without running the imported script?
upvote count: 1

http://stackoverflow.com/comment/87973920
score: 0
comment on: http://stackoverflow.com/q/50479789
type: Comment
has text: From my understanding the span is the formula α=2/(span+1) which is the multiplier for weighting the EMA and the span is the period I want to calculate. It can also be written as (2 / (selected time period + 1)) = (2 / (10 + 1)) = 0.1818 (18.18%) as an example.
type: QuestionComment

http://stackoverflow.com/q/50459431
type: Question
tagged with: pandas
tagged with: matplotlib
tagged with: python
has title: In pandas and matplotlib, why is plt not called directly on the dataframe?
has comment: http://stackoverflow.com/comment/87932137
has comment: http://stackoverflow.com/comment/87932288
score: 2
upvote count: 2
type: AnsweredQuestion
has body: It's not clear to me why plotting is done like this: import pandas as pd import matplotlib.pyplot as plt df.boxplot(column='initial_cost', by='Borough', rot=90) plt.show() How is the dataframe tied to plt.show()? I've done a few web searches and even took a look at the documentation(!) but couldn't find anything addressing this specifically. I would expect something more like: boxplot = df.boxplot(column='initial_cost', by='Borough', rot=90) plt.show(boxplot) Or even something like this: boxplot = df.boxplot(column='initial_cost', by='Borough', rot=90) boxplot.plt.show()
downvote count: 0
accepted answer: http://stackoverflow.com/a/50461264
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50461264

http://stackoverflow.com/comment/87938468
type: Comment
has text: Do you mean that I create an ACL file for the account.invoice model?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50461444

http://stackoverflow.com/a/50430923
score: 1
accepted answer of: http://stackoverflow.com/q/50430511
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50430511
downvote count: 0
type: Answer
upvote count: 1
has body: Here it is , describe_spot_fleet_instances(**kwargs) Request syntax : response = client.describe_spot_fleet_instances( DryRun=True|False, MaxResults=123, NextToken='string', SpotFleetRequestId='string' ) Parameters DryRun (boolean) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . MaxResults (integer) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. NextToken (string) -- The token for the next set of results. SpotFleetRequestId (string) -- [REQUIRED] The ID of the Spot Fleet request. Here is how you will make low-level client object client = boto3.client('ec2')

http://stackoverflow.com/q/50385179
type: Question
has title: How to extract the specific line in HTML file from python?
type: UnansweredQuestion
tagged with: python
has body: I want to extract the specific red line of item from the HTML files (10 files). For example I have a code in the html file : Function A() { if ---- "Which is red color" { Print "Hello" } else-if { print "World" } } "End of function A" Function B () { if { Print "Hello" } else-if ---- "Which is red color" { print "World" } } "End of function B"' HTML format as : Sample.html Function A { if { Print Hello; ! ! ! ! So on ... Output Need as : Funct A - if Funct B - else-if I have written a python Program as : def searchhtml(data): soup = BeautifulSoup(data, 'html.parser') for ran in soup.findAll('font', {'color':'#FF311D'}) : print ran.text if __name__=='__main__': page = urllib.urlopen('Sample.html').read() searchhtml(page) Problem is : I am getting the output as : if else-if But I need as Function A - if Function B - else-if Please help me to get the correct output format .
answer count: 0
has comment: http://stackoverflow.com/comment/87900970
has comment: http://stackoverflow.com/comment/87821704
score: 0
upvote count: 1
tagged with: html-parsing
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50539256
has answer: http://stackoverflow.com/a/50539848
favorite count: 0
type: Question
tagged with: numpy
has body: I have a Pandas DataFrame like this : Date Descriptive 0 2017-1-1 Time12:30 Id124562 American electronic commerce and cloud computing company based in Seattle 1 2017-1-2 Time12:40 Id124565 Amazon has separate retail websites for the United States 2 2017-1-3 Time12:45 Id124561 In 2020, Amazon will build a new downtown Seattle building How can I generate a new DataFrame like this with Python? Date time id descriptive 0 2017-1-1 12:30 124562 American electronic commerce and cloud computing company based in Seattle 1 2017-1-2 12:40 124565 Amazon has separate retail websites for the United States 2 2017-1-3 12:45 124561 In 2020, Amazon will build a new downtown Seattle building PS: Sorry, I makeup this dataframe to represent the real data cleaning problem i met. Length of id is fixed to 6. Thanks a lot.
has answer: http://stackoverflow.com/a/50539305
has title: extracting characters from strings and forming new columns in Python
tagged with: python
possible better answer: http://stackoverflow.com/a/50539436
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50539305
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50539436
score: 1
upvote count: 3
downvote count: 2

http://stackoverflow.com/a/50513987
accepted answer of: http://stackoverflow.com/q/50511329
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50511329
has body: I may not fully understand what you're trying to do, but perhaps the following, which doesn't use functools.partial(), might help because it works without needing the index value. What it does is pass your makePool() function an iterator which will produce the paired values the Parse() function expects and passes them as a tuple. from multiprocessing.pool import ThreadPool def pairwise(iterable): "s -&gt; (s0,s1), (s2,s3), (s4, s5), ..." a = iter(iterable) return zip(a, a) strSiteMap = ['site0', 13, 'site1', 42] def makePool(cP, func, iters): try: pool = ThreadPool(cP) pool.map_async(func, iters).get(99999) pool.close() pool.join() except Exception: print('Pool Error') raise finally: pool.terminate() def Parse(args): RowNum, Link = args print('Parse({!r}, {!r}) called'.format(RowNum, Link)) makePool(50, Parse, pairwise(strSiteMap))
type: Answer

http://stackoverflow.com/a/50488871
score: 1
has body: neo4j.v1 is not a default python module, it is not automatically installed when you install python. To install neo4j.v1 Follow the instructions here. Its possible to install it directly from pycharm, as other answers have pointed out, but its better to download from the official source to make sure all related dependencies and packages are properly installed.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50488707
type: Answer
has comment: http://stackoverflow.com/comment/87992052

http://stackoverflow.com/q/50399071
has comment: http://stackoverflow.com/comment/87814066
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/87813927
favorite count: 0
has title: Replace square brackets and comma in JSON file
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: dataframe
tagged with: python
score: -2
tagged with: replace
type: Question
has answer: http://stackoverflow.com/a/50399183
has body: I have a pandas dataframe df which is as follows: | Name | Age | |---------|-----| | Dinesh | 23 | | Karthik | 34 | | Amit | | | Mishra | 10 | I need to convert this into JSON so that my output is: { "Name": "Dinesh", "Age": 23 } { "Name": "Karthik", "Age": 34 } { "Name": "Amit", "Age": null } { "Name": "Mishra", "Age": 10 } I tried: df.to_json('abcd', orient = 'records') But I got the output for 'abcd' as: [ { "Name": "Dinesh", "Age": 23 }, { "Name": "Karthik", "Age": 34 }, { "Name": "Amit", "Age": null }, { "Name": "Mishra", "Age": 10 } ] I want to eliminate square brackets and the comma after each curly bracket. How can I do this in Python?

http://stackoverflow.com/q/50417922
tagged with: opencv
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50417952
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50417952
has title: Python specifying file location directory
accepted answer: http://stackoverflow.com/a/50418074
has answer: http://stackoverflow.com/a/50418074
type: Question
tagged with: python-import
tagged with: python
has body: I am using Python 64 bit IDLE on Windows 7 machine to attempt to write a script for opencv machine learning. Im trying to figure out why my code below cannot find the directory where my picture files are located on my Windows PC. Is there a better way to do this? Nothing happens in the shell output in IDLE and I was hoping the print function would work. I have the .py files in a folder called faces on my C:drive, as shown below. C:\Users\ben\Documents\Python\opencv\Faces\images\ben And the picture files are located in Faces\images\ben import cv2 import os import numpy as np from PIL import Image import pickle BASE_DIR = os.path.dirname(os.path.abspath(__file__)) image_dir = os.path.join(BASE_DIR, "images") for root, dirs, files in os.walk(image_dir): for file in files: if file.endswith("png") or file.endswith("JPEG"): path = os.path.join(root, file) label = os.path.basename(root).replace(" ", "-").lower() print(path)

http://stackoverflow.com/a/59958618
answers question: http://stackoverflow.com/q/50419637
type: Answer
downvote count: 0
upvote count: 5
score: 5
has body: This seems to work for me: Start-Process -FilePath ./python-3.7.6-amd64.exe -ArgumentList "/quiet InstallAllUsers=1 PrependPath=1" -NoNewWindow -Wait

http://stackoverflow.com/comment/88056812
type: Comment
has text: Its like , We want to add two existing csv into a new csv in tabs.
comment on: http://stackoverflow.com/q/50522258
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87845685
comment on: http://stackoverflow.com/q/50414300
score: 2
has text: Spark handles tall tables (lots of rows) really well, but it's not as great with wide tables (lots of columns).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88007086
score: 0
type: Comment
has text: @nolwenb Assert is just an instruction to stop the program if the statement is false. You can remove them, they were just for me to make sure there won't be any empty list passed to the function.
comment on: http://stackoverflow.com/a/50489905
type: AnswerComment

http://stackoverflow.com/comment/87952617
type: AnswerComment
score: 0
has text: We've advanced, got a new problem `ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters`.
type: Comment
comment on: http://stackoverflow.com/a/50468231

http://stackoverflow.com/comment/87855130
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50419584
has text: I think I disagree, @chrisz. Testable, readable, maintainable code that is fast enough is definitely good practice in a professional production system. Optimize for performance when you discover that performance is an issue. Otherwise, optimize for code you can maintain. I've personally never experienced an issue using apply, and haven't heard it considered bad practice before. I'm open to learning something, however. But I suppose these comments aren't the right place for the debate.
type: Comment

http://stackoverflow.com/q/50468303
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87976076
tagged with: negative-lookbehind
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87949881
has answer: http://stackoverflow.com/a/50468496
has comment: http://stackoverflow.com/comment/87952471
type: UnansweredQuestion
tagged with: python
tagged with: regex
has body: I want to look/parse for a unit (Pa, K, degC, °C) and want to make sure it is followed and preceded by something other than a letter because K, Pa or whatever units I match are obviously part of many many words. ;-) The regex [^A-Za-z][Dd][Ee][Gg][Cc][^A-Za-z] works, however it matches in text: blablablatext degC blablabla the degC + whitespaces. I want to match only degC! I tried (?![A-Za-z]) [Dd][Ee][Gg][Cc] (?>![A-Za-z]) but it doesn't match ever and I don't know how. If I use only the negative lookahead or the negative lookbehind it works and matches only degC without whitespaces. Could someone please explain me how to make sure my target word is preceded and followed by anything other than letters?
has title: python regex lookbehind, lookahead
upvote count: 1
tagged with: regex-lookarounds
score: 1

http://stackoverflow.com/q/50490240
tagged with: statistics
has title: How to simplify a list comprehension of distributions in python
tagged with: distribution
type: AnsweredQuestion
has body: Get objects for continuous distributions in scipy.stats This is the sample code: getditributions.py import scipy.stats as st CONTINUOUS_DISTRIBUTIONS = [getattr(st,d) for d in dir(st) if isinstance(getattr(st,d), st.rv_continuous)] print ('number of distributions = ', len(CONTINUOUS_DISTRIBUTIONS)) print ('CONTINUOUS_DISTRIBUTIONS = ') print(CONTINUOUS_ DISTRIBUTIONS) Obs: This code works but I have called getattr twice in the list comprehension. How to simplify this code to have just one call to getattr? Or alternative solution?
linked to: http://stackoverflow.com/q/29820026
accepted answer: http://stackoverflow.com/a/50490299
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50490299
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/87850092
comment on: http://stackoverflow.com/q/50417109
score: 1
type: Comment
has text: @tdelaney: From the post: *`file1.py` imports `file2.py`*
type: QuestionComment

http://stackoverflow.com/comment/87990819
comment on: http://stackoverflow.com/a/50486615
score: 0
type: AnswerComment
has text: we have key and dict as value of those key, i want whenever we have the same key in all sub dict to merge the new dict with the existing one not to override with the new object @ Ali Yılmaz
type: Comment

http://stackoverflow.com/comment/88033219
comment on: http://stackoverflow.com/q/50504523
score: 0
type: Comment
type: QuestionComment
has text: All of them or only the most recent?

http://stackoverflow.com/a/50485724
score: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/87984663
type: Answer
accepted answer of: http://stackoverflow.com/q/50485560
has comment: http://stackoverflow.com/comment/87984533
has comment: http://stackoverflow.com/comment/92887188
has body: Instead of having cookie.txt you can have cookie.py and import it to your main program file. cookie.py cookies = [ { "domain":"xxx" }, {"domain":"yyy"} ] main.py from cookies import cookies driver.add_cookie(cookies[0]) It's way simpler than manually parsing the file, or opening the file and using it.
upvote count: 2
answers question: http://stackoverflow.com/q/50485560

http://stackoverflow.com/a/50419584
has comment: http://stackoverflow.com/comment/87854674
has comment: http://stackoverflow.com/comment/87854998
has comment: http://stackoverflow.com/comment/87854900
has comment: http://stackoverflow.com/comment/87854980
has comment: http://stackoverflow.com/comment/87855020
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/87854630
has body: Write a function that takes in the row and performs your logic: Because you say you have many columns, we'll use any and all from the std lib. This assumes that index_total is the last column and the ID is the first column def functo(row): if (any([i == -2 for i in row[1:-1]]) and row[-1] == 2): return 1 elif (all(i == 0 for i in row[1:-1]) and row[-1] == 2): return 1 else: return 0 and apply it to your dataframe: df['flag'] = df.apply(functo, axis=1) We use axis=1 to apply your function to rows instead of columns. Also, a tip: I would avoid naming columns index because in pandas terminology, the index refers to a row.
score: 1
answers question: http://stackoverflow.com/q/50419394
downvote count: 1
has comment: http://stackoverflow.com/comment/87855130

http://stackoverflow.com/comment/87961107
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50414768
has text: On Windows Excel acquires an exclusive lock on the file, but this is not the case on the other major OS for which Excel is available. The specification mandates zip files as the package format and these are not editable inplace, this precludes concurrent editing. But, hey, you know better so I'm looking forward to your library.

http://stackoverflow.com/comment/87962061
has text: @OP this is a good solution if you're okay with dropping Header 1 and Header 2.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50473161
type: AnswerComment

http://stackoverflow.com/comment/88046112
type: Comment
score: 0
type: AnswerComment
has text: @vas I have added a 2nd example using your code to show what needed to be update.
comment on: http://stackoverflow.com/a/50516033

http://stackoverflow.com/comment/87924665
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50455590
has text: Can you provide data showing really weird numbers? This works with the given example.

http://stackoverflow.com/a/54099358
answers question: http://stackoverflow.com/q/50519924
score: 0
type: Answer
has body: According to data reader docs, Yahoo!, Google Options, Google Quotes and EDGAR have been immediately deprecated due to large changes in their API and no stable replacement. Use 'iex' instead import pandas_datareader.data as web import datetime as dt start = dt.datetime(2018,1,1) end = dt.datetime(2019,1,1) aapl = web.DataReader('AAPL', 'iex', start, end) aapl.shape (251, 5) aapl.head() open high low close volume date 2018-01-02 167.6431 169.7514 166.7564 169.7120 25555934 2018-01-03 169.9780 171.9682 169.4165 169.6825 29517899 2018-01-04 169.9879 170.9041 169.5347 170.4707 22434597 2018-01-05 170.8746 172.7760 170.4904 172.4115 23660018 2018-01-08 171.7711 173.0125 171.3573 171.7711 20567766

http://stackoverflow.com/q/50408226
upvote count: 0
type: UnansweredQuestion
has title: getting into infinite loop when using a while loop
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50408470
has comment: http://stackoverflow.com/comment/87831947
tagged with: while-loop
tagged with: python
has comment: http://stackoverflow.com/comment/87832053
score: -4
has body: I am using this code to use a dataframe lookup for every single record in the first dataframe. for i in range(len(a1)): title_derived = [] k = 100000 print(i) for j in range(len(b1)): print(j) while j &lt; (k + 6): #print(b1.iloc[i][10], a1.iloc[j][3]) if b1.iloc[j][10] == a1.iloc[i][3]: print(j,k) print('1st if ' + str(j)) print (b1.iloc[j][1], a1.iloc[i][11], b1.iloc[j][5]) if (((pd.to_datetime(b1.iloc[j][1]) &lt;= pd.to_datetime(a1.iloc[i][11]) &lt;= pd.to_datetime(b1.iloc[j][5]))) or ((pd.to_datetime(b1.iloc[j][1]) &lt;= pd.to_datetime(a1.iloc[i][8]) &lt;= pd.to_datetime(b1.iloc[j][5])))) : print('2nd if' + str(j)) title_derived.append(b1.iloc[j][15]) print('inserted ' + b1.iloc[j][15] + ' in ' + str(i) + ' th record ') a1.iat[i,65] = title_derived It prints, 0 0 and then goes into a an infinite loop.
has comment: http://stackoverflow.com/comment/87831873
downvote count: 4
tagged with: infinite-loop

http://stackoverflow.com/comment/87831075
type: QuestionComment
score: 0
has text: What are you actually asking? Do you want us to explain lists? Do you want us to debug your code? Try to be clear as to what you're asking and what sort of answers you require. I debugged your code for you and I hope I helped, but if you make it clear what you want people to put, then it will be easier for us to provide an answer.
type: Comment
comment on: http://stackoverflow.com/q/50403205

http://stackoverflow.com/a/56855189
type: Answer
score: -1
answers question: http://stackoverflow.com/q/50479614
has body: I am working on a project that uses moviepy to edit and add overlays automatically to videos, and what you describe it is absolutely possible. I recommend you to read the moviepy documentation. Here you can see an example of a project using moviepy to create a musical video clip.
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/50464584
has comment: http://stackoverflow.com/comment/89113436
answer count: 1
has body: I am doing Android App Automation using Appium and Python, I am stuck at place where i have to select value from Numberpicker. I tried send_keys, Click, swipe but no luck enter image description here
has comment: http://stackoverflow.com/comment/87947924
has comment: http://stackoverflow.com/comment/89158304
tagged with: numberpicker
has answer: http://stackoverflow.com/a/59561001
type: Question
has comment: http://stackoverflow.com/comment/87973285
has title: Python: Android App Automation : Unable to select from Number picker
tagged with: automation
tagged with: appium
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87981202
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/88019542
has comment: http://stackoverflow.com/comment/88015261
score: 0
has comment: http://stackoverflow.com/comment/88019675
has comment: http://stackoverflow.com/comment/87973600
has comment: http://stackoverflow.com/comment/87973451

http://stackoverflow.com/q/50434194
has comment: http://stackoverflow.com/comment/87886724
has body: I am trying to work with a point cloud in Python, Visual&nbsp;Studio&nbsp;2017 and the Point Cloud Library from Sirokujira (PCL), installed on Windows&nbsp;10 64 bit and Anaconda 4.4.10 (Python 3.5) with: conda config --append channels conda-forge conda install -c sirokujira python-pcl As I can use methods I do not get a preview of available methods and parameters, and it is rather hard to figure out how to use the methods. Is there a chance to add the missing information into Visual Studio?
has comment: http://stackoverflow.com/comment/87938039
tagged with: python
has comment: http://stackoverflow.com/comment/87937844
type: Question
tagged with: visual-studio-2017
answer count: 0
type: UnansweredQuestion
score: 0
has title: Python pcl_visualization, sirokujira, no method/parameter preview in Visual Studio 2017
has comment: http://stackoverflow.com/comment/87886804

http://stackoverflow.com/comment/87945841
comment on: http://stackoverflow.com/q/50466289
type: QuestionComment
score: 0
has text: You have to return result in your render_to_pdf(): `return HttpResponse(result.getvalue(), content_type='application/pdf')`.
type: Comment

http://stackoverflow.com/q/50466050
upvote count: 1
type: UnansweredQuestion
favorite count: 0
tagged with: optimization
has title: How to create custom graphs for dask dataframes?
type: Question
tagged with: dataframe
tagged with: python
score: 1
has body: I'm trying to paralelize some operations to be done on a Dask Dataframe but I'm not completely understanding the best way to do it. For example, I'm reading a dask dataframe from parquet and I want to add one unit to the first column by one and two to the second column: import dask.dataframe as dd ddf = dd.read_parquet('dataframe') ddf['a'] = ddf['a'] + 1 ddf['b'] = ddf['b'] + 2 ddf.visualize() Here is the graph of this computation. (The dataframe was created with 2 partitions). As can be seen, the two operations are done one after another, where we know that they could be done in parallel (at least parts of it) because they are adding some value to different columns. Thus, I tried to paralelize these operations by using delayed functions instead: from dask import delayed import dask.dataframe as dd @delayed def increment(df, x, val): print('Type: ',type(df)) df[x] = df[x] + val return df @delayed def overwrite(df1 , df2, col): df1[col] = df2[col] return df1 ddf = dd.read_parquet('dataframe') op1 = increment(ddf'a', 'a', 1) op2 = increment(ddf'b', 'b', 2) op3 = overwrite(ddf, op1, 'a') op4 = overwrite(op3, op2, 'b') op4.visualize() Here is the graph of this computation and, as can be seen, some part of the work is being done in parallel. Of course, these operations are very simple and this is an overkill but it's just to demonstrate the point. However, I am printing the type of the input dataframe inside the increment function and, for my surprise, when I run the op4.compute(), the type is pandas.core.frame.DataFrame while I was expecting it to be dask.dataframe.core.DataFrame. Then I decided to delay the parquet file reading: @delayed def read(name): return dd.read_parquet(name) ddf = read('dataframe') op1 = increment(ddf'a', 'a', 1) op2 = increment(ddf'b', 'b', 2) op3 = overwrite(ddf, op1, 'a') op4 = overwrite(op3, op2, 'b') op4.visualize() The graph shows that the jobs are being done in parallel and when I run op4.compute() the type of the input d…
tagged with: dask
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/87891112
type: AnswerComment
has text: As mentioned I do not want to use any external libraries due to some reasons.
type: Comment
comment on: http://stackoverflow.com/a/50438570
score: 0

http://stackoverflow.com/a/50441738
has body: Missing break in a couple spots. Also, this work-in-progress is not a prime number finder at this point, it will simple find even and odd numbers because of how the loops are structured.
type: Answer
answers question: http://stackoverflow.com/q/50441421
score: 0

http://stackoverflow.com/q/50505250
linked to: http://stackoverflow.com/q/43087668
has title: Using NumPy array operations with Numba's @guvectorize
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
has body: I've been experimenting with Numba lately, and here's something that I still cannot understand: In a normal Python function with NumPy arrays you can do something like this: # Subtracts two NumPy arrays and returns an array as the result def sub(a, b): res = a - b return res But, when you use Numba's @guvectorize decorator like so: # Subtracts two NumPy arrays and returns an array as the result @guvectorize(['void(float32[:], float32[:], float32[:])'],'(n),(n)-&gt;(n)') def subT(a, b, res): res = a - b The result is not even correct. Worse still, there are instances where it complains about "Invalid usage of [math operator] with [parameters]" I am baffled. Even if I try this: # Subtracts two NumPy arrays and returns an array as the result @guvectorize(['void(float32[:], float32[:], float32[:])'],'(n),(n)-&gt;(n)') def subTt(a, b, res): res = np.subtract(a,b) The result is still incorrect. Considering that this is supposed to be a supported Math operation, I don't see why it doesn't work. I know the standard way is like this: # Subtracts two NumPy arrays and returns an array as the result @guvectorize(['void(float32[:], float32[:], float32[:])'],'(n),(n)-&gt;(n)') def subTtt(a, b, res): for i in range(a.shape[0]): res[i] = a[i] - b[i] and this does work as per expected. But what is wrong with my way? P/S This is just a trivial example to explain my problem, I don't actually plan to use @guvectorize just to subtract arrays :P P/P/S I suspect it has something to do with how the arrays are copied to gpu memory, but I am not sure... P/P/P/S This looked relevant but the function here operates only on a single thread right...
tagged with: numba
tagged with: python
accepted answer: http://stackoverflow.com/a/50518171
score: 4
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50518171

http://stackoverflow.com/comment/88054564
type: AnswerComment
comment on: http://stackoverflow.com/a/50521139
score: 0
has text: hello! The string can be a lot of different combination of letter though so by doing if 'abc' is kinda hardcoding it
type: Comment

http://stackoverflow.com/comment/87974152
comment on: http://stackoverflow.com/a/50472190
score: 1
type: Comment
has text: Please post how you read the response from the webserver, lokks like this the place where the encoding get wrangled.
type: AnswerComment

http://stackoverflow.com/comment/88046016
has text: @coldspeed that did not work because it matches the space before.
type: Comment
comment on: http://stackoverflow.com/q/50516666
score: 0
type: QuestionComment

http://stackoverflow.com/q/50536582
tagged with: android
tagged with: cross-platform
tagged with: image
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50537235
type: UnansweredQuestion
tagged with: python
has title: Python: Displaying Graphics on Android Screen from Desktop Script
has answer: http://stackoverflow.com/a/50536668
score: 0
has body: Skip the first two paragraphs if your not interested in why I'm asking this question. Here is the situation: I'm using a Moto Z Play with the Projector Modification, the mod is really cool and allows me to literally project my phone screen onto the wall. I've been writing a personal assistant program that helps me with my daily life I.E. Sorting gmails, reminding me of calendar events, keeping track of anything I want it to remember and reminding me of those things when I've asked it to, and much more. Its basically a personal secretary. One new feature I just added was a habit tracker. I created a small graphical interface on my phone using Tasker that would email my "assistant" who would then record the habit and create a really cool graph that shows my past habit record as well as using a neural network to predict the next days habit. Only problem is, the graph got really intricate really fast. I want to show a months worth of habits (16 total habits), creating what can be up to a 16 x 31 floating point graph with labels. My laptop screen is just not big enough to display all of that without it just being a mess! I really want to display the graph from my projector mod, the entire wall will definitely be big enough to show all that data. Ok, now my question (thanks for hanging in there I know that was a lot): Is there any way that I can display an image on my phone from a Python program without creating a standalone app? Even if my phone needs to be plugged into my computer to stream the data through a cable. I would use a service like Kivy to create a standalone app, but then it wouldn't be hooked up to my assistant, completely defeating the purpose. I'm not looking for anything similar to a notification, I really want to draw over the entire screen of my phone. This is something I did with Processing (Java library) a while back, but now I'm using Python because it's more machine learning friendly. I've looked into a lot of services but nothing seems to be able …

http://stackoverflow.com/comment/87937671
score: 0
has text: Can you add some data sample with expected output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50462309

http://stackoverflow.com/comment/87995617
comment on: http://stackoverflow.com/q/50478223
type: QuestionComment
has text: Are you asking about getting the indices back to *Python*? If so, you will have to run a Bokeh server app. When you make standalone Bokeh output, it generates static HTML and JS code that is not connected to any Python process.
score: 0
type: Comment

http://stackoverflow.com/comment/88087270
type: AnswerComment
has text: Thank you again for helping me with this. I will try your code!. It seems that it is working.
comment on: http://stackoverflow.com/a/50518958
type: Comment
score: 0

http://stackoverflow.com/a/50462185
has body: You can use: In [20]: [k for e in a for k in (e if isinstance(e, list) else [e])] ...: Out[20]: [2, 33, 4, 2, 3, 4, 6]
type: Answer
accepted answer of: http://stackoverflow.com/q/50462078
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50462078
score: 0

http://stackoverflow.com/q/50416785
has body: I have 3 subplots and wish to plot temperature and rainfall on each subplot. The temp scale is [-5,110] and the rain scale is [0, 2]. I want the rain data to use the full height of the subplot for display. If I have a single plot, I can use twinx to create a 2nd scale. How can I achieve the same effect with multiple subplots?
has title: Multi-scaled subplots in matplotlib
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: subplot
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87919820
downvote count: 1
has comment: http://stackoverflow.com/comment/87849206
has answer: http://stackoverflow.com/a/61759169
score: 0
has comment: http://stackoverflow.com/comment/87849987
tagged with: matplotlib

http://stackoverflow.com/a/50471305
has body: You can look in the source code of scipy to see the implementation of the excitingmixing option: https://github.com/scipy/scipy/blob/c948e96ebb3454f6a82e9d14021cc601d7ce7a85/scipy/optimize/nonlin.py#L1272 You're likely not going to want to reimplement the entire root finding algorithm in numba. I better strategy you can test is to use numba to optimize the function that you pass to the scipy method. You're still going to pay some overhead of scipy calling a function, but you might see a performance increase if the bottleneck is evaluating the function and that can be done faster with a numba jitted version. I've found it best to just experiment with numba and test with the timeit method.
downvote count: 0
has comment: http://stackoverflow.com/comment/87959256
upvote count: 2
answers question: http://stackoverflow.com/q/50470855
type: Answer
score: 2

http://stackoverflow.com/a/50415221
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50411052
score: 1
answers question: http://stackoverflow.com/q/50411052
type: AcceptedAnswer
downvote count: 0
has body: I think the main problem is that k goes to nearly 0 here, which makes it hard for the fitting process to determine the other parameters. When parameters hit their bounds, it can be hard for the algorithm to be able to move away from it. Here it looks like it tries a of ~15, then that pushes k toward zero and it ends up so far away it doesn't know how to get unstuck. Generally, it's a good idea to set bounds based on physical limitations, or to know how the fit will respond to values near the bounds. That said, I don't really know why this case is so bad.
type: Answer

http://stackoverflow.com/q/50430479
type: Question
has comment: http://stackoverflow.com/comment/111872511
tagged with: linux
upvote count: 2
has title: Compilation Python 3.6.5 static binary for arm32 fail
type: UnansweredQuestion
tagged with: android
tagged with: compilation
tagged with: python
score: 2
answer count: 0
has body: I'm trying, on Debian 9.4 x64, to compiling static Python binaries for arm32. I have initialy: downloaded the "Gzipped source tarball" source file from: https://www.python.org/downloads/release/python-365/ extracted source files in: /python3.6.5/ downloaded and extract "binutils-gold-2.29.1-16.1.armv7hl.rpm" by cmd line: rpm -qlp /python3.6.5/binutils-gold-2.29.1-16.1.armv7hl.rpm try to compile the binary with this following command: ./configure --build=arm --prefix="$PWD"/out LDFLAGS="-static -static-libgcc -Wl,--unresolved-symbols=ignore-all -Wl,--export-dynamic" CPPFLAGS=-static CXXFLAGS=-static CFLAGS="-Os -static" LDFLAGS=-static LD=ld.gold And i get this errors: /usr/bin/ld: BFD assertion (GNU Binutils for Debian) 2.28 as failed ../../bfd/elflink.c:14098 /usr/bin/ld: BFD (GNU Binutils for Debian) 2.28 internal error, aborting at ../../bfd/elf64-x86-64.c:6137 in elf_x86_64_finish_dynamic_symbol /usr/bin/ld: Thanks to report this anomaly. collect2: error: ld returned 1 exit status Makefile:561 : the recipe for the "python" target has failed -make: *** [python] Error 1 I'm trying to find how i could fix this error, but unfortunatly the support webpage on Python website isn't helpfull (https://wiki.python.org/moin/BuildStatically). Finally, I would like to compile Python 3.6.5 for all processor platforms on which Android can run (arm32, aarm64, x86_x64, mips, mipsx64,...), to ultimately get a single binary file (i will repeat tasks for all other archs when i will have done with arm32). So one file for each architectures cited, not multiple files/folders. In a static way to avoid any dependencies with external libraries. I chose to carry out the build operations, but if other less hazardous and simpler solutions exist i am taker. NB: all cmd line has been made through LXTerminal on root session by default. Thanks by advance for help.
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88122406
has text: Have you tried using the domain name (`LDAP://domain.com`) rather than an IP?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50536918
type: Comment

http://stackoverflow.com/q/50472999
has answer: http://stackoverflow.com/a/50473146
tagged with: python
has comment: http://stackoverflow.com/comment/87959840
tagged with: ip-address
has answer: http://stackoverflow.com/a/71082443
has answer: http://stackoverflow.com/a/50473545
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87959881
score: 0
has comment: http://stackoverflow.com/comment/87959751
downvote count: 2
has comment: http://stackoverflow.com/comment/87959630
has title: Python convert a list of ips into a list of networks
has answer: http://stackoverflow.com/a/50473426
has comment: http://stackoverflow.com/comment/87959719
has answer: http://stackoverflow.com/a/50473253
possible better answer: http://stackoverflow.com/a/50473253
has comment: http://stackoverflow.com/comment/87959814
has comment: http://stackoverflow.com/comment/87959683
accepted answer: http://stackoverflow.com/a/71082443
favorite count: 0
has comment: http://stackoverflow.com/comment/87959791
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87959800
answer count: 5
linked to: http://stackoverflow.com/q/6708272
linked to: http://stackoverflow.com/q/29539071
has comment: http://stackoverflow.com/comment/87959747
has body: I have a list of ips like this; ban = ['162.210.197.58', '36.72.31.198', '163.172.221.63', '134.35.42.49', '176.65.117.81', '46.8.28.110', '110.139.16.72', '31.29.61.218', '38.95.109.67', '31.155.204.143', '5.254.65.190', '46.101.127.145', '111.15.193.84', '187.142.198.151', '188.227.45.110', '125.236.168.242', '5.254.65.122', '5.254.65.28', '185.182.81.93', '188.210.133.199', '151.241.125.237', '207.148.111.126', '145.239.70.231', '2.94.113.65', '204.85.191.30', '2.229.128.135', '92.127.255.182', '46.133.77.143', '118.69.63.15', '46.39.55.162', '185.182.81.14', '188.244.132.49', '138.197.160.121', '176.15.222.56', '82.178.233.175', '94.41.43.252', '78.137.73.171', '5.142.90.22', '212.2.212.151', '207.244.77.174', '176.59.46.108', '179.7.106.194', '154.118.17.57', '5.254.65.119', '176.33.236.247', '41.218.215.25', '199.249.224.47', '207.244.83.97', '84.241.13.93', '197.210.54.218', '93.35.166.148', '218.107.49.9', '39.55.130.71', '78.168.207.252', '213.141.227.238', '36.69.70.20', '5.254.65.218', '103.10.197.12', '207.244.83.194', '122.163.128.154', '93.185.16.82', '95.24.168.216', '103.16.26.148', '118.100.59.199', '209.59.188.147', '207.244.93.234', '88.81.46.212', '23.105.140.146', '89.104.104.225', '83.149.21.13', '41.34.51.195', '146.185.133.214', '37.204.108.198', '188.123.231.194', '85.140.3.172', '185.182.81.45', '185.182.81.61', '5.254.65.213', '185.182.81.136', '103.10.197.205', '185.182.81.86', '207.244.79.138', '116.240.84.42', '91.219.101.68', '80.191.221.23', '178.62.220.63', '209.58.148.85', '167.114.159.186', '108.59.8.246', '74.82.17.84', '178.129.172.216', '36.72.178.137', '41.254.7.157', '185.190.241.83', '185.182.81.58', '107.77.209.79', '207.244.77.137', '58.27.54.130', '69.15.118.106', '85.94.0.117', '41.215.173.28', '185.182.81.28', '46.101.18.209', '5.254.65.185', '195.123.217.178', '2.48.190.213', '188.247.190.79', '192.119.160.190', '95.72.13.156', '68.149.146.193', '197.157.244.206', '103.10.197.157', '176.195.155.114', '194.88.107.55', '8…

http://stackoverflow.com/comment/87812256
has text: This article is not helpful
score: 1
comment on: http://stackoverflow.com/q/50397782
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87974498
type: AnswerComment
has text: Thank you so much Austin. This was really very helpful to me :)
comment on: http://stackoverflow.com/a/50470431
score: 0
type: Comment

http://stackoverflow.com/a/52483423
has body: Based on the fact that ids serialization (query) is handled pretty straightforwardly by DjangoObjectType, I will assume your question relates to mutations. Also, since good practice is rather oriented towards generating ids on server side, I will also ignore the fact that you mention UUID: I have a feeling this logic should be handled outside of the graphql layer. The question we therefore seem to be left with is: Is there a graphene-django Input field to validate primary keys used as mutation arguments ? Couldn't find any doc on that, so I ventured with the following: def PrimaryKey(model: django.db.models.Model): """ This contrived way of creating PrimaryKey classes is due to the fact that parse_literal is a static method of graphene.Scalar. """ def parse_literal(node): if isinstance(node, ast.IntValue): pk = node.value elif isinstance(node, ast.StringValue): pk = int(node.value) else: raise GraphQLError(f'Unsupported type for PrimaryKey: {type(node)}') return model.objects.get(pk=pk) return type( f'{model.__name__}PrimaryKey', (graphene.Scalar,), dict( parse_literal=parse_literal, serialize=lambda x: None, parse_value=lambda x: None, ) ) Suggestion of usage (not all models shown): class CreateProject(graphene.Mutation): class Arguments: name = graphene.String() owner = PrimaryKey(User) # graphene.List(PrimaryKey(User)) works too ok = graphene.Boolean() @staticmethod def mutate(root, info, name: str, owner: User): # owner has been instantiated pass # do business
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50413481

http://stackoverflow.com/comment/87840028
type: QuestionComment
has text: Show us your code so far. Is this in pandas? numpy? a list of lists? We simply need more detail and then we can help you.
score: 0
comment on: http://stackoverflow.com/q/50412165
type: Comment

http://stackoverflow.com/comment/88017349
score: 1
type: Comment
type: QuestionComment
has text: @dhinar That's great! I suggest editing those thoughts into your question.
comment on: http://stackoverflow.com/q/50502442

http://stackoverflow.com/comment/87829726
type: AnswerComment
has text: Updated that code line and change variable name `data-mode` to `data_mode`, former is illegal variable name.
score: 0
comment on: http://stackoverflow.com/a/50404269
type: Comment

http://stackoverflow.com/q/50409452
has answer: http://stackoverflow.com/a/50411303
upvote count: 2
has body: How can I sum values in dataframe that a separated by semicolon? Got: col1 col2 2018-03-05 2.1 8 2018-03-06 8 3.1;2 2018-03-07 1;1 8;1 Need: col1 col2 2018-03-05 2.1 8 2018-03-06 8 5.1 2018-03-07 2 9
has title: Python pandas: apply on separated values
has answer: http://stackoverflow.com/a/50409502
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50409509
type: AnsweredQuestion
answer count: 3
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/50409509
possible better answer: http://stackoverflow.com/a/50411303
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50456107
type: Question
has title: Finding a bug in getTotalX function. Python
has comment: http://stackoverflow.com/comment/87932478
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87926008
score: 0
has answer: http://stackoverflow.com/a/50473799
answer count: 1
tagged with: python
has body: Recently I was asked the following question in an interview to be programmed via python: The elements of the first array are all factors of the integer being considered The integer being considered is a factor of all elements of the second array These numbers are referred to as being between the two arrays. You must determine how many such numbers exist. Input Format The first line contains two space-separated integers describing the respective values of n, the number of elements in array a, and m, the number of elements in array b. The second line contains n distinct space-separated integers describing a0, a1, ... an-1. The third line contains m distinct space-separated integers describing b0, b1, ... bn-1. Constraints n,m in the range 1,10 ai in the range 1,100 bi in the range 1,100 Output Format Print the number of integers that are considered to be between a and b. Sample Input: 2 3 2 4 16 32 96 Sample Output: 3 Explanation: 2 and 4 divide evenly into 4, 8, 12 and 16. 4, 8 and 16 divide evenly into 16, 32, 96. 4, 8 and 16 are the only three numbers for which each element of A is a factor and each is a factor of all elements of B. This is the code that I wrote (I only had to complete the function 'getTotalX'. The remaining code already existed): Code. The function body getTotalX is what I wrote However, it seems, my solution was incorrect but the reason was not told to me. Looking for some help in identifying the bug.

http://stackoverflow.com/comment/87847728
type: AnswerComment
score: 1
has text: Spare yourself the `reset_index` by using `ignore_index=True` in `pd.concat`.
type: Comment
comment on: http://stackoverflow.com/a/50416031

http://stackoverflow.com/a/50536857
score: 4
has comment: http://stackoverflow.com/comment/88086105
upvote count: 4
has body: df.apply(lambda x: x == x.max(), axis=1).astype(int) should do it. This works by checking if the value is the maximum of that column, and then casting to integer (True -> 1, False -> 0) Instead of apply-ing a lambda row-wise, it is also possible to transpose the dataframe &amp; compare to max and then transpose back (df.T == df.T.max()).T.astype(int) And lastly, a very fast numpy based solution: pd.DataFrame((df.T.values == np.amax(df.values, 1)).T*1, columns = df.columns) The output is in all cases: A B C 0 0 1 0 1 1 0 0 2 1 0 0 3 1 0 0 4 0 0 1
has comment: http://stackoverflow.com/comment/88086429
has comment: http://stackoverflow.com/comment/88085822
downvote count: 0
has comment: http://stackoverflow.com/comment/88085850
answers question: http://stackoverflow.com/q/50536762
type: Answer
has comment: http://stackoverflow.com/comment/88086385
has comment: http://stackoverflow.com/comment/88085900

http://stackoverflow.com/comment/87993228
type: Comment
has text: IMO you'd be better off just storing the df as the values in a dictionary with the filename as the key, your proposal requires you to somehow keep track of dfN with whatever file it came from by reading a column name
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50490145

http://stackoverflow.com/comment/87878637
type: QuestionComment
comment on: http://stackoverflow.com/q/50431803
has text: Also, IIRC, the Mac `unzip` tool isn't the Info-ZIP one, but one of the alternatives that silently handles a bunch of similar but incompatible formats—but `zipinfo` and/or `file` should be able to tell you if that's what's going on.
score: 0
type: Comment

http://stackoverflow.com/comment/87976607
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50481242
has text: If you're new to Python, is there a reason you're using Python 2.7 instead of 3.6?
type: Comment

http://stackoverflow.com/comment/87855020
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/50419584
type: Comment
has text: I'm sorry, but I just cannot agree with that reasoning. If cython is needed, then write a function and cythonize it. Until then, you should stick to good practices and seek to vectorize where pandas lets you.

http://stackoverflow.com/comment/87899834
type: QuestionComment
score: 0
has text: `list(result[0])` returns `TypeError: 'Particle' object is not iterable `
comment on: http://stackoverflow.com/q/50442889
type: Comment

http://stackoverflow.com/comment/87946099
score: 0
comment on: http://stackoverflow.com/a/50464973
type: Comment
has text: Please note that `if m:` is not a valid test for success of `re.match`. You _could_ use `if m.end():` but however, clearly writing `if m.end() > 0:` or sth similar is always clearer to read and understand immediately.
type: AnswerComment

http://stackoverflow.com/comment/88114839
type: AnswerComment
has text: I tried to incorporate this in my line of code but it doesn't work.
comment on: http://stackoverflow.com/a/50541561
type: Comment
score: 0

http://stackoverflow.com/q/50520233
answer count: 1
has body: Does anyone have a working sample in Github or other link that demonstrates the use of Aspose Word Cloud (https://products.aspose.cloud/words) in NodeJS or Python? Case scenario.. you have a MS Word file with content "Hello World". Your demo will upload the .docx file to Aspose Cloud, replace the text content to "How are you, Universe?" and download the .docx file.
tagged with: python
tagged with: aspose.words
tagged with: node.js
score: 0
tagged with: aspose
type: Question
has answer: http://stackoverflow.com/a/50523657
has title: Aspose Word Cloud API - NodeJS
type: UnansweredQuestion

http://stackoverflow.com/a/50449606
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/50449174
upvote count: 4
has body: You can use mapper-events in sqlalchemy http://docs.sqlalchemy.org/en/latest/orm/events.html#mapper-events before_update end before_insert and then you can edit your instance before :) ex.: def before_insert_function(mapper, connection, target): # 'target' is your object print(target.user_id ) print(target.password) target.hash = "Other" event.listen(User, 'before_insert', before_insert_function) or @event.listens_for(User, 'before_update') def before_insert_function(mapper, connection, target): # 'target' is your object print(target.user_id ) print(target.password) target.hash = "Other"
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50449174

http://stackoverflow.com/q/50486328
tagged with: arrays
has comment: http://stackoverflow.com/comment/87985502
tagged with: python
tagged with: where-clause
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/87988832
score: 0
has comment: http://stackoverflow.com/comment/87985485
has comment: http://stackoverflow.com/comment/87985479
has title: Why does python "where" produce empty array even if element is in list?
has comment: http://stackoverflow.com/comment/87988777
has body: I'm pretty new to python. I produced a long list of numbers (about 6144000 elements). Then I find the smallest number with min(), and finally I want to recover the index corresponding to such number, but an empty array is returned. I copy and paste all the inputs and outputs (using Canopy): **INPUT**: min(ravel(loss)) Out[89]: 1.6158025919749239e-37 **INPUT**: ind=where(loss==1.6158025919749239e-37) **INPUT**: ind Out[91]: (array([], dtype=int64),) **INPUT**: type(loss) Out[92]: list **INPUT**: 1.6158025919749239e-37 in loss Out[93]: True What is the issue?
type: Question
tagged with: numpy
type: UnansweredQuestion

http://stackoverflow.com/comment/88231795
score: 0
comment on: http://stackoverflow.com/q/50488894
type: Comment
has text: Seems like a bug, since parent properties are still getting updated to child properties, even though the child properties are getting set, can you raise it up with the plotly team? Are you interested in a solution with two traces, one for marker and one for line?
type: QuestionComment

http://stackoverflow.com/q/50451593
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87917753
tagged with: list
answer count: 3
score: 1
downvote count: 0
has title: Read and order vector from txt file
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50452327
possible better answer: http://stackoverflow.com/a/50451782
has answer: http://stackoverflow.com/a/50453028
has answer: http://stackoverflow.com/a/50452327
has answer: http://stackoverflow.com/a/50451782
tagged with: arrays
tagged with: python
has body: Is a beginner question, but i don't succeed to go out from the error. I have a text file with value written like: [ 2 3 4 5 1] and another vector where i write the order in which i want reorder the first vector. So if the order vector is [ 5 3 2 1 4 ] the first vector will become [ 1 4 3 2 5 ]. The idea was import the file.txt with np.loadtxt and than: for i in range (5): a=int('order[i]') b = a c = suono[b] suono2.write[i] = c suono2.save(c) emp = "" suono2.save(emp) suono2.close

http://stackoverflow.com/a/50442988
accepted answer of: http://stackoverflow.com/q/50442708
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50442708
score: 2
downvote count: 0
type: Answer
has body: You can use the .next_sibling property to get the text you want. Find the &lt;div&gt; tag with class="__cast-image wow fadeIn" first. The text you want is located after this tag. So, use .next_sibling on this tag. But first you'll get &lt;br/&gt;, so use it again. &gt;&gt;&gt; soup.find('div', class_='__cast-image').next_sibling &lt;br/&gt; &gt;&gt;&gt; soup.find('div', class_='__cast-image').next_sibling.next_sibling 'Developer'
upvote count: 2

http://stackoverflow.com/q/50437741
tagged with: python
favorite count: 0
type: Question
answer count: 0
tagged with: scrapinghub
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has title: Scraping Hub Periodic Script / IOError No such file or directory
tagged with: scrapy
has body: I am trying to run a periodic script and connect it with a json file within my project. I tried this (https://support.scrapinghub.com/support/solutions/articles/22000200416-deploying-non-code-files) but this is not working for me, structure imported from scraping hub looks very different. Script is working well until i need to call this file. The error which I got is : IOError: [Errno 2] No such file or directory : 'resources/bmibmi-67d3f1f00f49.json' with this in setup.py : package_data={ 'project': ['resources/*.json'] }, Thanks a lot for your help.
score: 1

computer-vision
tags question: http://stackoverflow.com/q/50502004
tags question: http://stackoverflow.com/q/50508309
tags question: http://stackoverflow.com/q/50458412
tags question: http://stackoverflow.com/q/50531699
tags question: http://stackoverflow.com/q/50494991
tags question: http://stackoverflow.com/q/50395617
tags question: http://stackoverflow.com/q/50529731
tags question: http://stackoverflow.com/q/50525568
tags question: http://stackoverflow.com/q/50458452
tags question: http://stackoverflow.com/q/50387905
tags question: http://stackoverflow.com/q/50508452
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/50528148
tags question: http://stackoverflow.com/q/50454353
tags question: http://stackoverflow.com/q/50431647

http://stackoverflow.com/a/50399040
upvote count: 2
type: Answer
has body: list(dict(sorted(zip(scooby, snacks))).items()) [(1, 18), (4, 28)] Crappy one-liner in O(n) [ (k, max(v)) for k, v in (lambda d, x=defaultdict(list): ([x[k].append(v) for k, v in d], x)) (zip(scooby, snacks))[1].items() ]
answers question: http://stackoverflow.com/q/50398738
score: 1
downvote count: 1

http://stackoverflow.com/q/50464891
tagged with: python
has title: Class variable instantiation process
has comment: http://stackoverflow.com/comment/87942978
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50465201
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/87943010
downvote count: 1
favorite count: 0
type: Question
has body: As shown in the picture: pic1 In [1]: from datetime import datetime In [2]: class A(object): ...: now = datetime.now() ...: def __init__(self): ...: pass ...: def p(self): ...: print(self.now) ...: In [3]: datetime.now() Out[3]: datetime.datetime(2018, 5, 22, 17, 54, 4, 593295) In [4]: a_1 = A() In [5]: a_1.p() 2018-05-22 17:53:57.597022 In [6]: datetime.now() Out[6]: datetime.datetime(2018, 5, 22, 17, 54, 29, 177489) In [7]: a_2 = A() In [8]: a_2.p() 2018-05-22 17:53:57.597022 I can't understand how Python initializes a class variable, and why I created two class objects, but the values of the class variables of these two classes are the same? Thank you for your help.
has answer: http://stackoverflow.com/a/50465201
has answer: http://stackoverflow.com/a/50465040
accepted answer: http://stackoverflow.com/a/50465040

http://stackoverflow.com/comment/87958199
has text: @musikreck Done
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50471957

http://stackoverflow.com/q/50500107
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88012958
answer count: 1
has comment: http://stackoverflow.com/comment/88013085
has answer: http://stackoverflow.com/a/50500465
type: Question
has comment: http://stackoverflow.com/comment/88012938
type: UnansweredQuestion
tagged with: python
has body: How do I check element exists in list using re method in efficient way? list = ['abc', 'efg','xyz:3+1'] a = "efg" if a in list: print "element exist" else: print "element not exist" Expected Output:element exist if a = "123" Expected output: element not exist if a = "xyz" Expected output: element not exist What i have to achieve is when a is xyz:number + number, then print "element exists". if a = "xyz:10 + 5" Expected Output:element exist if a = "xyz:3 + 1" Expected Output:element exist if a = "xyz:10 + " Expected Output:element not exist if a = "xyz:10" Expected Output:element not exist
has title: Check if element exists in list using re

http://stackoverflow.com/a/50413777
answers question: http://stackoverflow.com/q/50413721
downvote count: 0
type: AcceptedAnswer
upvote count: 5
has body: string arg = string.Format(@"C:\Users\marco\eclipse-workspace\my_project\src\InsertSemantic.py {0}", nome, formVerb, contesto, sinonimi, significato, class_gramm, class_prag, class_sem, retorico); is only taking the first format value with {0}. You need to include the rest of the values as well, eg. {0},{1},{2} et cetera. string arg = string.Format(@"C:\Users\marco\eclipse-workspace\my_project\src\InsertSemantic.py {0} {1} {2} {3} {4} {5} {6} {7} {8}", nome, formVerb, contesto, sinonimi, significato, class_gramm, class_prag, class_sem, retorico); the above should include the rest of the parameters to add to your formatted string. In the future, you can solve this by stepping through your code in the debugger and you would notice that when arg is assigned to, only the first of your parameters gets passed, indicating that the problem is at the time of assignment.
score: 5
accepted answer of: http://stackoverflow.com/q/50413721
type: Answer

http://stackoverflow.com/comment/88089026
score: 0
comment on: http://stackoverflow.com/a/50538275
type: AnswerComment
has text: Did you do anything else with Windows? It seems like a missing dll file is related to a missing windows piece.
type: Comment

http://stackoverflow.com/a/50511087
has comment: http://stackoverflow.com/comment/88065177
has comment: http://stackoverflow.com/comment/88035668
answers question: http://stackoverflow.com/q/50510407
downvote count: 0
has comment: http://stackoverflow.com/comment/88037215
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88035247
has comment: http://stackoverflow.com/comment/88035388
has body: I achieved this with resample but it also requires a bit of fiddling so it might not be the best solution. First of all we need to the index to be of type DatetimeIndex, TimedeltaIndex or PeriodIndex. # set Time to be index df.set_index('Time', inplace=True) # change index type to datetime df.index = pd.to_datetime(df.index) using resample - I have used the rule of 60 minutes. You can look at the rules in the follwoing link resample new_df = df.resample('60T').mean().reset_index() now we have a new_df with average values every 60 minutes. we just need to do the following to have it in the format you want. from datetime import timedelta new_df['EndTime'] = new_df['Time'] + timedelta(seconds=3600) and finally renaming the columns: new_df.rename(columns={'Time': 'StartTime', 'Value': 'AvgValue'}, inplace=True) Output: StartTime AvgValue EndTime 0 2018-01-03 12:00:00 10.0 2018-01-03 13:00:00 1 2018-01-03 13:00:00 30.0 2018-01-03 14:00:00 2 2018-01-03 14:00:00 45.0 2018-01-03 15:00:00 EDIT: This time using the first dataframe (df1) for the time ranges you can do the following df1['AvgTime'] = df1.T.apply(lambda x: df.loc[x['StartTime']:x['EndTime']].mean()).T
has comment: http://stackoverflow.com/comment/88035442
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50510407

http://stackoverflow.com/comment/87904950
type: Comment
comment on: http://stackoverflow.com/a/50445564
type: AnswerComment
score: 0
has text: What's the difference in the last 2 pieces of code?

http://stackoverflow.com/a/50421038
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50420969
has body: It looks like the version of pygame you've installed on your computer is an old version, using deprecated methods. As it seems to be working on my computer with both Python 2 &amp; 3, I'd suggest to update pygame by running pip3 install --user pygame # or pip2 if using python2
type: Answer
has comment: http://stackoverflow.com/comment/87884587
has comment: http://stackoverflow.com/comment/87876617
answers question: http://stackoverflow.com/q/50420969
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87964560
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50462188
has text: Thanks for the heads up. Do you have a better idea to resolve the problem?
type: Comment

http://stackoverflow.com/comment/87890413
has text: t is just a parameter to the function. In this case it is the text of the tag. And here, we are not assigning the function to text. Just as you were matching text using `text=thetext`, we are checking if text is equal to the conditions specified in the function. So it'll return a tag whose text matches the given conditions.
type: Comment
comment on: http://stackoverflow.com/a/50435359
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87836381
type: AnswerComment
comment on: http://stackoverflow.com/a/50410273
score: 0
has text: So true! I get it now! Thanks buddy!
type: Comment

http://stackoverflow.com/comment/87846410
has text: All good answers but this is the most straightforward solution I think. Thanks very much.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50414049
score: 2

mixed-models
tag name: mixed-models
type: Tag
tags question: http://stackoverflow.com/q/50513545

http://stackoverflow.com/comment/87831081
type: AnswerComment
score: 0
type: Comment
has text: @FlyingThunder string is string, it won't become other things until you explicitly call some methods.
comment on: http://stackoverflow.com/a/50407791

http://stackoverflow.com/q/50506046
tagged with: database
has answer: http://stackoverflow.com/a/50506830
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88024110
has body: I am making graphs using bokeh in python and for that I was calling an HTML page to fetch data inside my dataframe but now I want to fetch data directly from database inside my dataframe. So which method is more efficient?
score: 0
has comment: http://stackoverflow.com/comment/88024161
has title: Which is more efficient ? Fetching data directly from databse or from an HTML page in pandas dataframe?
has comment: http://stackoverflow.com/comment/88024226
answer count: 1
has comment: http://stackoverflow.com/comment/88024222
has comment: http://stackoverflow.com/comment/88024747
tagged with: api
type: Question
tagged with: pandas

http://stackoverflow.com/comment/88208857
comment on: http://stackoverflow.com/a/50587988
type: Comment
has text: are there any alternates you know of where I can use asycnio?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87914505
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50448446
score: 0
has text: My anaconda for some reason decided that the best tensorflow version for it was 1.5.0 for keras 2.1.5. (Very very recently, so I think this is the best compatibility for now).

odbc
tags question: http://stackoverflow.com/q/50468030
type: Tag
tag name: odbc
tags question: http://stackoverflow.com/q/50464360

http://stackoverflow.com/comment/87958592
has text: @kvmahesh well i know we can delete a pair though deleting respective key? but can we just delete a value? i got this question in a interview thats why i asked here.
comment on: http://stackoverflow.com/q/50472476
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50439740
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50439668
score: 3
has body: The first one selects an entire column for each element of r. The second just an element. You can directly compare the two cases like so: &gt;&gt;&gt; P = np.arange(12).reshape(4, 3) &gt;&gt;&gt; r = np.random.randint(0, 3, (4,)) &gt;&gt;&gt; r array([1, 1, 2, 0]) &gt;&gt;&gt; &gt;&gt;&gt; P[:, r] array([[ 1, 1, 2, 0], [ 4, 4, 5, 3], [ 7, 7, 8, 6], [10, 10, 11, 9]]) &gt;&gt;&gt; P[np.arange(4), r] array([1, 4, 8, 9]) As you can see the second produces essentially the diagonal of the first. You may profit from having a look at section "Combining advanced and basic indexing" in the numpy docs.
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50439668

http://stackoverflow.com/q/50511318
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88035386
has title: Transposing per variable
type: Question
has comment: http://stackoverflow.com/comment/88036262
has comment: http://stackoverflow.com/comment/88035319
accepted answer: http://stackoverflow.com/a/50511841
has comment: http://stackoverflow.com/comment/88036067
answer count: 1
has answer: http://stackoverflow.com/a/50511841
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88035293
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88035004
has body: Just starting out with python and pandas, SO is fantastic for learning. Have been looking through documentation and tutorials for a few hours, but I think I'm lacking the python vocab to find what I'm after. I have temperature data (c) logged at consistent times (b) but in different locations (a). I'd like to transpose (unstack?) by variable. For example: a b c 0001 2016-02-01 00:00 19.93 0001 2016-02-01 00:30 19.5 0001 2016-02-01 01:00 19.25 ... 0002 2016-02-01 00:00 23.37 0002 2016-02-01 00:30 22.93 0002 2016-02-01 01:00 22.56 to go to: 0001 0002 2016-02-01 00:00 19.93 23.37 Thanks for any help!

http://stackoverflow.com/comment/87893402
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50439517
has text: @RyanTam what's the equivalent of `isnull()` for checking empty string value?

http://stackoverflow.com/comment/88000419
has text: No, I’m not. Thanks for your tips @juanpa.arrivillaga
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50431921

http://stackoverflow.com/comment/115194255
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50449103
has text: you have installed mysqlclient to your system python (`c:\program files\python37\lib\s ite-packages`), but you're trying to run `python manage.py syncdb` from a virtualenv (`C:\Users\Administrator\PycharmProjects\BugTracker\venv\lib\site-packages\django...`). All packages need to be installed to the same Python environment if you want to use them together.

http://stackoverflow.com/comment/88045421
comment on: http://stackoverflow.com/a/50516033
type: AnswerComment
has text: Thank you Mike, I made a change which you suggested by changing lower case "x" it did not work. But I took you example which you provided and worked beautifully. Thanks for your time and suggestion.
score: 0
type: Comment

http://stackoverflow.com/comment/88086429
has text: It will be just about as fast, if not slightly faster than my approach, but again, it will return duplicated `1s` if two columns share the same value.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50536857

http://stackoverflow.com/q/50435172
has body: Im trying to get tesseract to only recognize numbers but no matter what I put for configuration, it ignores it. pytessseract is in version 0.2.0 and tesseract in 4.00.00alpha from PIL import Image import pytesseract as tes import glob tes.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract' a = glob.glob(r'C:\Users\Pascal\Desktop\visible\*.png') for imgPath in a: casd = Image.open(imgPath).convert('L').point(lambda x: 0 if x &lt; 200 else 255, '1') im = tes.image_to_string(casd, config='outputbase digits') print(im) Some outputs: ® a 69 ® 0 ® a 69 ® 0 ® ase ® 0 ® aso ® 0
type: Question
tagged with: tesseract
accepted answer: http://stackoverflow.com/a/50458735
has answer: http://stackoverflow.com/a/50458735
tagged with: python
has title: Why is tesseract not accepting the config?
type: AnsweredQuestion
score: 0
tagged with: python-tesseract
answer count: 1

http://stackoverflow.com/comment/87885879
type: QuestionComment
has text: You can just do `for j in file:` to loop over the lines. And I just that you have `for l in identify:`. But `identify` is a string, so that loop iterates over the characters of that string.
score: 1
comment on: http://stackoverflow.com/q/50435725
type: Comment

http://stackoverflow.com/comment/88155824
type: AnswerComment
comment on: http://stackoverflow.com/a/50538231
type: Comment
has text: Another thing that I just noticed: in the arguments' list, you can only pass tensors, but not general objects, such as another function. In my case, I would want to pass a tokenizer since I am working with text, but anyway this is still doable in the **mapfunc** function's body.
score: 0

http://stackoverflow.com/q/50423332
type: UnansweredQuestion
downvote count: 2
has title: getting functions from other files
tagged with: python
has answer: http://stackoverflow.com/a/50423441
has comment: http://stackoverflow.com/comment/87861471
score: 0
answer count: 2
has body: So I've got this function that I use through multiple file, is there a way to turn this into a class saved on a separate file and call for it on each of my other files? def count(): for name in data: if name not in topUsers: topUsers[name] = 1 else: topUsers[name] += 1 count()
has answer: http://stackoverflow.com/a/50423626
has comment: http://stackoverflow.com/comment/87861469
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/q/50511551
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88035867
has body: This code redirects to another page which is an error page but I didn't use redirect function and I want to stop it from redirecting Python code: @app.route("/record",methods = ['POST','GET']) def get_voice(): print("record's button was clicked") TFIDF = tfidf.TFIDF_CLASS() TFIDF.choosen_Type(1,"") return "" html code: &lt;form action="http://localhost:5000/record"&gt; &lt;input id="record" onclick="voice_message()" type="submit" method="POST" value=' Record'&gt; &lt;/form&gt;
type: Question
has comment: http://stackoverflow.com/comment/88074598
has title: Python my code redirect without redirect function
has comment: http://stackoverflow.com/comment/88037108
type: UnansweredQuestion
tagged with: http-redirect

http://stackoverflow.com/comment/87992569
type: Comment
type: QuestionComment
has text: Hey thank you for your insight! I will look into it!
score: 0
comment on: http://stackoverflow.com/q/50478806

http://stackoverflow.com/a/50425762
has comment: http://stackoverflow.com/comment/87881441
has comment: http://stackoverflow.com/comment/87984366
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87881342
has comment: http://stackoverflow.com/comment/87881394
has comment: http://stackoverflow.com/comment/100093484
has body: I can see, this is due to circular import in your urls.py You are doing from . import views You should do like from .views import XyzView, AbcView This is because you are importing all imports done in views.py as well. Hope you got the idea.
has comment: http://stackoverflow.com/comment/87908080
has comment: http://stackoverflow.com/comment/87962879
has comment: http://stackoverflow.com/comment/87959517
has comment: http://stackoverflow.com/comment/88002783
accepted answer of: http://stackoverflow.com/q/50424524
has comment: http://stackoverflow.com/comment/88002944
type: Answer
has comment: http://stackoverflow.com/comment/87941406
has comment: http://stackoverflow.com/comment/87881663
has comment: http://stackoverflow.com/comment/87881567
answers question: http://stackoverflow.com/q/50424524
has comment: http://stackoverflow.com/comment/87962776
has comment: http://stackoverflow.com/comment/87984542
score: 2
has comment: http://stackoverflow.com/comment/87964869
has comment: http://stackoverflow.com/comment/87920933
upvote count: 2

http://stackoverflow.com/q/50412204
type: Question
tagged with: deconvolution
type: UnansweredQuestion
answer count: 1
tagged with: python
score: 0
tagged with: conv-neural-network
has title: Reconstructing a classified image from a simple Convolution Neural Network
has body: I have a CNN trained on a classification task (Network is simple, 2 convolution + pooling layers and 2x fully connected layers). I would like to use this to reconstruct an image if I input a classification label. Is this possible to achieve? Is it possible to share weights between corresponding layers in the 2 networks?
has answer: http://stackoverflow.com/a/50412247
has comment: http://stackoverflow.com/comment/88045802
tagged with: tensorflow

http://stackoverflow.com/comment/88036262
comment on: http://stackoverflow.com/q/50511318
score: 0
type: Comment
type: QuestionComment
has text: Great spot @RafaelC, in my actual data there is, however, I messed up in the comments. Sorry!

http://stackoverflow.com/q/50426870
tagged with: python
has comment: http://stackoverflow.com/comment/97524454
score: 4
has comment: http://stackoverflow.com/comment/87873776
has comment: http://stackoverflow.com/comment/87871705
tagged with: windows-10
has answer: http://stackoverflow.com/a/60842081
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has title: python opens new console window instead of printing into cmd
type: UnansweredQuestion
has body: My Python 3 (3.6) opens new black console window for each Python command I run (pip is just the same). Example: When I create a hello_world.py with a while True: print("hello world") Loop in it and start it from PowerShell via python test.py it will open a new window, print "hello world" in the new window and leave the console I used to run the script empty... (same happens with Cygwin) using CMD it won't even open the Python window and just closes gives me back a new CMD prompt-line. Even worse when using PyCharm each time a background-task runs (e.g. syntax-check) a black console window opens for ~1 sec. and thus blocks me from writing code. Example images to show what is happening: Code used for test.py: while True: print("Hello World") So far I tried: creating and modifying manifest files for python.exe/pythonw.exe reinstalling Python3 installing a different Python3 Version changing the default codepage for CMD/PowerShell setting PYTHONENCODING and PYTHONIOENCODING to UTF-8 starting PowerShell/Python as admin //edit: the Question is: How can I get back the default Python behavior, as seen on every other (Windows) Computer.
has comment: http://stackoverflow.com/comment/87868614
answer count: 1
downvote count: 0
tagged with: powershell

http://stackoverflow.com/q/50518634
tagged with: python
type: Question
has body: I'm trying to scrape a website that is mainly ran by javascript and it's giving me a huge headache because I don't know javascript. This is what I have so far: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.common.keys import Keys binary = FirefoxBinary(r'C:\Users\kwright\AppData\Local\Mozilla Firefox\firefox.exe') driver = webdriver.Firefox(firefox_binary=binary) driver.get('http://www.papowerswitch.com/shop-for-electricity/shop-for-your-home') #zipcode = driver.find_element_by_id('edit-zipcode') monthlyuse = driver.find_element_by_name('estimated-monthly-usage') button = driver.find_element_by_id("edit-submit-residential-rate-search2") driver.execute_script("document.getElementById('edit-zipcode').value='18707'") This works fine and it give me the value I need in the zip code section. The next part I'm having trouble with because the Id names aren't unique, but the name tag is, my problem is that I don't know the javascript function to get the element by the name tag and input the data I need. I tried this and several variations of this and it didn't work. driver.execute_script("driver.findElement(webdriver.By.name('estimated-monthly-usage')).value='1000'") can anyone help me out here and let me know what script I need to add to get that part of the form filled out? Thank you. Edit: Here is the HTML Monthly Usage
has comment: http://stackoverflow.com/comment/88050085
tagged with: selenium
has comment: http://stackoverflow.com/comment/88050067
tagged with: javascript
tagged with: web-scraping
has title: Selenium in Python - Running JavaScript
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50518767
accepted answer: http://stackoverflow.com/a/50518767
answer count: 1

http://stackoverflow.com/q/50506478
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50507945
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/69171779
has body: i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me import re def add_shtner(add): return re.sub(r"\bROAD\b","RD",add) print(add_shtner("100,BROAD ROAD")) # a code to check valid roman no. ptn=r"^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}$)" def romancheck(num): num=num.upper() if re.search(ptn,num): return "VALID" else: return "INVALID" print(romancheck("MMMLXXVIII")) print(romancheck("MMMLxvviii")) mul_line_str='''adding third argument re.VERBOSE in re.search() will ignore whitespace and comments''' print(re.search("re.search()will",mul_line_str,re.VERBOSE)) print(re.search("re.search() will",mul_line_str,re.VERBOSE)) print(re.search("ignore",mul_line_str,re.VERBOSE)) ptn=''' ^ #beginning of the string M{0,3} #thousands-0 to 3 M's (CM|CD|D?C{0,3} #hundreds (XC|XL|L?XXX) #tens (IX|IV|V?III) #ones $ #end of the string ''' print(re.search(ptn,"MMMCDLXXIX",re.VERBOSE)) def romanCheck(num): num=num.upper() if re.search(ptn,num,re.VERBOSE): return "VALID" else: return "INVALID" print(romanCheck("mmCLXXXIV")) print(romanCheck("MMMCCLXXXiv")) i wrote this code and i ran it but i got this- 100,BROAD RD VALID INVALID None None &lt;_sre.SRE_Match object; span=(120, 126), match='ignore'&gt; Traceback (most recent call last): File "G:\pydev\xyz\rts\regular_expressions.py", line 46, in &lt;module&gt; print(re.search(ptn,"MMMCDLXXIX",re.VERBOSE)) File "C:\Users\Owner\AppData\Local\Programs\Python\Python36\lib\re.py", line 182, in search return _compile(pattern, flags).search(string) File "C:\Users\Owner\AppData\Local\Programs\Python\Python36\lib\re.py", line 301, in _compile p = sre_compile.compile(pattern, flags) File "C:\Users\Owner\AppData\Local\Programs\Python\Python36\lib\sre_compile.py", line 562, in compile p = sre_parse.parse(p, flags) File "C:\Users\Owner\AppData\Local\Programs\Python\Python36\l…
score: 0
answer count: 2
has title: sre_constants.error: missing ),unterminated subpattern

file
tags question: http://stackoverflow.com/q/50500721
type: Tag
tags question: http://stackoverflow.com/q/50432668
tags question: http://stackoverflow.com/q/50502148
tags question: http://stackoverflow.com/q/50510875
tags question: http://stackoverflow.com/q/50485037
tags question: http://stackoverflow.com/q/50418250
tags question: http://stackoverflow.com/q/50413377
tags question: http://stackoverflow.com/q/50393155
tags question: http://stackoverflow.com/q/50523308
tags question: http://stackoverflow.com/q/50496229
tag name: file
tags question: http://stackoverflow.com/q/50537218
tags question: http://stackoverflow.com/q/50498851
tags question: http://stackoverflow.com/q/50480555
tags question: http://stackoverflow.com/q/50457085
tags question: http://stackoverflow.com/q/50401562
tags question: http://stackoverflow.com/q/50426232
tags question: http://stackoverflow.com/q/50526862
tags question: http://stackoverflow.com/q/50514973
tags question: http://stackoverflow.com/q/50524921
tags question: http://stackoverflow.com/q/50424659

http://stackoverflow.com/comment/87811372
score: 0
type: Comment
type: QuestionComment
has text: @ArjunAthreya I wasn't able to install the virtualenv. This is my first time using Python and Tensorflow. Do I need virtualenv to work on this codelab? https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/
comment on: http://stackoverflow.com/q/50397477

http://stackoverflow.com/a/50520335
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50519820
has body: In order to avoid explicitly converting list a to a numpy.ndarray, you can call numpy's comparison operators directly: np.all(np.equals(a, 0)) However, if your data are already a Python list, simply use Python's all() to get the same result at a fraction of the time it takes numpy to compute all(): In [1]: import random In [2]: import numpy as np In [3]: a = [random.random() for _ in range(1000000)] In [4]: %timeit all(x == 0 for x in a) 615 ns ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [5]: %timeit np.all(np.equal(a, 0)) 24.2 ms ± 2.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
type: Answer
upvote count: 3

http://stackoverflow.com/q/50533119
has comment: http://stackoverflow.com/comment/88086158
favorite count: 0
has title: How to set environment variables in pyenv?
downvote count: 1
answer count: 1
tagged with: linux
type: Question
upvote count: 9
has body: I'm using pyenv. The environment is created with these commands: pyenv install 3.6.0 pyenv virtualenv 3.6.0 foo pyenv local foo python my_app.py In the application I want to load some environment variables with this command: SOME_VARIABLE = environ.get('MY_ENV_VAR', None) The problem is, that although MY_ENV_VAR is set with export MY_ENV_VAR=test (and I can display its content with echo $MY_ENV_VAR), the python code reads no value. So how can this be done correctly?
tagged with: pyenv
has answer: http://stackoverflow.com/a/70536080
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88132652
tagged with: virtualenv
score: 8

http://stackoverflow.com/comment/88093659
comment on: http://stackoverflow.com/q/50541020
type: Comment
has text: @SmartManoj I'm already using Django 2
score: 0
type: QuestionComment

http://stackoverflow.com/a/50457791
accepted answer of: http://stackoverflow.com/q/50455760
score: 0
answers question: http://stackoverflow.com/q/50455760
type: Answer
has body: As for ListView, use ModalView to control selection and invoke getname() method. Please refer to the two examples (ListView and RecycleView) for details. Note ListView has been deprecated since version 1.10.0, use RecycleView instead. Example 1 - ListView mainlistview.py from kivy.app import App from kivy.uix.modalview import ModalView from kivy.properties import ObjectProperty class MyListView(ModalView): list_view = ObjectProperty(None) def __init__(self, **kwargs): super(MyListView, self).__init__(**kwargs) self.list_view.adapter.bind(on_selection_change=self.callback_function) def callback_function(self, instance): print(instance) App.get_running_app().getname() class MainListViewApp(App): title = "ListView ListItemButton Demo" def build(self): return MyListView() def getname(self): print("App.getname() - Called") if __name__ == '__main__': MainListViewApp().run() mainlistview.kv #:kivy 1.10.0 #:import lv kivy.uix.listview #:import la kivy.adapters.listadapter &lt;MyListView&gt;: list_view: list_view ListView: id: list_view adapter: la.ListAdapter( data=["Item #{0}".format(i) for i in range(100)], selection_mode='single', allow_empty_selection=True, cls=lv.ListItemButton) Output - ListView Example 2 - RecycleView mainrecycleview.py from kivy.app import App from kivy.uix.recycleview import RecycleView from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.button import Button from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.properties import ObjectProperty class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): """ Adds selection and focus behaviour to the view. """ pass class SelectableButton(RecycleDataViewBehavior, Button): """ Add selection support to the Label """ index = None def refresh_view_attrs(self, rv, index, data): """ Catch and handle the view changes """ self.index = i…
type: AcceptedAnswer

timer
tag name: timer
tags question: http://stackoverflow.com/q/50411002
tags question: http://stackoverflow.com/q/50519924
type: Tag
tags question: http://stackoverflow.com/q/50512524
tags question: http://stackoverflow.com/q/50540204

http://stackoverflow.com/comment/87933591
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50460233
score: 0
has text: Definitely a duplicate... You need to tell Python **how to print** your object by implementing a function other than the constructor called `__repr__`

http://stackoverflow.com/a/50414875
accepted answer of: http://stackoverflow.com/q/50414823
type: AcceptedAnswer
downvote count: 0
has body: Try X_train = X_train_num.join( pd.DataFrame(X_train_cat, X_train_num.index).add_prefix('cat_') )
has comment: http://stackoverflow.com/comment/87845631
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50414823
score: 5
has comment: http://stackoverflow.com/comment/87845628

http://stackoverflow.com/a/50464492
has comment: http://stackoverflow.com/comment/87942686
answers question: http://stackoverflow.com/q/50464361
has comment: http://stackoverflow.com/comment/87943285
has comment: http://stackoverflow.com/comment/87943217
type: Answer
has comment: http://stackoverflow.com/comment/87943306
score: 0
has comment: http://stackoverflow.com/comment/87943359
has body: do like this: {% for lists in list1 %} &lt;tr&gt; {%for li in lists %} &lt;td&gt;{{li}}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %}

http://stackoverflow.com/comment/88090812
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50539511
has text: a probably the data frame in python. But in this case pyhton is not able to read or load the data. How can I read the file which includes this ascii codes.

http://stackoverflow.com/comment/88060673
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50521628
has text: mm i can't give the full code, its an assignment and i have no doubt someone will copy it if its found. I am new to coding but can research it. Does binding the function to add_to_cart mean that if it fails it will proceed to run the call back? That would be my understanding of your response but again have only just started learning.

http://stackoverflow.com/comment/87973735
type: QuestionComment
comment on: http://stackoverflow.com/q/50480175
score: 0
has text: @AChampion May I ask why it is a bad idea so I can avoid it in the future.
type: Comment

http://stackoverflow.com/comment/87985046
comment on: http://stackoverflow.com/a/50484638
type: Comment
type: AnswerComment
has text: If I understand correctly, the GridSearchCV function , you need to transfer all the data, that is X,y? That is: grid_searcher.fit(X, y). The question arises of the data being mixed in the GridSearchCV function. Since in " train_test_split "I use"random_state=42"?
score: 0

http://stackoverflow.com/comment/87914237
type: Comment
score: 0
type: AnswerComment
has text: The idea is that my program then will be able to predict only among 3 verbs and not 5926! I hope this was clearer..sorry if I could not explain better before!
comment on: http://stackoverflow.com/a/50410911

http://stackoverflow.com/comment/88004331
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50495738
has text: Does this help: https://docs.python.org/3/faq/programming.html#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another

combinations
tags question: http://stackoverflow.com/q/50526134
tags question: http://stackoverflow.com/q/50427300
type: Tag
tag name: combinations

list-comprehension
tags question: http://stackoverflow.com/q/50535455
type: Tag
tags question: http://stackoverflow.com/q/50529157
tags question: http://stackoverflow.com/q/50396068
tags question: http://stackoverflow.com/q/50409807
tags question: http://stackoverflow.com/q/50404487
tags question: http://stackoverflow.com/q/50420229
tags question: http://stackoverflow.com/q/50462078
tags question: http://stackoverflow.com/q/50500209
tags question: http://stackoverflow.com/q/50489802
tags question: http://stackoverflow.com/q/50492114
tags question: http://stackoverflow.com/q/50494638
tags question: http://stackoverflow.com/q/50504844
tags question: http://stackoverflow.com/q/50534072
tags question: http://stackoverflow.com/q/50484276
tags question: http://stackoverflow.com/q/50480726
tags question: http://stackoverflow.com/q/50511707
tag name: list-comprehension
tags question: http://stackoverflow.com/q/50387793

http://stackoverflow.com/comment/88086599
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50536645
type: QuestionComment
has text: It is just a random example, I even do not have any idea about using the correct data structure, but it should be something like (inner dims could be different): `dataset = [{'A':19, 'B':55, 'A':20}, {'A':10, 'B':68, 'A':6, 'B':68}]`

http://stackoverflow.com/a/50592261
has body: The issue is that the module you use does something you don't expect modules to do. print ( 'WARNING: problems with charset recognition', repr(temp)) Well something that can't be just disabled like that. But then their are good SO threads on how to achieve the same. Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call Suppress calls to print (python) So combining both of them import iptcinfo origianl_IPTCInfo = iptcinfo.IPTCInfo def patch_IPTCInfo(*args, **kwargs): import os, sys class HiddenPrints: def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open('/dev/null', 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout = self._original_stdout with HiddenPrints(): return origianl_IPTCInfo(*args, **kwargs) iptcinfo.IPTCInfo = patch_IPTCInfo iptc = iptcinfo.IPTCInfo("/Users/tarunlalwani/Downloads/image.jpg") print(iptc) and it just works great
type: Answer
accepted answer of: http://stackoverflow.com/q/50407738
answers question: http://stackoverflow.com/q/50407738
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88194173
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50428055
answers question: http://stackoverflow.com/q/50427992
type: Answer
score: 0
has body: Have you tried it several times? You should also check res.text, maybe there is some error response related to your issue. Maybe you should try a proxy? http://docs.python-requests.org/en/master/user/advanced/#proxies The code above works and returns this: &gt;&gt;&gt; res.json() {'jsonrpc': '2.0', 'result': '0x4017bc319327a00', 'id': 1}

http://stackoverflow.com/q/50499552
upvote count: 2
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
favorite count: 0
type: Question
has title: Looping 2 1d-arrays to create 2d array in numpy
tagged with: python
has answer: http://stackoverflow.com/a/50504856
has body: I have to 1d arrays x = [1,2,3,4,5] y = [5,6,7,8,9] and a zero 2d array 2d_array=np.zeros((5, 5)) I have this equation : 50*x + 20*y I want to make a loop to find all possible answers from x and y and store them in the 2d_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] so this should be [50*x[0]+20*y[0],50*x[1]+20*y[0],50*x[2]+20*y[0],50*x[3]+20*y[0],50*x[4]+20*y[0] 50*x[0]+20*y[1],50*x[1]+20*y[1]50*x[2]+20*y[1],50*x[3]+20*y[1],50*x[4]+20*y[1]....... And so on, I'm not sure if the explanation is clear, but if it is not tell me and I'll upload the actual file of the problem. Thanks
score: 2
has answer: http://stackoverflow.com/a/50499608
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/88077384
has text: Yes. That is just a matter of loading the correct data from the dictionary to the text field of the label. So using my example do you want the labels to say "Age 30" or just "30"?
comment on: http://stackoverflow.com/a/50532582
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87801683
type: AnswerComment
comment on: http://stackoverflow.com/a/50392651
score: 1
type: Comment
has text: I would assume the error is caused by your current version of Pytorch. I hope the alternative works out for you otherwise. Cheers!

http://stackoverflow.com/a/51683511
has body: Unfortunately, the Python profile does not store the entire call tree. (This would be too expensive.) I've documented the problem here and as a snakeviz issue. I recently created tuna for visualizing Python profiles to work around some of these problems. tuna cannot show the entire call tree, but at least it doesn't show wrong info either. Install with pip3 install tuna Create a runtime profile python -m cProfile -o program.prof yourfile.py and just run tuna on the file tuna program.prof
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/50436881
score: 8
downvote count: 0

http://stackoverflow.com/comment/87941594
score: 0
comment on: http://stackoverflow.com/q/50464040
type: Comment
has text: I have tried to put 0、1、2 into the x.group(),and I don't know why x.group(0) and x.group(1) return the same result.x.group(2) return an error is resonable.
type: QuestionComment

http://stackoverflow.com/comment/87918153
score: 1
type: QuestionComment
has text: Can you post a slightly larger sample of your dataframe so we can reproduce this?
comment on: http://stackoverflow.com/q/50452467
type: Comment

http://stackoverflow.com/a/50527813
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/50526939
has body: Try printing it on the upcoming frame, instead of in the initiation of the object. After the object is created, you can access the properties. You do that with Clock. Like this: from kivy.clock import Clock class TestWidget(Widget): test_property = StringProperty() def __init__(self, **kwargs): super(TestWidget, self).__init__(**kwargs) Clock.schedule_once(self.after_init) # run method on next frame def after_init(self,dt): print('Test OUTPUT:', self.test_property)
downvote count: 1

http://stackoverflow.com/comment/88011375
type: QuestionComment
comment on: http://stackoverflow.com/q/50499290
score: 0
has text: every single value in all sublists will by multiplied by the same value. In other words, all the numbers will by multiplied by one number. In the example: (1.0, 2.0, 3.0, 4.0) are multiplied by 10.0
type: Comment

http://stackoverflow.com/comment/88015001
comment on: http://stackoverflow.com/q/50480518
type: QuestionComment
type: Comment
score: 0
has text: [`Query.correlate()`](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.correlate) would be the answer normally, but for some reason I couldn't make it work in your case. Still looking into it. Autocorrelation's behaviour is explained [here](http://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.Select.correlate) (and probably elsewhere as well). It has something to do with the fact that you're referring to the alias in a subsubquery. Works for a simple subquery as it should.

http://stackoverflow.com/q/50389955
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50415861
has title: Snakemake wildcard in output only
has answer: http://stackoverflow.com/a/50415861
type: AnsweredQuestion
score: 1
tagged with: snakemake
accepted answer: http://stackoverflow.com/a/51556055
has answer: http://stackoverflow.com/a/51556055
favorite count: 0
type: Question
tagged with: pipeline
answer count: 2
has body: I have a script which takes a large input file then breaks this down into a number of chunks from 1 to n using an unpredictable algorithm. Then a following script will process each of these chunks iteratively. How can I create a snakemake rule which essentially states that the output files will exist from 1 to n, and the following script should be run once for each of the 1 to n input files. Thanks!
has comment: http://stackoverflow.com/comment/87811477
downvote count: 0

http://stackoverflow.com/comment/88047960
type: QuestionComment
comment on: http://stackoverflow.com/q/50516074
type: Comment
score: 1
has text: When using venv (comes with Python) I remove any Python from the PATH and depend on `activate.bat` to configure things correctly.

http://stackoverflow.com/q/50447930
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50447978
tagged with: python-2.7
score: 0
has title: Best Python API for formula based Spreadsheet?
has body: My requirement is to fetch the data out of Spreadsheet(.xlsx) by inputting values in some cells . On inputting value, other formula cells must have the calculated values based on the formula embedded in the sheet. lets say I am inputting values in Cell A and B . C is a formula cell =A+B . SO need to get the value in C and also other formula cells. Had written following code in python 3. import openpyxl as op new_excel = op.load_workbook('WorkBook1.xlsx',read_only=False) spreadsheet = new_excel .get_sheet_by_name('Input Quote') spreadsheet['B30'] = 'VAU' spreadsheet['D30'] = 1000 spreadsheet['F30'] = 5000 new_excel.save('WorkBook2.xlsx')#saving in a new file as I need to maintain versions loa_excel1 = op.load_workbook('WorkBook2.xlsx',data_only='TRUE')#Opening the new file spreadsheet1 = loa_excel1.get_sheet_by_name('Input Quote') print(spreadsheet1['J13'].value) # Output is None J13 is a formula Cell that has dependency on B30,D30 and F30(inputted values). How can we achieve this in Python 3 ?
answer count: 1
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/88125713
comment on: http://stackoverflow.com/q/50539728
score: 0
has text: Operating in O(n) time is not possible, since there are O(n**2) results. But if you don't need to copy the data (which takes O(n) per result), you can use only O(n**2) time rather than O(n**3).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88033124
type: AnswerComment
comment on: http://stackoverflow.com/a/50510347
score: 0
type: Comment
has text: @AngelDraghici No problem! :)

http://stackoverflow.com/a/50760587
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50412235
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50412235
has body: Possible Reason Not knowing what the "sometimes dramatic differences" are, it is hard to answer for sure; but having different results when running [block_1 x1; block_2 x1] xN (read "running block_1 then block_2 once; and repeat both operations N times) and [block_1 x1; block_2 xN] x1 makes sense, given how pseudo-random number generators (PRNGs) and seeds work. In the first case, you are re-initializing the PRNGs in block_1 after each block_2, so each of the N instances of block_2 will access the same sequence of pseudo-random numbers, seeded by each block_1 before. In the second case, the PRNGs are initialized only once, by the single block_1 run. So each instance of block_2 will have different random values. (For more on PRNGs and seeds, you could check: random.seed(): What does it do?) Simplified Example Let's suppose numpy/CUDA/pytorch are actually using a really poor PRNG, which only returns incremented values (i.e. PRNG(x_n) = PRNG(x_(n-1)) + 1, with x_0 = seed). If you seed this generator with 0, it will thus return 1 the first random() call, 2 the second call, etc. Now let also simplifies your blocks for the sake of the example: def block_1(): seed = 0 print("seed: {}".format(seed)) prng.seed(seed) -- def block_2(): res = "random results:" for i in range(4): res += " {}".format(prng.random()) print(res) Let's compare [block_1 x1; block_2 x1] xN and [block_1 x1; block_2 xN] x1 with N=3: for i in range(3): block_1() block_2() # &gt; seed: 0 # &gt; random results: 1 2 3 4 # &gt; seed: 0 # &gt; random results: 1 2 3 4 # &gt; seed: 0 # &gt; random results: 1 2 3 4 block_1() for i in range(3): block_2() # &gt; seed: 0 # &gt; random results: 1 2 3 4 # &gt; random results: 4 5 6 7 # &gt; random results: 8 9 10 11
upvote count: 2

http://stackoverflow.com/q/50422064
downvote count: 1
has body: Problem description Note that I didn't make my code to be something transferable as a module by installing on other computers. I have several codes with several level of directory. Everytime I transfer to other computer, I do this following import sys import os sys.path.insert(0, os.path.abspath('../src/')) Question What is the best way to add path in my python code in order to make it transferable easily? Besides the above soultion, I know the following ways make the whole code as a module that can be python setup install on any other computers use environment variable, which I think is very ugly.
has answer: http://stackoverflow.com/a/50422118
has comment: http://stackoverflow.com/comment/87864506
has title: What is the best way to initialize python path?
has comment: http://stackoverflow.com/comment/87859482
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
score: -1

http://stackoverflow.com/q/50448922
type: Question
has comment: http://stackoverflow.com/comment/87911369
tagged with: performance
has body: I have a python code with nested for loop and it is taking too much time, consider having a dictionary like dict = {'110': ('jade'), '2': ('amber'), '111' : ('harry')} and here is my code- all_keys = dict.keys() for number in all_keys: for more_number in all_keys: if SequenceMatcher(None, number, more_number).ratio() &gt; 0.5: dict[number] = dict[number].union(dict[more_number]) Output:- dict = {'110' : ('jade', 'harry'), '2' : ('amber')} what this code is doing is checking if the keys have a matching probability of more than 0.5 and if so it is adding both the keys in a set and storing it. For more data, it is taking so much time for obvious reasons. Is there any way to optimise?
tagged with: python
score: -1
tagged with: optimization
accepted answer: http://stackoverflow.com/a/50449018
has comment: http://stackoverflow.com/comment/87911313
type: AnsweredQuestion
has title: Nested for loop taking much time in Python (Optimization)
tagged with: for-loop
has answer: http://stackoverflow.com/a/50449018
has comment: http://stackoverflow.com/comment/87911707
has comment: http://stackoverflow.com/comment/87911288
upvote count: 0
has comment: http://stackoverflow.com/comment/87911391
answer count: 1
has comment: http://stackoverflow.com/comment/87911353
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87973107
comment on: http://stackoverflow.com/q/50479845
type: Comment
type: QuestionComment
score: 0
has text: Isn't your input supposed to be like `*-` and not `.-` to print `"A"`?

http://stackoverflow.com/a/50436643
has comment: http://stackoverflow.com/comment/87892910
has comment: http://stackoverflow.com/comment/87891803
score: 0
answers question: http://stackoverflow.com/q/50430271
has comment: http://stackoverflow.com/comment/87893791
type: Answer
has body: I think the problem stems from the fact that, in my opinion, the official documentation is a bit ambiguous on the meaning of Non-Python created threads. Quoting from it: When threads are created using the dedicated Python APIs (such as the threading module), a thread state is automatically associated to them and the code showed above is therefore correct. However, when threads are created from C (for example by a third-party library with its own thread management), they don’t hold the GIL, nor is there a thread state structure for them. I have highlighted in bold the parts that I find off-putting. As I have stated in the OP, I am calling PyThread_start_new_thread. Whilst this creates a new thread from C, this function is not part of a third-party library, but of the dedicated Python (C) APIs. Based on this assumption, I ruled out that I actually needed to use the PyGILState_Ensure/PyGILState_Release paradigm. As far as I can tell from what I've seen with my experiments, a thread created from C with (just) PyThread_start_new_thread should be considered as a non-Python created thread.

http://stackoverflow.com/q/50439908
tagged with: arrays
tagged with: memoryview
tagged with: python
has comment: http://stackoverflow.com/comment/87894621
has comment: http://stackoverflow.com/comment/87920369
has comment: http://stackoverflow.com/comment/87919546
has comment: http://stackoverflow.com/comment/87922521
linked to: http://stackoverflow.com/q/10465091
score: 2
has comment: http://stackoverflow.com/comment/87899926
has comment: http://stackoverflow.com/comment/87909834
downvote count: 0
has comment: http://stackoverflow.com/comment/87920532
has title: Array of memoryviews in Cython
has comment: http://stackoverflow.com/comment/87910437
has comment: http://stackoverflow.com/comment/87911773
tagged with: cython
has comment: http://stackoverflow.com/comment/87894487
has comment: http://stackoverflow.com/comment/87894287
favorite count: 0
has answer: http://stackoverflow.com/a/50441558
linked to: http://stackoverflow.com/q/50395855
has body: Building upon this answer from my previous questions, I'd like to make arrays of memoryviews. Problem 1 Build a 2D array of memoryviews with fixed lenghts, e.g. mv1 = memoryview(b'1234') mv2 = memoryview(b'abcd') cdef const unsigned char[:,:] tmv = (mv1, mv2) With this I get: TypeError: a bytes-like object is required, not 'tuple' I tried using C arrays of pointers: ctypedef const unsigned char[:] k_t cdef unsigned char* mva[2] mv1 = memoryview(b'1234') mv2 = memoryview(b'abcd') cdef k_t mvk1 = mv1 cdef k_t mvk2 = mv2 mva = (&amp;mvk1, &amp;mvk2) But that didn't work either: Cannot take address of memoryview slice Problem 2 Build an arbitrarily long 3D array, basically a list of the above 2D array objects. This other answer to a similar question and the Cython docs on allocating memory got me a bit closer (I believe I should be using malloc and pointers, I would not want to introduce C++ if not necessary) but I am still stuck with problem #1. Any suggestions are welcome! Edit (problem #1): Even throwing a Cython array in the mix gives me the same error: from cython cimport view mv1 = memoryview(b'1234') mv2 = memoryview(b'abcd') cvarr = view.array(shape=(2,1), itemsize=sizeof(char), format='B') cvarr = (mv1, mv2) print(cvarr[0][1]) # So far so good... this prints `50` as expected. cdef const unsigned char[:,:] cvw = cvarr # Adding this last line throws `a bytes-like object is required, not 'tuple'` Now I'm really confused. Why would the tuple be good for the Cython array but not for the memview?
type: Question
upvote count: 2
answer count: 2
linked to: http://stackoverflow.com/q/50419431
has answer: http://stackoverflow.com/a/50450222
tagged with: typed-memory-views
type: UnansweredQuestion

http://stackoverflow.com/comment/87922355
has text: I found the error, I had some nan's left in my y_math_gpa.
type: Comment
comment on: http://stackoverflow.com/q/50426680
type: QuestionComment
score: 0

aws-security-group
type: Tag
tags question: http://stackoverflow.com/q/50531423
tag name: aws-security-group

http://stackoverflow.com/q/50423697
linked to: http://stackoverflow.com/q/28549761
type: Question
has answer: http://stackoverflow.com/a/50424034
accepted answer: http://stackoverflow.com/a/50424034
has title: Fast way to check whether number in list is in given range
downvote count: 0
has comment: http://stackoverflow.com/comment/87862191
duplicate of: http://stackoverflow.com/q/1193477
has comment: http://stackoverflow.com/comment/87862338
has comment: http://stackoverflow.com/comment/87862421
has comment: http://stackoverflow.com/comment/87862355
has comment: http://stackoverflow.com/comment/87862256
favorite count: 0
has comment: http://stackoverflow.com/comment/87862252
tagged with: python-3.x
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50423907
score: 3
has comment: http://stackoverflow.com/comment/87862201
answer count: 3
has comment: http://stackoverflow.com/comment/87862379
possible better answer: http://stackoverflow.com/a/50423872
tagged with: python
has body: I have a list of dictionaries in the following way: list1 = [{'some_id': 1, 'lower_range': 3, 'upper_range': 7}, {'some_id': 2, 'lower_range': 8, 'upper_range': 12}, {'some_id': 3, 'lower_range': 13, 'upper_range': 16}] A second list contains some integers: list2 = [{'value': 4, 'data': 'A'}, {'value': 8, 'data': 'B'}, {'value': 9, 'data': 'C'}, {'value': 15, 'data': 'D'}] I now want to join 'some_id' and 'data' such that 'value' is between 'lower_range' and 'upper_range' in a new list. I.e., I want the output to be list3 = [{'some_id': 1, 'data': 'A'}, {'some_id': 2, 'data': 'B'}, {'some_id': 2, 'data': 'C'}, {'some_id': 3, 'data': 'D'}] One way to do this would be list3 = [] for i in list1: for j in list2: if (j['value'] &gt;= i['lower_range'] and j['value'] &lt;= i['upper_range']): list3.append({'some_id': i['some_id'], 'data': j['data']}) However, this seems highly inefficient. Is there some faster way?
has answer: http://stackoverflow.com/a/50423872
linked to: http://stackoverflow.com/q/1193477

http://stackoverflow.com/comment/87995147
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50418099
has text: after trying some other for loops I think I have found part of the issue. the key when iterating is type, location etc. but it determines there is only one other value which includes the entire reference --> OrderedDict([('member', ['aaa', 'bbb'])])), so my real challenge is finding a way to ignore OrderedDict([('member', and only select the last part.
score: 0

http://stackoverflow.com/q/50418697
score: 3
has answer: http://stackoverflow.com/a/50419005
has comment: http://stackoverflow.com/comment/87853465
linked to: http://stackoverflow.com/q/46614289
downvote count: 0
has body: I have a weak grasp of Pandas and not a strong understanding of Python. I am wanting to update a column (d.Alias) based on the value of existing columns (d.Company and d2.Alias). d.Alias should be equal to d2.Alias if d2.Alias is a substring of d.Company. Example datasets: d = {'Company': ['The Cool Company Inc', 'Cool Company, Inc', 'The Cool Company', 'The Shoe Company', 'Muffler Store', 'Muffler Store'], 'Position': ['Cool Job A', 'Cool Job B', 'Cool Job C', 'Salesman', 'Sales', 'Technician'], 'City': ['Tacoma', 'Tacoma','Tacoma', 'Boulder', 'Chicago', 'Chicago'], 'State': ['AZ', 'AZ', 'AZ', 'CO', 'IL', 'IL'], 'Alias': [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]} d2 = {'Company': ['The Cool Company, Inc.', 'The Shoe Company', 'Muffler Store LLC'], 'Alias': ['Cool Company', np.nan, 'Muffler'], 'First Name': ['Carol', 'James', 'Frankie'], 'Last Name': ['Fisher', 'Smith', 'Johnson']} The np.nan for The Shoe Company is because for that instance an alias is not necessary. I have tried using .loc, for loops, while loops, pandas.where, numpy.where, and several variations of each with no desirable outcomes. When using a for loop, the end of d2.Alias was copied to all rows in d.Alias. I have not been able to reproduce that, however. Previous posts that I have looked at which I wasn't able to get to work, or I didn't understand them: Conditionally fill column with value from another DataFrame based on row match in Pandas pandas create new column based on values from other columns Any help is greatly appreciated! EDIT: Expected output Update: After a few days of tinkering I reached the desired outcome. With Wen's response I had to change a couple of things. First, I created a list from df2.Alias called aliases: aliases = df2.Alias.unique() Then, I had to remove .map(df2.set_index('Company').Alias. The line that generated my desired resutls: df1['Alias'] = df1.Company.apply(lambda x: [process.extract(x, aliases, limit=1)][0][0][0]).
has comment: http://stackoverflow.com/comment/87853107
has comment: http://stackoverflow.com/comment/87853347
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50418978
has comment: http://stackoverflow.com/comment/87853417
tagged with: python
has title: Update column values based on other columns
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50419005
answer count: 2
has answer: http://stackoverflow.com/a/50418978
tagged with: pandas
linked to: http://stackoverflow.com/q/26886653
upvote count: 3

http://stackoverflow.com/q/50422102
type: Question
tagged with: numpy
has title: Numpy reshape from (m,w,l) to (w,m,l) dimension
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87859157
downvote count: 1
favorite count: 0
has body: I'm working with financial time series data and a bit confused with numpy reshape function. My goal is to calculate log-returns for adj_close parameter. inputs = np.array([df_historical_data[key][-W:], axis = 1).values for key in stock_list]) inputs.shape //(8, 820, 5) prices = inputs[:, :, 0] prices.shape //(8, 820) prices[:,0] array([ 4.17000004e+02, 4.68800000e+00, 8.47889000e-03, 3.18835850e+00, 3.58412583e+00, 8.35364850e-01, 5.54610005e-04, 3.33600003e-05]) //close prices of 8 stock for 0 day However for my program, I need the shape of my inputs be (820, 8, 5) so I decided to reshape my numpy array inputs = np.array([df_historical_data[key][-W:], axis = 1).values for key in stock_list]).reshape(820, 8, 5) inputs.shape //(820, 8, 5) prices = inputs[:, :, 0] prices.shape //(820, 8) prices[0] array([ 417.00000354, 436.5100001 , 441.00000442, 440. , 416.10000178, 409.45245 , 422.999999 , 432.48000001]) // close price of 1 stock for 8 days // but should be the same as in the example above Seems that I didn't reshaped my array properly. Anyway I can't understand why such strange behaviour occurs.
linked to: http://stackoverflow.com/q/42312670
has comment: http://stackoverflow.com/comment/87859568
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50422849
has comment: http://stackoverflow.com/comment/87859318

http://stackoverflow.com/comment/88066505
has text: Just a question, have you activated the correct environment? also just try opening python prompt in anaconda environment and import numpy, to see if you are still facing the same error.. it could be mostly due to loading package from different paths issue
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50511312
type: Comment

http://stackoverflow.com/a/50529045
score: 2
has comment: http://stackoverflow.com/comment/88070004
downvote count: 0
has body: Don't do anything in divide. It's not its job to fix bad input parameters, nor catch the resulting exception. The caller can do those things. def divide(a,b): c=a/b print(c) return c Make the correction in main instead: def main(): try: r=0 t=1000 divide(t,r) except ZeroDivisionError: print('except block') r+=1000 divide(t,r)
upvote count: 2
answers question: http://stackoverflow.com/q/50528947
type: Answer
has comment: http://stackoverflow.com/comment/88072399

http://stackoverflow.com/comment/88665589
has text: Sort of. Some programs might not even support it entirely, they are not obliged to write every information possible into the file.
comment on: http://stackoverflow.com/a/50516528
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50483856
answers question: http://stackoverflow.com/q/50483459
has body: You might drop the upper column index level. If you don't want to modify the original dataframe, this could be done on a copy of it. df2 = df.copy() df2.columns = df2.columns.map('_'.join) df2.plot(secondary_y=('B_second'))
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87980708
downvote count: 0

http://stackoverflow.com/a/50431460
answers question: http://stackoverflow.com/q/50431417
accepted answer of: http://stackoverflow.com/q/50431417
has body: According to the docs: Python: cv2.VideoCapture.read([image]) → retval, image This returns 2 values, the first indicates if the frame is obtained correctly and the second is the frame. So in your case the code should be as follows: import cv2 import numpy as nmp capture=cv2.VideoCapture(0) while True: res, frame = capture.read() if res: cv2.imshow("Webcam", frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break capture.release() cv2.destroyAllWindows()
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87877331
has comment: http://stackoverflow.com/comment/87877303
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87877436
has comment: http://stackoverflow.com/comment/87877380

rss
type: Tag
tag name: rss
tags question: http://stackoverflow.com/q/50396492

http://stackoverflow.com/a/50496579
type: Answer
score: -1
answers question: http://stackoverflow.com/q/50496549
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/88005930
has body: What you can do is make a reverse lookup table from the values to all working keys, like so: def reverse(ids): table = {} for key in ids: if ids[key] not in table: table[ids[key]] = [] table[ids[key]].append(key) return table
has comment: http://stackoverflow.com/comment/88006509

http://stackoverflow.com/comment/113827952
comment on: http://stackoverflow.com/a/50590177
has text: I tried the same, but still get the ERROR: Command errored out with exit status 128. What is the cause of this?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88090773
type: QuestionComment
has text: Are you sure you're using the right `pip` to install?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50539516

http://stackoverflow.com/a/54027125
upvote count: 4
score: 3
has body: As of version 1.2.0, scipy includes softmax as a special function: https://scipy.github.io/devdocs/generated/scipy.special.softmax.html Use the axis argument do run it over rows. from scipy.special import softmax softmax(arr, axis=0)
downvote count: 1
answers question: http://stackoverflow.com/q/50423310
type: Answer

flask
tags question: http://stackoverflow.com/q/50389735
tags question: http://stackoverflow.com/q/50506842
tags question: http://stackoverflow.com/q/50472831
tags question: http://stackoverflow.com/q/50513770
tags question: http://stackoverflow.com/q/50505510
tags question: http://stackoverflow.com/q/50386162
tags question: http://stackoverflow.com/q/50454861
tags question: http://stackoverflow.com/q/50385495
tags question: http://stackoverflow.com/q/50389847
tags question: http://stackoverflow.com/q/50425098
tags question: http://stackoverflow.com/q/50415184
tags question: http://stackoverflow.com/q/50421935
tags question: http://stackoverflow.com/q/50489943
tags question: http://stackoverflow.com/q/50398246
tags question: http://stackoverflow.com/q/50491283
tags question: http://stackoverflow.com/q/50531192
tags question: http://stackoverflow.com/q/50386970
tags question: http://stackoverflow.com/q/50511034
tags question: http://stackoverflow.com/q/50535964
tags question: http://stackoverflow.com/q/50401604
tags question: http://stackoverflow.com/q/50402816
tags question: http://stackoverflow.com/q/50515397
tags question: http://stackoverflow.com/q/50400733
tags question: http://stackoverflow.com/q/50490138
tags question: http://stackoverflow.com/q/50461813
tags question: http://stackoverflow.com/q/50508358
tags question: http://stackoverflow.com/q/50389273
tags question: http://stackoverflow.com/q/50417731
tags question: http://stackoverflow.com/q/50484197
tags question: http://stackoverflow.com/q/50504523
tags question: http://stackoverflow.com/q/50506316
tags question: http://stackoverflow.com/q/50520345
tags question: http://stackoverflow.com/q/50511942
tags question: http://stackoverflow.com/q/50456993
tags question: http://stackoverflow.com/q/50539451
tags question: http://stackoverflow.com/q/50433962
tags question: http://stackoverflow.com/q/50468777
tags question: http://stackoverflow.com/q/50415433
tags question: http://stackoverflow.com/q/50409865
tags question: http://stackoverflow.com/q/50520387
tags question: http://stackoverflow.com/q/50529779
tags question: http://stackoverflow.com/q/50407729
tags question: http://stackoverflow.com/q/50533266
tags question: http://stackoverflow.com/q/50403405
tags question: http://stackoverflow.com/q/50457394
tags question: http://stackoverflow.com/q/50505329
tags question: http://stackoverflow.com/q/50476880
tags question: http://stackoverflow.com/q/50485530
tags question: http://stackoverflow.com/q/50398492
tags question: http://stackoverflow.com/q/50403760
tags question: http://stackoverflow.com/q/50409345
tags question: http://stackoverflow.com/q/50458750
tags question: http://stackoverflow.com/q/50403464
tags question: http://stackoverflow.com/q/50447865
tags question: http://stackoverflow.com/q/50527916
tags question: http://stackoverflow.com/q/50428919
tags question: http://stackoverflow.com/q/50459025
tags question: http://stackoverflow.com/q/50474314
tags question: http://stackoverflow.com/q/50511561
tags question: http://stackoverflow.com/q/50430508
tags question: http://stackoverflow.com/q/50454420
tags question: http://stackoverflow.com/q/50399293
tags question: http://stackoverflow.com/q/50525890
tags question: http://stackoverflow.com/q/50501409
tags question: http://stackoverflow.com/q/50474000
tag name: flask
tags question: http://stackoverflow.com/q/50478594
tags question: http://stackoverflow.com/q/50502669
tags question: http://stackoverflow.com/q/50464643
tags question: http://stackoverflow.com/q/50492494
tags question: http://stackoverflow.com/q/50428329
tags question: http://stackoverflow.com/q/50459142
tags question: http://stackoverflow.com/q/50494073
tags question: http://stackoverflow.com/q/50425008
tags question: http://stackoverflow.com/q/50426615
tags question: http://stackoverflow.com/q/50492765
tags question: http://stackoverflow.com/q/50417461
tags question: http://stackoverflow.com/q/50486824
tags question: http://stackoverflow.com/q/50447633
tags question: http://stackoverflow.com/q/50531353

http://stackoverflow.com/a/50553429
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50533139
has body: Well, the .pb was accidentally associated with ‘notebook’. Once I removed the open with association, the problem went away. I’m not sure how or why, but problem solved.

http://stackoverflow.com/comment/87984215
type: Comment
score: 0
has text: Maybe you need `polylines()`... https://docs.opencv.org/3.1.0/dc/da5/tutorial_py_drawing_functions.html
type: QuestionComment
comment on: http://stackoverflow.com/q/50484270

http://stackoverflow.com/a/63305787
downvote count: 1
has body: If you're creating an empty tensor, tf.zeros will do &gt;&gt;&gt; a = tf.zeros([0, 4]) &gt;&gt;&gt; tf.concat([a, [[1, 2, 3, 4], [5, 6, 7, 8]]], axis=0) &lt;tf.Tensor: shape=(2, 4), dtype=float32, numpy= array([[1., 2., 3., 4.], [5., 6., 7., 8.]], dtype=float32)&gt;
score: 6
answers question: http://stackoverflow.com/q/50463092
upvote count: 7
type: Answer

http://stackoverflow.com/comment/88010854
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50478464
has text: Ok I found a problem but it didn't lead to a solution. For some reason virtualenv --system-site-packages ~/venv installs python 2.6 instead of 3.6. I fixed the problem and now everything is in python 3 but it's still not able to find my module. I have venv activated and when I use ~/venv/bin/pip freeze --local my module shows up. which python and which pip both point to ~/venv/bin My error is ModuleNotFoundError: No module named 'my_module.class_file'; 'my_module' is not a package. I'm running my python code from the downloads folder. I'm going to look into it before asking a new question
score: 0

http://stackoverflow.com/comment/87858124
type: AnswerComment
comment on: http://stackoverflow.com/a/50416076
has text: Perfect. Just added items() call to the end and it's immediately iterable and printable.
type: Comment
score: 0

http://stackoverflow.com/comment/87873658
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50422566
has text: Debugging questions (1) does your install work with Arnold in GUI mode? (2) have you tried doing the same tasks interactively with Mayapy.exe from the command line?

http://stackoverflow.com/q/50427368
has answer: http://stackoverflow.com/a/50433489
downvote count: 1
has comment: http://stackoverflow.com/comment/87869437
answer count: 1
favorite count: 0
tagged with: percentile
has body: I was using the following code to boxplot the values with 5th and 95th percentiles as upper and lower bounds. Surprisingly, I have got two different plots by using matplotlib 1.4.0 in python 2.7.3 and matplotlib 2.2.0 in python 3.6.5. The version 1.4.0 seems to show the maximum value (49.33) and version 2.2.0 to show a value around 25 as 95th percentile, while the actual 95th percentile is 36.13. What could be a possible reason of these differences? And, which one should be considered as correct? import numpy as np import matplotlib.pyplot as plt values = np.array([0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,49.33,0.00,0.00,25.33]) f, (ax1) = plt.subplots() ax1.boxplot(values, whis=[5.0,95.0], showfliers=False) plt.show()
has comment: http://stackoverflow.com/comment/87875279
type: Question
accepted answer: http://stackoverflow.com/a/50433489
has title: Why boxplot by matplotlib 1.4.0 is not as same as boxplot by matplotlib 2.2.0 for same data?
tagged with: matplotlib
tagged with: boxplot
has comment: http://stackoverflow.com/comment/87870025
has comment: http://stackoverflow.com/comment/87876232
score: 1
has comment: http://stackoverflow.com/comment/87869509
has comment: http://stackoverflow.com/comment/87878002
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87869963
tagged with: python

http://stackoverflow.com/comment/88060684
type: QuestionComment
comment on: http://stackoverflow.com/q/50524328
has text: @Netwave it would, which is why I'm disappointed the answer below parroting Aran-Fey's comment has 2 upvotes and no one's offered a Counter-based solution yet.
score: 1
type: Comment

http://stackoverflow.com/comment/87817886
type: QuestionComment
comment on: http://stackoverflow.com/q/50401028
has text: Does that not suggest you should focus your attention on researching the difference between `&` and `and`?
score: 3
type: Comment

http://stackoverflow.com/q/50465316
type: UnansweredQuestion
tagged with: android
downvote count: 0
tagged with: python
has body: I installed tensorflow from source following these steps on a MacOS environment. The configuration and the build with bazel was successful but when I try to generate the libtensorflow_inference.so to add the native support for my android app following this link I get an error while executing the bazel build command in the provided link. Here is the error : ERROR: /private/var/tmp/_bazel_aboussaada/60096eee641a597e34b524b059acf8b3/external/protobuf_archive/BUILD:265:1: Executing genrule @protobuf_archive//:generate_js_well_known_types_embed failed (Exit 126): bash failed: error executing command (cd /private/var/tmp/_bazel_aboussaada/60096eee641a597e34b524b059acf8b3/execroot/org_tensorflow &amp;&amp; \ exec env - \ PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/munki \ PYTHON_BIN_PATH=/usr/local/opt/python@2/bin/python2.7 \ PYTHON_LIB_PATH=/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages \ TF_DOWNLOAD_CLANG=0 \ TF_NEED_CUDA=0 \ TF_NEED_OPENCL_SYCL=0 \ /bin/bash -c 'source external/bazel_tools/tools/genrule/genrule-setup.sh; bazel-out/armeabi-v7a-opt/bin/external/protobuf_archive/js_embed external/protobuf_archive/src/google/protobuf/compiler/js/well_known_types/any.js external/protobuf_archive/src/google/protobuf/compiler/js/well_known_types/struct.js external/protobuf_archive/src/google/protobuf/compiler/js/well_known_types/timestamp.js &gt; bazel-out/armeabi-v7a-opt/genfiles/external/protobuf_archive/src/google/protobuf/compiler/js/well_known_types_embed.cc') /bin/bash: bazel-out/armeabi-v7a-opt/bin/external/protobuf_archive/js_embed: cannot execute binary file Target //tensorflow/contrib/android:libtensorflow_inference.so failed to build INFO: Elapsed time: 0,361s, Critical Path: 0,08s INFO: 0 processes. FAILED: Build did NOT complete successfully i changed my NDK version to r12b since I was using r14b following this thread and rebuild tensorflow but nothing works. I'm working with python 2.7 and …
has comment: http://stackoverflow.com/comment/87960955
has comment: http://stackoverflow.com/comment/88017086
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88016705
tagged with: tensorflow
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/43541845
has title: Error building libtensorflow_inference.so

python-keyring
type: Tag
tag name: python-keyring
tags question: http://stackoverflow.com/q/50505179

http://stackoverflow.com/comment/87872395
score: 0
type: QuestionComment
has text: You need to take into account that Python 3.x is not backward compatible with Python 2.x. If you need to run code written for Python 2.x you cannot use the 3.x interpreter.
comment on: http://stackoverflow.com/q/50428680
type: Comment

http://stackoverflow.com/comment/88114789
has text: @JoeT.Boka I prefer using xpath inspecting and then by right click and copy pasting the same so that there is chance of such mistake.
comment on: http://stackoverflow.com/a/50541687
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50501820
has comment: http://stackoverflow.com/comment/88015948
type: Question
tagged with: server
type: UnansweredQuestion
tagged with: iis
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88016397
has body: HTTP Error 500.0 - Internal Server Error C:\Python34\python.exe - The FastCGI process exited unexpectedly This is the error I'm getting. I'm using python 3.4.2 but for some reason, it still doesn't work. I was following a youtube video and did everything exactly the way he did it. Anyone got any idea as to what is going on?
score: 0
has title: Django on IIS (Internal Server Error)
answer count: 0
tagged with: windows
has comment: http://stackoverflow.com/comment/88032071
has comment: http://stackoverflow.com/comment/88052619

http://stackoverflow.com/q/50455962
has comment: http://stackoverflow.com/comment/87925416
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87927612
tagged with: django
tagged with: django-models
tagged with: python
has title: (Django) Cannot update/add into manytomany field
has comment: http://stackoverflow.com/comment/87926805
tagged with: manytomanyfield
score: 0
tagged with: django-views
answer count: 0
has body: So I currently in a project where I want the team leaders to update their groups and add/remove members but it doesn't work and idk why I tried doing it by the add/remove way as you can see in the code under. How can I fix this? Models class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) ingroup = models.BooleanField(default=False) leader = models.BooleanField(default=False) groupleader = models.BooleanField(default=False) class TeamGroup(models.Model): name = models.CharField(max_length=50) team = models.ForeignKey(Team) ingroup = models.ManyToManyField(TeamMembership, blank=True) Currently the code are this @login_required def teamsettings_members_updategroup(request, team_pk, group_pk): requested_team = get_object_or_404(Team, pk=team_pk) for member in requested_team.teammembership_set.all().order_by('-leader'): if member.user.pk == request.user.pk and member.leader: group = TeamGroup.objects.get(pk=group_pk) if request.method == 'POST': name = request.POST['name'] users = request.POST.getlist('users[]') group.name = name for user in users: for ingroup in group.ingroup.all(): if ingroup.pk != user: group.ingroup.remove(user) TeamMembership.objects.filter(pk=user).update(ingroup=False) group.ingroup.add(user) TeamMembership.objects.filter(pk=user).update(ingroup=True) group.save() return redirect('teamsettings_members', team_pk) feedback = FeedbackSupportForm() context = { 'feedback' : feedback, 'group' : group, 'requested_team': requested_team, } return render(request, 'team/update_group.html', context) return redirect('team', team_pk)
type: Question
has comment: http://stackoverflow.com/comment/87926836

http://stackoverflow.com/comment/88062911
has text: The easiest way to achieve this is to append the path of your script into /etc/rc.local
type: Comment
comment on: http://stackoverflow.com/a/50519712
score: 0
type: AnswerComment

http://stackoverflow.com/q/50498944
downvote count: 0
answer count: 1
tagged with: unit-testing
favorite count: 0
has title: Django RequestFactory add HTTP_X_FORWARDED_FOR
type: Question
upvote count: 4
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50499060
has answer: http://stackoverflow.com/a/50499060
tagged with: django
tagged with: python
score: 4
type: AnsweredQuestion
has body: I have this code block that I am trying to write tests for: def get_client_ip(req): """ This is used to get the user's IP from the request object. """ x_forwarded_for = req.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = req.META.get('REMOTE_ADDR', "unknown") return ip So far I have been able to test the else section of the if statement. This is what my test currently looks like: def test_get_client_ip(self): """ Test the get Client IP fuction with a request. """ # Create an instance of a GET request. request = self.factory.get('/home') ip = get_client_ip(request) self.assertEqual(ip, '127.0.0.1') How would I go about adding "HTTP_X_FORWARDED_FOR" to META of the request object?

http://stackoverflow.com/q/50522769
score: 2
answer count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/88060428
linked to: http://stackoverflow.com/q/10245641
favorite count: 0
type: Question
tagged with: selenium-chromedriver
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/10245641
upvote count: 2
has comment: http://stackoverflow.com/comment/88058467
type: UnansweredQuestion
downvote count: 0
has body: I use python-binding selenium with chromedriver. I use webdriverwait until expected condition of an element is not displayed from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec def view_journal_entry(self): self.driver.refresh() self.driver.find_element_by_css_selector('a.small_journal_link.get-ajax-account-transaction').click() try: WebDriverWait(self.driver, 10).until( ec.invisibility_of_element_located((By.CSS_SELECTOR, 'div.blinkdot'))) finally: pass def check_journal_entry(self): self.view_journal_entry() debit = self.driver.find_element_by_css_selector('td.gl_total_debit').get_attribute('innerHTML') credit = self.driver.find_element_by_css_selector('td.gl_total_credit').get_attribute('innerHTML') index = 0 while ((debit != credit) or (debit == '0,00') or (credit == '0,00')) and index &lt; 2: self.view_journal_entry() index += 1 if (debit == credit) and (debit != '0,00') and (credit != '0,00'): print('debit is ' + debit + '\n' + 'credit is ' + credit) print('journal entry is balanced \n') self.driver.refresh() elif (debit == '0,00') or (credit == '0,00'): print('debit or credit is 0, please check sidekiq \n') self.driver.refresh() else: print('debit is ' + debit + '\n' + 'credit is ' + credit) print('journal entry is not balanced \n') self.driver.refresh() The problem is the webdriver does not wait for the element to be not displayed until the timeout, and the only thing I need is to change normal refresh into refresh bypass cache so that the element is not displayed when I loop the function. How do you refresh bypass cache using python selenium with chromedriver?
tagged with: python
has title: How do you refresh bypass cache using python-binding selenium with chromedriver?

http://stackoverflow.com/a/50560128
upvote count: 2
score: 2
has body: First check the version of scikit-learn you are using. If its v0.19 , then you are using the deprecated module. You are doing this: from sklearn.grid_search import RandomizedSearchCV And you must have gotten a warning like: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. ... ... ... The classes in the grid_search module are old and deprecated and dont contain the multi-metric functionality you are using. Pay attention to that warning and do this: from sklearn.model_selection import RandomizedSearchCV ... ... ... random_search = RandomizedSearchCV(xgb_algo, param_distributions=params, n_iter=max_models, scoring= scoring_evals, n_jobs=4, cv=5, verbose=False, random_state=2018, refit=False ) Now look closely at the refit param. In the multi-metric setting, you need to set this so that the final model can be fitted to that, because the best hyper-parameters for the model will be decided based on a single metric only. You can either set it to False if you dont want the final model and only want the performance of the model on the data and different params or set that to any of the key you have in your scoring dict.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50537651

average
tags question: http://stackoverflow.com/q/50540817
type: Tag
tag name: average

http://stackoverflow.com/comment/88079638
type: QuestionComment
comment on: http://stackoverflow.com/q/50533746
score: 0
type: Comment
has text: I suggest that you handle each field individually in the form rather than loop through, like `form.field_name` is the input for `field_name`, `form.field_name.id_for_label` is the id,`form.field_name.errors` catch all the validation errors for that field,

http://stackoverflow.com/comment/88061492
score: 0
comment on: http://stackoverflow.com/q/50524328
has text: I totally understand, however my question more generic in nature than already answered question.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87900444
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50443248
has text: `itertools.product(*your_list)`
score: 0

http://stackoverflow.com/a/50540273
score: 0
answers question: http://stackoverflow.com/q/50540125
has body: To make it run when you run the file (I guess that's what you are looking for) change the following bookmark_func() to if __name__ == "__main__" : bookmark_func() This checks the calling points and makes it run.
has comment: http://stackoverflow.com/comment/88092134
type: Answer

http://stackoverflow.com/q/50478162
upvote count: 6
tagged with: python
has title: Monkeypatching a function namespace
has comment: http://stackoverflow.com/comment/87970573
has comment: http://stackoverflow.com/comment/87970130
possible better answer: http://stackoverflow.com/a/50478364
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87971832
accepted answer: http://stackoverflow.com/a/50478367
answer count: 2
downvote count: 2
has body: Inspired by "Define @property on function", I tried to override a function's namespace: &gt;&gt;&gt; class MyDict(dict): ... def __getitem__(self, item): ... if item == 'k2': ... return 'v2' ... return super().__getitem__(item) ... &gt;&gt;&gt; def f(): ... pass ... ... &gt;&gt;&gt; f.__dict__ = MyDict({'k1': 'v1'}) &gt;&gt;&gt; &gt;&gt;&gt; f.k1 'v1' &gt;&gt;&gt; f.k2 AttributeError: 'function' object has no attribute 'k2' Why can f.k1 resolve, but f.k2 can't?
linked to: http://stackoverflow.com/q/50477609
has comment: http://stackoverflow.com/comment/87971342
has comment: http://stackoverflow.com/comment/87970549
score: 4
has answer: http://stackoverflow.com/a/50478364
has comment: http://stackoverflow.com/comment/87970261
favorite count: 0
has comment: http://stackoverflow.com/comment/87971789
type: Question
has answer: http://stackoverflow.com/a/50478367
has comment: http://stackoverflow.com/comment/87971453

http://stackoverflow.com/q/50428039
type: Question
has body: I have a pandas object of time. How do I convert them into seconds. I have over 8 hours worth of data. 0 [0:00:03] 1 [0:00:03] 2 [0:00:03] 3 [0:00:04] 4 [0:00:04]
has comment: http://stackoverflow.com/comment/87870881
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87871561
has comment: http://stackoverflow.com/comment/87870839
tagged with: timestamp
has answer: http://stackoverflow.com/a/50430249
has title: Python: convert TimeObject [0:00:07] into seconds
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87871712

http://stackoverflow.com/comment/87792434
comment on: http://stackoverflow.com/q/50388128
type: Comment
type: QuestionComment
has text: @jpp There are 3 replace methods. I am looking for a way to reduce the chain :)
score: 0

http://stackoverflow.com/q/50410283
tagged with: python
accepted answer: http://stackoverflow.com/a/50410353
has comment: http://stackoverflow.com/comment/87835809
has answer: http://stackoverflow.com/a/50410353
type: AnsweredQuestion
answer count: 3
tagged with: regex
has answer: http://stackoverflow.com/a/50410627
has title: Fetch string matching a pattern
favorite count: 0
has answer: http://stackoverflow.com/a/50410779
type: Question
tagged with: python-3.x
upvote count: 0
has comment: http://stackoverflow.com/comment/87836424
has body: I have a text like this - EventTimestamp H 9EventType 8document 2ID 2b837c02-40c9-4d33-b81b-d489a06fa302-DCUP LogToAuditTrail SourceAppCD 5DOCSV SourceAppUID 2b837c02-40c9-4d33-b81b-d489a06fa302 6UserID 5a8ce656-1a31-456b-b3dd-5ec0859c9f3e1 I want to fetch the document-id which is present in the above string as 2b837c02-40c9-4d33-b81b-d489a06fa302 The Id has a specific pattern - &lt;8characters(alpha numeric)&gt; - &lt;4characters(alpha numeric)&gt; - &lt;4characters(alpha numeric)&gt; - &lt;4characters(alpha numeric)&gt; - &lt;12characters(alpha numeric)&gt; The above string has other similar ids, but I am interested in getting the pattern after the substring document 2ID. Again this string is not fixed any kind of number, string or white space can come between document &amp; ID
score: -2
downvote count: 2
possible better answer: http://stackoverflow.com/a/50410627

http://stackoverflow.com/comment/88001529
score: 0
type: QuestionComment
has text: also in that tutorial: "The thread module has been "deprecated" for quite a long time. Users are encouraged to use the threading module instead."
type: Comment
comment on: http://stackoverflow.com/q/50480456

http://stackoverflow.com/comment/88083865
score: 0
comment on: http://stackoverflow.com/q/50535832
has text: @AdamSmith I'm far better in C++ compared to python, but fun thing what I said works in C++. I thought it should be same in theory. I'll post an example code in C++ now, maybe it helps more. (with the output)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50492377
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
linked to: http://stackoverflow.com/q/11553721
tagged with: python
tagged with: variables
has comment: http://stackoverflow.com/comment/87997651
score: 0
duplicate of: http://stackoverflow.com/q/1373164
answer count: 0
has body: How could i get below code working? I want to assign value to variable Reputation Risk_22may_only. I got the below code from here. But it doesn't work for me risk_type="Reputation Risk" xxx1=risk_type + "_22may_only" exec(xxx1 + " = 'something else'") exec(xxx1 + " = 'something else'") Traceback (most recent call last): File "C:\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-38-c9a2a2cf48c3&gt;", line 1, in &lt;module&gt; exec(xxx1 + " = 'something else'") File "&lt;string&gt;", line 1 Reputation Risk_22may_only = 'something else' ^ SyntaxError: invalid syntax
tagged with: string
has comment: http://stackoverflow.com/comment/87997800
has comment: http://stackoverflow.com/comment/87998398
has comment: http://stackoverflow.com/comment/87997767
type: Question
has title: python create variable from string variable

http://stackoverflow.com/a/50519862
has comment: http://stackoverflow.com/comment/88052899
score: 31
answers question: http://stackoverflow.com/q/50519798
upvote count: 31
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50519798
has comment: http://stackoverflow.com/comment/124850372
has comment: http://stackoverflow.com/comment/132134891
has comment: http://stackoverflow.com/comment/120977567
downvote count: 0
type: Answer
has body: You can try this : from collections import deque deq = deque([1, 2, 3, 4]) del deq[1] print(deq) Output: deque([1, 3, 4])
has comment: http://stackoverflow.com/comment/127994469

http://stackoverflow.com/comment/88014410
type: AnswerComment
has text: Try `print`ing `music_class_id` and `music_class`. Do they contain any data?
type: Comment
comment on: http://stackoverflow.com/a/50500775
score: 0

http://stackoverflow.com/q/50429038
has comment: http://stackoverflow.com/comment/87873234
has comment: http://stackoverflow.com/comment/87873262
score: 0
tagged with: pandas
answer count: 0
has body: Hello I'm trying to replace the ingers for both 'score1' and 'score2'. Sometimes they print random numbers. Strings replace correctly, but not integers. import pandas as pd raw_data = { "city" : ["new york", "Sydney", "miami", "Rome", ], "rank": ["1st", "2nd", "2", "3"], "score1": [33, 48, 25, 33], "score2": [33, 48,33, 48] } df = pd.DataFrame(raw_data, index = pd.Index (['a', 'b', 'd', 'e'], name = 'letter'), columns = pd.Index(['city', 'rank', 'score1', 'score2'], name='attributes')) df['score1'].replace([33, 48, 25, 33], [1,2,3,4], inplace=True) df['score2'].replace([33, 48,33, 48], [1,3,4,5], inplace=True) print(df)
type: Question
has title: Data Frame: repacing inccorect values
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87872745
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/57565711
score: 3
has comment: http://stackoverflow.com/comment/102605175
has body: Gensim actually has the official way to do this. Documentation about it
has comment: http://stackoverflow.com/comment/102659127
answers question: http://stackoverflow.com/q/50492676
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/106720845
has comment: http://stackoverflow.com/comment/106000320
type: Answer

http://stackoverflow.com/q/50493505
linked to: http://stackoverflow.com/q/50428095
has answer: http://stackoverflow.com/a/50493710
has comment: http://stackoverflow.com/comment/88000521
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50493602
type: UnansweredQuestion
score: -2
has title: Count the unique elements in an array with effective way
tagged with: python
upvote count: 0
downvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/100200223
has body: I can't release something better than: (Python 3.6) N=int(input()) #count of input elements a=[] #buffer k=0 #counter tel=0 #next number for i in range(N): tel=int(input()) if(not tel in a): a.append(tel) k+=1 print(k) #count of unique elements But my teacher says that my solution is not very effective, coz I save data to array a... Hm... He also says that I should save something in variable and permanently rewrite it. Have You any idea un this case? UPD "Effective way" - program must uses as little memory as possible, and works fast as possible

scope
tags question: http://stackoverflow.com/q/50465802
type: Tag
tags question: http://stackoverflow.com/q/50463520
tags question: http://stackoverflow.com/q/50525997
tag name: scope
tags question: http://stackoverflow.com/q/50526174

plot
tags question: http://stackoverflow.com/q/50524188
tags question: http://stackoverflow.com/q/50488327
tags question: http://stackoverflow.com/q/50458498
tags question: http://stackoverflow.com/q/50515007
tags question: http://stackoverflow.com/q/50405248
type: Tag
tags question: http://stackoverflow.com/q/50483279
tags question: http://stackoverflow.com/q/50526344
tags question: http://stackoverflow.com/q/50514138
tags question: http://stackoverflow.com/q/50501364
tags question: http://stackoverflow.com/q/50526962
tags question: http://stackoverflow.com/q/50388325
tags question: http://stackoverflow.com/q/50497990
tags question: http://stackoverflow.com/q/50486357
tags question: http://stackoverflow.com/q/50521709
tag name: plot
tags question: http://stackoverflow.com/q/50470220
tags question: http://stackoverflow.com/q/50479425
tags question: http://stackoverflow.com/q/50494352
tags question: http://stackoverflow.com/q/50434278
tags question: http://stackoverflow.com/q/50416872
tags question: http://stackoverflow.com/q/50467393
tags question: http://stackoverflow.com/q/50436597
tags question: http://stackoverflow.com/q/50425217
tags question: http://stackoverflow.com/q/50522888
tags question: http://stackoverflow.com/q/50474674
tags question: http://stackoverflow.com/q/50540653
tags question: http://stackoverflow.com/q/50450783
tags question: http://stackoverflow.com/q/50385348
tags question: http://stackoverflow.com/q/50396015

http://stackoverflow.com/a/50424756
answers question: http://stackoverflow.com/q/50424725
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You've over-complicated things. You can shuffle the list in-place and then iterate it, which guarantees that you can only print each word once, provided that you don't have duplicate words (in which case you could convert to a set() beforehand). import random words = ['a', 'b', 'c'] random.shuffle(words) for word in words: print(word) Because this works in place, you'll lose the initial ordering. If you need to retain the initial ordering then you can shuffle a copy of the list. import random words = ['a', 'b', 'c'] word_copy = words.copy() random.shuffle(word_copy) for word in word_copy: print(word)
type: Answer
accepted answer of: http://stackoverflow.com/q/50424725
score: 2

http://stackoverflow.com/q/50494440
has answer: http://stackoverflow.com/a/50494501
has body: I initialize variable a and b. a has id=559599568, b has id=559251864. I then assign b to a in the function change(), expecting a points to b's location and a has b's value. However, what I found is a indeed points to b's location within the function (as you can see, they all have id=559251864 when print inside the function change), but once the function returns, a points back to it's original id which is 559599568. Why a points back to its original memory id once returns? I thought python is passing by reference if it is a mutable object? Please correct me. a = pd.DataFrame(range(3)) b = pd.DataFrame(range(5)) def change(origin,new): print id(origin) print id(new) origin = new print id(origin) print id(new) change(a,b) Out[24]: change(a,b) 559599568 559251864 559251864 559251864 a Out[25]: 0 0 0 1 1 2 2 b Out[26]: 0 0 0 1 1 2 2 3 3 4 4 id(a) Out[27]: 559599568L id(b) Out[28]: 559251864L
linked to: http://stackoverflow.com/q/986006
has title: pass by reference for mutable object?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88001738
duplicate of: http://stackoverflow.com/q/575196
has comment: http://stackoverflow.com/comment/88001891
duplicate of: http://stackoverflow.com/q/986006
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/88001771
tagged with: pandas
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87927369
comment on: http://stackoverflow.com/q/50456885
type: QuestionComment
score: 1
has text: What do you want to achieve with this? I don't think what you want to achieve is the best way to do it. So **why** do you want to have both files in one?
type: Comment

http://stackoverflow.com/a/50503225
accepted answer of: http://stackoverflow.com/q/50502617
has comment: http://stackoverflow.com/comment/88041061
type: Answer
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88037744
answers question: http://stackoverflow.com/q/50502617
has body: You are storing all values in single variable. You will get the last value always. I am storing it in list. So that, you can iterate over the list as given below. It may solve your issue. deal_title = browser.find_elements_by_xpath("//") titles = [] for title in deal_title: titles.append(title.text) deal_link = browser.find_elements_by_xpath("//") links = [] for link in deal_link: links.append(link.get_attribute('href')) for title, link in zip(titles, links): f.write("&lt;a href=" + link + "&gt;" + title + "&lt;/a&gt;")
has comment: http://stackoverflow.com/comment/88042489

http://stackoverflow.com/comment/87900753
type: Comment
has text: the shape is also 700, I mentioned in my question that there are 700 samples of x and y values, I extracted both of them and implemented a 'view' operation to reshape them
comment on: http://stackoverflow.com/a/50439853
type: AnswerComment
score: 0

http://stackoverflow.com/comment/124490772
comment on: http://stackoverflow.com/q/50435310
score: 0
type: Comment
has text: If you don't specifically want to use PyTorch try FastText or Hugging-face transformers to train or extract word embeddings
type: QuestionComment

http://stackoverflow.com/comment/88118809
type: Comment
comment on: http://stackoverflow.com/a/50540242
score: 0
type: AnswerComment
has text: @Anthony.H This dataframe was created only to show concept. `iloc` method will return `DataFrame` object, so you can apply methods from my answer to it. In terms of your question, just substitute `df1` and `df2` with `data2011` and `df2016` respectively

http://stackoverflow.com/q/50437243
has comment: http://stackoverflow.com/comment/87888583
has comment: http://stackoverflow.com/comment/87888523
has body: It's my first time asking a question on Stack Overflow. As titled, I want to make a simple dictionary. Here is my C++ code: class Dict { public: Dict(string key, int value); ~Dict(); void append(string key, int value); int operator[](string search); //int operator=(int value); private: string* keys; int have_keys; int* values; }; Methods: Dict::Dict(string key, int value) { keys = new string[1]; keys[0] = key; have_keys = 1; values = new int[1]; values[0] = value; } //append a key an a value void Dict::append(string key, int value) { string* temp_keys = new string[have_keys+1]; memcpy(temp_keys, keys, sizeof(string)*have_keys); temp_keys[have_keys] = key; int* temp_values = new int[have_keys+1]; memcpy(temp_values, values, sizeof(int)*have_keys); temp_values[have_keys] = value; have_keys++; keys = new string[have_keys]; memcpy(keys, temp_keys, sizeof(string)*have_keys); delete[]temp_keys; values = new int[have_keys]; memcpy(values, temp_values, sizeof(int)*have_keys); delete[]temp_values; } //a = dict["hello"]; int Dict::operator[](string search) { for(int i = 0;i&lt;have_keys;i++){ if(keys[i]==search){ return values[i]; } } } I could do this: Dict dict = Dict("hello", 10); int a = dict["hello"]; show(a); However, for... dict["hello"]=20; How can I overload operators to do that? I don't want this: dict.set("hello", 20); Thanks!
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87888450
has title: C++ class: How to use dict["hello"]=20; like Python
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87890306
has comment: http://stackoverflow.com/comment/87892164
tagged with: class
tagged with: c++
tagged with: overloading
type: AnsweredQuestion
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/50437320
accepted answer: http://stackoverflow.com/a/50437320
has comment: http://stackoverflow.com/comment/87888594

http://stackoverflow.com/comment/87798679
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50391464
score: 0
has text: You should have `tf.reset_default_graph` before `tf.train.import_meta_graph(filepath)` not after. You're importing the graph then resetting it.

http://stackoverflow.com/comment/87814196
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50398165
has text: @Chiefir: see https://wiki.archlinux.org/index.php/File_permissions_and_attributes
type: AnswerComment

http://stackoverflow.com/comment/87913417
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50449810
has text: Thanks for this. In my case all the fields are of variable length. For this reason I struggle to organise the placement with the grid manager.
type: Comment

http://stackoverflow.com/comment/87998293
type: Comment
type: QuestionComment
has text: @roganjosh i got this error after update the code UnicodeEncodeError: 'latin-1' codec can't encode character '\u201c' in position 97: ordinal not in range(256)
comment on: http://stackoverflow.com/q/50492652
score: 0

http://stackoverflow.com/comment/87981199
comment on: http://stackoverflow.com/q/50480583
has text: If the project is configured to use that venv, yes. You'll want to make sure that a) you are aware which interpreter or venv will be used when your software runs "natively", i.e. outside of PyCharm in whatever can be considered your production environment, b) this interpreter or venv is also linked to the project and c) has the required packages installed. Is the venv you are referring to the same as the one that you use when calling Django's manage.py?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87878334
comment on: http://stackoverflow.com/q/50431537
has text: The ChangeToSurvive is a float, so sometimes is 29.2 and after training again change to 30.5 or other number.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/112094709
has text: `I am aware this error is known and widely answered before` Its answered where?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50445182
type: Comment

http://stackoverflow.com/comment/88039749
comment on: http://stackoverflow.com/q/50513091
type: QuestionComment
type: Comment
score: 0
has text: How are you decrypting and un-tarring?

http://stackoverflow.com/comment/87790897
has text: Works for me too.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50387354
type: QuestionComment

http://stackoverflow.com/q/50477318
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/74108319
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42320132
has body: I am trying to import numpy in Cygwin. I get the following error message. I have numpy 1.11.2-1, a.k.a. the python2-numpy: Python scientific computing module package, installed through the Cygwin installer. I also have Python 2.7.14-1, a.k.a. the python2: Python 2 language interpreter package also installed through Cygwin. I don't have a local installation of Python on my machine. $ python Python 2.7.14 (default, Oct 31 2017, 21:12:13) [GCC 6.4.0] on cygwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/site-packages/numpy/__init__.py", line 142, in &lt;module&gt; from . import add_newdocs File "/usr/lib/python2.7/site-packages/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/usr/lib/python2.7/site-packages/numpy/lib/__init__.py", line 8, in &lt;module&gt; from .type_check import * File "/usr/lib/python2.7/site-packages/numpy/lib/type_check.py", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "/usr/lib/python2.7/site-packages/numpy/core/__init__.py", line 14, in &lt;module&gt; from . import multiarray ImportError: No such file or directory cygcheck: $ cygcheck -c python2-numpy Cygwin Package Information Package Version Status python2-numpy 1.11.2-1 OK Also, I was able to import numpy in Cygwin on another computer. There seem to be a number of posts on this but all lacking a solution that works for me. I tried restarting my computer per Not able to import numpy in cygwin, but that did not work. I have also edited my $PATH variable: $ echo $PATH /usr/lib/python2.7/site-packages/numpy/:/usr/lib/python2.7/site-packages/:/usr/bin The solution: $ PATH=/usr/lib/lapack:$PATH
has comment: http://stackoverflow.com/comment/88000596
tagged with: cygwin
tagged with: python
has comment: http://stackoverflow.com/comment/87972291
has title: Cygwin: import numpy error
score: 2
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/74108319
upvote count: 2
has comment: http://stackoverflow.com/comment/88000569
accepted answer: http://stackoverflow.com/a/50496136
downvote count: 0
has comment: http://stackoverflow.com/comment/87978936
has answer: http://stackoverflow.com/a/50496136

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/50401827
tag name: python-packaging

http://stackoverflow.com/q/50526015
favorite count: 0
tagged with: python-3.x
type: Question
has body: I have been looking around the site for a similar answer and the closest I managed to find is this one. The answer gives the following C program for achieving this: //My code file #include &lt;stdio.h&gt; #include &lt;Python.h&gt; void main() { FILE* file; int argc; char * argv[3]; argc = 3; argv[0] = "mypy.py"; argv[1] = "-m"; argv[2] = "/tmp/targets.list"; Py_SetProgramName(argv[0]); Py_Initialize(); PySys_SetArgv(argc, argv); file = fopen("mypy.py","r"); PyRun_SimpleFile(file, "mypy.py"); Py_Finalize(); return; } I would like to do something similar to this (using python 3, I don't know if that makes a difference) and generate an output using matplotlib. However I don't know how to adapt this to a C++ program, especially given the types required by the functions (such as wchar_t** for argv). Is there a way to do this without having to perform various typecasts to C types?
tagged with: python
type: UnansweredQuestion
has title: Running a python .py file in C++ with command line arguments
answer count: 1
tagged with: c++
has answer: http://stackoverflow.com/a/50526195
score: 3
upvote count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/12142174

http://stackoverflow.com/comment/87878226
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50426036
has text: @Alex If you review well the image that you show in the following link https://ibb.co/kyFELo you will see that the .kv extension has .py, so I recommend you change it, for that it enables the visibility of the extensions.
score: 0

http://stackoverflow.com/q/50435190
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87884575
has answer: http://stackoverflow.com/a/50435972
score: 0
has comment: http://stackoverflow.com/comment/87884524
tagged with: matplotlib
type: Question
has title: Matplotlib: Gaussian contour plot from two arrays
linked to: http://stackoverflow.com/q/39549331
type: UnansweredQuestion
has body: I have two numpy arrays, one of shape (239,2) containing my data points and one of shape (239,) containing the values of a bivariate gaussian density for these data points. How can I create a contour plot with Matplotlib for my density function on top of a scatter plot of the data points? Currently I get a TypeError: Input z must be a 2D array, when trying to use the contour function in matplotlib. Why does z have to be 2D if I have a value for the X-axis, Y-axis and probability density for every data point? Do I need to interpolate in some way? fig, ax = plt.subplots() ax.scatter(X[:,0], X[:,1], c='green') ax.scatter(X[:,0], X[:,1], c='orange') ax.contour(z, X[:,0], X[:,1]) &lt;-- TypeError happens here plt.show() X is of shape (239, 2), z is of shape (239,)

http://stackoverflow.com/comment/87832775
has text: I suggest you provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) that includes imports and correct indentation. And you attract the right people by adding the tags for the libraries you use.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50408327

http://stackoverflow.com/q/50470212
has title: All the new widgets are having the same background image as "centralwidget",how can I rest them?
has comment: http://stackoverflow.com/comment/87954435
answer count: 1
downvote count: 1
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/87957910
type: Question
tagged with: pyqt4
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87957519
has body: I'm using Qt Designer and I wanted to insert an image to be as a background to my app so What I did is the following: Right click on 'centralwidget' -&gt; Change styleSheet -&gt; "border-image: url(:/Resources/MyImage.jpg);" The problem is all the widgets( buttons, Labels...) now have MyImage.jpg as a background image. I've read that this is happening because the new widgets are inheriting from "centralwidget". How can I rest them to Default?
tagged with: qt-designer
has comment: http://stackoverflow.com/comment/87957305
has answer: http://stackoverflow.com/a/50472239
upvote count: 0
tagged with: pyqt

http://stackoverflow.com/a/50469977
score: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50469887
has body: Assuming this part is generating the dates you want in a list: #range for single_date in daterange(dataObject, dataObject1): print (single_date.strftime("%Y-%m-%d")) Change it to this: mylist = [] #range for single_date in daterange(dataObject, dataObject1): mylist.append(single_date.strftime("%Y-%m-%d"))
type: Answer
accepted answer of: http://stackoverflow.com/q/50469887
upvote count: 3

http://stackoverflow.com/comment/88066512
type: QuestionComment
comment on: http://stackoverflow.com/q/50527401
score: 0
type: Comment
has text: module1 is in the package1 and module2 is in the package2

http://stackoverflow.com/q/50436658
upvote count: 4
tagged with: slug
type: AnsweredQuestion
has body: I have an Album field with a list of Songs class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=250) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000,blank=True) slug = models.SlugField(unique=True) def __str__(self): return self.album_title class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) artist = models.CharField(max_length=250, blank=True) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=100) def __str__(self): return self.artist I would like to know how to generate slugs from the album title. I am following a tutorial which is using django 1.8 which uses regular expressions to implement this task. But from looking through the documentation they have introduced a more simpler approach (''). So can you help explain how I can implement it for a beginner to understand not only in this context but if possible across board. Thanks in advance.
answer count: 3
has answer: http://stackoverflow.com/a/72626678
downvote count: 0
has answer: http://stackoverflow.com/a/69187489
tagged with: django
linked to: http://stackoverflow.com/q/50244523
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/53664884
possible better answer: http://stackoverflow.com/a/69187489
has answer: http://stackoverflow.com/a/53664884
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/87887468
has title: How to auto generate slug from my Album model in django 2.0.4

http://stackoverflow.com/q/50435725
has comment: http://stackoverflow.com/comment/87885642
has answer: http://stackoverflow.com/a/50435813
type: UnansweredQuestion
has body: The following code looks up a text file to see if there are any matches. For example, a line may be "charlie RY content" and the next line may be "charlie content". However, the counter seems to be off and isn't counting correctly. file = open("C:/file.txt", "rt") data = file.readlines() dictionary = dict() counter = 0 count = 0 setlimit = 10 #int(input("Please enter limit for N. Then press enter:")) parameter = ["RY", "TZ"] for j in data: user = j.split()[0] identify = j.split()[1] for l in identify: #l = a[1:2] if user not in dictionary.keys() and identify not in parameter: count = 1 data = dictionary.update({user:count}) break #print(user, count,"&lt;-- Qualifies") elif user in dictionary.keys() and identify not in parameter: data = dictionary.update({user: count}) count += 1 break print(dictionary) As seen in the code, it looks for either RY or TZ and ignores this line and if a line without this condition is met, the counter will increase by one. Sample Data: charlie TZ this is a sentence zac this is a sentence steve RY this is a sentence bob this is a sentence bob this is another sentence Expected Output: {zac:1, bob:2}
has answer: http://stackoverflow.com/a/50436094
tagged with: python
has title: Counter Not Working Correctly
has comment: http://stackoverflow.com/comment/87885879
has comment: http://stackoverflow.com/comment/87885836
has comment: http://stackoverflow.com/comment/87885643
answer count: 3
has comment: http://stackoverflow.com/comment/87886155
has comment: http://stackoverflow.com/comment/87885596
score: 0
has comment: http://stackoverflow.com/comment/87885827
has answer: http://stackoverflow.com/a/50435845
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87819109
has text: What Python version are you using? f-strings are a relatively recent addition to the language.
type: Comment
type: QuestionComment
score: 9
comment on: http://stackoverflow.com/q/50401632

http://stackoverflow.com/comment/87924893
type: AnswerComment
has text: Yeah, looks like I'd have to dig in more!. Appreciate your help though. Thanks
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50455590

http://stackoverflow.com/comment/87929417
type: QuestionComment
comment on: http://stackoverflow.com/q/50457115
has text: What are you trying to accomplish? Can you verify if `from django.conf import settings` works?
type: Comment
score: 0

http://stackoverflow.com/comment/87956087
has text: try `sudo apt-get install libffi-dev` instead of with `pip`.
comment on: http://stackoverflow.com/q/50471010
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87817483
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50400784
type: Comment
has text: I didn't downvote... but I think OP's question is a bit weird at this point, and unclear. Do they want every value replaced or just the NaNs? The `I realize the day_charge column is can be produced by a a function of day_mins` comment seems to suggest the other.

http://stackoverflow.com/comment/88167558
score: 1
has text: This is helpful, though probably incomplete as someone mentions in the comments in the link you posted - `save_manifest` probably needs to be overridden as well.
comment on: http://stackoverflow.com/a/50481802
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50515863
type: Answer
answers question: http://stackoverflow.com/q/50515596
upvote count: 2
has body: You can use lstrip as the key function to ignore the whitespace on the left, front of the string. r = sorted(['1 ', ' 9' , ' 4', '2 '], key=str.lstrip) # r == ['1 ', '2 ', ' 4', ' 9'] key specifies a function of one argument that is used to extract a comparison key from each list element, doc.
has comment: http://stackoverflow.com/comment/88046733
score: 2
downvote count: 0

http://stackoverflow.com/comment/87992855
type: QuestionComment
comment on: http://stackoverflow.com/q/50481346
has text: This suggests you can: https://youtu.be/BhgE6d7zhYQ doesn’t it?
score: 0
type: Comment

http://stackoverflow.com/q/50417089
answer count: 0
has comment: http://stackoverflow.com/comment/87850038
has body: Well I have already grant the user to 'CREATEDB'. but when I run the test using python manage.py test I got this error, Creating test database for alias 'default'... Got an error creating the test database: permission denied to create database This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'USER': 'my_admin', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', 'TEST' : { 'NAME': 'test_my_db' } } }
has title: Can't run test on the Python/Django application
has comment: http://stackoverflow.com/comment/87849908
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87849818
linked to: http://stackoverflow.com/q/14186055
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87849828
score: 0

http://stackoverflow.com/comment/88067302
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50527856
type: AnswerComment
has text: What's stopping you from using a simple `for` loop between the `h3` and `h2` tags then and simply checking the tag?

http://stackoverflow.com/comment/87808028
type: AnswerComment
has text: I added comments in my code. I also added a one-line style solution.
comment on: http://stackoverflow.com/a/50395496
score: 0
type: Comment

http://stackoverflow.com/comment/87805127
has text: That is probably a custom object manager one of your collegues wrote.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50394607
type: Comment

http://stackoverflow.com/q/50537407
has body: When embedding Python in my application, and writing an extension type, I can add a signature to the method by using a properly crafted .tp_doc string. static PyMethodDef Answer_methods[] = { { "ultimate", (PyCFunction)Answer_ultimate, METH_VARARGS, "ultimate(self, question='Life, the universe, everything!')\n" "--\n" "\n" "Return the ultimate answer to the given question." }, { NULL } }; When help(Answer) is executed, the following is returned (abbreviated): class Answer(builtins.object) | | ultimate(self, question='Life, the universe, everything!') | Return the ultimate answer to the given question. This is good, but I'm using Python3.6, which has support for annotations. I'd like to annotate question to be a string, and the function to return an int. I've tried: static PyMethodDef Answer_methods[] = { { "ultimate", (PyCFunction)Answer_is_ultimate, METH_VARARGS, "ultimate(self, question:str='Life, the universe, everything!') -&gt; int\n" "--\n" "\n" "Return the ultimate answer to the given question." }, { NULL } }; but this reverts to the (...) notation, and the documentation becomes: | ultimate(...) | ultimate(self, question:str='Life, the universe, everything!') -&gt; int | -- | | Return the ultimate answer to the given question. and asking for inspect.signature(Answer.ultimate) results in an exception. Traceback (most recent call last): File "&lt;string&gt;", line 11, in &lt;module&gt; File "inspect.py", line 3037, in signature File "inspect.py", line 2787, in from_callable File "inspect.py", line 2266, in _signature_from_callable File "inspect.py", line 2090, in _signature_from_builtin ValueError: no signature found for builtin &lt;built-in method ultimate of example.Answer object at 0x000002179F3A11B0&gt; I've tried to add the annotations after the fact with Python code: example.Answer.ultimate.__annotations__ = {'return': bool} But the builtin method descriptors can't have annotations added this way. Traceback (most recent call last): File "&lt;string&gt;", …
tagged with: python-c-api
upvote count: 11
favorite count: 0
accepted answer: http://stackoverflow.com/a/50763175
has answer: http://stackoverflow.com/a/50763175
type: Question
has comment: http://stackoverflow.com/comment/88103489
downvote count: 0
has comment: http://stackoverflow.com/comment/88086978
answer count: 1
tagged with: python-3.6
tagged with: signature
score: 11
has title: Add a signature, with annotations, to extension methods
has comment: http://stackoverflow.com/comment/88086941
tagged with: python-internals
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/comment/87885971
type: AnswerComment
has text: Aren't they the same thing? If you group by _a, it means you are putting duplicated values of _a in the same group?
comment on: http://stackoverflow.com/a/50435907
score: 1
type: Comment

http://stackoverflow.com/comment/88329198
comment on: http://stackoverflow.com/a/50595645
has text: Thanks,I tried to execute the code by commenting this line and it worked but didn't know how it worked,thanks for the explanation.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88106172
type: AnswerComment
has text: @mgus: The usual way to do extended floating-point precision in Python is the `decimal` module, but that does real numbers only, not complex numbers. The [mpmath module](http://mpmath.org/) does "real and complex floating-point arithmetic with arbitrary precision." It is not included in standard Python but it is included and installed by default in the Anaconda installation of Python (which is what I use). You may want to examine your matrix-inversion routine--there are many, and some are more careful with precision than others. mpmath does do matrix inversion, according to its feature list.
comment on: http://stackoverflow.com/a/50545540
type: Comment
score: 0

http://stackoverflow.com/a/50506709
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50505827
score: 1
has body: All elements are inside the frame. So that, it is throwing No Such Element exception. Please try to switch to the frame before all actions as given below. browser = webdriver.Firefox( executable_path='/mypath/to/geckodriver') url = 'https://secure6.e-boekhouden.nl/bh/' browser.get(url) browser.switch_to.frame(browser.find_element_by_id("mainframe")) browser.find_element_by_id('txtEmail') browser.find_element_by_xpath('//*[@name="txtEmail"]') browser.find_element_by_class_name('INPUTBOX')
answers question: http://stackoverflow.com/q/50505827
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/50451165
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/87915835
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87915507
tagged with: python
has comment: http://stackoverflow.com/comment/87915551
score: 0
has body: When I run this code in my commandline; scrapy crawl indeed -o items.csv, I receive an output with blank spaces between each row. See image. How do i solve this? import scrapy class IndeedSpider(scrapy.Spider): name = 'indeed' allowed_domains = ['indeed.nl'] start_urls = ['https://www.indeed.nl/vacatures?q=developer&amp;l='] def parse(self, response): jobs =response.xpath('//div[@class=" row result" or @class="lastRow row result"]') for job in jobs: jobtitle = job.xpath('h2/a/@title').extract_first() company = job.xpath('.//span[@class="company"]/text()').extract_first() yield{ 'jobtitle': jobtitle, 'company': company}
answer count: 0
has comment: http://stackoverflow.com/comment/87915452
has comment: http://stackoverflow.com/comment/87915524
has title: Why are there blank spaces between my CSV between each row?

http://stackoverflow.com/comment/87893306
comment on: http://stackoverflow.com/a/50438744
type: AnswerComment
has text: RishuA: You can easily create custom dialog boxes with `tkinter`. Here's some (dated Python 2) [documentation](http://effbot.org/tkinterbook/tkinter-dialog-windows.htm), but it you search online (including this website) you'll probably be able to locate more current information.
score: 0
type: Comment

http://stackoverflow.com/q/50486478
has comment: http://stackoverflow.com/comment/87986378
has comment: http://stackoverflow.com/comment/87986792
has comment: http://stackoverflow.com/comment/87985879
has answer: http://stackoverflow.com/a/50487435
score: 0
has body: I have faced a problem while I was reading from GEOSGeometry object. I have used this code ds = DataSource(shp file path) lyr = ds[0] for feat in lyr: geom_t = feat.geom.transform(wgs84, clone=True) name =feat.get('name') this code works fine for my shape files.but if name field contains a utf8 string such as 'تست' it raises this error DjangoUnicodeDecodeError at /views/importdata/ 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte. You passed in b'\xc8\xe1\xe6\xc7\xd1 \xc7\xe3\xc7\xe3 \xd1\xd6\xc7' (&lt;class 'bytes'&gt;) Unicode error hint The string that could not be encoded/decoded was: ����� well I find out this is an internal error which is related to gdal or geos wrapper in django. the error comes from this line return force_text(string, encoding=self._feat.encoding, strings_only=True) in field.py in this directory D:\Python\Python36\lib\site-packages\django\contrib\gis\gdal\field.py in as_string is there any way to find a solution for this problem? thanks
tagged with: django
tagged with: python
type: UnansweredQuestion
has title: DjangoUnicodeDecodeError while getting field
has comment: http://stackoverflow.com/comment/87986558
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87985804
tagged with: geodjango
has comment: http://stackoverflow.com/comment/87986731
has comment: http://stackoverflow.com/comment/87986651

http://stackoverflow.com/comment/88011542
score: 0
type: Comment
type: AnswerComment
has text: Thank you very much @leoschet. I'll keep it in mind.
comment on: http://stackoverflow.com/a/50499352

http://stackoverflow.com/q/50516416
answer count: 1
tagged with: neural-network
has title: Neural Network converges on answer, then oscillates wildly
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/88047739
has comment: http://stackoverflow.com/comment/88045472
has answer: http://stackoverflow.com/a/50517347
score: 0
tagged with: gradient-descent
has body: In trying to understand fully connected ANN's, I'm starting with a simple 2-D linear regression example. My network is trivial - one input layer and an output layer with a set of weights between them. If my understanding is correct, the weight should essentially learn the slope of the best fit line of my data. My training data is a slightly noisy line as below. It's just a fuzzy line with slope of m = .5. My code pulls one point, propagates it through my network and backpropagates to update the weights. Weight update happens either every datum or averaged over every 5, 10 or 20 points. My weights are randomized, but I've fixed the seed for sanity's sake while debugging. When I plot the square error from every training example, I get the following hump, settling, then explosion. Corresponding to the decrease in square error, my algorithm finds the slope of the linear data...then violently rejects it, lol. My initial thought was that the oscillations I coded into my training data were too wild and might throw the solution out of the local minima. But then I tightened up the spread around y=.5x in my training data with not much effect. To also try to smooth out these effects, I implemented averaged stochastic weight updates to only update after a batch of a few training samples. No love. I'm also using a very small learning rate (.0005) as I thought that the noise might have got me oscillating down a gradient hill. This initially helped, but the figures are the result of alpha = .005. Any suggestions on what I'm missing? I'd like to handle this situation so I can approach multi-variate regression. import random import matplotlib.pyplot as plt import numpy as np random.seed(0) def gen_linear_regression_data(num_points, slope=.5, var=1.0, plot=False, seed=None): if seed is not None: np.random.seed(seed) data = [idx for idx in range(num_points)] labels = [data[idx] * slope for idx in range(num_points)] # add noise labels = [l + np.random.uniform(-var, var) for l in labels…
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/88046054
type: UnansweredQuestion

http://stackoverflow.com/q/50453254
has body: I am using python to send a scorecard to users on a monthly basis. I would like to use the delegated Gmail account to send email to users. Attached images for your reference. I can send email to users using my personal account. But I can't send email to users using the Delegated account. Attached error message screenshot here. I google error message and I couldn't find any posts related to the error message. Gmail Delegated Account Image Python Script Image Python Error Message Image
favorite count: 0
tagged with: python-2.7
tagged with: python
has answer: http://stackoverflow.com/a/50453318
type: Question
tagged with: gmail-api
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
has title: Python Send email from a delegated account
tagged with: python-requests

http://stackoverflow.com/comment/87954435
type: Comment
has text: I'm using Qt Designer how can or where i can do that
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50470212

http://stackoverflow.com/q/50457043
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50457741
accepted answer: http://stackoverflow.com/a/50457741
has body: I've scoured the questions/answers and have attempted to implement changes to the following, but to no avail. I'm trying to scrape pages of course listings from Coursera's "Data Analysis" results, https://www.coursera.org/browse/data-science/data-analysis?languages=en&amp;page=1. There are 9 pages, each with 25 courses, and each course is under its own &lt;h2&gt; tag. I've found some success with the following code, but it has not been consistent: courses_data_sci = [] for i in range(10): page = "https://www.coursera.org/browse/data-science/data-analysis? languages=en&amp;page=" + str(i) html = urlopen(page) soup = BeautifulSoup(html.read(), "html.parser") for meta in soup.find_all('div', {'id' : 'rendered-content'}): for x in range(26): try: course = meta.find_all('h2')[x].text.strip() courses_data_sci.append(course) except IndexError: pass This code seems to return the first 2-3 pages of results and the last page of results; sometimes, if I run it again after clearning courses_data_sci, it will return the 4th page of results a few times. (I'm working in Jupyter, and I've restarted the kernel to account for any issues there.) I'm not sure why the code isn't working correctly, let alone why it is returning inconsistent results. Any help is appreciated. Thank you. UPDATE Thanks for the ideas...I am trying to utilize both to make the code work. Just out of curiosity, I pared down the code to see what it was picking up, with both comments in mind. courses_data_sci = [] session = requests.Session() for i in range(10): page = "https://www.coursera.org/browse/data-science/data-analysis? languages=en&amp;page=" + str(i) html = urlopen(page) soup = BeautifulSoup(html.read(), "html.parser") for meta in soup.find_all('div', {'id' : 'rendered-content'}): course = meta.find_all('h2') courses_data_sci.append(course) # This is to check length of courses_data_sci across pages print('Page: %s -- total length %s' % (i, len(courses_data_sci))) This actually results in a list of lists…
tagged with: beautifulsoup
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87929298
has title: Python/BeautifulSoup Web-scraping Issue--Irregular Returns
answer count: 1

http://stackoverflow.com/a/50448504
type: AcceptedAnswer
has body: It looks like the problem was with a paramiko object not getting closed. Once the SFTPClient or the SSHClient is opened, it has to be closed explicitly. I have assumed that along with my class object (where paramiko object is defined) it would get closed. But it doesnt. So on the end of my process i call below lines. Now the threads seems getting closed properly if objs.ssh: objs.ssh.close() if objs.sftp: objs.t.close() objs.sftp.close() del objs gc.collect()
accepted answer of: http://stackoverflow.com/q/50407729
score: 0
answers question: http://stackoverflow.com/q/50407729
type: Answer

http://stackoverflow.com/a/50495066
type: AcceptedAnswer
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/89731238
type: Answer
accepted answer of: http://stackoverflow.com/q/50494352
has body: This is probably https://github.com/bokeh/bokeh/issues/7497 I'd suggest you add any detailed information you can there.
upvote count: 2
answers question: http://stackoverflow.com/q/50494352

http://stackoverflow.com/comment/87941964
has text: Thank you vey much.
comment on: http://stackoverflow.com/q/50444618
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50515638
has comment: http://stackoverflow.com/comment/88059481
accepted answer of: http://stackoverflow.com/q/50515170
type: AcceptedAnswer
score: 1
answers question: http://stackoverflow.com/q/50515170
has body: Let's review the basics of an array - it has a flat data buffer, a shape, strides, and dtype. Those three attributes are used to view the elements of the data buffer in a particular way, whether it is a simple 1d sequence, 2d or higher dimensions. A true view than use the same data buffer, but applies different shape, strides or dtype to it. To get [2, 4, 3, 1] from [1,2,3,4] requires starting at 2, jumping forward 2, then skipping back to 1 and forward 2. That's not a regular pattern that can be represented by strides. arr[1::2] gives the [2,4], and arr[0::2] gives the [1,3]. (U, V, S, T) to (U*S, V*T) requires a transpose to (U, S, V, T), followed by a reshape arr.transpose(0,2,1,3).reshape(U*S, V*T) That will require a copy, no way around that. In [227]: arr = np.arange(2*3*4*5).reshape(2,3,4,5) In [230]: arr1 = arr.transpose(0,2,1,3).reshape(2*4, 3*5) In [231]: arr1.shape Out[231]: (8, 15) In [232]: arr1 Out[232]: array([[ 0, 1, 2, 3, 4, 20, 21, 22, 23, 24, 40, 41, 42, 43, 44], [ 5, 6, 7, 8, 9, 25, 26, 27, 28, 29, 45, 46, 47, 48, 49], ....) Or with your x In [234]: x1 = x.transpose(0,2,1,3).reshape(4,4) In [235]: x1 Out[235]: array([[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]) Notice that the elements are in a different order: In [254]: x.ravel() Out[254]: array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]) In [255]: x1.ravel() Out[255]: array([1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4]) ndarray.sort is in-place and changes the order of bytes in the data buffer. It is operating at a low level that we don't have access to. It isn't a view of the original array.
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/87837027
comment on: http://stackoverflow.com/a/50408325
has text: My query is not about training. As mentioned above assume I have trained a network and have done typical accuracy measures and launched it. After the launch, I'd like to give the user some sort of confidence, i.e. QC or accuracy measure, on the predictions from the new instances.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50465106
has answer: http://stackoverflow.com/a/50472787
has comment: http://stackoverflow.com/comment/87946946
possible better answer: http://stackoverflow.com/a/66792805
has comment: http://stackoverflow.com/comment/87946769
downvote count: 0
has answer: http://stackoverflow.com/a/66792805
has comment: http://stackoverflow.com/comment/126629836
has body: I get the following error when I'm reading my .pkl files on spyder (python 3.6.5): IN: with open(file, "rb") as f: data = pickle.load(f) Traceback (most recent call last): File "&lt;ipython-input-5-d9796b902b88&gt;", line 2, in &lt;module&gt; data = pickle.load(f) AttributeError: Can't get attribute 'Signal' on &lt;module '__main__' from 'C:\\Python36\\lib\\site-packages\\spyder\\utils\\ipython\\start_kernel.py'&gt; The context: My program is made of one file: program.py In the program, a class Signal is defined as well as many functions. A simplified overview of the program is provided below: import numpy as np import _pickle as pickle import os # The unique class class Signal: def __init__(self, fq, t0, tf): self.fq = fq self.t0 = t0 self.tf = tf self.timeline = np.round(np.arange(t0, tf, 1/fq*1000), 3) # The functions def write_file(data, folder_path, file_name): with open(join(folder_path, file_name), "wb") as output: pickle.dump(data, output, -1) def read_file(folder_path, file_name): with open(join(folder_path, file_name), "rb") as input: data= pickle.load(input) return data def compute_data(# parameters): # do stuff The function compute_data will return a list of tuples of the form: data = [((Signal_1_1, Signal_1_2, ...), val 1), ((Signal_2_1, Signal_2_2, ...), val 2)...] With, of course, the Signal_i_k being an object Signal. This list will be saved in .pkl format. Moreover, I'm doing a lot of iteration with different parameters for the compute_data functions. Many iterations will use past computed data as a starting point, and thus will read the corresponding and needed .pkl files. Finally, I'm using several computers at the same time, each of them saving the computed data on the local network. Thus each computer can access the data generated by the others and use it as a starting point. Back to the error: My main issue is that I never have this error when I start my programs by double-clicking the file or by the windows cmd or PowerShell. The program never…
score: 19
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/45616584
has comment: http://stackoverflow.com/comment/87946582
tagged with: spyder
tagged with: pickle
tagged with: python
has title: AttributeError when reading a pickle file
has comment: http://stackoverflow.com/comment/87946856
accepted answer: http://stackoverflow.com/a/50472787
type: AnsweredQuestion
upvote count: 19
answer count: 2

http://stackoverflow.com/comment/88098679
has text: I executed the part where the model architecture was defined,not the training part,and then loaded the graph and I assumed that the values will get assigned to the variables after loading.
type: Comment
comment on: http://stackoverflow.com/q/50484453
type: QuestionComment
score: 0

http://stackoverflow.com/a/50527822
answers question: http://stackoverflow.com/q/50525301
type: Answer
score: 0
has body: I have few experience with model proxies so I can't tell if this would properly work (without bearking anything I mean) nor how complicated this might be, but you could use an item_type:ProxyClass mapping and override your model's queryset (or provide a second manager with custom queryset etc) that actually lookup this mapping and instanciates the correct proxy model. BTW you may want at django.models.base.Model.from_db, which (from a very quick glance at the source code) seems to be the method called by QuerySet.populate() to instanciate models. Just overriding this method might possibly be enough to solve the problem - but here again it might also breaks something...

http://stackoverflow.com/a/50439813
answers question: http://stackoverflow.com/q/50439452
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87969395
has body: As long as you want this to be a single query in database, you have to use SQL, so you cannot just apply arbitrary python functions. To take a length of char column there is a Length expression in Django(https://docs.djangoproject.com/en/1.11/ref/models/database-functions/#django.db.models.functions.Length), which you can use like this Length(F('name')). It will add necessary code to generated SQL so database do the right thing. So finally, if you need for example to set some column to the length of another column value, you can use Model.objects.update(name_length=Length(F('name')))

http://stackoverflow.com/comment/88090865
comment on: http://stackoverflow.com/a/50536171
has text: I ran the above script and it showing that files uploaded. But when I go to that folder its empty.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50442401
has title: How to set the default option as -h for Python click?
tagged with: python
has body: How to set the default option as -h for Python click? By default, my script, shows nothing when no arguments is given to the duh.py: import click CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--toduhornot', is_flag=True, help='prints "duh..."') def duh(toduhornot): if toduhornot: click.echo('duh...') if __name__ == '__main__': duh() [out]: $ python3 test_click.py -h Usage: test_click.py [OPTIONS] Options: --toduhornot prints "duh..." -h, --help Show this message and exit. $ python3 test_click.py --toduhornot duh... $ python3 test_click.py Question: As shown above, the default prints no information python3 test_click.py. Is there a way such that, the default option is set to -h if no arguments is given, e.g. $ python3 test_click.py Usage: test_click.py [OPTIONS] Options: --toduhornot prints "duh..." -h, --help Show this message and exit.
answer count: 4
tagged with: command-line-interface
upvote count: 13
has answer: http://stackoverflow.com/a/50491613
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58997967
tagged with: python-click
has answer: http://stackoverflow.com/a/63566351
possible better answer: http://stackoverflow.com/a/63566351
downvote count: 0
score: 13
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50491613
has answer: http://stackoverflow.com/a/50442496
has comment: http://stackoverflow.com/comment/87950426
tagged with: argparse

http://stackoverflow.com/q/50433131
score: 1
upvote count: 1
has title: Django: Moving 'oscar' site-package
answer count: 1
tagged with: django-oscar
tagged with: site-packages
has body: I am starting my own Django-Oscar project, and am wondering about the possibility of changing the location of the 'oscar'-directory (containing all apps, a models.py etc), moving it from the default on-installation site-packages directory within my virtual environment - into my project root directory. Would it be possible to simply copy the 'oscar'-directory, and paste it into a new location, assuming I also change the locations of the 'INSTALLED_APPS', and make sure that my project-structure is the same (i.e. not changing things like the directory-name 'oscar' so that imports etc break)? If so, would that mean that I could delete it all together from site-packages (DRY-solution)? This would mimic the sandbox-installation, and would be a set up I'd feel more comfortable with as a beginner who needs visible overhead. Thank you!
favorite count: 0
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50437287
accepted answer: http://stackoverflow.com/a/50437287
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/50435928
has body: Have you registered 'website_dj' in your installed apps in settings.py?
type: Answer
answers question: http://stackoverflow.com/q/50432712
score: 0

http://stackoverflow.com/comment/87864866
comment on: http://stackoverflow.com/q/50424820
score: 0
has text: I added it already
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50538563
linked to: http://stackoverflow.com/q/47204919
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
answer count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50538941
linked to: http://stackoverflow.com/q/50460930
has comment: http://stackoverflow.com/comment/88089101
tagged with: python
has comment: http://stackoverflow.com/comment/88089318
linked to: http://stackoverflow.com/q/44671194
has answer: http://stackoverflow.com/a/50538941
tagged with: data-science
tagged with: svm
has comment: http://stackoverflow.com/comment/88089474
has title: Grading System - Input Features
has body: I am working on a Grading System ( graduation project ). I have preprocessed the data, then used TfidfVectorizer on the data and used LinearSVC to fit the model. The System goes as follows, it has 265 definitions, of arbitrary lengths; but in total, they sum up to shape of (265, 8581 ) so when I try to input some new random sentence to predict against it, I get this message Error Message you could have a look at the code used ( Full &amp; long ) if you want to; Code used; def normalize(df): lst = [] for x in range(len(df)): text = re.sub(r"[,.'!?]",'', df[x]) lst.append(text) filtered_sentence = ' '.join(lst) return filtered_sentence def stopWordRemove(df): stop = stopwords.words("english") needed_words = [] for x in range(len(df)): words = word_tokenize(df) for word in words: if word not in stop: needed_words.append(word) return needed_words def prepareDataSets(df): sentences = [] for index, d in df.iterrows(): Definitions = stopWordRemove(d['Definitions'].lower()) Definitions_normalized = normalize(Definitions) if d['Results'] == 'F': sentences.append([Definitions, 'false']) else: sentences.append([Definitions, 'true']) df_sentences = DataFrame(sentences, columns=['Definitions', 'Results']) for x in range(len(df_sentences)): df_sentences['Definitions'][x] = ' '.join(df_sentences['Definitions'][x]) return df_sentences def featureExtraction(data): vectorizer = TfidfVectorizer(min_df=10, max_df=0.75, ngram_range=(1,3)) tfidf_data = vectorizer.fit_transform(data) return tfidf_data def learning(clf, X, Y): X_train, X_test, Y_train, Y_test = \ cross_validation.train_test_split(X,Y, test_size=.2,random_state=43) classifier = clf() classifier.fit(X_train, Y_train) predict = cross_validation.cross_val_predict(classifier, X_test, Y_test, cv=5) scores = cross_validation.cross_val_score(classifier, X_test, Y_test, cv=5) print(scores) print ("Accuracy of %s: %0.2f(+/- %0.2f)" % (classifier, scores.mean(), scores.std() *2)) print (classification_report(Y_test, predict)) Then I …
has comment: http://stackoverflow.com/comment/88089410
has comment: http://stackoverflow.com/comment/88089451
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50505087
accepted answer of: http://stackoverflow.com/q/50504743
has comment: http://stackoverflow.com/comment/88024926
has body: The condition function (cond) of tf.while_loop() must return a boolean tensor of rank 0 (i.e. of shape [], i.e. a single boolean). Your cond is returning a boolean tensor of rank 2 (as tf.greater(now, pre) returns a tensor of same shape as now, performing per-element comparison).
type: Answer
answers question: http://stackoverflow.com/q/50504743
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer

numbers
tags question: http://stackoverflow.com/q/50424659
tags question: http://stackoverflow.com/q/50402373
tags question: http://stackoverflow.com/q/50428030
tags question: http://stackoverflow.com/q/50468756
tags question: http://stackoverflow.com/q/50420906
tags question: http://stackoverflow.com/q/50518424
tags question: http://stackoverflow.com/q/50504143
type: Tag
tag name: numbers
tags question: http://stackoverflow.com/q/50470889

http://stackoverflow.com/comment/87799175
type: QuestionComment
comment on: http://stackoverflow.com/q/50390643
type: Comment
has text: @Anton vBr Becuase I want to be able to copy any values from `GB` `Col2` to `FR` `COL2.`
score: 0

http://stackoverflow.com/a/53742520
answers question: http://stackoverflow.com/q/50387587
type: Answer
has comment: http://stackoverflow.com/comment/113087386
upvote count: 6
has body: The answer of @John and Kogan is great but doesn't give the full code needed to make this work: As @Danra mentioned you need to also save the staticfiles.json in the source folder to make this work. Here's the code I've created based on the above answer: import json import os from django.conf import settings from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage from whitenoise.storage import CompressedManifestStaticFilesStorage # or if you don't use WhiteNoiseMiddlware: # from django.contrib.staticfiles.storage import ManifestStaticFilesStorage class LocalManifestStaticFilesStorage(CompressedManifestStaticFilesStorage): """ Saves and looks up staticfiles.json in Project directory """ manifest_location = os.path.abspath(settings.BASE_DIR) # or settings.PROJECT_ROOT depending on how you've set it up in your settings file. manifest_storage = FileSystemStorage(location=manifest_location) def read_manifest(self): try: with self.manifest_storage.open(self.manifest_name) as manifest: return manifest.read().decode('utf-8') except IOError: return None def save_manifest(self): payload = {'paths': self.hashed_files, 'version': self.manifest_version} if self.manifest_storage.exists(self.manifest_name): self.manifest_storage.delete(self.manifest_name) contents = json.dumps(payload).encode('utf-8') self.manifest_storage._save(self.manifest_name, ContentFile(contents)) Now you can use LocalManifestStaticFilesStorage for your STATICFILES_STORAGE. When running manage.py collectstatic, your manifest will be saved to your root project folder and Django will look for it there when serving the content. If you have a deployment with multiple virtual machines, make sure to run collectstatic only once and copy the staticfiles.json file to all the machines in your deployment as part of your code deployment. The nice thing about this is that even if some machines don't have the latest update yet, they will still be serving the correct content …
has comment: http://stackoverflow.com/comment/116501811
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/111453618

http://stackoverflow.com/a/50430308
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50428329
type: Answer
has body: @charlietfl in the comments and this link got me on the right track. One can use FormData and then an .ajax call to achieve the desired outcome. So the important parts of above's link are (the complete files can be found below): Choose file... and // Get form var form = $('#fileUploadForm')[0]; // Create an FormData object var data = new FormData(form); and $.ajax({ type: "POST", enctype: 'multipart/form-data', url: "/_get_table", data: data, processData: false, The processData: false, is important to prevent jQuery form transforming the data into a query string as explained in the link above. On the flask site, we can then easily retrieve the file by doing: file = request.files['myfile'] df = pd.read_csv(file) which turns the .csv into a pandas dataframe. Clearly, there should be checks etc before doing this. The entire HTML page index_formdata.html would look like this: Some great stuff Choose file... Upload and process! the flask file as follows: from flask import Flask, render_template, request, jsonify import pandas as pd import numpy as np import json # Initialize the Flask application app = Flask(__name__) @app.route('/') def index(): return render_template('index_formdata.html') @app.route('/_get_table', methods=["POST", "GET"]) def get_table(): # catch file from the form; if you have several files, just make several requests (access by name) file = request.files['myfile'] df = pd.read_csv(file) return jsonify(my_table=json.loads(df.to_json(orient="split"))["data"], columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]]) if __name__ == '__main__': app.run(debug=True) and the testdata.csv file A,B,C 1,3,123 2,4,456
answers question: http://stackoverflow.com/q/50428329
score: 0

http://stackoverflow.com/a/50510180
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50508838
answers question: http://stackoverflow.com/q/50508838
score: 1
has body: I managed to solve this issue using the SQLTransformer. This is what I have done sqlTrans_formatter = SQLTransformer(statement="SELECT CAST(date1 AS date), CAST(date2 AS date), CAST(date3 AS date), CAST(date4 AS date), CAST(date5 AS date), CAST(date6 AS date), CAST(integer1 AS int) FROM __THIS__") df = sqlTrans_formatter.transform(ddf) Hopefully it would be helpful for others as well.
type: AcceptedAnswer

http://stackoverflow.com/q/50427549
score: 1
has comment: http://stackoverflow.com/comment/87884445
tagged with: methods
type: Question
tagged with: python-3.x
tagged with: trie
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
tagged with: tree
has title: Python: how to speed up this method of exhaustion? Trie?
has body: I have a corpus with lines of sentences without spaces between words: thenextdayonmayanarchistsstagedarallyatchicagoshaymarketsquare abombwasthrownbyanunknownpartyneartheconclusionoftherallykillinganofficer intheensuingpanicpoliceopenedfireonthecrowdandeachother sevenpoliceofficersandatleastfourworkerswerekilled I need to separate every sentence with vocabulary in a dictionary such as: {'the': 1, 'next':2, 'thenext':3'...}The numbers are just frequencies, which are not important here. The output will be the variants(lists) of segmentations, just like: [[the, next, day...], [thenext, day...]...] And here is my code (filter_worddict is the dictionary) def segment(sentence): if sentence == '': yield [] for w in filter_worddict: if sentence.startswith(w): for rest in segment(sentence[len(w):]): yield [w] + rest with open('sentences.txt', 'r') as f4, open('result.txt', 'w') as f5: for line4 in f4: line4 = line4.strip() corpus = list(segment(line4)) for corpusline in corpus: f5.write(str(corpusline) + '\n') How can this code speed up? The last time I tried with a corpora (less than 30MB), the dictionary was 5MB, and it took 48h. . . I have looked around and I've got the choice between Trie and Pytrie, which seems it's a promising solution. But I don't know how to do it in this case correctly. Thanks in advance!

http://stackoverflow.com/comment/87962301
has text: Thanks for the great answer! I will start with Flask, as its more lightweight, and if not successful, I'll switch to Django.
comment on: http://stackoverflow.com/a/50442057
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87888450
score: 6
type: Comment
has text: Is this an exercise in operator overloading? If not, then use e.g. [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map) like the rest of us.
type: QuestionComment
comment on: http://stackoverflow.com/q/50437243

http://stackoverflow.com/comment/87926870
comment on: http://stackoverflow.com/q/50456633
has text: Oh thank @youroganjosh, fixed it.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50391949
has comment: http://stackoverflow.com/comment/87799581
has comment: http://stackoverflow.com/comment/87799583
has comment: http://stackoverflow.com/comment/87799498
score: -4
has title: How to insert a dictionary inside list
answer count: 1
upvote count: 1
has body: I want to create a list and add my dictionary dict inside that list like below Ex: list1 =[] dict1 = {'name': 'None', 'age':20, 'dead':'NO'} I want this to look like [{'name': 'None', 'age':20, 'dead':'NO'}]
has comment: http://stackoverflow.com/comment/87800198
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50392041
has comment: http://stackoverflow.com/comment/87799484
has answer: http://stackoverflow.com/a/50392041
has comment: http://stackoverflow.com/comment/87799739
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/87799724
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87799555
has comment: http://stackoverflow.com/comment/87799465
has comment: http://stackoverflow.com/comment/87799611
type: AnsweredQuestion

http://stackoverflow.com/q/50459578
favorite count: 0
possible better answer: http://stackoverflow.com/a/50460022
type: Question
tagged with: numpy
has body: I have a 2D NumPy of strings array like: a = array([['1,2,3'], ['3,4,5']], dtype=object) and I would like to convert it into a 2D Numpy array like this: a = array([['1','2','3'], ['4','5','6']]). I would then like to also convert the strings to floats, so the final array would look like this: a = array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]). Any help is greatly appreciated.
has comment: http://stackoverflow.com/comment/87932626
has comment: http://stackoverflow.com/comment/87932385
has answer: http://stackoverflow.com/a/50459986
accepted answer: http://stackoverflow.com/a/50459986
has answer: http://stackoverflow.com/a/65611908
tagged with: arrays
tagged with: python
score: -1
type: AnsweredQuestion
downvote count: 2
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/87932690
has comment: http://stackoverflow.com/comment/87932360
has comment: http://stackoverflow.com/comment/87933135
has title: Split 2D NumPy array of strings on "," character
tagged with: string
has answer: http://stackoverflow.com/a/50460022
has comment: http://stackoverflow.com/comment/87932776

http://stackoverflow.com/comment/92662435
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50438924
has text: @ThisGuyCantEven Please provide input in order not to confuse future readers
score: 0

http://stackoverflow.com/q/50474524
tagged with: python
has answer: http://stackoverflow.com/a/50474726
tagged with: lstm
type: Question
score: 2
has body: I'm trying to use Keras to train a LSTM recursive neural network capable of predicting the next note played by receiving a sequence of notes. Basically my dataset is something like this and I want my model to predict the fifth note played: Note1 Note2 Note3 Note4 | Note5 1 [A,2,#] [B,3,b] [C,4,#] [A,2,b] | [B,3,b] 2 [B,2,#] [B,2,b] [B,5,#] [A,2,#] | [A,3,#] 3 [C,2,#] [B,5,#] [A,4,#] [A,1,#] | [A,8,b] ... Each note is an array of 3 features and all of them are categorical. I'm struggling to understand how I can feed the neural network with this information, so any help with code about how to process the data or network architecture is welcome. Thanks in advance.
upvote count: 3
answer count: 1
tagged with: neural-network
accepted answer: http://stackoverflow.com/a/50474726
tagged with: keras
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
has title: How to use LSTM neural network with 3D categorical input and output?

http://stackoverflow.com/a/50476236
answers question: http://stackoverflow.com/q/50476198
type: AcceptedAnswer
has body: pd.DataFrame([[i] for i in np.array([[1,2,3],[4,5,6],[7,8,9]])])
downvote count: 1
score: 3
accepted answer of: http://stackoverflow.com/q/50476198
type: Answer
upvote count: 4

http://stackoverflow.com/q/50501829
has body: Stack Members, I am very new to this site, please bear with me for my question and the format :) I have two files - one CSV and one Excel(From here i have to search) CSV looks like below: aips process port 111.230.36.78 qmt 234 "169.254.95.120 10.96.9.10 " qwe 890 12.4.5.2.4 mnb 987 89.56.7.8.1 hbgs abc Excel Looks Like Address code 12.4.5.2.4 LMN 111.230.36.78 PQR "16.24.15.120 100.6.9.10" XYZ 110.20.7.200 sqm I want out put like below. In short I want to search for code in excel file through aips(in csv) and Address(in excel)- both are ip's and then add the found code in the csv file. aips service port code 111.230.36.78 qmt 234 PQR "169.254.95.120 10.96.9.10" qwe 890 XYZ 12.4.5.2.4 mnb 987 LMN 89.56.7.8.1 hbgs 7876 NA I am trying to write python code for this but not able to recall how can I apply vlookup here. Can any one help me with the code. I want to read it and understand. If I get this I can apply with my modification as required. This is just a dummy process I want to learn please. I have read other stack questions and solution but not able to get it correctly.I have seen pandas library but very new to it not able to implement it. When doing df1['code'] = df1['aips'].map(df2.set_index('Address')['code']) getting below error base.py", line 2684, in get_indexer raise InvalidIndexError('Reindexing only valid with uniquely' series.py", line 2309, in map indexer = arg.index.get_indexer(values) To fix index issue i tried reset instead of set in above code, bit of no use.
downvote count: 1
has comment: http://stackoverflow.com/comment/88016332
has comment: http://stackoverflow.com/comment/88016248
has comment: http://stackoverflow.com/comment/88022305
favorite count: 0
tagged with: excel
has comment: http://stackoverflow.com/comment/88016040
has comment: http://stackoverflow.com/comment/88028109
has comment: http://stackoverflow.com/comment/88022754
has comment: http://stackoverflow.com/comment/88016284
has comment: http://stackoverflow.com/comment/88031568
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88031388
has comment: http://stackoverflow.com/comment/88022846
score: 1
has comment: http://stackoverflow.com/comment/88022343
tagged with: python
has comment: http://stackoverflow.com/comment/88021395
has comment: http://stackoverflow.com/comment/88022959
has comment: http://stackoverflow.com/comment/88016328
has comment: http://stackoverflow.com/comment/88018800
linked to: http://stackoverflow.com/q/43909479
type: Question
has comment: http://stackoverflow.com/comment/88031544
upvote count: 2
has title: Search Data between excel and csv file python- its like vlookup
has comment: http://stackoverflow.com/comment/88031525
has comment: http://stackoverflow.com/comment/88030894
answer count: 0
tagged with: pandas
tagged with: vlookup
duplicate of: http://stackoverflow.com/q/43909479
type: UnansweredQuestion

http://stackoverflow.com/a/50443308
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50443257
has body: You can use zip. dicto = [{100: 1, 90: 2, 80: 3, 70: 4}, {100: 1, 90: 2, 80: 3}, {105: 1, 100: 2, 90: 3, 80: 4}] listo = [70,80,105] track = [] for key, d in zip(listo, dicto): try: track.append(d[key]) except KeyError: pass print(track) # [4, 3, 1] If you want None as the value if the key is missing, you can use this: track = [d.get(key) for key, d in zip(listo, dicto)]
answers question: http://stackoverflow.com/q/50443257
type: Answer
upvote count: 3

http://stackoverflow.com/q/50397442
score: 0
has comment: http://stackoverflow.com/comment/87811038
has answer: http://stackoverflow.com/a/50397778
answer count: 1
has title: Python: Finding a bipartite graph by DFS
has body: I'm trying to transform DFS programme to check if graph is bipartite. I want to go through the path and send visited nodes to different subsets as far as they aren't adjacent. For example: if path would look like this: 1->2->3->4->5 Two subsets should look like this: [1,3,5] [2,4] And here is DFS code: def dfs(x, node, visited): if node not in visited: visited.append(node) for n in x[node]: dfs(x,n, visited) return visited
tagged with: bipartite
type: Question
tagged with: graph
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87811645
tagged with: python
tagged with: depth-first-search
tagged with: adjacency-matrix

http://stackoverflow.com/q/50424524
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87864282
has answer: http://stackoverflow.com/a/50424683
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50424914
has comment: http://stackoverflow.com/comment/87864428
has title: Django: Cannot import name 'model'
has comment: http://stackoverflow.com/comment/87864207
has comment: http://stackoverflow.com/comment/87864134
tagged with: django
accepted answer: http://stackoverflow.com/a/50425762
tagged with: python
has comment: http://stackoverflow.com/comment/87864169
has comment: http://stackoverflow.com/comment/87864105
has answer: http://stackoverflow.com/a/50425762
linked to: http://stackoverflow.com/q/21142366
has comment: http://stackoverflow.com/comment/87864126
has comment: http://stackoverflow.com/comment/87865021
has body: So I am a student and I am trying to build a small shop using Django, so when I run the project on my laptop it works as expected but when I upload it to the server I got this error cannot import name 'CustomerOrderModel' views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from HomePage.models import Product from HomePage.forms import Customer from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger #other functions def customer_order_view(request, pk): product = get_object_or_404(Product, id=pk) form = Customer(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.customer_product_name = product instance.save() messages.success(request, "Success \n we will contact you soon") context = {'form': form, 'product': product} return render(request, 'HomePage/customerDetail.html', context) forms.py from django import forms from HomePage.models import CustomerOrderModel #the error in this line class Customer(forms.ModelForm): class Meta: model = CustomerOrderModel fields = [# some fields] url.py from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from HomePage.views import index_view, GiftView, FlowerView, BalloonView, detail_view, customer_order_view app__name = 'HomePage' urlpatterns = [ url(r'^$', index_view, name='index'), url(r'^gift/$', GiftView.as_view(), name='gift'), url(r'^flower/$', FlowerView.as_view(), name='flower'), url(r'^balloon/$', BalloonView.as_view(), name='balloon'), url(r'^(?P&lt;pk&gt;[0-9]+)/$', detail_view, name='detail'), url(r'^(?P&lt;pk&gt;[0-9]+)/order/$', customer_order_view, name='product_form'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) admin.py from django.contrib import admin from HomePage.models import Product, CustomerOrderModel #some code models.py from django.db import models from django.core.validators import RegexValidator #som…
has comment: http://stackoverflow.com/comment/87864663
answer count: 3
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/87864268
has comment: http://stackoverflow.com/comment/87864014
possible better answer: http://stackoverflow.com/a/50424683
has comment: http://stackoverflow.com/comment/87863876
downvote count: 1
has comment: http://stackoverflow.com/comment/87864205

http://stackoverflow.com/comment/87957751
type: QuestionComment
comment on: http://stackoverflow.com/q/50471326
score: 0
type: Comment
has text: This is the end of the code for now because this is the most important part and it is still not working. I tried the next code but it did not work: process = subprocess.Popen(...) process.wait()

http://stackoverflow.com/comment/87979983
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50479318
has text: @PaulCornelius fixed.
type: Comment

http://stackoverflow.com/a/50516268
has body: You have define your variables. column_to_add = 'secure_id' column_to_check = 'device_model' Your function will be like here def new_column(df, list, column_to_add, column_to_check): df1 = df.withColumn(column_to_add, when(df[column_to_check].isin(list), "Y").otherwise('N')) return df1 Then invoke your function like newer_df = new_column(df, list, column_to_add, column_to_check) Then you won't get any errors
type: Answer
accepted answer of: http://stackoverflow.com/q/50515267
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50515267

http://stackoverflow.com/q/50409919
type: Question
has body: I'm using pymysql to connect to a local MySQL installation. I've made a connection as shown below, but my question is about the return value from the execute() call on the last line. The documentation says the return value of the execute method is equal to the number of rows affected. I know the database table has exactly 205299 rows, so would anyone be able to tell me why I'm seeing the much larger number of 18446744073709551615? &gt;&gt;&gt; import pymysql &gt;&gt;&gt; conn = pymysql.connect( ... host='localhost', ... port=3306, ... user='username', ... passwd='password', ... db='dbname', ... cursorclass = pymysql.cursors.SSCursor ... ) &gt;&gt;&gt; cursor = conn.cursor() &gt;&gt;&gt; cursor.execute("SELECT support_id FROM tablename") 18446744073709551615
score: 0
has answer: http://stackoverflow.com/a/50503679
tagged with: python
tagged with: mysql
type: UnansweredQuestion
answer count: 1
tagged with: pymysql
has title: Pymysql execute() - return value is not equal to the number of affected rows

http://stackoverflow.com/comment/88110623
score: 1
type: Comment
has text: Adding aspect='auto', then changing extent to be equal dimensions seems to do the trick.
type: AnswerComment
comment on: http://stackoverflow.com/a/50545446

http://stackoverflow.com/comment/87842612
score: 0
has text: can you post the URL of the website that you are trying or the HTML code?
comment on: http://stackoverflow.com/q/50413206
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87859989
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50422593
has text: You never instantiate your class.

http://stackoverflow.com/comment/87915425
has text: If there is not always a `'pagination'` key in the top-level object you need to code defensively. Use exception handling or `dict.get()` and then testing if `None` was returned instead, etc.
type: QuestionComment
comment on: http://stackoverflow.com/q/50451087
score: 1
type: Comment

http://stackoverflow.com/comment/87959457
score: 0
type: Comment
type: QuestionComment
has text: Why do you also say that `np.concatenate()` **to no surprise** did not work? _I am_ surprised!
comment on: http://stackoverflow.com/q/50472775

http://stackoverflow.com/a/50502463
upvote count: 3
score: 3
has body: From pycharm, GoTo File -> Settings You will get a pop-up window of settings. Select the plugins then click on Browse repositories at the bottom. Then you will get the pop-up window of Browse repositories, search for Source synchronizer. Then click on Install to install that plugin for scp, ftp ... Restart the pycharm Now you can make use of it to do scp
type: Answer
answers question: http://stackoverflow.com/q/50498721
downvote count: 0

http://stackoverflow.com/q/50409440
tagged with: excel
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50424159
possible better answer: http://stackoverflow.com/a/50424159
tagged with: win32com
tagged with: python
has comment: http://stackoverflow.com/comment/87834057
has body: I'm using Python 3.5 and win32com to insert an object (.pdf file) into excel with the following method: Embedded_object.Add(ClassType=None, Filename=file_loction, Link=False, DisplayAsIcon=True, Left=3, Top=0, Width=50, Height=50) This works fine, however it always embeds the object in the A1 cell, is there a way to embed the object into a specific row and column using the above method? Edit: I also tried the following: worksheet.Range('A1:A1').Copy() worksheet.Paste(Destination=worksheet.Range('C2:C2')) It puts the object in a specific cell, but also what's behind the object in A1:A1, so it's not really a solution yet
has comment: http://stackoverflow.com/comment/87862463
has answer: http://stackoverflow.com/a/50425533
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50425533
answer count: 2
upvote count: 2
downvote count: 0
has title: Python: Insert object into excel in a specific row and column with win32com

http://stackoverflow.com/q/50439309
has body: Using Windows 10 with Spyder IDE running Python 3.5. I am seeing following in the __init__.py file complaining about unable to detect undefined names: However, it seems __init__.py file is in the same folders as all other files. So why it is complaining? I tried to remove the leading dot in the front, but it still complains. Please give me some pointers.
score: 9
type: Question
upvote count: 9
tagged with: spyder
has answer: http://stackoverflow.com/a/55503878
tagged with: python
has title: Spyder IDE complaining about unable to detect undefined names
has comment: http://stackoverflow.com/comment/87892865
tagged with: python-import
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/55503878
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50439398
tagged with: import
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50439398

http://stackoverflow.com/a/50464997
answers question: http://stackoverflow.com/q/50464010
has body: You need to convert the indices to full indices, and using gather_nd. Can be achieved by doing: result = tf.squeeze(tf.gather_nd(x,tf.stack([tf.range(indices.shape[0])[...,tf.newaxis], indices[...,tf.newaxis]], axis=2)))
accepted answer of: http://stackoverflow.com/q/50464010
type: AcceptedAnswer
type: Answer
downvote count: 1
score: 2
upvote count: 3

http://stackoverflow.com/q/50472476
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/5844672
has comment: http://stackoverflow.com/comment/87959269
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50473451
has comment: http://stackoverflow.com/comment/87958543
has answer: http://stackoverflow.com/a/50473451
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87958592
has body: Suppose a dictionary is: sd = {'q':1,'w':2,'e':4} i know we can delete a pair though deleting respective key? but can we just delete a value? i got this question in a interview thats why i asked here.
has title: Can we delete or remove a value of any key in dictionary?
has comment: http://stackoverflow.com/comment/87958660
has comment: http://stackoverflow.com/comment/87958560
answer count: 1

http://stackoverflow.com/a/50474539
score: 0
answers question: http://stackoverflow.com/q/50474426
has body: You can use eval() as it treats string as code. a = '5 + 6' eval(a)
type: Answer

http://stackoverflow.com/a/50418378
type: Answer
has comment: http://stackoverflow.com/comment/88006860
has body: Welcome to stackoverflow, your question can be split into several steps: Step 1 - read the data I have stored your data in a file called data.txt. I don't know Pandas very well but this can also be handled with the nice simple function of Numpy called loadtxt. Your data is a bit problematic because of the text 'Distance' value in the first column and first row. But don't panic we load the file as a matrix of strings: raw_data = np.loadtxt('data.txt', delimiter=';', dtype=np.string_) Step 2 - transform the raw data To extract the wanted data from the raw data we can do the following: angle = raw_data[0 , 1:].astype(float) distance = raw_data[1:, 0 ].astype(float) data = raw_data[1:, 1:].astype(float) With indexing the raw data we select the data that we want and with astype we change the string values to numbers. Intermediate step - making the data a bit fancier Your data was a bit boring, only the value -45, i took the liberty to make it a bit fancier: data = (50 + angle[np.newaxis,:]) / (10 + np.sqrt(distance[:,np.newaxis])) Step 4 - make a wireframe plot The example at matplotlib.org looks easy enough: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(X, Y, Z) plt.show() But the trick is to get the X, Y, Z parameters right... Step 3 - make the X and Y data The Z data is simply our data values: Z = data The X and Y should also be 2D array's such that plot_wireframe can find the x and y for each value of Z in the 2D arrays X an Y at the same array locations. There is a Numpy function to create these 2D array's: X, Y = np.meshgrid(angle, distance) Step 5 - fancing it up a bit ax.set_xticks(angle) ax.set_yticks(distance[::2]) ax.set_xlabel('angle') ax.set_ylabel('distance') Putting it together All steps together in the right order: # necessary includes... from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np raw_data = np.loadtxt('data.txt', delimiter=';', dtype=np.string_) angle = raw_data[0 , 1:].ast…
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87855321
answers question: http://stackoverflow.com/q/50415667

http://stackoverflow.com/comment/87999319
type: QuestionComment
comment on: http://stackoverflow.com/q/50483687
has text: Like I've mentioned before, you could learn how to use kivy's [`Clock`](https://kivy.org/docs/api-kivy.clock.html) and attempt to scan a tag every n seconds, for example every 0.01 seconds, in which case you would also need to check if a given barcode was already scanned, to avoid having the same barcode scanned many times. This will behave like a while loop without stopping your code. However, a new problem will appear if your scanning function is noticeably slow.
score: 0
type: Comment

http://stackoverflow.com/comment/87911773
comment on: http://stackoverflow.com/q/50439908
type: QuestionComment
score: 0
has text: The memoryviews in my real program are only 3 x 5 bytes for each set, so I may as well copy them--it's just that there could be zero to millions of those sets in my top level (arbitrarily long) array.
type: Comment

http://stackoverflow.com/comment/87832121
type: QuestionComment
has text: Do you have to use a regex?
type: Comment
comment on: http://stackoverflow.com/q/50408357
score: 0

http://stackoverflow.com/q/50416416
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/94830253
type: Question
tagged with: opencv
type: UnansweredQuestion
has title: Python-opencv import error, packages installed
has answer: http://stackoverflow.com/a/50416794
tagged with: python
score: 1
has body: I've installed opencv as said here: https://docs.opencv.org/3.4/d2/de6/tutorial_py_setup_in_ubuntu.html --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-2-5c56e811bdd3&gt; in &lt;module&gt;() 11 12 import os ---&gt; 13 import cv2 14 import sys 15 import copy /jet/var/python/lib/python3.6/site-packages/cv2/__init__.py in &lt;module&gt;() 1 import importlib 2 ----&gt; 3 from .cv2 import * 4 from .data import * 5 ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory already done: sudo apt-get install libglib2.0-0:amd64 sudo apt-get update sudo apt-get install libgtk2.0-dev !apt-get update !apt-get -y upgrade !pip install opencv-python !apt-get install libgtk2.0-dev -y !apt-get install python-opencv -y --allow-unauthenticated

http://stackoverflow.com/comment/87965174
has text: You might find this answer useful: https://stackoverflow.com/questions/39137597/how-to-restore-variables-using-checkpointreader-in-tensorflow/39142780#39142780
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50457943

http://stackoverflow.com/comment/87853525
has text: @deceze That won't work. `B.C` and `B.D` are completely different, with completely different iteration methods and one `__slots__` etc. Is there a way for B to control how `B.C` and `B.D` are being created?
comment on: http://stackoverflow.com/q/50418785
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50535102
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/50535243
favorite count: 0
type: Question
tagged with: ctypes
has answer: http://stackoverflow.com/a/50535243
has title: No sound is generated when using PlaySound()
tagged with: playsound
has comment: http://stackoverflow.com/comment/88082311
has body: Basically I want to use the PlaySound() function in ctypes. Yes I know winsound module is built on it and I could use that, but I have a reason to not do so :) In C I would call the function like this: PlaySound("sound.wav", NULL, SND_FILENAME); I have my Python script equivalent: import ctypes winmm = ctypes.WinDLL('winmm.dll') winmm.PlaySound("sound.wav", None, 0x20000) I run it, no error is returned but the sound does not play either. I suspect that the problem lies with the hex value (0x20000) since everything else seems fine. I got this value like this: import winsound print(hex(winsound.SND_FILENAME)) Or in a different way: import ctypes, winsound winmm = ctypes.WinDLL('winmm.dll') winmm.PlaySound("sound.wav", None, winsound.SND_FILENAME) So how can I get this working so that my file plays?
tagged with: windows
tagged with: python
accepted answer: http://stackoverflow.com/a/50538283
has comment: http://stackoverflow.com/comment/88082919
has answer: http://stackoverflow.com/a/50538283
type: AnsweredQuestion
answer count: 2
score: 1

http://stackoverflow.com/q/50453121
answer count: 1
has body: I am going through the code of python logging module both in Python2(2.7.12 default on Ubuntu 16.04) and Pyton 3.5 (3.5.2 default on Ubuntu 16.04). The question is - if we look at the implementation of def _log that eventually calls self.handle, the check about self.disabled is done actually made in the handle method, but it's not done in the _log method. Agree, checking it again in self.handle might make sense, but why not check it first thing in self._log or even better in self.isEnabledFor that avoids doing a lot of work that is done in self._log method. What is it that I am missing? Update: Did some profiling when logger is disabled - The code is in the following gist. Following gists have the actual cprofile data indicating performance impact when the logger is disabled and when the logger is enabled. It appears, there's considerable performance impact when the logger is disabled. May be it is worth considering?
has comment: http://stackoverflow.com/comment/87963479
tagged with: logging
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88316310
has comment: http://stackoverflow.com/comment/87959207
has title: logger.disabled check much later in python logging module. What's the rationale?
has comment: http://stackoverflow.com/comment/87963341
tagged with: python
has comment: http://stackoverflow.com/comment/87970656
has comment: http://stackoverflow.com/comment/87955017
has comment: http://stackoverflow.com/comment/88286603
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50652837
has comment: http://stackoverflow.com/comment/87958070
accepted answer: http://stackoverflow.com/a/50652837

http://stackoverflow.com/a/50533219
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88079049
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50533072
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50533072
has body: Indeed your code does not work, and it is due to the line SL[:] = []: it changes the content of the list referenced by SL. By doing this, you change all the elements of L, because you always append the list referenced by SL to L in the loop. Replacing with SL = [] will fix the problem, because in this case you create a new list without overwriting the previous one. It could be fixed, and also be more readable and easier to debug (if needed) with the following suggestion: L = [] for i in range(0, x + 1): for j in range(0, y + 1): for k in range(0, z + 1): if i + j != n and i + k != n and k + j != n and i + j + k != n: L.append([i, j, k]) print(L) With x=1, y=2, z=3, n=4: it gives me the following output: [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 2, 3], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 2, 0]]
has comment: http://stackoverflow.com/comment/88078834
has comment: http://stackoverflow.com/comment/88078487

http://stackoverflow.com/q/50516006
accepted answer: http://stackoverflow.com/a/50516206
type: AnsweredQuestion
score: 0
tagged with: wagtail
answer count: 1
tagged with: django
has body: I'm fairly new to wagtail so please excuse any glaring mistakes. I'm attempting to create a new page type called PortfolioItemPage. I am getting the following error when trying to use runserver, makemigrations or migrate: Unhandled exception in thread started by &lt;function check_errors. &lt;locals&gt;.wrapper at 0x10900f048&gt; Traceback (most recent call last): File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/db/models/options.py", line 566, in get_field return self.fields_map[field_name] KeyError: 'project_title' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/checks.py", line 62, in get_form_class_check edit_handler = cls.get_edit_handler() File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/utils/decorators.py", line 53, in __call__ return self.value File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[s…
type: Question
has title: Wagtail "has no field name"
tagged with: python
has answer: http://stackoverflow.com/a/50516206

http://stackoverflow.com/comment/87920814
type: QuestionComment
score: 0
has text: yes but i can't figure out which value to give to the 'value' param, i see that value=1 replace all my '\N' to 1 but i want dynamic values compared to the other column
type: Comment
comment on: http://stackoverflow.com/q/50453503

http://stackoverflow.com/q/50397818
has comment: http://stackoverflow.com/comment/87811972
has comment: http://stackoverflow.com/comment/87812247
has comment: http://stackoverflow.com/comment/87811401
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87811442
tagged with: python
tagged with: psycopg2
linked to: http://stackoverflow.com/q/43767658
has comment: http://stackoverflow.com/comment/87811419
has comment: http://stackoverflow.com/comment/87811887
has body: I'm trying to connect to a postgres database with psycopg2: def get_posts(): db = psycopg2.connect(database=DBNAME) c = db.cursor() Which returns: File "/vagrant/forum/solution/forumdb_solved.py", line 9, in get_posts db = psycopg2.connect(database=DBNAME) AttributeError: 'module' object has no attribute 'connect' I have researched other solutions to this problem (Psycopg2: 'module' object has no attribute 'connect'). None of my folder/file structure contains psycopg2 though. The other issue which seems to come up is read/write privileges of the folder in which psycopg2 is installed. I have psycopg2 installed in multiple locations (don't ask!) and not sure how to check this. Any help would be appreciated by a total newbie.
score: 0
has comment: http://stackoverflow.com/comment/87811534
answer count: 0
has comment: http://stackoverflow.com/comment/87812750
has comment: http://stackoverflow.com/comment/87811929
has comment: http://stackoverflow.com/comment/87813218
has comment: http://stackoverflow.com/comment/87812220
has comment: http://stackoverflow.com/comment/87813561
has comment: http://stackoverflow.com/comment/87811323
has comment: http://stackoverflow.com/comment/87812691
type: Question
has title: Psycopg2: module object has no attribute 'connect'
has comment: http://stackoverflow.com/comment/87811451

http://stackoverflow.com/q/50482527
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50482592
possible better answer: http://stackoverflow.com/a/50482592
tagged with: list
upvote count: 1
accepted answer: http://stackoverflow.com/a/50482629
downvote count: 2
tagged with: selenium
has comment: http://stackoverflow.com/comment/87978296
has answer: http://stackoverflow.com/a/50482628
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/50482629
has body: In the below code I'm extracting emails id and storing in the list in python chrome_driver_path = os.path.abspath('..') + "\\Drivers\\chromedriver.exe" driver=webdriver.Chrome(chrome_driver_path) driver.maximize_window() driver.get("http://www.airindia.in/contact-details.htm") driver.implicitly_wait(3) doc = driver.page_source emails = re.findall(r'[\w\.-]+@[\w\.-]+', doc) list_new = [] for email in emails: list_new.extend(str(email)) #print(email) print("total emails - ",len(list_new)) driver.quit() print(list_new) but getting the output as ['c', 'a', 'l', 'l', '.', 'd', 'e', 'l', '@', 'a', 'i', 'r', 'i', 'n'] I need output as ['call.del@airindia.in','airindiaretros.ai@iclployalty.com'] I'm new to selenium python sample code with my console output https://github.com/venkywarriors619/selenium_with_python/blob/master/Python_basics/SeleniumWebDriver_Advanced/RegularExpression.py
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/252703
has answer: http://stackoverflow.com/a/50482698
has answer: http://stackoverflow.com/a/50482676
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/87978115
has title: how to add web element into list in python

http://stackoverflow.com/comment/87794903
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50385640
has text: You might want to look at [this](https://www.pyimagesearch.com/2016/02/22/writing-to-video-with-opencv/).

http://stackoverflow.com/q/50387243
has comment: http://stackoverflow.com/comment/87795573
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87794936
type: UnansweredQuestion
has title: sparse to dense einsum in tensorflow
tagged with: python
has body: Is there a way to perform actions efficiently on sparse matrices when I have complicated operations? (actually I am not even sure how can my example be simplified to anything without slicing) In the example I try to multiple inputs coming in a batch (b) with a complex kernel vector that is different for each example in the batch (as it was constructed by weights multiplied by another input). The inputs are dense, the kernel is sparse. Example: outputs = special_math_ops.einsum("bi,bnilo-&gt;bnlo", x, kernel)
score: 2
tagged with: performance
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/87907461
comment on: http://stackoverflow.com/a/50437287
type: Comment
has text: It would be wrong to say that. Benefits of forking the app are mentioned in the docs - [classes-are-loaded-dynamically](http://django-oscar.readthedocs.io/en/releases-1.6/internals/design-decisions.html#classes-are-loaded-dynamically) and [why so](http://django-oscar.readthedocs.io/en/releases-1.6/topics/class_loading_explained.html#why). In short, it's mostly to avoid duplication, ease of maintenance and upgrading with latest changes.
type: AnswerComment
score: 0

http://stackoverflow.com/a/58333782
answers question: http://stackoverflow.com/q/50504590
upvote count: 0
downvote count: 1
has body: ip_list = ['input{}'.format(i) for i in range(1,10)] for item in ip_list[3:]: print(item)
type: Answer
score: -1

http://stackoverflow.com/q/50441576
score: 3
has comment: http://stackoverflow.com/comment/87897680
has comment: http://stackoverflow.com/comment/87899035
has comment: http://stackoverflow.com/comment/87898984
has comment: http://stackoverflow.com/comment/87898766
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87897386
has answer: http://stackoverflow.com/a/50441641
has comment: http://stackoverflow.com/comment/87898175
type: AnsweredQuestion
has body: I ran into this problem when I was trying to make sure some properties of data frame's view. Suppose I have a dataframe defined as: df = pd.DataFrame(columns=list('abc'), data=np.arange(18).reshape(6, 3)) and a view of this dataframe defined as: df1 = df.iloc[:3, :]. We now have two dataframes as following: print(df) a b c 0 0 1 2 1 3 4 5 2 6 7 8 3 9 10 11 4 12 13 14 5 15 16 17 print(df1) a b c 0 0 1 2 1 3 4 5 2 6 7 8 Now I want to output the id of a particular cell of these two dataframes: print(id(df.loc[0, 'a'])) print(id(df1.loc[0, 'a'])) and I have the output as: 140114943491408 140114943491408 The weird thing is, if I continuously execute those two lines of 'print id' code, the ids change as well: 140114943491480 140114943491480 I have to emphasize that I did not execute the 'df definition' code when I execute those two 'print id' code, so the df and df1 are not redefined. Then, in my opinion, the memory address of each element in the data frame should be fixed, so how could the output changes? A more weird thing happens when I keep executing those two lines of 'print id' codes. In some rare scenarios, those two ids even do not equal to each other: 140114943181088 140114943181112 But if I execute id(df.loc[0, 'a']) == id(df1.loc[0, 'a']) at the same time, python still output True. I know that since df1 is a view of df, their cells should share one memory, but how come the output of their ids could be different occasionally? Those strange behaviors make me totally at lost. Could anyone explain those behaviors? Are they due to the characteristics of data frame or the id function in python? Thanks! FYI, I am using Python 3.5.2.
tagged with: pandas
has comment: http://stackoverflow.com/comment/87897608
upvote count: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50441641
linked to: http://stackoverflow.com/q/20753364
linked to: http://stackoverflow.com/q/47972633
has title: Why id of a pandas dataframe cell changes with each execution?
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87816252
type: QuestionComment
has text: My guess is that you need to add a wait. Wait until all the elements that match your locator are visible and you will probably be good. You can also simplify your locator to use a CSS selector, `span.text` and you won't need the nested `.find_element_*`... just print `each.text`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50399540

http://stackoverflow.com/comment/87905145
type: Comment
has text: I executed for p in psutil.process_iter() code to list the processes running. But how to find the process that has handle open to my file?
comment on: http://stackoverflow.com/a/50405554
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87981866
has text: Check the job information to see what the actual error is...if you have the job ID, use the `bq` command-line line and run `bq show -j <job_id>`. You can also use `bq ls -j` to list recent jobs. There is a way to see the loading errors from the Python client, too, but I don't know where to look off the top of my head.
comment on: http://stackoverflow.com/a/50483783
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50509949
type: Question
tagged with: rest
tagged with: klein-mvc
has answer: http://stackoverflow.com/a/50510409
has answer: http://stackoverflow.com/a/55631531
downvote count: 1
tagged with: python
score: -1
upvote count: 0
answer count: 2
type: UnansweredQuestion
has body: I am using Klein to develop REST endpoints. (similar to Python Flask) I am interested in how can I pass parameters to the HTML file I want to serve, if that is even possible. from twisted.web.static import File from klein import Klein app = Klein() @app.route('/', branch=True) def pg_index(request): return File('./') app.run("localhost", 8080)
has title: How to send parameters to html file I am serving through Klein(Flask) application?
tagged with: flask
favorite count: 0

http://stackoverflow.com/q/50389840
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87795510
tagged with: python
has body: I'm new in python, I was looking into a code which is similar to as follows, import numpy as np a = np.ones([1,1,5,5], dtype='int64') b = np.ones([11], dtype='float64') x = b[a] print (x.shape) # (1, 1, 5, 5) I looked into the python numpy documentation I didn't find anything related to such case. I'm not sure what's going on here and I don't know where to look. Edit The actual code def gausslabel(length=180, stride=2): gaussian_pdf = signal.gaussian(length+1, 3) label = np.reshape(np.arange(stride/2, length, stride), [1,1,-1,1]) y = np.reshape(np.arange(stride/2, length, stride), [1,1,1,-1]) delta = np.array(np.abs(label - y), dtype=int) delta = np.minimum(delta, length-delta)+length/2 return gaussian_pdf[delta]
has comment: http://stackoverflow.com/comment/87795363
type: AnsweredQuestion
score: 0
has title: Python numpy indexing confusion
answer count: 1
accepted answer: http://stackoverflow.com/a/50389989
upvote count: 1
has comment: http://stackoverflow.com/comment/87795407
has answer: http://stackoverflow.com/a/50389989
downvote count: 1

http://stackoverflow.com/comment/87874748
score: 0
type: AnswerComment
has text: I see, thank you! Would there be a way to correct what I have (as in evaluating char.isalpha() to true or false and doing it that way)?
comment on: http://stackoverflow.com/a/50430062
type: Comment

http://stackoverflow.com/q/50442423
has comment: http://stackoverflow.com/comment/87898990
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87899285
has comment: http://stackoverflow.com/comment/87899103
type: Question
has answer: http://stackoverflow.com/a/50443107
has answer: http://stackoverflow.com/a/50442877
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87898927
has comment: http://stackoverflow.com/comment/87898851
has comment: http://stackoverflow.com/comment/87898997
has comment: http://stackoverflow.com/comment/87898987
has comment: http://stackoverflow.com/comment/87899126
upvote count: 2
score: 0
has body: Im trying to pass a dict (as a string) as an argument to a python script. when i run it from terminal I get an error not enough values to unpack (expected 2, got 1) From terminal this I run : python3 "./cleanuplogs.py" --dict='{"a":["anv", "huj"], "s":["dc", "dc"]}' Could someone be able to help me fix this error. Below is the python script import argparse import subprocess as sp import json def main(): parser = argparse.ArgumentParser() parser.add_argument('--dict', help='Directory and Files', required=True, type=str) args = parser.parse_args() try: for folder, files in json.loads(args.dict): for file in files: sp.call(["rm -r", folder+file]) except Exception as e: print (e) if __name__ == '__main__': main()
answer count: 2
downvote count: 2
has title: not enough values to unpack (expected 2, got 1) when I use argparse
favorite count: 0

http://stackoverflow.com/comment/87930613
has text: Welcome to Stack Overflow! Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
score: 3
comment on: http://stackoverflow.com/q/50458566
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50529839
accepted answer: http://stackoverflow.com/a/50530075
tagged with: django
tagged with: python
has body: In my forms.py I have this field below that returns 2 records, but it displays 3 records on my screen. I don't want the first one "---------". tipopagamento = forms.ModelChoiceField(widget=forms.RadioSelect(), queryset=tipopagamento.objects.all(), required=True) My screen displays:
type: AnsweredQuestion
upvote count: 1
tagged with: radio-button
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50530075
has title: Remove "---------" from model choice field with radio select widget
tagged with: django-forms
favorite count: 0
type: Question
tagged with: django-templates
downvote count: 0

http://stackoverflow.com/q/50436171
upvote count: 6
has comment: http://stackoverflow.com/comment/87886579
tagged with: python
has comment: http://stackoverflow.com/comment/87887268
has comment: http://stackoverflow.com/comment/87887095
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50436813
answer count: 2
has comment: http://stackoverflow.com/comment/87886537
tagged with: setuptools
downvote count: 1
tagged with: pip
has title: not able to update my package on pypi.org
tagged with: pypi
favorite count: 0
has comment: http://stackoverflow.com/comment/87888978
type: Question
possible better answer: http://stackoverflow.com/a/53320214
has comment: http://stackoverflow.com/comment/87886974
has answer: http://stackoverflow.com/a/50436813
has comment: http://stackoverflow.com/comment/87886621
score: 5
tagged with: twine
has answer: http://stackoverflow.com/a/53320214
has body: I have made changes to package I had submitted long time back in 2015 now today I added support markdown on pypi and updated setup.py to support pip version 10, however now I am facing a strange problem: If I run this command python setup.py sdist upload -r http://pypi.org Password: # I enter the password Submitting dist/maildiff-1.2.1.tar.gz to http://pypi.org Server response (200): OK but on pypi its not updated. The strange part is even if I enter wrong password I get the message Submitting dist/maildiff-1.2.1.tar.gz to http://pypi.org Server response (200): OK

http://stackoverflow.com/comment/88050466
has text: @Aran-Fey While I do agree that it's probably too clever, I do find it very readable once it's broken into multiple lines like i have shown.
score: 0
comment on: http://stackoverflow.com/q/50518761
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88100785
has text: @barny The truth is I tried a few ways and gave up after getting lost. But I'll share what I have after trying at this problem again this afternoon.
comment on: http://stackoverflow.com/q/50539692
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50426466
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87867533
has comment: http://stackoverflow.com/comment/87867610
has comment: http://stackoverflow.com/comment/87867637
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87867633
answers question: http://stackoverflow.com/q/50426390
has comment: http://stackoverflow.com/comment/87867619
has comment: http://stackoverflow.com/comment/87867675
accepted answer of: http://stackoverflow.com/q/50426390
has body: You're looking for the get_parent() method: print(self.label.get_parent())

http://stackoverflow.com/q/50532073
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: Sort, rank, groupby and sum combined -> Python pandas
upvote count: 1
tagged with: sorting
favorite count: 0
type: Question
tagged with: pandas
score: 1
tagged with: grouping
tagged with: python
has body: I have a pandas dataframe with paragraph pairs. There are around 500 paragraphs and each is listed as a pair in the following format (sorted by paragraphA and ranked by highest prediction): ParagraphA | paragraphB | label | prediction Paragraph1 | Pragraph2 | 1 ----| 0.9890 Paragraph1 | Pragraph10 | 1 ----| 0.9870 Paragraph1 | Pragraph17 | 0 ----| 0.9860 Paragraph1 | Pragraph34 | 1 ----| 0.9820 I already sorted and grouped this (beforehand the paragraphs and predictions were in random order): sorted_grouped = df.sort_index(by=['paragraphA', 'predictions'], ascending=[True, False]) This is a ranking problem where I tried to predict the likelihood that there was a link between paragraphs. I would now like to measure precision based on the number of links that actually exist (see 'label'). How would I count the number of '1's under label for each Paragraph (under paragraphA) and also the number of times these '1's appear in the top x results? (x is based on the total number of '1's for that paragraph. If there were seven '1's, I would look at the top seven results) For my example above, let's say there are overall three '1's under label for Paragraph1, but in the top three, there are only two '1's. I would therefore like to extract that info: 1) Overall 1's = 3 2) 1's in top 3 = 2
has answer: http://stackoverflow.com/a/50532924

http://stackoverflow.com/a/50449718
downvote count: 0
score: 3
upvote count: 3
type: Answer
has body: I think you can just filter the dataframe to remove rows where score is zero. df_to_plot = df1.loc[lambda df: df['score'] == 0]
has comment: http://stackoverflow.com/comment/127908219
answers question: http://stackoverflow.com/q/50449628

http://stackoverflow.com/a/50480389
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87975392
has comment: http://stackoverflow.com/comment/87975458
has comment: http://stackoverflow.com/comment/87975305
accepted answer of: http://stackoverflow.com/q/50480354
has body: You can try like this : from collections import defaultdict v = defaultdict(list) d = {'light':4,'plane':4, 'vehicle':5} for key, value in sorted(d.items()): v[value].append(key) This will also work : k = {} for key, value in sorted(d.items()): k.setdefault(value, []).append(key) UPDATE : If you want to print it in your desired format : for i, j in v.items(): print(i,", ".join(l for l in j)) O/P will be like : 4 light, plane 5 vehicle UPDATE 2: The code to print in the desired format mentioned above is completed below: from collections import defaultdict v = defaultdict(list) d = {'light':4,'plane':4, 'vehicle':5} for key, value in sorted(d.items()): v[value].append(key) for i, j in v.items(): print(i,", ".join(l for l in j))
has comment: http://stackoverflow.com/comment/87975360
answers question: http://stackoverflow.com/q/50480354
type: Answer
downvote count: 0

http://stackoverflow.com/comment/87796519
score: 0
comment on: http://stackoverflow.com/q/50390506
has text: [sudo](https://memegenerator.net/img/instances/68579288/just-sudo-it.jpg). This is usually caused by insufficient permissions
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50408325
has comment: http://stackoverflow.com/comment/87837027
score: 1
has comment: http://stackoverflow.com/comment/87833874
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50408243
has comment: http://stackoverflow.com/comment/87905963
has body: No, unfortunately you cannot take a trained model and try to get the corresponding input. The reason for this is that you have infinite possible solutions for each output. Furthermore, backpropagation is not passing an output backwards through the network. Its the idea of determining what parameters in the model are contributing to what extent to loss function. This will not give the inputs to these hidden layers, but the extent at which the weights affected your decision.
has comment: http://stackoverflow.com/comment/87832273
type: Answer
has comment: http://stackoverflow.com/comment/87833798
has comment: http://stackoverflow.com/comment/87906202
has comment: http://stackoverflow.com/comment/87836957
has comment: http://stackoverflow.com/comment/87867043

http://stackoverflow.com/comment/87967633
comment on: http://stackoverflow.com/a/50476900
score: 1
type: Comment
type: AnswerComment
has text: @AntonvBR, The `list` conversion is intentional, [see here why](https://stackoverflow.com/a/37782238/9209546). You're right that accessing `values` is unnecessary, updated.

http://stackoverflow.com/comment/87947867
comment on: http://stackoverflow.com/q/50465122
score: 0
type: QuestionComment
type: Comment
has text: So I would implement the safe functionality first (send the file with post) and then display the image if you get a "success message"

http://stackoverflow.com/q/50491283
tagged with: python
tagged with: flask
has title: How to migrate from using Flask-JWT to PyJWT in my app?
tagged with: jwt
score: 0
has answer: http://stackoverflow.com/a/50511487
answer count: 1
tagged with: pyjwt
type: Question
has body: I want to switch from using Flask-JWT since it is no longer being updated. My problem is that I'm not sure how to achieve some of the functionality that Flask-JWT was giving me. For example: jwt = JWT(app, verify, identify) With Flask-JWT i could pass the flask app, authentication method and a identify function that does he following: def identify(payload): user_id = payload['identity'] return {"user_id": user_id} Now my main problem is that I do not fully understand what the decorator @jwt_required() does and how I could replicate it using PyJWT. So if I had the following function: class PrivateResource(Resource): @jwt_required() def get(self): return {"badge_number": 445566} How could I do the same function as @jwt_required() while using PyJWT?
type: UnansweredQuestion

http://stackoverflow.com/a/50871876
score: 4
upvote count: 4
has body: I think the use of MultiIndex overcomplicates this objective: I need to map my user and item IDs to a continuous range of integer IDs starting at 0. This solution falls in to the below category: Alternatives without MultiIndex are completely acceptable. def add_mapping(df, df2, df3, column_name='user_id'): initial = df.loc[:, column_name].unique() new = df2.loc[~df2.loc[:, column_name].isin(initial), column_name].unique() maps = np.arange(len(initial)) mapping = dict(zip(initial, maps)) maps = np.append(maps, np.arange(np.max(maps)+1, np.max(maps)+1+len(new))) total = np.append(initial, new) mapping = dict(zip(total, maps)) df3[column_name+'_map'] = df3.loc[:, column_name].map(mapping) return df3 add_mapping(df, df2, df3, column_name='item_id') add_mapping(df, df2, df3, column_name='user_id') user_id item_id rating item_id_map user_id_map 0 1 1 1.0 0 0 1 1 3 1.0 1 0 2 3 1 1.0 0 1 3 3 3 1.0 1 1 0 2 1 1.0 0 2 1 2 2 1.0 2 2 Explanation This is how to maintain a mapping for the user_id values. Same holds for the item_id values as well. These are the initial user_id values (unique): initial_users = df['user_id'].unique() # initial_users = array([1, 3]) user_map maintains a mapping for user_id values, as per your requirement: user_id_maps = np.arange(len(initial_users)) # user_id_maps = array([0, 1]) user_map = dict(zip(initial_users, user_id_maps)) # user_map = {1: 0, 3: 1} These are the new user_id values you got from df2 - ones that you didn't see in df: new_users = df2[~df2['user_id'].isin(initial_users)]['user_id'].unique() # new_users = array([2]) Now we update user_map for the total user base with the new users: user_id_maps = np.append(user_id_maps, np.arange(np.max(user_id_maps)+1, np.max(user_id_maps)+1+len(new_users))) # array([0, 1, 2]) total_users = np.append(initial_users, new_users) # array([1, 3, 2]) user_map = dict(zip(total_users, user_id_maps)) # user_map = {1: 0, 2: 2, 3: 1} Then, just map the values from user_map to df['user_id']: df3['user_map'] = df…
has comment: http://stackoverflow.com/comment/88893790
has comment: http://stackoverflow.com/comment/88746254
has comment: http://stackoverflow.com/comment/88894121
downvote count: 0
answers question: http://stackoverflow.com/q/50430404
has comment: http://stackoverflow.com/comment/88746524
has comment: http://stackoverflow.com/comment/88894522
has comment: http://stackoverflow.com/comment/88894459
has comment: http://stackoverflow.com/comment/88746471
type: Answer

http://stackoverflow.com/q/50470991
tagged with: list
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50472549
has body: Any efficient way to solve the following problem assuming data is large. I solved the problem but how can I improve the code, which will make it efficient. any suggestions? Data: movie_sub_themes = { 'Epic': ['Ben Hur', 'Gone With the Wind', 'Lawrence of Arabia'], 'Spy': ['James Bond', 'Salt', 'Mission: Impossible'], 'Superhero': ['The Dark Knight Trilogy', 'Hancock, Superman'], 'Gangster': ['Gangs of New York', 'City of God', 'Reservoir Dogs'], 'Fairy Tale': ['Maleficent', 'Into the Woods', 'Jack the Giant Killer'], 'Romantic':['Casablanca', 'The English Patient', 'A Walk to Remember'], 'Epic Fantasy': ['Lord of the Rings', 'Chronicles of Narnia', 'Beowulf']} movie_themes = { 'Action': ['Epic', 'Spy', 'Superhero'], 'Crime' : ['Gangster'], 'Fantasy' : ['Fairy Tale', 'Epic Fantasy'], 'Romance' : ['Romantic']} themes_keys = movie_themes.keys() theme_movies_keys = movie_sub_themes.keys() #Iterate in movie_themes #Check movie_themes keys in movie_sub_keys #if yes append the movie_sub_keys into the newdict newdict = {} for i in range(len(themes_keys)): a = [] for j in range(len(movie_themes[themes_keys[i]])): try: if movie_themes[themes_keys[i]][j] in theme_movies_keys: a.append(movie_sub_themes[movie_themes[themes_keys[i]][j]]) except: pass newdict[themes_keys[i]] = a # newdict contains nested lists # Program to unpack the nested list into single list # Storing the value into theme_movies_data theme_movies_data = {} for k, v in newdict.iteritems(): mylist_n = [j for i in v for j in i] theme_movies_data[k] = dict.fromkeys(mylist_n).keys() print (theme_movies_data) Output: {'Action': ['Gone With the Wind', 'Ben Hur','Hancock, Superman','Mission: Impossible','James Bond','Lawrence of Arabia','Salt','The Dark Knight Trilogy'], 'Crime': ['City of God', 'Reservoir Dogs', 'Gangs of New York'], 'Fantasy': ['Jack the Giant Killer','Beowulf','Into the Woods','Maleficent','Lord of the Rings','Chronicles of Narnia'], 'Romance': ['The English Patient', 'A Walk to Remember', 'Casabla…
has comment: http://stackoverflow.com/comment/87955481
tagged with: performance
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50472733
has comment: http://stackoverflow.com/comment/87959921
has title: How can I make the following python program(code) more efficient?
type: Question
score: 0

http://stackoverflow.com/q/50478594
tagged with: python
type: UnansweredQuestion
tagged with: flask
answer count: 1
downvote count: 1
has body: When I use gunicorn to deploy the project, I can't find the module. When I use the test environment it is normal. Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/iHome_Flask/ihome_pyhon02/manage.py", line 4, in &lt;module&gt; from flask_script import Manager ImportError: No module named flask_script [2018-05-23 09:15:46 +0000] [29933] [INFO] Worker exiting (pid: 29933) [2018-05-23 09:15:46 +0000] [29928] [INFO] Shutting down: Master [2018-05-23 09:15:46 +0000] [29928] [INFO] Reason: Worker failed to boot. (flask_py2) [root@iZbp1bvf97jli08phztpplZ ihome_pyhon02]# vim manage.py
type: Question
tagged with: flask-script
has answer: http://stackoverflow.com/a/50478800
favorite count: 0
score: -1
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/87970781
upvote count: 0
has title: I made a mistake when I was deploying projects with gunicorn

http://stackoverflow.com/comment/87843253
has text: does multiplying by 1.0 not convert values to a float?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50412603
type: Comment

http://stackoverflow.com/comment/88014232
type: Comment
has text: so far this is the best answer, but seems to be a problem if i have more than 100 value in list. looping combination gonna be heavy.
comment on: http://stackoverflow.com/a/50494041
type: AnswerComment
score: 0

http://stackoverflow.com/q/50531584
type: Question
type: UnansweredQuestion
has body: Using the Cloudera Manager API I can easily make scripts that stop,start,restart series of services. However I want to make a script that permanently disables a service in such a way that if I have to reboot a server or the cloudera environment for any reason it doesn't start up on boot. I am not finding info about this online and would like to know if there Iis there any way to configure this through the API?
tagged with: python
tagged with: cloudera-manager
has title: Using Cloudera Manager API to permanetly disable a service
has answer: http://stackoverflow.com/a/50845749
tagged with: cloudera-cdh
score: 0
tagged with: cloudera
answer count: 1

http://stackoverflow.com/comment/88075758
score: 0
has text: @brunodesthuilliers In his original question he asked not to look at the check password function and only help him with the loop.
type: AnswerComment
comment on: http://stackoverflow.com/a/50524840
type: Comment

http://stackoverflow.com/comment/87991423
type: QuestionComment
comment on: http://stackoverflow.com/q/50487743
score: 0
type: Comment
has text: How are you calling your script? `python3.6 app.py`?

http://stackoverflow.com/comment/87879336
comment on: http://stackoverflow.com/a/50432569
has text: I'm using macos
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87870791
comment on: http://stackoverflow.com/a/50428047
type: AnswerComment
score: 0
type: Comment
has text: can you help me understand what is wrong in my code

http://stackoverflow.com/comment/87979139
type: QuestionComment
has text: https://stackoverflow.com/a/50469642/9709132 This is what solved it for me. Good luck!
comment on: http://stackoverflow.com/q/50479607
score: 0
type: Comment

http://stackoverflow.com/comment/87790239
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50386865
score: 0
has text: There is a known issue about `flask-security` which will significantly slow down response with token-authorization. Maybe you are suffering the same issue?

http://stackoverflow.com/comment/88022862
has text: @Aimery I have promoted `fault()` however now I have the error `NameError: name 'lowvolt' is not defined`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50484813
score: 0

http://stackoverflow.com/q/50401123
has comment: http://stackoverflow.com/comment/87821357
tagged with: try-except
score: 1
has answer: http://stackoverflow.com/a/50402900
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87818199
has comment: http://stackoverflow.com/comment/87818109
type: UnansweredQuestion
downvote count: 0
answer count: 1
has body: If the script below is ran, it starts with all the people I would like (Example: Nick Ahmed, Alex Avila, etc). But gives me a KeyError: 'row' after 9 or so. SCRIPT. import csv import requests import datetime from pprint import pprint # GET TEAM ID AND STORE AS team_id req = requests.get('http://lookup-service-prod.mlb.com/json/named.team_all_season.bam?sport_code=%27mlb%27&amp;all_star_sw=%27N%27&amp;sort_order=name_asc&amp;season=%272018%27') data = req.json()['team_all_season']['queryResults']['row'] for teams in data: team_id = teams['team_id'] team = teams['name_abbrev'] # GET PLAYER ID using team_id string and store PLAYER ID as playerId req1 = requests.get('http://lookup-service-prod.mlb.com/json/named.roster_40.bam?team_id=' + str(team_id) + '') roster = req1.json()['roster_40']['queryResults']['row'] for info in roster: player = info['name_display_first_last'] playerId = info['player_id'] # Use playerId string to run through PECOTA BATTING PROJECTIONS req2 = requests.get("http://lookup-service-prod.mlb.com/json/named.proj_pecota_batting.bam?season='2018'&amp;player_id='" + str(playerId) + "'") info1 = req2.json()['proj_pecota_batting']['queryResults']['row'] # KEYS hr = info1['hr'] sac = info1['sac'] rbi = info1['rbi'] tb = info1['tb'] slg = info1['slg'] bavg = info1['avg'] bb = info1['bb'] ops = info1['ops'] hbp = info1['hbp'] games = info1['g'] d = info1['d'] e = info1['e'] so = info1['so'] sf = info1['sf'] tpa = info1['tpa'] h = info1['h'] cs = info1['cs'] obp = info1['obp'] t = info1['t'] s = info1['s'] r = info1['r'] sb = info1['sb'] sbpct = info1['sbpct'] ab = info1['ab'] ibb = info1['ibb'] print(player,team,hr,sac,rbi,tb,slg,bavg,bb,ops,hbp,games,d,e,so,sf,tpa,h,cs,obp,t,s,r,sb,sbpct,ab,ibb) If I add in a try: except(KeyError): It will work but skips a lot of players in the process, like the examples I used earlier. Which does not make sense to me because if they worked before the try why would they not now? Copying in the edited portion only of the s…
upvote count: 1
tagged with: python
has title: Try and Except with Python request
has comment: http://stackoverflow.com/comment/87818097

http://stackoverflow.com/q/50421656
has answer: http://stackoverflow.com/a/50421817
tagged with: directory
upvote count: 1
has answer: http://stackoverflow.com/a/50421943
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87858498
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87858479
score: 0
has title: How to swap files with one file extension with identically named but different files with a different extension and maintain the directory structure?
answer count: 2
has body: I work in audio and I need a number of files transcribed by a third party. To do so I have to swap out an entire directory of .wav files with .mp3s I have compressed while still maintaining the file directory. It's about 20,000 files. e.g. wav: Folder1 Folder 1a sound1.wav sound2.wav Folder 1b sound3.wav sound4.wav Folder2 Folder 2a Folder 2aa sound5.wav sound6.wav Folder 2ab sound7.wav Folder2b sound8.wav etc. mp3: Folder1 sound1.mp3 sound2.mp3 sound3.mp3 sound4.mp3 sound5.mp3 sound6.mp3 sound7.mp3 sound8.mp3 etc. I had to group them together to do the batch compression in Adobe Audition, but now I would like to be able to switch them out with the wav files that are perfectly identical save for file extension as doing this manually is not a reasonable option. Any help would be greatly appreciated. I have a little experience with python so that language is preferable, but I'm open to any solutions.

http://stackoverflow.com/comment/88186608
comment on: http://stackoverflow.com/a/50535447
score: 0
type: AnswerComment
type: Comment
has text: this does not work with a polyval with degree 1 i.e. p=1

http://stackoverflow.com/comment/87992716
has text: @MelDev I understand. So then, in this case, resulting dictionary's Key=properties will have two dicts, right? In other words, we can keep a list of dicts for each key, so that whenever another list is added to that KEY, we can append the corresponding dictionary to this KEYs value. Is this what you intend to do? If not, I would like you to explain *merging* two dictionaries.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50486615

http://stackoverflow.com/a/50450204
has body: This is how I interpreted what you said df.assign(sum_values=df.groupby('id').dnm.transform('sum')).query('sum_values &gt; 300') id date rt dnm sum_values 0 101122 2017-01-24 0.00000 70 574 1 101122 2017-01-08 0.00000 49 574 2 101122 2017-04-13 0.02976 67 574 3 101122 2017-08-03 1.02565 39 574 4 101122 2016-12-01 0.00000 46 574 5 101122 2017-01-25 0.00000 69 574 6 101122 2017-01-02 0.00000 76 574 7 101122 2017-07-18 0.02631 38 574 8 101122 2016-06-02 0.00000 120 574 9 221344 2016-10-21 0.00182 176 1050 10 221344 2016-09-21 0.47732 194 1050 11 221344 2016-06-23 0.00000 169 1050 12 221344 2017-10-10 0.91391 151 1050 13 221344 2017-04-29 0.00000 33 1050 14 221344 2017-02-05 0.00000 31 1050 15 221344 2017-10-16 0.00000 196 1050 16 221344 2016-09-25 0.00000 33 1050 17 221344 2016-07-17 0.00000 21 1050 18 221344 2016-07-21 0.00000 46 1050 This is how I'd get your desired results. f, u = pd.factorize(df.id) sums = np.bincount(f, df.dnm) mask = sums &gt; 300 pd.DataFrame(dict( sum_values=sums[mask], ID=u[mask] )) ID sum_values 0 101122 574.0 1 221344 1050.0
answers question: http://stackoverflow.com/q/50449876
has comment: http://stackoverflow.com/comment/87913428
upvote count: 2
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/a/57053415
has comment: http://stackoverflow.com/comment/114298252
type: Answer
has comment: http://stackoverflow.com/comment/115961788
has comment: http://stackoverflow.com/comment/125981695
score: 79
has comment: http://stackoverflow.com/comment/109969769
has body: I had a similar issue and fixed it using the python-certifi-win32 package (now out of maintenance): As of 2022 (as mentioned by Briareos386 in the comments) pip install pip-system-certs Original answer (out of maintenance) pip install python-certifi-win32 now you can just use: requests.get(url, verify=True) and the certificate is checked using the Windows Certificate Store. Note: This only works if the certificate is installed in the Windows Certificate Store...
upvote count: 79
has comment: http://stackoverflow.com/comment/128326203
answers question: http://stackoverflow.com/q/50422136
downvote count: 0
has comment: http://stackoverflow.com/comment/128637478

http://stackoverflow.com/q/50484693
type: Question
accepted answer: http://stackoverflow.com/a/50484704
duplicate of: http://stackoverflow.com/q/35277075
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/35277075
has answer: http://stackoverflow.com/a/50484704
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has body: Like df.isnull().sum() for counting Nan value, I m looking to count another value : 'MISSED'. Does anybody know if there is any build-in fonction in pandas to do that, or how to do that ?
has title: How to count value in pandas dataFrame

http://stackoverflow.com/comment/88051903
comment on: http://stackoverflow.com/q/50519583
has text: Thanks. I thought about pickle. The point is that the object should be "compressed" and not saved on any file. Just be stored in a variable and sent through requests.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87916291
has text: Your first option is wrong because the OP is on Windows, so there's no `source` available. Besides, he's using Anaconda, so the right recommendation is to use conda envirinments, not pip ones.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50449312
type: AnswerComment

http://stackoverflow.com/a/50508983
score: 0
has body: You can simply iterate over each row in file: tweets = list() with open('stream.txt', 'r') as f: for line in f: if "DM" not in line and "RT" not in line: tweets.append(line.split())
type: Answer
answers question: http://stackoverflow.com/q/50508756

http://stackoverflow.com/q/50418202
has comment: http://stackoverflow.com/comment/87851938
downvote count: 0
has answer: http://stackoverflow.com/a/50420112
has body: I have a data frame with many null records: Col_1 Col_2 Col_3 10 5 2 22 7 7 3 9 5 4 NaN NaN 5 NaN NaN 6 4 NaN 7 6 7 8 10 NaN 12 NaN 1 I want to remove all NaN values in all rows of columns . As you could see, each column has different number of rows. So, I want to get something like this: Col_1 Col_2 Col_3 10 5 2 22 7 7 3 9 5 4 4 7 6 6 1 7 10 8 12 I tried filtered_df = df.dropna(how='any') But it removes all records in the dataframe. How may I do that ?
has comment: http://stackoverflow.com/comment/87851955
linked to: http://stackoverflow.com/q/43119503
has answer: http://stackoverflow.com/a/50419837
has title: Pandas: Remove all NaN values in all columns
has comment: http://stackoverflow.com/comment/88039214
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47897166
tagged with: pandas
has comment: http://stackoverflow.com/comment/87854858
duplicate of: http://stackoverflow.com/q/43119503
has answer: http://stackoverflow.com/a/50703749
possible better answer: http://stackoverflow.com/a/50419837
tagged with: dataframe
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50419752
answer count: 4
tagged with: nan
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87854952
linked to: http://stackoverflow.com/q/44558215
accepted answer: http://stackoverflow.com/a/50420112

http://stackoverflow.com/a/50504924
score: 11
has comment: http://stackoverflow.com/comment/88022199
has comment: http://stackoverflow.com/comment/88022795
answers question: http://stackoverflow.com/q/50504844
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88027978
accepted answer of: http://stackoverflow.com/q/50504844
has body: Yes, by using generator comprehensions: b = [('---', None), *((key, key.upper()) for key in a)] Instead of using a generator comprehension, you could also use a list comprehension. The benefit of using generator comprehensions is that they don't create a new list, but hand out items one by one. If your list (a) is big, that can make an impact on memory use and/or performance. Using the asterisk (the "splat operator") to unpack such a sequence is PEP 448 — Additional Unpacking Generalizations. It allows you to use the * not just in function calls, but in list, generator, and set comprehensions (the same applying to ** and dictionary comprehensions).
downvote count: 1
has comment: http://stackoverflow.com/comment/88022987
upvote count: 12
type: Answer
has comment: http://stackoverflow.com/comment/88024373

http://stackoverflow.com/comment/88208555
comment on: http://stackoverflow.com/a/50587988
type: AnswerComment
has text: so 5.0 will not install? or it installs but is named 4.0.2? when I try and run I get this error ModuleNotFoundError: No module named 'amqp.types'
score: 0
type: Comment

http://stackoverflow.com/comment/88030434
has text: Manage.py available now, should have included the files with the original posts, sorry peeps!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50499449
score: 0

http://stackoverflow.com/comment/88085679
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50477293
has text: I would appreciate a response to my question above.

http://stackoverflow.com/q/50435315
accepted answer: http://stackoverflow.com/a/50435445
tagged with: python
has answer: http://stackoverflow.com/a/50435445
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87884845
has body: I'm creating a virtual OS with different files, like boot.py and Run.py It worked for a while until I typed this in: if Run.run == 0: error() else: start() There is no errors saying about it like red lines or any. Now I get this error: AttributeError("module 'boot' has no attribute 'bootup'",) Here's the code: boot.py: #Imports import Run #Varibles name = "PyOS" version = 1 creator = "© Dragon Softwares" def bootup(run): if Run.run == 0: error() else: start() def start(): print("Starting PyOS") print("Version ", version) def error(): print("Please Run 'Run.py' To bootup the system") bootup() Run.py: #Imports import time import boot #Varibles run = 0 def main(): run = 1 time.sleep(0.1) boot.bootup main()
has title: AttributeError("module 'name' has no attribute 'def name'",)
type: Question
has comment: http://stackoverflow.com/comment/87884786
has comment: http://stackoverflow.com/comment/87884822

http://stackoverflow.com/q/50500017
has title: Python cannot import CSV using Pandas
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I am currently learning Pandas for data analysis and having some issues reading a csv file in Jupyter Notebook editor. When I am running the following code: import pandas as pd df = pd.read_csv("C:\PythonHow\nycrime.csv") I get an error message, which ends with FileNotFoundError: File b'C:\\PythonHow\nycrime.csv' does not exist and it's full lenght: FileNotFoundError Traceback (most recent call last) &lt;ipython-input-36-75f2b616e06c&gt; in &lt;module&gt;() ----&gt; 1 lf2 = pd.read_csv("C:\PythonHow\nycrime.csv") ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 653 skip_blank_lines=skip_blank_lines) 654 --&gt; 655 return _read(filepath_or_buffer, kwds) 656 657 parser_f.__name__ = name ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 403 404 # Create the parser. --&gt; 405 parser = TextFileReader(filepath_or_buffer, **kwds) 406 407 if chunksize or iterator: ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds) 762 self.options['has_index_names'] = kwds['has_index_names'] 763 --&gt; 764 self._make_engine(self.engine) 765 766 def close(self): ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine) 983 def _make_engine(self, engine='c'): 984 if engine == 'c': --&gt; 985 self._engine = CParserWrapper(self.f, **…
score: 0
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50500073
has answer: http://stackoverflow.com/a/50500088
has answer: http://stackoverflow.com/a/50500163
type: Question

http://stackoverflow.com/q/50537296
tagged with: windows-subsystem-for-linux
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88088411
answer count: 1
has title: Using matplotlib to create a histogram on Windows Subsystem for Linux Ubuntu
has body: I am trying to create a simple histogram for a csv file named "count_backers.csv". The code that I have so far is as follows: import matplotlib.pyplot as plt # import numpy as np import plotly.plotly as py import csv def make_hist(csv_filepath): data = open(csv_filepath) reader = csv.reader(data) column = [] for row in data: column.append(row) plt.hist(column) plt.title("Number of Backers") plt.xlabel("Frequency") plt.ylabel("Value") plt.show() # fig = plt.gcf() # plot_url = py.plot_mpl(fig, filename='backers_histogram') backer_data = r"C:/Users/user/Documents/user/Programming/count_backers.csv" make_hist(backer_data) I began learning python using Learn Python the Hard Way, and I am used to executing python files from PowerShell. However, I was struggling to install and build matplotlib on Windows and for the sake of time I decided to install it on Windows Subsystem for Linux Ubuntu. After I was able to get that working I am now getting the following error: Traceback (most recent call last): File "histogram.py", line 22, in &lt;module&gt; make_hist(backer_data) File "histogram.py", line 7, in make_hist data = open(csv_filepath) FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/user/Documents/user/Programming/count_backers.csv' I have tried several different versions of the filepath including: backer_data = r"C:\Users\user\Documents\user\Programming\count_backers.csv" backer_data = "mnt/c/Users/user/Documents/user/Programming/count_backers.csv" backer_data = r"mnt\c\Users\user\Documents\user\Programming\count_backers.csv" These produce the following errors respectively: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\Documents\\user\\Programming\\count_backers.csv' FileNotFoundError: [Errno 2] No such file or directory: 'mnt/c/Users/user/Documents/user/Programming/count_backers.csv' FileNotFoundError: [Errno 2] No such file or directory: 'mnt\\c\\Users\\user\\Documents\\user\\Programming\\count_backers.csv' When I use ls on t…
has answer: http://stackoverflow.com/a/50537833
type: Question
accepted answer: http://stackoverflow.com/a/50537833
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/88089424
tagged with: ubuntu

http://stackoverflow.com/q/50407849
downvote count: 1
accepted answer: http://stackoverflow.com/a/50408904
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87831107
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50408904
score: 3
possible better answer: http://stackoverflow.com/a/50407959
has answer: http://stackoverflow.com/a/50407959
tagged with: python
has answer: http://stackoverflow.com/a/50407949
has body: I have a random generated list that could look like: [1, 0, 0, 1, 1, 0, 1, 0, 0, 0] I need to find all of the distance between the 1's including the ones that wrap around. For an example the list above, the first 1 has a distance of 3 to the next 1. The second 1 has a distance of 1 to the following 1 and so on. How do I find the distance for the last 1 in the list using wrap around to the first 1? def calc_dist(loc_c): first = [] #lst2 = [] count = 0 for i in range(len(loc_c)): if loc_c[i] == 0: count += 1 #lst2.append(0) elif loc_c[i] == 1: first.append(i) count += 1 loc_c[i] = count #lst2.append(loc_c[i]) #if loc_c[i] + count &gt; len(loc_c): # x = loc_c[first[0] + 11 % len(loc_c)] # loc_c[i] = x count = 0 return loc_c My expected outcome should be [3, 1, 2, 4].
upvote count: 4
type: AnsweredQuestion
tagged with: list
answer count: 3
has comment: http://stackoverflow.com/comment/87831303
has title: List wrapping for finding distance between indices

http://stackoverflow.com/q/50454718
upvote count: 4
tagged with: forms
has title: Passing data through Django forms
type: Question
has comment: http://stackoverflow.com/comment/87922816
downvote count: 0
has answer: http://stackoverflow.com/a/50454855
accepted answer: http://stackoverflow.com/a/50454855
answer count: 1
tagged with: django
score: 4
favorite count: 0
type: AnsweredQuestion
has body: I feel I'm missing the obvious but I can't work it out! I have written a custom form (for use outside of django admin), which I want to use to create / update instances of a number of model instances as well as hold conditional fields. However I seem to be losing my conditional data. In my view I instansiate an instance of my form and pass it into the request context:- view.py form = MyForm(my_bool=True, pid=7) render(request 'my_page.html', {'form': form}) forms.py class MyForm(forms.Form): def __init__(self, *args, **kwargs): my_bool = kwargs.pop('my_bool', False) self.pid = kwargs.pop('pid', None) super(MyForm, self).__init__(*args, **kwargs) if my_bool: self.fields['textbox'] = forms.CharField(max_length=256) That all works fine and the form renders as expected. Now when I submit the form it hits the below view.py if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): # Do Stuff My problem is that the form object in the above code does not contain my 'textbox' or 'pid' fields even though the form I submitted did. I'm certain whatever I'm doing wrong is extremely obvious but from a whole lot of googling I cant work out a simple way to instantiate a form, pass it some data about what fields I want to show as well as say the id of the model I eventually want it to update and then have access to the info I passed in the post part of the code. The # Do Stuff part of my code is supposed to take the 'pid' I passed to the form and use that to fetch a product e.g. Product.objects.get(pk=pid), however without storing the pid in the session I cant work out how to access it from the postback. If a validation error occurs in my form i.e. form.is_valid() returns false I render the request again passing the form I already have, that way I see the validation errors however any conditional fields I passed initially are missing and their values ignored. Maybe I'm just going about it completely wrong and I should be doing this a different way. What I am tryin…
tagged with: python

http://stackoverflow.com/comment/87875575
comment on: http://stackoverflow.com/a/50430477
has text: doesn't work, it returns the exact same output as temp = previous
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87849043
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50416060
has text: Thanks for the answer. This workaround seems to be much more work than I had hoped for :-) Just asking for Linux box at work might be easier or at least I can install Linux on a VM.
score: 0

http://stackoverflow.com/a/50421666
accepted answer of: http://stackoverflow.com/q/50421361
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50421361
type: Answer
has body: Generate variables : You can create variables from a list of strings with the following code, but I don't think this is common practice. name = ['a','b','c','d'] values = [random.randint(1, 10) for i in range(len(name))] for var_value, var_name in zip(values,name): locals()[var_name] = var_value name = [a,d,c,b] #[8, 8, 6, 4] Better to make a dictionary: You can do what you want to by creating a dictionary. names = ['a','b','c','d'] values = [random.randint(1, 10) for i in range(len(name))] # make a list of tuples that become the dictionary names_and_values = [] for var_value, var_name in zip(values,name): names_and_values.append((var_value, var_name)) # create a dictionary with defined vairables names = {name: value for name, value in names_and_values} #{1: 'c', 2: 'd', 3: 'a', 5: 'b'}
score: 1

http://stackoverflow.com/q/50503899
favorite count: 0
has comment: http://stackoverflow.com/comment/88025183
has comment: http://stackoverflow.com/comment/88020828
has comment: http://stackoverflow.com/comment/88024725
type: Question
accepted answer: http://stackoverflow.com/a/50507178
has comment: http://stackoverflow.com/comment/88021242
has comment: http://stackoverflow.com/comment/88024850
has comment: http://stackoverflow.com/comment/88021376
linked to: http://stackoverflow.com/q/33176228
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/50507178
has comment: http://stackoverflow.com/comment/88023474
has comment: http://stackoverflow.com/comment/88023529
has comment: http://stackoverflow.com/comment/88023737
has comment: http://stackoverflow.com/comment/88021086
has body: What I would like to achieve is something like a self-checkout Kiosk. So I would like to scan some barcodes. And have kivy screen show the list of item scanned. And when I have no more barcodes to scan, be able to press a button and calculate the price of all the items scanned. I thought the best way to go about it is a while loop that keeps asking for inputs from the barcode scanner. And be able to break it by pressing a button on screen. The problem is: when the loop is listening for input, all the buttons on screen hangs and cannot be pressed. So let's say I have no more barcode to scan but because the loop is still listening for input, the whole screen hangs. And i can't do anything except to terminate the whole script on terminal. How should i go about resolving this problem? How do these self checkout kiosks work? How are their codes like? I read some suggestion about kivy clock. But even then when it reaches the part of the code that asks for input, it hangs. What about "select", "subprocessing" or "threading"? Do you think it will resolve my problem? However, even after reading up on it, i have no clue how to implement it. If it is the right way to go about it, might you suggest some example code, pls? I am using a mac, python 2.7, eventually would be running it on raspberry pi with LCD screen. Here is my loop: def getItem(): while True: answer = input('What is the box ID? ') if answer == 999: # to break out from loop break elif type(answer) == int: display on kivy screen else: print('Sorry I did not get that') here's what it looks like on kivy: Updated code: this is in the kv file: &lt;ScreenTwo&gt;: member_status: memberStatus box_no: boxNo text_in: textIn BoxLayout: Label: id: memberStatus text: '' GridLayout: rows: 3 padding: [100,500] spacing: 10 BoxLayout: Label: id: boxNo text: '' BoxLayout: TextInput: id: textIn write_tab: False multiline: False on_text_validate: root.sayHello() self.text = "" self.focus = True #also tried root.inputFocus() BoxLayout…
has comment: http://stackoverflow.com/comment/88023559
has comment: http://stackoverflow.com/comment/88024240
has comment: http://stackoverflow.com/comment/88023829
type: AnsweredQuestion
has title: Read Barcode Scanner with Kivy
linked to: http://stackoverflow.com/q/12037379
downvote count: 0
has comment: http://stackoverflow.com/comment/88021276
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88020762
has comment: http://stackoverflow.com/comment/88024040
has comment: http://stackoverflow.com/comment/88020920
answer count: 1

http://stackoverflow.com/q/50534397
has answer: http://stackoverflow.com/a/51115933
score: 0
has body: I installed 3.5.2 and 3.5.3 version using pyenv. # pyenv versions * system (set by /usr/local/pyenv/version) 3.5.2 3.5.3 But, when I run this command as sudo (not login as root) it not gives me all versions. $ sudo /usr/local/bin/pyenv versions * system (set by /root/.pyenv/version) I tried using setting the PYENV_ROOT path, but that also not works. $ export PYENV_ROOT=/usr/local/pyenv/ $ sudo /usr/local/pyenv/bin/pyenv versions * system (set by /root/.pyenv/version) I already have path set in .bash_profile in myuser $ cat ~/.bash_profile # .bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi # User specific environment and startup programs PATH=$PATH:$HOME/bin export PATH export PYENV_ROOT=/usr/local/pyenv/ export PATH="/usr/local/pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" Also set in root user $ sudo cat /root/.bash_profile # .bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi # User specific environment and startup programs PATH=$PATH:$HOME/bin export PATH export PYENV_ROOT=/usr/local/pyenv/ export PATH="/usr/local/pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" I am using centos $ cat /etc/issue CentOS release 6.9 (Final)
tagged with: pyenv
answer count: 1
type: Question
tagged with: centos
type: AnsweredQuestion
has title: Pyenv not shows all version when used as sudo
tagged with: python
accepted answer: http://stackoverflow.com/a/51115933

http://stackoverflow.com/q/50508154
tagged with: pandas
has comment: http://stackoverflow.com/comment/88028736
duplicate of: http://stackoverflow.com/q/24458645
has comment: http://stackoverflow.com/comment/88029049
duplicate of: http://stackoverflow.com/q/39357882
type: Question
has comment: http://stackoverflow.com/comment/88037044
has title: keras pandas column value to numpy array
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88028843
has body: I have column like username UserName , exam, score Peter, 1, 70 Richard, 2, 80 Peter, 2, 60 ... would like to convert sth like below and pass as input array for model UserName , exam,score 1,1,70 2,2,80 1,2,60 i can create a new col and do mapping by {'Peter':'1','Richard':'2'....} but any smarter code can do this? or Keras have some API to do that I have around 100 user name in the column Actually I also think so use function concept like below def NameToInt(pd): listName=[] i=0 for x in pd.unique(): listName.append('X':'i') i=i+1 return listName Thanks
tagged with: python
linked to: http://stackoverflow.com/q/24458645
tagged with: keras
has comment: http://stackoverflow.com/comment/88028867
linked to: http://stackoverflow.com/q/39357882
score: 0
has comment: http://stackoverflow.com/comment/88028717
answer count: 0

http://stackoverflow.com/q/50509570
score: 0
has body: I use the image transformation function of PIL according to How does perspective transformation work in PIL?, which works fine. The only thing which does not work is increasing the resolution of the resulting image. import numpy as np import matplotlib.pyplot as plt from PIL import Image imgData=plt.imread('img.jpg') print imgData.shape img=Image.fromarray(imgData) plt.imshow(img) the transformation without increasing the resolution works fine def find_coeffs(pa, pb): matrix = [] for p1, p2 in zip(pa, pb): matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]]) matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]]) A = np.matrix(matrix, dtype=np.float) B = np.array(pb).reshape(8) res = np.linalg.solve(A, B) return np.array(res).reshape(8) coeffs = find_coeffs( [(0, 0), (256, 0), (256, 256), (0, 256)], [(0, 0), (256, 0), (100, 200), (10, 200)]) imgNew=img.transform((256, 256), Image.PERSPECTIVE, coeffs, Image.BICUBIC) plt.imshow(imgNew) But if I want to increase the resolution there is some strange behaviour of PIL - the image is not reszized to the resulting canvas size imgNew2=img.transform((1500, 1500), Image.PERSPECTIVE, coeffs, Image.BICUBIC) imgNew2.save('imgNew2.jpg') plt.imshow(imgNew2) Any ideas how to solve this without resizing the image with PIL.Image.resize before tranforming it?
tagged with: python-imaging-library
tagged with: python
tagged with: image-processing
linked to: http://stackoverflow.com/q/14177744
type: Question
has comment: http://stackoverflow.com/comment/93477524
has comment: http://stackoverflow.com/comment/88032844
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88041168
has title: Upscaling while perspective transformation with PIL

http://stackoverflow.com/q/50429079
has answer: http://stackoverflow.com/a/50429155
downvote count: 4
type: UnansweredQuestion
upvote count: 1
answer count: 1
favorite count: 0
tagged with: opencv
type: Question
has body: It is opencv 3.4.1 *86. i've placed it showing tutorial step by step but it doesn't work
tagged with: windows
tagged with: python
tagged with: image-processing
score: -3
has title: How to import opencv in python?

http://stackoverflow.com/q/50397924
has title: define function with strings as parameter
has answer: http://stackoverflow.com/a/50397994
has comment: http://stackoverflow.com/comment/87812099
tagged with: user-defined-functions
score: 0
has answer: http://stackoverflow.com/a/50397985
upvote count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/50398067
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50397988
type: Question
has answer: http://stackoverflow.com/a/50398006
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87811646
has body: why when we define a function with strings as parameter we don't need quotation marks, but when we use it we need quotation marks? thanks! for example, def shout(word): shout_word = word + '!!!' (here we don't have quotation marks for 'word') shout_word('abd') but here we need '' for abd.. I already go through some materials online, but probably my question is too details or too basic so it seems no body asked it before. Thank you for your help!! it's important for me to learn python!

http://stackoverflow.com/q/50512663
tagged with: python
type: Question
tagged with: dropbox-api
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50513197
has answer: http://stackoverflow.com/a/50513197
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
tagged with: dropbox
has body: In my Python class, I have a function that generates a csv file, uploads this file to Dropbox, and then attempts to generate a shared link to the uploaded file with an expiration time of 5 minutes. I am attempting to follow the example provided here; my code is below: # Helper upload function def upload_file(self, dbx, file_from, file_to): """upload a file to Dropbox using API v2 """ with open(file_from, 'rb') as f: dbx.files_upload(f.read(), file_to, mode=WriteMode('overwrite')) # Target function def generate_expiring_dropbox_link(self, local_path, dbx_path): dbx = dropbox.Dropbox(self.temp_dropbox_token) expires = datetime.datetime.now() + datetime.timedelta(minutes=5) requested_visibility = dropbox.sharing.RequestedVisibility.team_only desired_shared_link_settings = dropbox.sharing.SharedLinkSettings(requested_visibility=requested_visibility, expires=expires) # open the file and upload it self.upload_file(dbx, local_path, dbx_path) shared_link_metadata = dbx.sharing_create_shared_link_with_settings(path=dbx_path, settings=desired_shared_link_settings) return shared_link_metadata I consistently get an API error related to the shared link settings: dropbox.exceptions.ApiError: ApiError('************', CreateSharedLinkWithSettingsError('settings_error', SharedLinkSettingsError('invalid_settings', None))) I can't find much documentation on this; has anyone encountered it/found a solution? Just wondering if there's a python-based fix or if wrapping an HTTP request is a better bet. I'm using Python 3.6 and Dropbox 8.9.0.
score: 1
has title: Python Dropbox API v2: error when passing SharedLinkSettings

http://stackoverflow.com/q/50435492
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50435522
linked to: http://stackoverflow.com/q/2371436
score: 0
has answer: http://stackoverflow.com/a/50435522
linked to: http://stackoverflow.com/q/9383740
accepted answer: http://stackoverflow.com/a/50435515
duplicate of: http://stackoverflow.com/q/2371436
has answer: http://stackoverflow.com/a/50435515
type: Question
answer count: 2
tagged with: python
has body: I am trying to create a short program to do a task. Unfortunately I keep getting an error. The problem boils down to the following. If I try to run: line = "1+1" int(line) I would like it to return 2 However I get the following error: invalid literal for int() with base 10: '1+1' From looking online this is due to the fact that Python cannot recognize the fact that I have used a non-number. However without some rework I can't get around this. I was hoping that there is a straight forward method for solving this. I have tried using float but that has the same problem.
has title: Turn string with operations into int?

http://stackoverflow.com/comment/93553484
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50540756
has text: Why does the same not work with mpmath quad? `def int_f(xrange): return [quad(lambda x: fl(x), [-1, 1], xr, method='tanh-sinh') for xr in xrange] ` doesn work for me? what am i missing?

http://stackoverflow.com/q/50484432
tagged with: python
has body: I'm having a problem in my django's app using mezzanine. I have specified models searchable this way : SEARCH_MODEL_CHOICES = ('organization-pages.CustomPage', 'organization-network.DepartmentPage', 'organization-network.TeamPage', 'organization-network.Person', 'organization-projects.ProjectTopicPage', 'pages.Page', 'organization-media.Playlist', 'mezzanine_agenda.Event', 'organization-projects.Project', 'shop.Product', 'organization-magazine.Article') PAGES_MODELS = ('organization-pages.CustomPage', 'organization-magazine.Topic', 'organization-network.DepartmentPage', 'organization-network.TeamPage', 'organization-projects.ProjectTopicPage', 'shop.Product') SEARCH_PARENTS_MODELS = ('organization-network.Person',) And i haven't touched any of Mezzanine's source code. I'm using django model-translation, having a object like that : d = DepartementPage.objects.create() d.title_fr = 'french' d.title_en = 'english' If i try to search it with Mezzanine's search engine, i'll only find it if i input the title of the language i'm currently using. I mean if i'm using application in english, i'll not get my object searching 'french', while it should do Do you know where my issue comes from ?
tagged with: mezzanine
has title: Django : Mezzanine front search module
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51031317
upvote count: 2
has comment: http://stackoverflow.com/comment/88956398
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51031317
type: Question
tagged with: django-modeltranslation
tagged with: django

http://stackoverflow.com/comment/88015018
has text: are you comfortable using sklearn? it provides both http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html and http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html
comment on: http://stackoverflow.com/q/50501238
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88062019
type: Comment
type: QuestionComment
has text: Not enough details for a sound answer, sorry. But REST/json APIs are most deftly a sure way to decouple subsystems indeed.
score: 1
comment on: http://stackoverflow.com/q/50524886

http://stackoverflow.com/a/50487539
type: Answer
has body: The answers you found, as general as they are, are correct. I'll try to explain it to you. As you are trying to automatize some activity, you have to use a script language to basically Get stuff references (like getting indexes, forms/fields IDs, etc) Insert/change stuff (like filling a field, following the field references) Save stuff (prepare a file, with field references and it's content, that can be injected to the specific system or website) One example of script language is Python. So you already have your script. Now you need to inject it on the page. The programming language that can do it for you is Javascript, or JS. It allows you to talk with the webpage, GETting data/references or POSTing data.
answers question: http://stackoverflow.com/q/50487345
score: 0

http://stackoverflow.com/comment/88052612
type: QuestionComment
comment on: http://stackoverflow.com/q/50496358
score: 0
has text: This seems to be a quite messy design with php for web page, one python script for start, sh for killing the script, and another python script to clean up GPIO. Why not just use pure python to create the website as well controlling the GPIO like [this one](https://www.e-tinkers.com/2018/04/how-to-control-raspberry-pi-gpio-via-http-web-server/). You didn't show the php and vrone.py, it is kind of hard to figure out what exactly is going on.
type: Comment

restore
tag name: restore
type: Tag
tags question: http://stackoverflow.com/q/50453911
tags question: http://stackoverflow.com/q/50391464

http://stackoverflow.com/a/50458372
has comment: http://stackoverflow.com/comment/87931090
type: Answer
has body: By using cumsum to create the key for groupby , then we using cumsum again df['SUM_IN'].replace(0,np.nan).ffill()+df.groupby(df['SUM_IN'].gt(0).cumsum()).SUM_OUT.cumsum() Out[292]: 0 500.0 1 97.0 2 39.0 3 0.0 4 100.0 5 2.0 6 276.0 7 137.0 8 78.0 9 8.0 dtype: float64 Update s=df['SUM_IN'].replace(0,np.nan).ffill()+df.groupby(df['SUM_IN'].gt(0).cumsum()).SUM_OUT.cumsum()-df.STOCK df['SUM_IN'].replace(0,np.nan).ffill()+df.groupby(df['SUM_IN'].gt(0).cumsum()).SUM_OUT.cumsum()-s.groupby(df['SUM_IN'].gt(0).cumsum()).bfill().fillna(0) Out[318]: 0 500.0 1 97.0 2 39.0 3 0.0 4 100.0 5 2.0 6 278.0 7 139.0 8 80.0 9 10.0 dtype: float64
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50458342
upvote count: 1
has comment: http://stackoverflow.com/comment/87930798
has comment: http://stackoverflow.com/comment/87930890

http://stackoverflow.com/comment/87854010
comment on: http://stackoverflow.com/q/50419214
type: QuestionComment
type: Comment
has text: @jasonharper except the sample only comes from 30 values, and the OP asks for 40 values.
score: 0

http://stackoverflow.com/a/50492256
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50492194
has body: Simply escape the [ and ] characters using \: Score = DF[DF['Name'].str.contains('j_perry\[\d+\]|j\[\d+\]')] &gt;&gt;&gt; Score index Name Value 4 4 j_perry[4] 75 5 5 j_perry[6] 81 6 6 j[3] 92 7 7 j[4] 72 10 10 r_j[11] 98 To make sure you don't get r_j, use the ^ to specify that your string needs to start with j: Score = DF[DF['Name'].str.contains('^j_perry\[\d+\]|^j\[\d+\]')] &gt;&gt;&gt; Score index Name Value 4 4 j_perry[4] 75 5 5 j_perry[6] 81 6 6 j[3] 92 7 7 j[4] 72
type: Answer
accepted answer of: http://stackoverflow.com/q/50492194

win32com
tags question: http://stackoverflow.com/q/50504112
tag name: win32com
tags question: http://stackoverflow.com/q/50406973
tags question: http://stackoverflow.com/q/50411526
tags question: http://stackoverflow.com/q/50479273
type: Tag
tags question: http://stackoverflow.com/q/50409440
tags question: http://stackoverflow.com/q/50395357

http://stackoverflow.com/a/50472285
score: 0
has body: From Django's Documentation: By default, Django gives each model the following field: id = models.AutoField(primary_key=True) This is an auto-incrementing primary key. If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added). If you want yours to explicitly be called movie_id you probably need something like: class Film(models.Model): movie_id = models.AutoField(primary_key=True)
answers question: http://stackoverflow.com/q/50471952
type: Answer

http://stackoverflow.com/q/50458480
tagged with: python
tagged with: mpi4py
type: AnsweredQuestion
score: 0
has body: I am trying to send a single complex number using Python implementation of MPI (MPI4py) from a single sender to a single receiver. Here is the code: from mpi4py import MPI import numpy as np comm = MPI.COMM_WORLD if comm.rank == 0: print("I am sender") a = np.matrix('5+1j') req = [None] #Send message with a predefined tag, like 15, to rank 1 req = comm.Isend([a, MPI.COMPLEX], dest=1, tag=15) MPI.Request.Wait(req) print("Sender sent: ") print(a[0]) else: print("I am receiver") A = np.empty_like(np.matrix([[0]*(1) for i in range(1)])) print("point 1") #Receive message with tag 15 from rank 0 rA = comm.Irecv(A, source=0, tag=15) rA.wait() print("Receiver received: ") print(A) Please note that the above example is a simplified version of my goal which is to send a numpy array (or numpy matrix) of many complex entries from one sender to multiple receivers. That's why I am using nonblocking send Comm::Isend() and receive Comm::Irecv(), along with Request::Wait() in this example. However in general, I would have one Comm::Isend() per iteration of a for loop and Request::Waitall() for a vector of requests, one for each receiver in general. For the above program the MPI processes created are just two, one sender and one receiver. Also my MPI4py installation is 3.0.0. and uses Python 2.7.14 and the kernel of Open MPI 2.1.2. Now, the program crashes at the rA.wait() with the following error mpi4py.MPI.Exception: MPI_ERR_TRUNCATE: message truncated which based on a search online means that the receiver's buffer is insufficient to store the received data i.e. the complex number, but I don't understand why.
tagged with: complex-numbers
answer count: 1
has answer: http://stackoverflow.com/a/50458695
type: Question
tagged with: buffer
tagged with: mpi
has title: MPI_ERR_TRUNCATE when sending complex number over MPI [MPI4py]
accepted answer: http://stackoverflow.com/a/50458695

http://stackoverflow.com/comment/87954121
type: Comment
has text: using `read_csv` worked great to get through the dataset (it is quite large). However, I am trying to pass in one item at a time from the `orders` list into the `line_item` dict but I get this error _in _wrapper self.__class__.__name__)) ValueError: The String type doesn't accept collections as value__. My guess is I am passing the entire `orders` list into the `line_item` but can't quite figure out what I need to do to solve the problem. Sorry if I am not being clear as I am a bit confused on the next steps.
type: AnswerComment
comment on: http://stackoverflow.com/a/50457189
score: 0

http://stackoverflow.com/comment/139439246
score: 0
has text: Had a similar issue with netcat with UDP broadcasts. As someone mentioned on a [superuser post](https://superuser.com/a/708133/532977) the solution was to add the `-k` option which "Forces nc to stay listening for another connection after its current connection is completed." [man page](https://linux.die.net/man/1/nc)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50438869

http://stackoverflow.com/comment/87999689
has text: Gotcha @Aran-Fey. It works now!
comment on: http://stackoverflow.com/q/50493298
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88057042
score: 0
type: Comment
has text: Brilliant. Did not think of it that it'd parse it as a numeric value anyway.
comment on: http://stackoverflow.com/a/50522139
type: AnswerComment

http://stackoverflow.com/comment/90592521
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50390674
type: Comment
has text: I don't see you using conda environment. Create an environment, activate and then install the package.

http://stackoverflow.com/comment/132134891
comment on: http://stackoverflow.com/a/50519862
has text: As shown in this document (https://wiki.python.org/moin/TimeComplexity), the append and pop last of list are O(1).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87833847
has text: It throws me an error saying "system cannot find the path specified"
type: AnswerComment
comment on: http://stackoverflow.com/a/50409103
score: 0
type: Comment

http://stackoverflow.com/comment/87926366
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50455701
type: Comment
has text: I'd recommend you to use `str.format()` and let it coerce your data types into strings, e.g.:`"{} {}".format(message, timestamp)`. Otherwise you'll have to manually match the types of the data you want to concatenate.

http://stackoverflow.com/comment/87817736
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50399438
has text: It is quite normal the `producer` of messages don't live in the same application as the `consumer` which is exactly the case here. I did not include the code publishing messages because it is working perfectly fine. And `REDIS_CHANNEL` is obviously just a constant. Why does it matter what it is?
score: 0

http://stackoverflow.com/comment/88031741
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50509256
has text: So there is problem, need change them. There is multiple `NaN`s columns?
score: 0

profiling
tags question: http://stackoverflow.com/q/50508048
type: Tag
tag name: profiling

http://stackoverflow.com/a/50537033
has comment: http://stackoverflow.com/comment/88086444
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50536967
answers question: http://stackoverflow.com/q/50536967
type: Answer
has comment: http://stackoverflow.com/comment/88086426
score: 4
has comment: http://stackoverflow.com/comment/88086581
has comment: http://stackoverflow.com/comment/88086571
upvote count: 4
has comment: http://stackoverflow.com/comment/88086526
has body: Like is specified in the documentation on creating custom commands: In addition to being able to add custom command line options, all management commands can accept some default options such as --verbosity and --traceback. So that means the handle(..) function is invoked with those parameters, even if you are not interested in these. You can however easily catch those and ignore them, by making using of keyword arguments: class Command(BaseCommand): def handle(self, email, username=None, password=None, **other): # ... # perform actions pass Here other is a dictionary that maps strings to values: the parameters with which the function is called, but that are not explicitly mentioned in the signature of the function. The documentation also mentions how to specify the parameters you want to use in the handle, such that helptext can be generated when the user requests how to use the custom command. You can for example write: class Command(BaseCommand): def add_arguments(self, parser): # Positional arguments parser.add_argument('email', required=True) # Named (optional) arguments parser.add_argument( '--username', help='The username for the user', ) parser.add_argument( '--password', help='The password for the user', ) def handle(self, email, username=None, password=None, **other): # ... # perform actions pass Note that passwords are hashed in Django, hence you should use create_user(..).

http://stackoverflow.com/comment/87790967
comment on: http://stackoverflow.com/q/50387146
score: 0
type: Comment
type: QuestionComment
has text: are you sure id is a key in both the cmd1/2 tables? Are there no duplicate ids in either? I'd bet there are.

http://stackoverflow.com/comment/87811745
type: Comment
comment on: http://stackoverflow.com/q/50397391
type: QuestionComment
score: 0
has text: CPython will drop to interactive mode if it's `stdin` is connected to a TTY. The default of Popen is for the default io handles to be inherited, which connects the second interpreter to your TTY as well. Try passing `stdin=None`.

http://stackoverflow.com/comment/88396045
score: 0
type: AnswerComment
type: Comment
has text: No, dynamodb is enough , u don't need anything else
comment on: http://stackoverflow.com/a/50392007

http://stackoverflow.com/q/50510624
score: 1
favorite count: 0
type: Question
has title: How to parallelize methods when one uses Tkinter
tagged with: python
accepted answer: http://stackoverflow.com/a/50518444
tagged with: concurrency
has answer: http://stackoverflow.com/a/50518444
has comment: http://stackoverflow.com/comment/88035630
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88042129
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88042058
has body: How do I run two methods concurrently if one of them is using Tkinter objects ? Problem Setup: Method A stops method B when a given time has passed. Until then, method A displays the remaining time in a Tkinter label. Problem: Methods do not run concurrently. Python version: 2.7 OS: Windows 7 I use Threads to implement concurrency. I have read that Python has something called Global Interpreter Lock which makes threads run in serial. I assume that this causes the problem. A workaround would be to use Processes. This is not possible since Tkinter objects can not be turned into character streams ("pickle"). I get this error when I try to use Processes: PicklingError: Can't pickle 'tkapp' object. The runnable example below mimics the real program which is a lot larger. For this reason it uses the Model-View-Controller design pattern. I have copied some code from Timeout on a function call. Use case: User clicks a button. This starts a background task which can take long time. While the background task is running, the front end continuously informs the user how much time is left until the program cancels the background task. The thread running in background is not implemented so it can be stopped. But that's not what I'm wondering about anyway. from Tkinter import * from time import sleep from threading import Thread, Timer class Frontend(Tk): def __init__(self): Tk.__init__(self) self.label = Label(self, text = "", font = ("Courier", 12)) self.button = Button(self, text = "Run thread in background.", font = ("Courier", 12)) self.label.grid() self.button.grid(sticky = "nsew") class Backend: def background_task(self): print "Background task is executing." sleep(6) print "Finished." class Controller: def __init__(self): self.INTERRUPT_AFTER = 4 self.done = True self.backend = Backend() self.frontend = Frontend() self.frontend.button.configure(command = self.run_something_in_background) class Decorator(object): def __init__(self, instance, time): self.instance = instance s…
linked to: http://stackoverflow.com/q/492519
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50457479
has title: Working with Change Data Capture in InfluxDB-Python?
tagged with: influxdb
has answer: http://stackoverflow.com/a/50691091
score: 3
answer count: 2
upvote count: 3
has answer: http://stackoverflow.com/a/75469246
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: influxdb-python
has body: I am a ML programmer, and I am building a High-Frequency trading model. Once I am in production, I need to capture data directly from the market. I am using an influxdb database, i.e. a time series database (TSDB), but I don't know how to capture data in real-time. I know there exists a design pattern we can probably use which is called Change Data Capture (CDC). Could we work with CDC in InfluxDB-Python? Is it a better solution that InfluxDB works with Debezium or alone?
tagged with: cdc

http://stackoverflow.com/comment/87922564
type: Comment
comment on: http://stackoverflow.com/a/50453292
type: AnswerComment
has text: Never heard of file input before, but it does the job perfectly. This saved me a lot of time. Appreciate your help!
score: 0

http://stackoverflow.com/comment/88082054
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50515109
score: 0
has text: I have solved this issue by cleaning the cloned files however now I am running into some apk not found error... Reinstalling the whole VM.

http://stackoverflow.com/comment/88076161
has text: Yes, in my case, the files always have the same number of lines. basically, I have a lot of these files and need to put them in this format to paste them in a spreadsheet. I only included two files because it is the simplest case.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50456885
type: QuestionComment

http://stackoverflow.com/comment/87892331
type: Comment
comment on: http://stackoverflow.com/q/50439035
score: 1
type: QuestionComment
has text: https://stackoverflow.com/questions/48198676/jupyter-input-display-print-excute-order-is-chaotic

http://stackoverflow.com/comment/87973597
type: AnswerComment
score: 0
has text: Wow, that sped up the entire code by a factor of about 3. Could you please elaborate on the last two tweaks you mentioned. It isn't very clear to me how you would implement those exactly in the code.
comment on: http://stackoverflow.com/a/50478456
type: Comment

http://stackoverflow.com/comment/88061342
has text: Agree (to some extend) but might not be true when it comes to the lemmatizer though =)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50508249
type: AnswerComment

http://stackoverflow.com/a/50429321
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87873364
score: 1
has comment: http://stackoverflow.com/comment/87873553
has comment: http://stackoverflow.com/comment/87873381
type: Answer
accepted answer of: http://stackoverflow.com/q/50429208
answers question: http://stackoverflow.com/q/50429208
has body: Given a Series ser = pd.Series([1,2,3,3,3,2,1,5,2,3,1,2,4,3]) You can do the following: ser.value_counts().reindex(ser.unique()).tolist() Out: [3, 4, 5, 1, 1] Reindex will reorder the value_counts items based on the order they appear.
upvote count: 1

http://stackoverflow.com/q/50513324
has body: I have a little crawler (python, bs4) that works mostly fine. But if the text I want to crawl has more than two wordwraps (new lines) in a row, the content will be written in more than one cell. For example: AAA BBB CCC The result into a cell of the csv is "AAA BBB CCC" Bad case: AAA BBB CCC The result looks like this: Cell 1: AAA BBB Cell 2 (second row): CCC The Code is: ... beschreibung_container = container.find_all("pre", {"class":"is24qa-objektbeschreibung text-content short-text"}) or "" beschreibung = beschreibung_container[0].get_text().strip() if beschreibung_container else "" ausstattung_container = container.find_all("pre", {"class":"is24qa-ausstattung text-content short-text"}) or "" ausstattung = ausstattung_container[0].get_text().strip() if ausstattung_container else "" lage_container = container.find_all("pre", {"class":"is24qa-lage text-content short-text"}) or "" lage = lage_container[0].get_text().strip() if lage_container else "" except: print("Es gab einen Fehler") f.write(objektid + "##" + titel + "##" + adresse + "##" + criteria.replace(" ", ";") + "##" + preis.replace(" ", ";") + "##" + energie.replace(" ", ";") + "##" + beschreibung.replace("\n", " ") + "##" + ausstattung.replace("\n", " ") + "##" + lage.replace("\n", " ") + "\n") ... Is there a possibility to replace all wordwraps?
answer count: 1
type: Question
tagged with: beautifulsoup
tagged with: python-3.x
has title: crawling into csv (python)
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50513573
accepted answer: http://stackoverflow.com/a/50513573

http://stackoverflow.com/a/50429419
has body: There's a couple of issues in your code: By default .split() uses space as its delimitor, to split each line into left and right you need to pass =. You have a logic error in your condition, or allows everything in because nothing can be '-0.0' and '0.0' at the same time. Switch it to an and to make it functional, or to make it better in reality it should be testing that col[-1] equals 1.0: if col[-1] == '1.0': In order for your input to be compared correctly you should strip whitespace out, you can use a list comprehension for this: col = [n.strip() for n in line.split('=')] col will still be left with whitespace if you striped the line as a whole. Hopefully that will get you back on the right track.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50429314
type: Answer
score: 1

http://stackoverflow.com/comment/87962789
has text: @Orenshi I have seen that link - but not solving my problem.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50474488

http://stackoverflow.com/a/50401118
accepted answer of: http://stackoverflow.com/q/50400996
answers question: http://stackoverflow.com/q/50400996
type: Answer
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87818938
type: AcceptedAnswer
has body: for the erroneous case, when you reach '14', available routes are shown as '1' and '5', not as '15'. You should set a list for each set, so that you can iterate over actual values. adj_matrix = {'1': set(['2']), '2': set(['3']), '3': set(['4', '5']), '4': set(''), '5': set(['6']), '6': set(['7']), '7': set(['8']), '8': set(['9', '14']), '9': set(['10', '11']), '10': set(''), '11': set(['12', '13']), '12': set(''), '13': set(''), '14': set(['15']), '15': set(['16']), '16': set(['17']), '17': set(['18', '19']), '18': set(''), '19': set('')} using the adj_matrix above, it gives correct result. here is your function with my debuggers. You can see how code flows from the terminal: def find_path(graph, start, end, path=[]): path = path + [start] print("st:%s, end:%s, path:%s" % (start,end,path)) if start == end: return path if start not in graph: return None print("available routes: %s" % graph[start]) for node in graph[start]: if node not in path: print("next node: %s" % node) newpath = find_path(graph, node, end, path) if newpath: return newpath return None Using your erroneous adj_matrix, it gives console output like this: (Watch closely when it comes to '14') C:\Users\rapac\Desktop\stackoverflow&gt;python adjgraph.py st:3, end:15, path:['3'] available routes: {'5', '4'} next node: 5 st:5, end:15, path:['3', '5'] available routes: {'6'} next node: 6 st:6, end:15, path:['3', '5', '6'] available routes: {'7'} next node: 7 st:7, end:15, path:['3', '5', '6', '7'] available routes: {'8'} next node: 8 st:8, end:15, path:['3', '5', '6', '7', '8'] available routes: {'9', '14'} next node: 9 st:9, end:15, path:['3', '5', '6', '7', '8', '9'] available routes: {'11', '10'} next node: 11 st:11, end:15, path:['3', '5', '6', '7', '8', '9', '11'] available routes: {'13', '12'} next node: 13 st:13, end:15, path:['3', '5', '6', '7', '8', '9', '11', '13'] available routes: set() next node: 12 st:12, end:15, path:['3', '5', '6', '7', '8', '9', '11', '12'] available routes: set() next node…

http://stackoverflow.com/comment/135572597
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52518512
type: Comment
has text: It need to do an upgrade on pip3 to work correctly for me: ```pip3 install --upgrade pip```

http://stackoverflow.com/comment/87792622
comment on: http://stackoverflow.com/q/50387248
score: 0
type: QuestionComment
has text: @zwer It does indeed ressemble to json. I've been searching for a syntax that doesnt exist for too long so I am going to make my own parser for python i guess! Thanks for your help!
type: Comment

http://stackoverflow.com/q/50391868
possible better answer: http://stackoverflow.com/a/55040649
tagged with: statsmodels
tagged with: importerror
answer count: 3
has comment: http://stackoverflow.com/comment/87836375
has answer: http://stackoverflow.com/a/55040649
has comment: http://stackoverflow.com/comment/87837107
has comment: http://stackoverflow.com/comment/137283321
tagged with: python
upvote count: 18
accepted answer: http://stackoverflow.com/a/50403307
linked to: http://stackoverflow.com/q/63377745
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50403307
has title: python 3.5 in statsmodels ImportError: cannot import name '_representation'
has body: I cannot manage to import statsmodels.api correctly when i do that I have this error: File "/home/mlv/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/tools.py", line 59, in set_mode from . import (_representation, _kalman_filter, _kalman_smoother, ImportError: cannot import name '_representation' I already try to re-install or update it, that does not change. plese i need help =)
tagged with: python-3.5
downvote count: 0
score: 18
has answer: http://stackoverflow.com/a/55912291
has comment: http://stackoverflow.com/comment/87818234
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87800741
has comment: http://stackoverflow.com/comment/87837724

http://stackoverflow.com/q/50453450
downvote count: 2
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50453497
answer count: 1
has title: group dictionary by values, return key and value list pair
has answer: http://stackoverflow.com/a/50453497
upvote count: 1
has body: Considering a dictionary with several recurring values. How to group the dictionary by value? For example: mydict = { 'germany': 'europe', 'france': 'europe', 'canada': 'north america', 'latvia': 'europe' 'usa': 'north america', 'china': 'asia' } Group by value into list. groupdDict = { 'europe': ['germany','france','latvia'], 'north america': ['canada','usa'], 'asia': ['china'] }
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/483666
duplicate of: http://stackoverflow.com/q/483666

http://stackoverflow.com/comment/87867627
type: QuestionComment
score: 0
has text: @Aldream, yes. a line looks like "flowers/daisy/image.jpg, 0". I use relative path
type: Comment
comment on: http://stackoverflow.com/q/50425700

http://stackoverflow.com/q/50465217
has body: I have the following variables: klasa = '3b' szkola = 'gimnazjum' When I'm creating a dictionary and trying to do a list from this, dictionary is corruped: In [12]: list(({'szkola':szkola, 'klasa':klasa})) Out[12]: ['szkola', 'klasa'] But when I'm doing this more simple, then everything is ok: In [11]: [{'szkola':szkola, 'klasa':klasa}] Out[11]: [{'klasa': '3b', 'szkola': 'gimnazjum'}] Is there any possible to create list of dictionary by using list() function?
has comment: http://stackoverflow.com/comment/87943896
linked to: http://stackoverflow.com/q/23703109
type: AnsweredQuestion
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/50465310
accepted answer: http://stackoverflow.com/a/50465310
duplicate of: http://stackoverflow.com/q/23703109
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87943742
has title: Python list() is not creating list of dictionary correctly
type: Question
answer count: 1

http://stackoverflow.com/q/50404783
has answer: http://stackoverflow.com/a/50482834
accepted answer: http://stackoverflow.com/a/50482834
favorite count: 0
type: Question
upvote count: 5
has body: Loading an OpenFOAM case in ParaView using python is straight forward with: ofReader = OpenFOAMReader(FileName='&lt;some OpenFOAM case directory&gt;') However, by default only the internalMesh mesh region is selected in the reader object. Using the trace method of ParaView is not of any help, since the MeshRegion property of the OpenFOAMReader object is simply set to the values of the mesh regions I select via mouse input: ofReader.MeshRegions = ['internalField', 'patch1', 'patch2'] Since I do not know in advance what the mesh region names are I cannot produce such a line in my python ParaView script. How is it possible to select and load all mesh regions of an OpenFOAM case in ParaView using a python script and only ParaView Python API functionality?
score: 5
tagged with: python
type: AnsweredQuestion
tagged with: openfoam
has title: How to select all mesh regions in ParaView OpenFOAM case using python scripting?
downvote count: 0
tagged with: paraview
answer count: 1

http://stackoverflow.com/comment/87813862
type: Comment
comment on: http://stackoverflow.com/q/50398988
type: QuestionComment
score: 1
has text: You can use `index_col=False` in `read_csv()`

http://stackoverflow.com/a/50499465
type: AcceptedAnswer
downvote count: 0
has body: As far as I know, no such function exist. However, it seems fairly simple to write a function as you described in your question: from typing import Iterable, Mapping def pretty_type(obj): obj_type = type(obj).__name__ if isinstance(obj, Mapping): k, v = next(iter(obj.items())) return '{}[{}, {}]'.format(obj_type, pretty_type(k), pretty_type(v)) elif isinstance(obj, Iterable) and not isinstance(obj, str): return '{}[{}]'.format(obj_type, pretty_type(obj[0])) else: return obj_type Testing &gt;&gt;&gt; print(pretty_type(0)) int &gt;&gt;&gt; print(pretty_type({1:{"a":2.2}})) dict[int, dict[str, float]] &gt;&gt;&gt; print(pretty_type([1, 2, 3])) list[int] &gt;&gt;&gt; print(pretty_type([{1:'a'}, {2:'b'}])) list[dict[int, str]] &gt;&gt;&gt; The above code could be extend pretty easily to suit any custom input/ouput. Of course, the code obviously assumes homogeneity between elements. As you noted in your question, heterogeneous elements would be problematic, and in my opinion it really would depend on one's tastes for how they would want to deal with such cases.
accepted answer of: http://stackoverflow.com/q/50499007
upvote count: 1
answers question: http://stackoverflow.com/q/50499007
score: 1
type: Answer

http://stackoverflow.com/q/50472092
has answer: http://stackoverflow.com/a/50475315
tagged with: sql
type: UnansweredQuestion
answer count: 1
type: Question
has title: How to better construct a SQL statement with values from a Data Frame?
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87961115
tagged with: mysql
has body: consider the following SQL statement: q="SELECT H_ID, CREATION_DATE FROM HOTEL WHERE H_ID IN (700,701,702...)" the values in the parenthesis should come from a Data Frame: df=pd.DataFrame({"H_ID":[701,702,703,704,705,706,707,708,709,710],"B":[0,0,0,0,0,0,1,1,2,2], "C":[4,3,3,3,2,2,2,1,1,2]}) at the moment, what I do is this? #convert H_ID column to a string separated by comma my_ids = str(list(df["H_ID"].apply(lambda x : str(x)))).replace("[","").replace("]","") and I add it to my query: q="SELECT H_ID, CREATION_DATE FROM HOTEL WHERE H_ID IN ("+my_ids+")" Question: is there a better way to do this by avoiding the conversion to string?
score: 0
has comment: http://stackoverflow.com/comment/87958008

http://stackoverflow.com/comment/88057417
type: Comment
type: QuestionComment
has text: (cont) There are some justifications for putting imports in non-standard places, as discussed in [Should import statements always be at the top of a module?](https://stackoverflow.com/questions/128478/should-import-statements-always-be-at-the-top-of-a-module), but bear in mind that some of the answers there are a little controversial.
comment on: http://stackoverflow.com/q/50494737
score: 0

http://stackoverflow.com/comment/87990735
type: QuestionComment
comment on: http://stackoverflow.com/q/50472129
has text: @bhupathituraga, tried that and it didn't work.
score: 0
type: Comment

http://stackoverflow.com/q/50427076
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87878766
tagged with: pyqt
has comment: http://stackoverflow.com/comment/87870176
answer count: 1
tagged with: mysql
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/87878751
has comment: http://stackoverflow.com/comment/87869730
type: Question
has answer: http://stackoverflow.com/a/50429019
has comment: http://stackoverflow.com/comment/87870101
tagged with: python
has title: How can I connect my ui form to mysql and insert data using the ui form?
accepted answer: http://stackoverflow.com/a/50429019
has body: I'm trying to connect my PyQt form to MySql database. I tried to use the following codes to connect to the database and insert data but it doesn't work. Anything that I missed? I'm getting an attribute error __enter__. what does this mean? from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox from PyQt5.QtCore import pyqtSlot import mysql.connector as mdb from mainwindow import Ui_MainWindow class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.btnAdd.clicked.connect(self.InsertData) @pyqtSlot() def InsertData(self): con = mdb.connect(user='root', password='password101', host='localhost', database='sample_sys') with con: cur = con.cursor() cur.execute("INSERT INTO name_info(name, age)" "VALUES('%s','%s')" % (''.join(self.le_name.text()), ''.join(self.le_age.text()))) QMessageBox.information(self, "Connection", "Data Inserted Successfully") self.close() if __name__ == "__main__": import sys app = QApplication(sys.argv) MainWindow = MainWindow() MainWindow.show() sys.exit(app.exec_()) Thank you in advance!
has comment: http://stackoverflow.com/comment/87880557

http://stackoverflow.com/a/50460775
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50459561
downvote count: 0
upvote count: 1
has body: Rename stuff and merge rename_dict = {'name': 'full', 'info': 'company'} df1.rename(columns=rename_dict).assign( name=lambda d: d.full.str.split().str[0]).merge(df2) full company name info 0 Bill Gates Microsoft Bill aaa 1 Steve Jobs Apple Steve ccc

http://stackoverflow.com/a/70949268
type: Answer
has body: I think it's too late for answer, but I want to answer anyway. You may have already solved problem, but if it doesn't work check this out: Different links navigate you same site or etc. It is not a code error but I want to say that this could cause of selenium.common.exceptions.NoSuchElementException: Message: no such element You logged a site and if you want to go back login screen, you should log out of your account, otherwise the site will automatically navigate to the home screen because you already logged in. That's all I wanted to say.
score: 0
answers question: http://stackoverflow.com/q/50498809

http://stackoverflow.com/q/50418779
has comment: http://stackoverflow.com/comment/87853121
tagged with: terminal
tagged with: python
has comment: http://stackoverflow.com/comment/87854497
has body: In my current project, I'm trying to receive a list of values (for now I'm ok with receiving them as a list of strings as that makes a part of the code easier), a name of a file, and iterate through the values to change the value on the file in order to submit many calls to the terminal at once. The problem I have right now is, I believe, that though I'm changing the values, the submitted files are not different from the initial file because I'm failing to realize that I'm not rewriting the file correctly. 1st Part - Input if __name__ == '__main__': if len(sys.argv) &lt; 1: print "Specify the input" exit(1) f = sys.argv[1] list = ast.literal_eval(sys.argv[3]) 2nd Part - Rewriting while i &lt; len(list): with open(f, 'r+') as file: programFile = file.read() for l in range(len(node)): if i==0: valuesDic.update({"initialValue":list[i]}) else: valuesDic.update({list[i-1]:list[i]}) multiValuesChange(programFile, valuesDic) out_file = open(f, "w") out_file.write(programFile) out_file.close() call(["qsub","-l","h=node10",f]) i=i+1 3rd Part - multiValuesChange def multiValuesChange(programFile, valuesDic): rc = re.compile('|'.join(map(re.escape, valuesDic))) def translate(match): return valuesDic[match.group(0)] return rc.sub(translate, programFile) Thank you.
has comment: http://stackoverflow.com/comment/87854315
has comment: http://stackoverflow.com/comment/87854961
tagged with: replace
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: Rewriting file and calling script recurrently
accepted answer: http://stackoverflow.com/a/50419610
answer count: 1
has comment: http://stackoverflow.com/comment/87854393
tagged with: file-writing
has answer: http://stackoverflow.com/a/50419610
type: Question

http://stackoverflow.com/q/50478121
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has body: I found the following code needs "storage_account_name","storage_account_key","storage_container_name" . def invokeBatchExecutionService(): storage_account_name = "mystorageacct" # Replace this with your Azure Storage Account name storage_account_key = "a_storage_account_key" # Replace this with your Azure Storage Key storage_container_name = "mycontainer" # Replace this with your Azure Storage Container name connection_string = "DefaultEndpointsProtocol=https;AccountName=" + storage_account_name + ";AccountKey=" + storage_account_key api_key = "abc123" # Replace this with the API key for the web service url = "https://ussouthcentral.services.azureml.net/workspaces/e810bf8e16bb4dec9719b07f0205b0bb/services/bc8304cebe1a42bfb2518b302eba979d/jobs" uploadFileToBlob("input1data.file_extension", # Replace this with the location of your input file, and valid file extension (usually .csv) "input1datablob.file_extension", # Replace this with the name you would like to use for your Azure blob; this needs to have the same extension as the input file storage_container_name, storage_account_name, storage_account_key) I can find "api_key" here: But where can I find "storage_account_name","storage_account_key","storage_container_name" ?
favorite count: 0
type: Question
has title: Where can I find the "storage_account_name","storage_account_key","storage_container_name" in azure?
tagged with: python
has answer: http://stackoverflow.com/a/50478323
accepted answer: http://stackoverflow.com/a/50478323
tagged with: azure-storage
type: AnsweredQuestion
tagged with: azure

http://stackoverflow.com/a/50529996
answers question: http://stackoverflow.com/q/50529846
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88074908
has body: Note that (5,)*2 expands to (5, 5), aka is a tuple. See the docs on tuples . Re pow(): according to the docs, pow(x,y) returns x to the power y: In your script, you use the * in power(*params) to insert the two items in the params tuple as individual parameters into the function. You could have achieved the same by typing power(5,5). Thus, 5^5, which equals 3125. A intuitive tutorial on tuples is here.
score: 1
downvote count: 0

http://stackoverflow.com/q/50483235
has answer: http://stackoverflow.com/a/70584335
score: 14
type: AnsweredQuestion
has title: Python Cannot install module spaCy
has comment: http://stackoverflow.com/comment/87979540
has comment: http://stackoverflow.com/comment/87979968
has comment: http://stackoverflow.com/comment/87980143
has answer: http://stackoverflow.com/a/64839685
has answer: http://stackoverflow.com/a/58283263
possible better answer: http://stackoverflow.com/a/58283263
has answer: http://stackoverflow.com/a/57774466
has comment: http://stackoverflow.com/comment/87980227
has answer: http://stackoverflow.com/a/60202712
has body: I´m new to python and I ran into a problem I can´t solve. I would like to install and use the package spacy in python. Therefore I opened cmd and ran pip install spacy While installing the dependecies I get an error message: ---------------------------------------- Command ""c:\users\xxx\appdata\local\programs\python\python37\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\xxx\AppData\Local\Temp\pip-install-6vcdnb_4\numpy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\xxx\AppData\Local\Temp\pip-record-jhmti8_8\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\xxx\AppData\Local\Temp\pip-install-6vcdnb_4\numpy\ but I have no idea what´s the problem... Does anybody has a solution for this? I use Windows and python version 3.7.0b4
has answer: http://stackoverflow.com/a/50486811
accepted answer: http://stackoverflow.com/a/50484284
tagged with: python
has answer: http://stackoverflow.com/a/52979380
has comment: http://stackoverflow.com/comment/87980205
has answer: http://stackoverflow.com/a/65633050
has answer: http://stackoverflow.com/a/62966572
has answer: http://stackoverflow.com/a/64531063
type: Question
has answer: http://stackoverflow.com/a/77646199
has comment: http://stackoverflow.com/comment/87980215
upvote count: 14
tagged with: installation
tagged with: spacy
has answer: http://stackoverflow.com/a/62051377
has answer: http://stackoverflow.com/a/62576956
downvote count: 0
has answer: http://stackoverflow.com/a/50484284
answer count: 17
has comment: http://stackoverflow.com/comment/87979554
has answer: http://stackoverflow.com/a/75218568
has answer: http://stackoverflow.com/a/64379780
has comment: http://stackoverflow.com/comment/87980009
favorite count: 0
has answer: http://stackoverflow.com/a/53602434

http://stackoverflow.com/a/50504859
score: 0
answers question: http://stackoverflow.com/q/50482770
type: Answer
has body: Actually, it turned out to be 2 things: Firstly, in article links.txt, each link was in a new line (i.e., ended with a \n). So, I had to do a=a.rstrip() before page = requests.get(a) to get the correct soup. Without the strip, if I print out the soup, it looks like this: >>> page = requests.get('http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law\n') >>> page <Response [400]> >>> page.text <TITLE>Bad Request Bad Request - Invalid URL HTTP Error 400. The request URL is invalid. As can be seen, without stripping the \n at the end of each link, it can't extract the info in the page (in particular, there's no tag artcle-wrap in the soup it extracts). Secondly, I added both html classes, article-wrap and mag-article-wrap to accommodate for the 2 different kinds of articles: html = soup.find(class_='article-wrap') if html==None: html = soup.find(class_='mag-article-wrap') text = get_text(html.text) Now it works fine.

http://stackoverflow.com/comment/87855540
has text: Please update the code to be *real* code (without *)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50419277
type: QuestionComment

http://stackoverflow.com/comment/87959825
score: 0
type: Comment
has text: Niiiiice. Thank you. This is what I was looking for.
type: AnswerComment
comment on: http://stackoverflow.com/a/50472680

http://stackoverflow.com/comment/88051978
type: QuestionComment
has text: Please share your code, and the relevant portion of your target page as text in the body of your question.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50519769

http://stackoverflow.com/a/50459405
answers question: http://stackoverflow.com/q/50459267
has body: Simpy call the numpy method: filters_C.numpy() It is a property of the EagerTensor class, which is the subclass of Tensor that is used by default in eager execution, which explains why this property pops up then.
accepted answer of: http://stackoverflow.com/q/50459267
upvote count: 2
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50495870
answers question: http://stackoverflow.com/q/50495664
score: 0
accepted answer of: http://stackoverflow.com/q/50495664
type: Answer
has body: You can use the cv2.inrange() module. The minimum and maximum value can be placed for any image. In your case since you are using a single-channeled image you can perform something like this: masked = cv2.inRange(im, 20, 30) cv2.imshow('masked',masked) In your question you have mentioned that cv.threshold() does half the job. You need to do it twice and subtract the resultant to get the full job done! ret1, img1 = cv2.threshold(im, 20, 255, cv2.THRESH_BINARY) ret2, img2 = cv2.threshold(im, 30, 255, cv2.THRESH_BINARY) cv2.imshow('double_threshold', img1 - img2)
type: AcceptedAnswer

http://stackoverflow.com/a/50533349
type: Answer
answers question: http://stackoverflow.com/q/50533072
downvote count: 0
upvote count: 1
score: 1
has body: This line clears the list by deleting all its items. The list stays the same variable (same object), only its contents is modified: SL[:] = [] Later in the code is this line (in a loop): L.append(SL) But SL is the same variable each time. All items in L refer to the same list SL. So when SL is modified, all items in L refer to the new contents of SL. This can be fixed by creating a new list for each result.

http://stackoverflow.com/q/50416322
answer count: 1
downvote count: 0
upvote count: 1
has title: How to selectively prettify certain elements of json in python
favorite count: 0
type: Question
has body: How is it possible to selectively prettify json files in python based on the key. For example, although i want it generally prettified, i want dictionaries under the key "DATE" to collapse to a single line to conserve space. { "String_entered": "string", "DATE": { "year":2013, "month":null, "day":null }, } To: { "String_entered": "string", "DATE": {"year":2013,"month":null,"day":null}, }
has answer: http://stackoverflow.com/a/50416849
tagged with: python
has comment: http://stackoverflow.com/comment/87848273
type: UnansweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/87813715
comment on: http://stackoverflow.com/q/50398738
has text: Use pandas, `import pandas as pd` `pd.DataFrame({'scooby':scooby,'snacks':snacks}).groupby('scooby',as_index=False)['snacks'].max().apply(tuple, 1).tolist()`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87852746
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50399588
has text: Hi rth, what if I want to set color to several countries all together? Say set red to ten different countries, is there a way to do it systematically in one or two lines of code instead of repeating the same code ten times? Ty.
type: Comment

http://stackoverflow.com/comment/87943459
score: 0
has text: @Rakesh: No, its direct html in python with other data tables which contains variable passed.
type: QuestionComment
comment on: http://stackoverflow.com/q/50464361
type: Comment

pyopenssl
tag name: pyopenssl
tags question: http://stackoverflow.com/q/50474361
type: Tag

http://stackoverflow.com/a/50415725
has body: You can use grid() inside Frame. Here is an example. Hope it helps... import tkinter as tk from tkinter import * from tkinter import ttk class GUI: def __init__(self, master): mainframe = ttk.Frame(master) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) list1 = Listbox(master, bd=0) list1.grid(column=0, row=0) list2 = Listbox(master, bd=0) list2.grid(column=1, row=0) separator1 = Frame(list1, height=2, bd=1, relief=SUNKEN) separator1.grid(column=0, row=0) separator2 = Frame(list1, height=2, bd=1, relief=SUNKEN) separator2.grid(column=1, row=0) separator3 = Frame(list2, height=2, bd=1, relief=SUNKEN) separator3.grid(column=2, row=0) separator4 = Frame(list2, height=2, bd=1, relief=SUNKEN) separator4.grid(column=3, row=0) e1 = Label(separator1, text='Label1') e1.grid(sticky=W+E) e2= Label(separator2, text='Label2') e2.grid(sticky=W+E) e3 = Label(separator3, text='Label3') e3.grid(sticky=W+E) e4= Label(separator4, text='Label4') e4.grid(sticky=W+E) root = Tk() my_gui = GUI(root) root.mainloop() Here's a very nice explanation for tkinter http://effbot.org/tkinterbook/grid.htm
has comment: http://stackoverflow.com/comment/87850708
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50415496

http://stackoverflow.com/q/50477664
score: 2
has answer: http://stackoverflow.com/a/50477710
tagged with: pandas
has comment: http://stackoverflow.com/comment/87969037
has comment: http://stackoverflow.com/comment/88009667
tagged with: python
has title: Count iterations of pandas dataframe apply function
upvote count: 3
type: UnansweredQuestion
answer count: 1
has body: I'm looking for a way to count how many times my database function runs. My code looks like this df = pd.read_csv("nodos_results3.csv") df['URL_dashboard'] = df.apply(create_url, axis = 1) df.to_csv('nodos_results4.csv', index = False) I want to count how many times the function "create_url" runs. If I was in C++, for example, I would simply have the function take in another input create_url(database i_DB, int i_count) { //stuff I want done to database i_count++; } but I'm not sure how to do something equivalent using pandas dataframe apply. Update: For anyone who might find this while googling in the future - I personally didn't solve this issue. I was moved to another project and didn't continue working on this. Sorry I can't be more help.
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/88071605
type: Comment
has text: @Kalyan That was my question, yes. I wanted to ask if it is possible to print out variables 'without' making the list of variables.
type: AnswerComment
comment on: http://stackoverflow.com/a/50529568
score: 0

http://stackoverflow.com/a/50434116
has body: For example: names = ['ron', 'james', 'kevin07'] best = max([len(i) for i in names]) print(best)
upvote count: 2
answers question: http://stackoverflow.com/q/50434088
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/87802650
type: Comment
comment on: http://stackoverflow.com/q/50392795
has text: You are missing a non-linear activation function in your MLP.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87839389
score: 1
has text: as I've said and as you see, peaks are almost removed from image and they are the most important for me.
type: Comment
comment on: http://stackoverflow.com/a/50411847
type: AnswerComment

http://stackoverflow.com/comment/112105436
type: AnswerComment
has text: See https://stackoverflow.com/a/29938398/498463 for a python 2.7 compatible equivalent of this
type: Comment
comment on: http://stackoverflow.com/a/50492861
score: 0

http://stackoverflow.com/q/50388366
has comment: http://stackoverflow.com/comment/87793596
downvote count: 0
has title: How to read pandas CSV file with comma separator and comma thousand separator
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87794306
has comment: http://stackoverflow.com/comment/87795576
has comment: http://stackoverflow.com/comment/87793294
has body: I have a csv file with rows that looks like this: 87.89,"2,392.05",14.77,373.2 ( third row has coma thousand separator) pandas keeps considering the comma in second column as a row separator and showing "Error tokenizing data" Error. is there a away in pandas to ignore comas between double quotes? thanks sample rows : 9999992613813558569,87.89,"2,392.05",14.77,373.2 9999987064038821584,95.11,"3,397.04",42.15,"1,461.14" 9999956300203713283,6.67,194.02,41.23,"1,105.45" 9999946809576027532,15.08,353.84,29.43,591.9 Edit: i already tried : read_csv(file, quotechar='"', encoding='latin1', thousands=',') read_csv(file, quotechar='"', encoding='latin1', escapechar ='"')
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50388564
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50388564
has comment: http://stackoverflow.com/comment/87793925
favorite count: 0
possible better answer: http://stackoverflow.com/a/58173312
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/58173312

http://stackoverflow.com/q/50470726
upvote count: 4
score: 4
tagged with: optimization
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50471214
tagged with: performance
downvote count: 0
tagged with: pandas
answer count: 1
has body: Suppose we have a dataframe of 100.000 rows and 3 columns, structured like so: | visitorId | timestamp | url | 1 | 1 | 11 | A | 2 | 1 | 12 | B | 3 | 2 | 21 | A | 4 | 3 | 31 | A | 5 | 3 | 32 | C | . . n | z | Z1 | A | This dataframe is always sorted, and stored in a variable called sortedData. First, we extract all the unique visitor IDs into a list called visitors, and create a path variable to hold all the URLs this visitor has visited. visitors = sortedData.visitorId.unique() visitors = visitors.tolist() paths = [] visitor_length = len(visitors) Now what I did was go into a loop for each visitor in order to find and store each visitor's traversed path, their timestamp and ID, and use it as an input in a secondary algorithm(not relevant). I went two ways to do this: A: for visitor in visitors: dataResult = sortedData.loc[sortedData['visitorId'] == visitor] timestamps = dataResult.timestamp.tolist() path = dataResult.pageUrl.tolist() paths.append((visitor, timestamps, path)) sortedData = sortedData.iloc[len(dataResult):] This uses the built-in pandas loc function to find the rows with the matching visitorId and extract the timestamps and paths into lists, and finally append them together. Then it goes on to delete the first x rows (equal to the length of the query result, aka the number of matches) in order to not traverse them in the future when doing similar matches. The process is repeated for every unique visitor in the visitors list. By timing this, I found that it took about 6.31 seconds to complete. In my case this was an 11.7MB file, 100.000 rows. On a 1.2GB file this scaled up to 14 hours. As such, I tried way B hoping for a speedup. Way B uses the logic that the data is always sorted, as such visitor 1 in visitors will always be the 1st visitor in sortedData, visitor 2 the 2nd etc. So I could use the pandas value_counts() function to count the occurrences x of the current visitor, and simply extract the data from the first x rows using head(x), since they …
tagged with: dataframe
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87958899
has answer: http://stackoverflow.com/a/50471214
has title: Pandas performance: loc vs using .head(x) in first x rows using Sorted Data
tagged with: python

python-unicode
tags question: http://stackoverflow.com/q/50455859
type: Tag
tags question: http://stackoverflow.com/q/50520222
tag name: python-unicode

http://stackoverflow.com/q/50392498
type: Question
has body: So I have one page which contains a form so that the user can submit data to the database and a second page which contains specific fields from that record by using the assigned pk value. My question is whether I can use the submit button to post the data to the database and then immediately load up a URL with the pk value from that submitted record to use some of the fields? Or would this need to be done in 2 steps? i.e. 1. insert data into DB, then 2. load the URL with the relevant pk.. urls.py: from django.urls import path from django.conf.urls import url, include from django.views.generic import TemplateView from .views import * from . import views urlpatterns = [ url(r'^$', UserView.as_view(), name='user_new.html'), # form temporarily directs here after saving the data to the DB url(r'^thanks/$', TemplateView.as_view(template_name='thanks.html'), name='thanks'), # I would like it to go here instead path('adherence_agreement/<int:id>', views.adherence_agreement, name='adherence_agreement'), ] views.py: from django.views.generic.edit import FormView,CreateView class UserView(CreateView): template_name = 'user_new.html' form_class = UserForm success_url = 'thanks/' def post(self, request, *args, **kwargs): self.object = None if request.method == 'POST': form = UserForm(data=request.POST) if form.is_valid(): form.save() return self.form_valid(form) else: return self.form_invalid(form) else: form = UserForm() def adherence_agreement(request, id): item = get_object_or_404(UserInfo, pk=id) return render(request, 'adherence_agreement.html', {'item': item}) At the moment, after you have clicked the "submit" button, the info is saved to the DB correctly and a basic page that says "Thanks!" is displayed (thanks.html). Also, if I enter the URL http://127.0.0.1:8000/userregistration/adherence_agreement/6 it takes me to a page that has certain fields pulled from that record (I manually enter the 6 in the URL based on a record in the DB). adherence_agreement.html: {% extends …
has title: Django: pull pk from form submitted data into subsequent URL
tagged with: django
accepted answer: http://stackoverflow.com/a/50392811
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: django-views
answer count: 1
tagged with: django-urls
has answer: http://stackoverflow.com/a/50392811
tagged with: django-forms

http://stackoverflow.com/q/50447034
has body: I am using JupyterLab version 0.32.1, pandas version 0.22.0, scipy version 0.19.1, numpy version 1.14.2. My python version is: 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)]. I have realised that JupyterLab crashes when I attempt to do the following: import scipy import numpy import pandas as pd filename ='pima-indians-diabetes.data.csv' data=pd.read_csv(filename) data.head() The webpage with my notebook restarts automatically every time I run the cell with data.head(). The same happens if you try to read (with pandas) a csv from a url. Is this a known issue? Is there any workaround available? NB: please find the csv file here: https://github.com/cxd/au.id.cxd.Math/blob/master/data/test-pima-diabetes/raw-pima-indians-diabetes.csv
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87907996
tagged with: pandas
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87908186
tagged with: jupyter-lab
tagged with: crash
has comment: http://stackoverflow.com/comment/87907747
type: Question
has title: JupyterLab crashes when printing df.head()

http://stackoverflow.com/a/50504361
has comment: http://stackoverflow.com/comment/88021009
has comment: http://stackoverflow.com/comment/88021357
has comment: http://stackoverflow.com/comment/88021342
downvote count: 1
has comment: http://stackoverflow.com/comment/88022779
has comment: http://stackoverflow.com/comment/88021523
answers question: http://stackoverflow.com/q/50503960
has comment: http://stackoverflow.com/comment/88022444
upvote count: 8
score: 7
has comment: http://stackoverflow.com/comment/88021070
type: Answer
has comment: http://stackoverflow.com/comment/88021129
has comment: http://stackoverflow.com/comment/112859901
has comment: http://stackoverflow.com/comment/88021658
has body: The dpi is just a number in the JPEG/TIFF/PNG header. It is entirely irrelevant to the world and his dog until you print the image and then it determines how large the print will be given the image's dimensions in pixels. During image processing, it is irrelevant. The only thing of any interest is the number of pixels you have. That is the ultimate determinant of image quality, or information content - however you want to describe it. I don't believe you can set it with OpenCV. You can certainly set it with ImageMagick like this in the Terminal: mogrify -set density 300 *.png # v6 ImageMagick magick mogrify -set density 300 *.png # v7 ImageMagick You can check it with: identify -format "Density: %x x %y" SomeImage.jpg # v6 ImageMagick magick identify -format ... as above # v7 ImageMagick You can do similar things with exiftool in Terminal - note that exiftool is MUCH smaller and easier to maintain than ImageMagick because it is "just" a (very capable) single Perl script: Extract image resolution from EXIF IFD1 information: exiftool -IFD1:XResolution -IFD1:YResolution image.jpg Extract all tags with names containing the word "Resolution" from an image|: exiftool '-*resolution*' image.jpg Set X/Y Resolution (density) on image.jpg: exiftool -xresolution=300 -yresolution=300 image.jpg Here is a little demonstration of what I mean at the beginning of my answer... Use ImageMagick to create an image 1024x768 with no dpi information: convert -size 1024x768 xc:black image.jpg Now examine it: identify -verbose image.jpg Image: image.jpg Format: JPEG (Joint Photographic Experts Group JFIF format) Mime type: image/jpeg Class: PseudoClass Geometry: 1024x768+0+0 Units: Undefined Colorspace: Gray Type: Bilevel ... ... Now change the dpi and set the dpi units and examine it again: mogrify -set density 300 -units pixelsperinch image.jpg # Change dpi identify -verbose image.jpg # Examine Image: image.jpg Format: JPEG (Joint Photographic Experts Group JFIF format) Mime type: image/jpe…
has comment: http://stackoverflow.com/comment/88022401

http://stackoverflow.com/comment/87934710
score: 0
comment on: http://stackoverflow.com/q/50460719
type: Comment
has text: Please show a full (including the '#!' if you use one, otherwise the command used to invoke) code that generates this error.
type: QuestionComment

http://stackoverflow.com/a/50470316
type: Answer
accepted answer of: http://stackoverflow.com/q/50465122
score: 2
answers question: http://stackoverflow.com/q/50465122
type: AcceptedAnswer
downvote count: 0
has body: Post your image with FileReader API (readAsDataURL). Write your image into a file with python (beware of base64 encoding) Then return a Json with Flask (either error or success) Display image or error message depending on result from server. I hope this is enough information. Happy coding
upvote count: 2
has comment: http://stackoverflow.com/comment/87991314

http://stackoverflow.com/a/50455406
answers question: http://stackoverflow.com/q/50443513
has comment: http://stackoverflow.com/comment/92811079
accepted answer of: http://stackoverflow.com/q/50443513
score: 2
has comment: http://stackoverflow.com/comment/92812600
has comment: http://stackoverflow.com/comment/92854043
has comment: http://stackoverflow.com/comment/92813710
type: AcceptedAnswer
downvote count: 0
has body: This message shows up in exception's formatting in Python 3 if another exception was raised in an exception handler or finally clause for the first one: A similar mechanism works implicitly if an exception is raised inside an exception handler or a finally clause: the previous exception is then attached as the new exception’s __context__ attribute Setting a breakpoint on the test in PyCharm, then stepping further into the machinery shows where this second exception is thrown. _jb_unittest_runner patches the assert methods in unittest: PyCharm Community Edition\helpers\pycharm\_jb_unittest_runner.py: from teamcity import unittestpy PyCharm Community Edition\helpers\pycharm\teamcity\unittestpy.py: def run(self, test): &lt;...&gt; patch_unittest_diff(subtest_filter) &lt;...&gt; PyCharm Community Edition\helpers\pycharm\teamcity\diff_tools.py: def patch_unittest_diff(&lt;...&gt;): old = unittest.TestCase.assertEqual def _patched_equals(self, first, second, msg=None): try: old(self, first, second, msg) return except AssertionError as native_error: if not test_filter or test_filter(self): error = EqualsAssertionError(first, second, msg) if error.can_be_serialized(): raise error raise native_error unittest.TestCase.assertEqual = _patched_equals
has comment: http://stackoverflow.com/comment/92810374
upvote count: 2
type: Answer

http://stackoverflow.com/a/50502349
answers question: http://stackoverflow.com/q/50499617
type: Answer
has body: Looks there is some pty related configuration wrong for this user and VM. Even I was not able to run the command from SSH -t and -T. Both of them hung up. ssh -t -i tej.pem tej@10.90.242.76 "ls -ltr /tmp" On a different machine I was able to pass through and is working fine.
score: 0

http://stackoverflow.com/comment/88060804
type: QuestionComment
comment on: http://stackoverflow.com/q/50523421
has text: Typo. A set can exist with itself. Will fix.
score: 1
type: Comment

http://stackoverflow.com/comment/87911206
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50440724
has text: Put the file in desktop and give the function the full path to it and I tried the code even with knowing that it's working and guess what it worked, of course.

http://stackoverflow.com/comment/87998236
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50487743
has text: Thanks a lot, I just checked when I call from script, the virtualenv path is not there, whereas in python shell its there, why???from the script: ['/home/sudip/myapp', '/usr/local/bin', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] in python shell within the virtualenv: ['/home/sudip/myapp/venv/lib/python3.6/site-packages
type: QuestionComment

http://stackoverflow.com/a/50433182
answers question: http://stackoverflow.com/q/50432645
has body: With the problem as stated, there is no reason you cannot use direct key-value assignment: con = {'a':{'b':'c'}, 'b':{'d':'e'}} con['a']['e'] = 'f' print(con) {'a': {'b': 'c', 'e': 'f'}, 'b': {'d': 'e'}} Notice we can chain dictionary keys. This is natural because con['a'] returns a dictionary, which can itself be assigned a new key-value pair.
type: Answer
score: 0

http://stackoverflow.com/q/50391967
has title: How to visualize a TFRecord?
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54840213
has body: I was asked this on another forum but thought I'd post it here for anyone that is having trouble with TFRecords. TensorFlow's Object Detection API can produce strange behavior if the labels in the TFRecord file do not align with the labels in your labels.pbtxt file. It will run, loss will likely decrease but the network will not produce good detections. Also, I for one always get confused between X-Y, row-col space, and so I always like to double check to make sure that my annotations are actually annotating the right parts of the image. The best way I've found to do this is by decoding the TFRecord and plotting it with TF tools. Here's some code below: import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from object_detection.utils import visualization_utils as vu from object_detection.protos import string_int_label_map_pb2 as pb from object_detection.data_decoders.tf_example_decoder import TfExampleDecoder as TfDecoder from google.protobuf import text_format def main(tfrecords_filename, label_map=None): if label_map is not None: label_map_proto = pb.StringIntLabelMap() with tf.gfile.GFile(label_map,'r') as f: text_format.Merge(f.read(), label_map_proto) class_dict = {} for entry in label_map_proto.item: class_dict[entry.id] = {'name':entry.display_name} sess = tf.Session() decoder = TfDecoder(label_map_proto_file=label_map, use_display_name=False) sess.run(tf.tables_initializer()) for record in tf.python_io.tf_record_iterator(tfrecords_filename): example = decoder.decode(record) host_example = sess.run(example) scores = np.ones(host_example['groundtruth_boxes'].shape[0]) vu.visualize_boxes_and_labels_on_image_array( host_example['image'], host_example['groundtruth_boxes'], host_example['groundtruth_classes'], scores, class_dict, max_boxes_to_draw=None, use_normalized_coordinates=True) plt.imshow(host_example['image']) plt.show()
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/69199064
tagged with: python
tagged with: object-detection
score: 12
upvote count: 12
answer count: 3
downvote count: 0
tagged with: tfrecord
has answer: http://stackoverflow.com/a/56544678

http://stackoverflow.com/a/78969252
answers question: http://stackoverflow.com/q/50426248
has body: It may be too late to submit an answer. But nevertheless, I recently did the below: Load the model and save the model as a json file. Then load the json file and print the num_tree details from the the json file. You may check the below code snippet: Run it as (after saving the code snippet to a file xgb_tree_count.py): python xgb_tree_count.py model-file-path import sys import json import xgboost as xgb if len(sys.argv) &lt; 2: print(f'Usage: {sys.argv[0]} &lt;model-file&gt;') exit(1) loaded_model = xgb.Booster() loaded_model.load_model(sys.argv[1]) loaded_model.save_model('/tmp/a_model.json') with open('/tmp/a_model.json', 'r') as fp: jsonrepr = json.load(fp) print(jsonrepr['learner']['gradient_booster']['model']['gbtree_model_param']['num_trees'])
type: Answer
score: 0

http://stackoverflow.com/comment/87951872
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50468535
has text: @piRSquared I do agree about the `None==None` but for some reason I don't observe this
type: AnswerComment

collaboration
type: Tag
tags question: http://stackoverflow.com/q/50495947
tag name: collaboration

http://stackoverflow.com/q/50387105
has comment: http://stackoverflow.com/comment/114899841
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87791811
favorite count: 0
type: Question
tagged with: object-detection-api
answer count: 0
type: UnansweredQuestion
has body: System information - What is the top-level directory of the model you are using: object_detection - Have I written custom code (as opposed to using a stock example script provided in TensorFlow): No, just a small tweak for inference - OS Platform and Distribution (e.g., Linux Ubuntu 16.04):Ubuntu 16.04 - TensorFlow installed from (source or binary): conda - TensorFlow version (use command below): 1.4.0 - GPU model and memory: Nvidia GTX 1060 6GB Problem: Theoretically, running inference on a batch of n images (n is the maximum number of images the GPU can accommodate) and 1 image should take almost the same time. I am trying to do batch inference using the faster_rcnn_inception_v2_coco's frozen_inference_graph. Visualizing the frozen inference graph shows that the input is of shape (None,None,None,3), thus I can safely process a batch of images simultaneously. . But when I tried processing a batch of 1 image vs a batch of 10 images, I didn't get the same inference time The last block in the object detection tutorial Ipython Notebook is modified as follows and the graph used is faster_rcnn_inception_v2_coco. import cv2 itr_num = 10 batch_size = 1 inference_times = [] with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: # Definite input and output Tensors for detection_graph image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular object was detected. detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') for im_num in range(itr_num): images = [cv2.cvtColor(cv2.imread(TEST_IMAGE_PATHS[1]),…
tagged with: python
tagged with: object-detection
has comment: http://stackoverflow.com/comment/87792368
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/52765373
has comment: http://stackoverflow.com/comment/94559479
has title: Time for processing a batch of images at once is almost equal to processing them sequentially in order
downvote count: 0

http://stackoverflow.com/a/50407224
has body: It seams that the ordering in the User model is overwritten by the ordering specified in UserAdmin. Specifying my own UserAdmin solved the problem. class MyUserAdmin(UserAdmin): ... ordering = ["last_name", "first_name"] ... admin.site.register(User, MyUserAdmin)
score: 0
answers question: http://stackoverflow.com/q/50394250
type: Answer

http://stackoverflow.com/a/50508701
upvote count: 1
score: 1
type: Answer
has body: lda_model = LatentDirichletAllocation(n_topics=NUM_TOPICS, max_iter=10, learning_method='online' random_state = 42) Worked ...!!! Thanks a lot Also, I had tried for this import numpy as np np.random.seed(42) But It is not effective. Thanks for resolution
downvote count: 0
has comment: http://stackoverflow.com/comment/88029300
answers question: http://stackoverflow.com/q/50446257

http://stackoverflow.com/a/50514143
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50513960
answers question: http://stackoverflow.com/q/50513960
has body: &gt;&gt;&gt; cd.scan('/tmp/EICAR') {'/tmp/EICAR': ('FOUND', 'Eicar-Test-Signature')} cd.scan('/tmp/EICAR') returns a dictionary. You can access values in dictionaries by their keys. In this case, the key is /tmp/EICAR. The value for that key is a tuple. To access a member of a tuple, you can do so just like you would with an array - tuplename[index]. result = cd.scan('/tmp/EICAR') if (result['tmp/EICAR'][0] == 'FOUND'): print("Send email") Similarly, the value 'Eicar-Test-Signature' in this case can be accessed via result['tmp/EICAR'][0]. I don't know what the side effects of the cd.scan function are, but you could bypass the variable result entirely and just use cd.scan('/tmp/EICAR')['/tmp/EICAR'][1] to access 'Eicar-Test-Signature'. Keep in mind if the cd.scan function fails or returns something other than what you expect, the key /tmp/EICAR may not be in the dictionary (I don't how the clamd library works or what it does). In that case, you can check whether a key exists in a dictionary like this: if '/tmp/EICAR' in result: print('key is present')
score: 1

http://stackoverflow.com/q/50475732
tagged with: statistics
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50475910
score: 1
tagged with: python
tagged with: scipy
has title: Calculating confidence levels of a distribution
downvote count: 0
accepted answer: http://stackoverflow.com/a/50475910
upvote count: 1
answer count: 1
has body: I have a set of data that looks like this: data = [1,1,2,3,3,5,5] point = 6 I do not know if this data is normal or anything else about its distribution. I would like to calculate with some confidence that point is significantly higher than the data. I have tried: import math from scipy.stats import t import numpy as np confidence = ( t.interval(0.95,len(data)-1,loc=np.mean(data), scale=np.std(data)/math.sqrt(len(data)))) This returns a lower and upper bound, but often when handling my actual data, the point I use appears to be significantly elevated, but is well below many of the numbers contained in data. Am I using the best test or is there something better?
has comment: http://stackoverflow.com/comment/87969150
favorite count: 0
type: Question

http://stackoverflow.com/a/50534946
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50532819
has body: You are getting this error because you are providing invalid hostnames. You should provide IPs of the routers in your file.

http://stackoverflow.com/q/50428919
has comment: http://stackoverflow.com/comment/87872853
has comment: http://stackoverflow.com/comment/87872727
tagged with: flask
has comment: http://stackoverflow.com/comment/87873168
downvote count: 1
favorite count: 0
type: Question
score: 0
has body: I am building a Python web app using Flask and SQLite as the DB. I get the above error when I attempt to login and validate user info from the database. My other database form inputs work and I am able to update and select data, so the database exists and the connection works in some parts of the app. The login script seems to be the issue. @app.route('/login', methods=['POST', 'GET']) def do_admin_login(): if request.method == "POST": u_stmt="SELECT CASE WHEN '"+ request.form['username'] +"' IN (SELECT uname FROM logins) THEN 1 ELSE 0 END" #uname in logins p_stmt="SELECT pword FROM logins WHERE uname = '"+request.form['username']+"'" # retrieve pwd of uname s_stmt="SELECT salt FROM logins WHERE uname = '"+request.form['username']+"'" # retrieve salt of uname print u_stmt print p_stmt print s_stmt with sql.connect("database.db") as con: cur = con.cursor() pwd = cur.execute(p_stmt) uname = cur.execute(u_stmt) salt = cur.execute(s_stmt) print uname print pwd print salt con.commit() con.close() hashed_password = hash_password(request.form['password'], salt) if hashed_password == pwd and uname == 1: session['logged_in'] = True flash('right password!') return render_template('home.html') else: flash('wrong password!') return home() else: return render_template('login.html') Here is the code from my login.html Login Log in Sign up Stacktrace (methinks) Any help is greatly appreciated. Thank you! def hash_password(password, salt): """ Take a password and a salt, and return a hashed password """ password_string = (password + salt).encode('utf-8') hashed_password = hashlib.sha512(password_string).hexdigest() return hashed_password def get_auth_for_user(user_id): """ Take a user_id, and return what we know about that user """ db_cursor.execute("SELECT * FROM user WHERE id=" + user_id) result = db_cursor.fetchone() return result Traceback with SQL output
tagged with: sqlite
has comment: http://stackoverflow.com/comment/87874548
has title: TypeError: coercing to Unicode: need string or buffer, sqlite3.Cursor found
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50451899
upvote count: 1

http://stackoverflow.com/comment/87976964
type: QuestionComment
has text: @J.A.Cado, Sorry for messing up the spacings, as initially, I had deleted some columns. Now , I just added the header and added 4 spacing between the columns. thanks
type: Comment
comment on: http://stackoverflow.com/q/50480997
score: 0

http://stackoverflow.com/comment/88144094
type: AnswerComment
comment on: http://stackoverflow.com/a/50550724
has text: Thanks @Norrus. It's helpful.
type: Comment
score: 0

http://stackoverflow.com/q/50494541
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88004989
has comment: http://stackoverflow.com/comment/88005287
tagged with: converters
has comment: http://stackoverflow.com/comment/88002980
has comment: http://stackoverflow.com/comment/88005725
possible better answer: http://stackoverflow.com/a/76775655
tagged with: python
tagged with: image
has comment: http://stackoverflow.com/comment/88001925
favorite count: 0
type: Question
has body: I want to convert my b&amp;w image(.png) to binary array(black is 1 white is 0). I have written some code, but it's not working. Error says: argument 2 to map() must support iteration. Here is my code: from PIL import Image from resizeimage import resizeimage import sys def threshold(col): s = sum(col) return int(s &gt; 255 * 3 // 2) img = Image.open("filename.png") ratio = float((img.size[1]) / (img.size[0])) img = resizeimage.resize_cover(img, [100, int(ratio * 100)]) pixels = img.getdata() binary = list(map(threshold, img)) array2d = [binary[i * img.size[0] : (i+1) * img.size[0]] for i in range(img.size[1])] print('\n'.join(''.join(map(str, line)) for line in array2d)) Here is the image:
has title: B&W image to binary array
score: 2
tagged with: binary
has comment: http://stackoverflow.com/comment/88002798
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88003729
linked to: http://stackoverflow.com/q/138250
accepted answer: http://stackoverflow.com/a/50496481
downvote count: 0
has answer: http://stackoverflow.com/a/50496481
has answer: http://stackoverflow.com/a/76775655
has comment: http://stackoverflow.com/comment/88002127
has comment: http://stackoverflow.com/comment/88005139

http://stackoverflow.com/q/50432033
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50432235
tagged with: enumerate
has answer: http://stackoverflow.com/a/50432125
score: 0
tagged with: pagination
tagged with: selenium
has body: I'm using selenium to scrape a directory and i'm using the enumerate operator to give me index. The problem is every time I go to a new page the idx starts over. So for example, if there are 15 listings per page, I get the idx repeating 0-15 for a list of 150 listings. How can I append the idx for each page in the pagination? while next_page is not None: for idx, company in enumerate(company_links_elements): company_id = idx company_url = company.get_attribute("href") # company_name = company.get_attribute("text") # company_address = remove_html_tags(company_address_elements[idx].get_attribute("innerHTML")) # writer.writerow((company_name, company_url, company_address)) writer.writerow((idx, company_url)) time.sleep(random.randint(1, 3)) next_page.click()
has title: Append index to for loop for pagination
type: Question
answer count: 2

http://stackoverflow.com/comment/87929525
has text: @Aran-Fey I have edited the question clarifying a bit further. I hope this will clear the confusion.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50457685

http://stackoverflow.com/comment/88016374
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50501926
has text: Totally agree, please show what you already have and what's the issue. However - is that really a regex problem? You know that your string starts with 15 letters ("Gold Coast area") and ends with 1 ("."). So your searched substring is s[15:-1].strip(), right?
type: Comment

http://stackoverflow.com/a/50511512
has body: You can try the following approach (not sure if it will work, but seems clean): Get the weights of your model and save it with numpy: #in 2.7 weights = model.get_weights() np.save('weights27.npy', weights) Create the model again via code in Python 3: #in python 3, do no load the saved model, create a new one: #same layers, same sizes, everything ...model code... model3 = Model(...) Load the weights into the model: model3.set_weights(np.load('weights27.npy')) Try using the model. Trying to work around the pickle problem: weights = model.get_weights() for i,w in enumerate(weights): np.save('weights-' + str(i) + ".npy", w, allow_pickle=False) In python 3: weights = [] for i in range(theTotalNumberOfSavedWeights): weights.append(np.load("weights-" + str(i) + ".npy", allow_pickle=False)) model2.set_weights(weights)
type: Answer
has comment: http://stackoverflow.com/comment/88039085
has comment: http://stackoverflow.com/comment/88035731
score: 0
answers question: http://stackoverflow.com/q/50511007
has comment: http://stackoverflow.com/comment/88036137
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88035469
accepted answer of: http://stackoverflow.com/q/50511007

http://stackoverflow.com/comment/88051412
type: AnswerComment
has text: What kind of model is this? If it's not an RNN, RL, or other time series model, then the model is most likely assuming IID and will not perform well under these assumptions. If your data is sequential you should probably look into an RNN, in which case you'll be modeling your dataset such that one sample is 3751 "timesteps". There is no sequence to a batch, each sample of a batch is independently computed and the gradients are simply averaged at the end.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50519277

http://stackoverflow.com/comment/87854021
type: Comment
has text: @deceze As I've said in the other answer, I'm trying to see how far I can bend the language without resorting to either string interpolation and an exec or frame jumping etc. It just feels wrong that such a thing can't be implemented.
type: QuestionComment
comment on: http://stackoverflow.com/q/50418785
score: 0

http://stackoverflow.com/q/50437365
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/87889704
has comment: http://stackoverflow.com/comment/87901598
tagged with: python
has title: TypeError: float() argument
favorite count: 0
score: -1
accepted answer: http://stackoverflow.com/a/50454612
type: Question
has comment: http://stackoverflow.com/comment/87920120
has answer: http://stackoverflow.com/a/50454612
has comment: http://stackoverflow.com/comment/87889621
has comment: http://stackoverflow.com/comment/87900243
downvote count: 2
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87900293
has body: I'm new with python, I have a problem with array in python. So I have a data with a list like this and I give a variable name of this list is fitur: [['F11', '1', '0', '0'], ['F2', '1', '1', '0'], ['F4', '1', '0', '0']] And then I have a probability with condition positif and negatif, in index[0] is belongs to F11 index[1] belongs to F2 and index[2] belongs to F4 Here is positif (bpf_pos) [0.42857142857142855, 0.5714285714285714, 0.5714285714285714] and here is negatif (bpf_neg) [0.14285714285714285, 0.2857142857142857, 0.2857142857142857] And I have the formula: f_pd_neg = (bpf_neg[i] ** float(uji[1])) * ((1 - bpf_neg[i]) ** (1 - float(uji[1]))) f_pd_pos = (bpf_pos[i] ** float(uji[1])) * ((1 - bpf_pos[i]) ** (1 - float(uji[1]))) So here is my problem i wanna calculate probability in the formula with the fitur. For the example bpf_neg[0] ** 1 (from the list in F11) * ((1- bpf_neg[0] ** (1 - 1) and so on until the value in list F11 finished And my expectation I have the output like this Positif is: 0 [0.571428571,0.571428571,0.428571429] 1 [0.428571429,0.571428571,0.571428571] 2 [0.571428571,0.428571429,0.428571429] Negatif is: 0 [0.285714286,0.285714286,0.714285714] 1 [0.142857143,0.857142857,0.857142857] 2 [0.285714286,0.714285714,0.714285714] And this is my code: d_neg = [] d_pos = [] for i, uji in enumerate(ab): f_pd_neg = (bpf_neg[i] ** float(uji[1])) * ((1 - bpf_neg[i]) ** (1 - float(uji[1]))) f_pd_pos = (bpf_pos[i] ** float(uji[1])) * ((1 - bpf_pos[i]) ** (1 - float(uji[1]))) d_pos.append(f_pd_pos) d_neg.append(f_pd_neg) I tried float(uji[1:]) I got the error TypeError: float() argument must be a string or a number How can I fix it? and I hope you understand because my english was terrible
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/50433473
has title: How to replace a part of a string in a pandas.Dataframe?
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/50433486
type: Question
accepted answer: http://stackoverflow.com/a/50433508
has body: I am trying to replace a part of all strings in pd.Dataframe, but it doe s not work. My data example: HLAA0101 HLAA0201 HLAA0202 HLAA0203 HLAA0205 What am I trying to obtain: A0101 A0201 A0202 A0203 A0205 My code: mhc = train_csv.mhc for i in mhc: i[0:2].replace('HLA', ' ') print(mhc) But it does not work.
score: 3
has answer: http://stackoverflow.com/a/50433508
possible better answer: http://stackoverflow.com/a/50433485
tagged with: python
has answer: http://stackoverflow.com/a/50433485
type: AnsweredQuestion
answer count: 3
tagged with: pandas
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/50518635
duplicate of: http://stackoverflow.com/q/9189172
score: 2
has body: I'm having a problem with the int() function. I tried to use it in a simple program, but remains not working. This is my short program. I use int() to turn the a variable from a str into a int. And use it to compeare with 2. But it returns an error, because it's still seen a as a str. What's happening?? a = '4' int (a) if a &gt; 2: print( "It's working" )
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50518680
answer count: 3
accepted answer: http://stackoverflow.com/a/50518652
has answer: http://stackoverflow.com/a/50518652
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/50522061
linked to: http://stackoverflow.com/q/9189172
has answer: http://stackoverflow.com/a/50518680
downvote count: 0
tagged with: python
has title: Turn a variable from string to integer in python

http://stackoverflow.com/comment/87975305
type: Comment
has text: How would I count the total of all words?
type: AnswerComment
comment on: http://stackoverflow.com/a/50480389
score: 0

http://stackoverflow.com/comment/87844435
score: 0
has text: Thanks, but now I'm getting `TypeError: 'multivariate_normal_frozen' object is not iterable`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50413691

http://stackoverflow.com/comment/87833253
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50408606
has text: yep actually my project does not start with that option. what is that?

http://stackoverflow.com/comment/88042447
has text: I understand but I left it on for like 5 minutes and still nothing.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50514912

http://stackoverflow.com/q/50406874
tagged with: python
has comment: http://stackoverflow.com/comment/87835329
has title: How to efficiently convert milliseconds offset to np.datetime64 in an ndarray of np.void
answer count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has body: Okay, bear with me, I've only just started using NumPy. I have a time series split over multiple files. Each file captures the data for a single day. The time field in each record is simply the of milliseconds since the start of that day Now I am trying to read this data in using numpy, but I have trouble to convert the milliseconds to an np.datetime64. What I have sofar: t_base = np.datetime64(&lt;some_date&gt;) dtype = np.dtype([ ("t", "i4"), ...&lt;other fields here&gt;... ]) data = np.fromfile(filename, dtype) This gives me a one-dimensional ndarray of np.void. So far so good. What I tried: for record in np.nditer(data, op_flags["readwrite"]): record["t"] = t_base + np.timedelta64(int(record["t"]), "ms") Unfortunately, this does not change the type. Instead it converts the constructed datetime64 back to int32, which is incorrect because int32 does not have the range to capture time in milliseconds. So how do I get this done in an efficient manner? Obviously, after the conversion I have no need for the millisecond offset anymore. Or alternatively, is there a way with fromfile to read an int32 into a int64 type? Then I can use an int64 as timestamp instead of datetime64.
has comment: http://stackoverflow.com/comment/87833085
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/94931535
type: AnswerComment
has text: instance of 1 i need to print 0 . same for 0 to 1 .How will do that .
comment on: http://stackoverflow.com/a/50496481
score: 0
type: Comment

http://stackoverflow.com/q/50517826
has comment: http://stackoverflow.com/comment/88072296
type: Question
has body: This is all in python pandas. I have a list of integers called different_rows that holds the row number of each row that has differences between 2 dataframes. In this case a dataframe holding data from netezza and a dataframe holding data from oracle. (prepped_net_df, prepped_ora_df) I am trying to pass in the row number to the original dataframes to get the row of data from the data frame. I want to able to add a tag to that row to know which dataframe it came from (i.e. netezza or oracle) and then i want to add that row (series) to a new dataframe. That int from different_rows needs to be passed to both into the netezza and oracle dataframes. The following code works but the problem is it runs really slow. I have a 2 part question. What would be the best approach for testing which one of the lines is causing this to run slow? Is there a way to optimize this code. This works fine for 10-1000 rows but sometimes i have data frames that are tens of thousands of rows. Thank you for your time. Any help is appreciated net_dict = {'ACCTG_DATE': ['2012-01-01 00:00:00', '2012-01-02 00:00:00', '2012-01-03 00:00:00', '2012-01-04 00:00:00' ], 'JRNL_ID_NO': ['00349-CAS','00350-CAS','00351-CAS','00352-CAS' ], 'JRNL_SEQ_NO': [43970,43971,43972,43973], 'ACCT_CODE': [8500016,8500017,8500018,8500019], 'BAL_BOOK_CODE': [8591,8592,8593,8594], 'PROD_CODE': ['12F7', '12F8', '12F9', '12G0'], 'SUSPENSE_SEQ_NO': [0, 1, 2, 3 ], 'TRAN_AMT': [8900.29, 8901.29, 8902.29, 8903.29], 'CENTER_CODE': ['', '', '', ''], 'BASIS_TYPE': ['C', 'C', 'C', 'C'], 'UPDATE_TSTP':['2011-12-31 00:00:00', '2012-01-01 00:00:00', '2012-01-02 00:00:00', '2012-01-03 00:00:00']} ora_dict = {'ACCTG_DATE': ['2012-01-01 00:00:00', '2012-01-02 00:00:00', '2012-01-04 00:00:00', '2012-01-04 00:00:00' ], 'JRNL_ID_NO': ['00349-CAS','00350-CAS','00351-CAS','00353-CAS' ], 'JRNL_SEQ_NO': [43970,43971,43972,43973], 'ACCT_CODE': [8500016,8500017,8500018,8500019], 'BAL_BOOK_CODE': [8591,8592,8593,8594], 'PROD_CODE': ['12F7', '12F8',…
accepted answer: http://stackoverflow.com/a/50532735
tagged with: dataframe
tagged with: python
has title: Passing list of row numbers into 2 dataframes, labeling, and adding to new dataframe
has comment: http://stackoverflow.com/comment/88048880
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50532735

http://stackoverflow.com/q/50512389
has answer: http://stackoverflow.com/a/50513703
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88037577
accepted answer: http://stackoverflow.com/a/50513703
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88037521
has title: How to move separate items with the same tag in tkinter?
type: AnsweredQuestion
tagged with: tkinter
upvote count: 0
answer count: 1
has body: I have tried to create a program where the user adds certain logic gates and they can move separately. I have tried to add a count and concatenate the tag but it will not work. My program below is what I have so far, I need some help on how to move gates separately even if the same gate is added to the canvas. from tkinter import * canvas=Canvas(width=600,height=600) canvas.grid() def andGATE(): canvas.create_line(150,50,150,150,width=5,tag="andgate") canvas.create_arc(150,50,200,150,start=90,extent=-180,width=5,fill="black",tag="andgate") canvas.create_line(150,75,120,75,width=5,tag="andgate") canvas.create_line(150,120,120,120,width=5,tag="andgate") canvas.create_line(200,100,250,100,width=5,tag="andgate") canvas.create_rectangle(150,50,180,150,width=5,fill="black",tag="andgate") canvas.tag_bind("andgate","&lt;B1-Motion&gt;",moveANDGate) def gateSelected(): sf=var.get() if sf=='AND': andGATE() def moveANDGate(event): x=event.x y=event.y coords=canvas.coords("andgate") movex=x-coords[0] movey=y-coords[1] canvas.move("andgate",movex,movey) root = Tk() root.geometry("500x500") var = StringVar(root) var.set('AND') choices = ['AND'] option = OptionMenu(root, var, *choices) option.pack(side="left",padx=10,pady=10) button = Button(root, text="Add Gate", command=gateSelected) button.pack(side="left",padx=10,pady=10) clearButton = Button(root,text="Clear",command=lambda:clearScreen()) clearButton.pack(side="left",padx=30,pady=10) root.mainloop()
downvote count: 1

http://stackoverflow.com/comment/88019307
has text: Okay but there is just one thing I've understood now: I'm actually already doing this. My class is defined at the top of my program after `# -*- coding: utf-8 -*-` and the imports; then I got the functions, and finally this: `if __name__ == '__main__':` with the multiprocessing program following, which calls functions defined above.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50472787

http://stackoverflow.com/comment/87894564
type: AnswerComment
comment on: http://stackoverflow.com/a/50440093
score: 0
has text: Wow I learned alot from your response. I have to practice understanding ' For loops ' and learning more about Itertools. I'm told the best way to learn a language is through purpose driven projects & this is one of mine. Thanks for the response
type: Comment

http://stackoverflow.com/a/50468254
has comment: http://stackoverflow.com/comment/87949707
accepted answer of: http://stackoverflow.com/q/50468164
type: Answer
has body: You need to pass *args and **kwargs when you call super(): def __init__(self, *args, **kwargs): super(SingleSampleForm, self).__init__(*args, **kwargs) At the moment, calling __init__ without any *args or **kwargs is equivalent to calling with data=None. The form is unbound, so will never be valid.
score: 7
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/87949662
answers question: http://stackoverflow.com/q/50468164

http://stackoverflow.com/a/50396969
score: 0
has body: look at create-a-dictionary-with-list-comprehension-in-python List comprehension is much faster - I assume this is meant by efficency.
has comment: http://stackoverflow.com/comment/87809843
has comment: http://stackoverflow.com/comment/87810084
has comment: http://stackoverflow.com/comment/87809796
answers question: http://stackoverflow.com/q/50396807
type: Answer

http://stackoverflow.com/q/50393718
type: Question
upvote count: 4
answer count: 2
has body: My question is: how can I determine which of the Aside and Bside sides of an already split rotated rectangular geometry are the "left" and "right" side of an arbitrary LineString that splits that geometry? For the purposes of this problem, "left" and "right" are defined as the left-hand and right-hand side of a LineString splitter when "walking" from node to node, in order. I've created this function for splitting any arbitrary shapely geometry (non collection) into two sides - the "left" and the "right": import shapely.geometry as geo import shapely.ops as ops def splitLR(geom, splitter): """Split a geometry into a 'left' and 'right' side using the shapely API""" if not isinstance(splitter, geo.LineString): raise TypeError("The splitter must be a LineString") if not splitter.is_simple: raise ValueError("Only simple splitter objects allowed") if hasattr(geom, "__iter__"): raise ValueError("Geometry collections not allowed") geom_extents = geo.GeometryCollection([geom, splitter]).minimum_rotated_rectangle sides = ops.split(geom_extents, splitter) try: Aside, Bside = sides except TypeError: # only 1 result - rotated rectangle wasn't split if len(ops.split(geom,splitter)) == 1: # geom isn't split by splitter raise ValueError("the splitter does not appear to split the geometry") else: # splitter too small for algorithm raise ValueError("the splitter must extend beyond minimum_rotated_rectangle " "of the combined geometry") # determine which is Lside and Rside here Lside,Rside = get_LRsides(Aside, Bside, splitter) return tuple(side.intersection(geom) for side in (Lside, Rside)) The idea of the above is illustrated in the notebook linked here (same link as above): http://nbviewer.jupyter.org/urls/dl.dropbox.com/s/ll3mchnx0jwzjnf/determine%20left-right%20split.ipynb To summarize: sides A and B are the two sides of the minimum_rotated_rectangle surrounding the geom geometry and the splitter line string together. When side.intersection(geom) is executed, the result is the po…
downvote count: 0
score: 4
accepted answer: http://stackoverflow.com/a/50868335
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50868335
has title: Determine the "left" and "right" side of a split shapely geometry
tagged with: shapely
possible better answer: http://stackoverflow.com/a/67051651
tagged with: python
has answer: http://stackoverflow.com/a/67051651
favorite count: 0

http://stackoverflow.com/comment/87797899
type: QuestionComment
has text: putting a strong threshold is sufficient for that i think
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50390995

http://stackoverflow.com/comment/118280892
has text: Great answer, and it worked for me, on IPTCInfo3-2.1.4.
type: AnswerComment
comment on: http://stackoverflow.com/a/50407886
score: 0
type: Comment

http://stackoverflow.com/comment/87863207
type: Comment
type: QuestionComment
has text: Oops, forgot to put that( I didn't copy but wrote again over here), editing again, thanks for telling,
comment on: http://stackoverflow.com/q/50422124
score: 0

http://stackoverflow.com/q/50540829
has title: datetime x-axis (timestamp not a string)
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50541017
tagged with: python
score: 0
has body: I started learning python panda. I want to have the date time on my x-axis, but I have the following Error: TypeError: ('TSLA', Timestamp('2018-01-01 00:00:00')) is not a string. Does anyone have a solution for this? import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web style.use('ggplot') start = dt.datetime(2018, 1, 1) end = dt.datetime(2018, 5, 24) df1 = web.DataReader('TSLA', 'morningstar', start, end) df1['100ma'] = df1['Open'].rolling(window=100).mean() ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1) ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1) ax1.plot(df1.index, df1['Close']) # (x,y) ax1.plot(df1.index, df1['100ma']) ax2.bar(df1.index, df1['Volume']) plt.show() This works: ax1.plot(df1['High'], df1['Close']) #works But I don't have 'access' to the column "Date": ax1.plot(df1['Date'], df1['Close']) # doesn't work Thank you in advance.
tagged with: pandas
has comment: http://stackoverflow.com/comment/88093103
answer count: 1

http://stackoverflow.com/q/50424496
tagged with: directory
type: Question
has answer: http://stackoverflow.com/a/50426000
tagged with: angularjs
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has body: I've got the hang of constructing rest API's to pass all data, but I'm having trouble knowing how to set up the folder structure to be able to load an angular template by visiting an URL. Lets say that in my settings.py I have a registered path api, that contains the JSON data i want to pass to the client, and have some angtemplate.html. I also have a Django app called apitest which gets data from the server and provides the data to the api that angular needs to get data from. How do I route the request so that when a user goes to a url on my server like 127.0.0.1:8000/apifetch, the user is presentet with angtemplate.html that has loaded the data from /apifetch? I realize this is a triple question involving first angular app-structure, second Django template syntax and folder structure, and thirdly url-patterns. I tried to follow the thinkster angular django tutorial, but was unable to connect the angular app to the website. My own theory is that inside the apitest Django application I create a few templates and in the static folder of that app I keep my angular apps, which I load as static into the template, and connect the url as I would usually do. However I've heard that you shouldn't mix Django and angular templates, which that would be doing. Broad answers are much appreciated, most of all just an example folder structure with the urls that make it work would be incredibly valuable, so that I can start experimenting with my self from a somewhat working base. I've been banging my head against the wall for some time with this.
favorite count: 0
tagged with: angular
score: 1
has title: Django Angular Folder structure to load angular templates
tagged with: python

http://stackoverflow.com/comment/87928450
comment on: http://stackoverflow.com/q/50430604
has text: Something is wrong in your question. `query_job = client.query(query)` just insert job into bigquery - and return job_id that you can use lately to check status. Could you please show us full code with details where you reading result of query
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50432207
tagged with: python
has answer: http://stackoverflow.com/a/50432309
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/87878675
upvote count: 0
has comment: http://stackoverflow.com/comment/87878765
downvote count: 2
has title: Python, eval command how to stop it not working when a 0*5 is entered
answer count: 1
has comment: http://stackoverflow.com/comment/87878755
has comment: http://stackoverflow.com/comment/87879603
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87878732
has comment: http://stackoverflow.com/comment/87878807
has comment: http://stackoverflow.com/comment/87879187
has comment: http://stackoverflow.com/comment/87878746
has body: I have a calculator which makes calculations via the command eval. Eval is a built in command in python to calculate math equations, but the equation does not work if you type 05*5 how can i make it so that when i type 05 it take the entry and deletes the 0 out of the list and then sends it to eval and make it 5*5 instead of 05?
has comment: http://stackoverflow.com/comment/87879307
linked to: http://stackoverflow.com/q/1832940
has comment: http://stackoverflow.com/comment/87878821
type: UnansweredQuestion
score: -2
linked to: http://stackoverflow.com/q/13013638

http://stackoverflow.com/a/50508321
answers question: http://stackoverflow.com/q/50502009
has body: you can just compute the rolling sum only for the last rows by using tail(4) res = df.tail(4).rolling('2d')['AMOUNT'].sum() Output: DATE 2017-01-31 NaN 2017-02-01 70.0 2017-02-02 90.0 2017-02-03 110.0 Name: AMOUNT, dtype: float64 If you want to merge those values - excluding 2017-01-31 then you can do the following: df.loc[res.index[1:]] = res.tail(3) Output: AMOUNT DATE 2017-01-29 10.0 2017-01-30 20.0 2017-01-31 30.0 2017-02-01 70.0 2017-02-02 90.0 2017-02-03 110.0
score: 0
has comment: http://stackoverflow.com/comment/88065127
has comment: http://stackoverflow.com/comment/88045312
has comment: http://stackoverflow.com/comment/88046034
type: Answer

http://stackoverflow.com/a/50560153
type: Answer
score: 4
upvote count: 4
has body: I think you have misunderstood the concept of subplots, the reason you are getting the error is because the make_subplots() function will create a layout object of its own, hence you are getting the error. 'layout' is not allowed in 'scatter' Path To Error: ['data'][0]['layout'] The proper way to modify the layout of a subplot is to create the subplot and access the individual object properties and set them, like shown below. updatemenus = list([ dict(active=-1, x=-0.15, buttons=buttons ) ]) fig['layout']['title'] = 'Title' fig['layout']['showlegend'] = False fig['layout']['updatemenus'] = updatemenus Also you are creating a new subplot object each time the for loop is run, which is wrong. I am talking about the below line. traces = [] for data in datas: fig = tools.make_subplots(rows=1, cols=2) You need to assign it only once, please refer the below working example and try to implement the same method to your usecase. import plotly.offline as py import plotly.graph_objs as go from plotly.offline import init_notebook_mode, iplot, plot from plotly import tools init_notebook_mode(connected=True) df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"]) labels = ["A", "B"] datas = [df, df] ### Create individual figures # START fig = tools.make_subplots(rows=2, cols=2) for i, data in enumerate(datas): trace1 = go.Bar( x=data.head(10).A, y=data.head(10).B, showlegend=False ) trace2 = go.Bar( x=data.tail(10).A, y=data.tail(10).B, showlegend=False ) fig.append_trace(trace1, i + 1, 1) fig.append_trace(trace2, i + 1, 2) ### Create buttons for drop down menu buttons = [] for i, label in enumerate(labels): visibility = [i==j for j in range(len(labels))] button = dict( label = label, method = 'update', args = [{'visible': visibility}, {'title': label}]) buttons.append(button) updatemenus = list([ dict(active=-1, x=-0.15, buttons=buttons ) ]) fig['layout']['title'] = 'Title' fig['layout']['showlegend'] = False fig['layout']['updatemenus'] = updatemenus iplot(fig, f…
downvote count: 0
answers question: http://stackoverflow.com/q/50518090

http://stackoverflow.com/comment/87900049
comment on: http://stackoverflow.com/q/50443117
type: Comment
type: QuestionComment
score: 0
has text: Can you better explain what you are trying to achieve.

http://stackoverflow.com/a/50397107
score: 0
answers question: http://stackoverflow.com/q/50396975
type: Answer
has body: Locale is the differences in how things are encoded based on how things are done in a geographic region. Typically this means things like how some regions might display today's date as 17 May, 2018 vs May 17, 2018, or how some regions will use . as a thousands separator and , as a fractional separator, like 9.000,1. You can find more information about the specifics of Python locale in the python docs: https://docs.python.org/3.6/library/locale.html

http://stackoverflow.com/q/50520215
has title: Efficient way to create a numpy boolean array from an array
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/18968660
has answer: http://stackoverflow.com/a/50521011
possible better answer: http://stackoverflow.com/a/50520686
duplicate of: http://stackoverflow.com/q/18968660
tagged with: scipy
accepted answer: http://stackoverflow.com/a/50520410
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50521082
has answer: http://stackoverflow.com/a/50520410
has body: I am trying to convert a numpy array np.array([1,3,2]) to np.array([[1,0,0],[0,0,1],[0,1,0]]) Any idea of how to do this efficiently? Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/50520686
answer count: 4

http://stackoverflow.com/comment/87994688
has text: guys i'm kinda new to coding so excuse my many mistakes... in my initial code my indentation was fine but writing it here I might hav made some mistakes xP... otherwise thanks for the help :)
score: 0
comment on: http://stackoverflow.com/q/50490713
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50472613
has title: How to get rid of LoopingCall in python code
tagged with: pymodbus
tagged with: pymodbus3
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50473850
answer count: 1
tagged with: modbus-tcp
has body: I'm using Modbus server example code from pymodbus library to make a data forwarder (reading some serial data, formatting and then assigning data to modbus registers for Modbus master to read). My issue is serial delay (reading from 6 different devices, each device has a 5 sec delay, but it's random, they not sending data at the same time). In this example they use LoopingCall, which is bad for my timing. How do I get rid of it, so I can call function myself? I tried just to get rid of : time = 2 # Update delay loop = LoopingCall(f=updating_writer, a=(context,)) loop.start(time, now=False) And simply call: updating_writer() But obviously I'm missing some arguments: a=(context,) Part of my code: def data_decoder6(): ser_read_JB1 = ser_JB6.read(386) if len(ser_read_JB1) != 0: # convert ascii to hex aTOh_JB1 = "".join("{:02x}".format(c) for c in ser_read_JB1) # convert to string iTOs_JB1 = str(aTOh_JB1) lokacija = [258,422,426,414,402,406,266,274,270,558, 530,534,538,322,326,330,334,338,342,346, 350,354,358,362,366,370,374,378,382,386, 390,394,398 ] values_JB1 = [0 for d in range(33)] values_2_JB6 = [0 for e in range(33)] for x in range(0, 33): values_JB1[x] = (iTOs_JB1[lokacija[x]] + iTOs_JB1[lokacija[x]+1] + iTOs_JB1[lokacija[x]+2] + iTOs_JB1[lokacija[x]+3]) #values1 = values.replace('"', '') values_2_JB6[x] = int(values_JB1[x], 16) #values.append( 2009 ) return values_2_JB6 else: values_2_JB6 = [0 for e in range(33)] return values_2_JB6 def updating_writer(a): allValues = [0 for d in range(198)] allValues = (data_decoder1() + data_decoder2() + data_decoder3() + data_decoder4() + data_decoder5() + data_decoder6()) # modbus part log.debug("updating the context") context = a[0] register = 0x03 slave_id = 0x01 address = 0x01 values = context[slave_id].getValues(register, address, count=198) values = allValues log.debug("new values: " + str(values)) context[slave_id].setValues(register, address, values) def run_updating_server(): store = ModbusSlaveContext( di = ModbusSe…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87987064
tagged with: twisted
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50499026
score: 6
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50498997
answers question: http://stackoverflow.com/q/50498997
type: AcceptedAnswer
downvote count: 0
has body: It performs case insensitive sorting. Let's modify your example a bit, to include another entry "dan": lst = ['Ronit', 'Dan', 'dan'] Naturally, you'd expect "Dan" and "dan" to occur together. But they don't, because of the properties of string ordering. Instead, a plain list.sort call will give you: lst.sort() print(lst) ['Dan', 'Ronit', 'dan'] On the other hand, specifying str.lower gives you this: lst.sort(key=str.lower) print(lst) ['Dan', 'dan', 'Ronit'] Here, the original list elements are sorted with respect to their lowercased equivalents. The second list.sort call with len should now be self-explanatory, assuming you understand what key does (yes, sort by length). To understand why the first is needed before the second, consider another contrived example: lst = ['Ronit', 'Dan', 'ram', 'dan'] First, consider just key=len: lst.sort(key=len) print(lst) ['Dan', 'ram', 'dan', 'Ronit'] That "ram" looks out of place here. THIS IS PRECISELY WHY WE HAVE THE FIRST STEP. Now, adding in that step makes our output a lot more sensible. lst.sort(key=str.lower) lst.sort(key=len) print(lst) ['Dan', 'dan', 'ram', 'Ronit'] So, in conclusion, the elements are ordered first case-insensitively, and then ordered by length.
has comment: http://stackoverflow.com/comment/88010920

http://stackoverflow.com/q/50465865
tagged with: paramiko
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50467699
has comment: http://stackoverflow.com/comment/87944875
answer count: 2
has comment: http://stackoverflow.com/comment/87947200
downvote count: 0
has answer: http://stackoverflow.com/a/50466721
has title: How to parse output in Python and use it in loop
has comment: http://stackoverflow.com/comment/87945469
has body: I need to extract 'xe-1/2/0' from the following UPD.result output: interface xe-1/2/0.0; interface ge-1/2/1.0; interface lo0.0 { (This is output from 'show configuration protocols ospf| match int' command) from one box in a list.) I'm using a netmiko library to connect to network devices and find some interfaces that is particulating in OSPF protocol, then I want to check errors count on this interfaces. import getpass import sys import time import textfsm import os from tabulate import tabulate import re from netmiko import ConnectHandler USER = raw_input("Login:") PASSWORD = getpass.getpass() FILENAME = raw_input("Name of file with results:") GETPATH= os.getcwd() GETPATH2 = (GETPATH+'/IP-ADD.txt') GETPATH3 = (GETPATH+'/template-desc.template') BOXES_IP = [line.strip() for line in open(GETPATH2, 'r')] print(BOXES_IP) for IP in BOXES_IP: print('CONNECTION TO DEVICE {}'.format(IP)) try: DEVICE_PARAMS = {'device_type': 'juniper_junos', 'ip': IP, 'username':USER, 'password':PASSWORD, 'verbose': True} with ConnectHandler(**DEVICE_PARAMS) as sss: sss.enable() result = sss.send_command('show configuration protocols ospf| match int') hostname = sss.send_command('show configuration system host-name') print(result) except: print('CONNECTION TO DEVICE FAILS {}'.format(IP)) continue f = open(FILENAME+'.txt', 'a') for row in hostname: f.write(row) for row in result: f.write(row) f.close() regex = re.compile(r'^(xe.[0-9].[0-9].[0-9])') results_list = [] b = open(FILENAME+'.txt', 'r') print b for line in b: match = regex.search(line) if not match: continue results_list.append(match.group()) print results_list I need to parse the output of command 'show configuration protocols ospf| match int' and find xe (e.g. xe-0/0/1) interfaces and after that enter the 'show interface xe-*** extensive' command and print results in a file. How can I do this? I'm trying to parse output file with compile but it doesn't work. UPDATE. print(result) output: interface lo0.0 { interface xe-1/3/1.0; in…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87946785
accepted answer: http://stackoverflow.com/a/50466721
has comment: http://stackoverflow.com/comment/87946703
tagged with: python
possible better answer: http://stackoverflow.com/a/50467699

http://stackoverflow.com/comment/87936581
score: 0
has text: I think your environment variable refers some other python variant. It may be conda
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50461126

http://stackoverflow.com/comment/87881974
comment on: http://stackoverflow.com/q/50433883
score: 1
has text: Welcome to Stack Overflow! Unfortunately [questions asking for: books, libraries, tutorials, tools are off-topic](https://stackoverflow.com/help/on-topic) and should be closed. Stack Overflow is a [Questions](https://stackoverflow.com/help/how-to-ask) & [Answers](https://stackoverflow.com/help/how-to-answer) website for specific programming questions.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88005324
type: Comment
has text: I am new here, but i will tick once i am allowed to.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50489380

http://stackoverflow.com/comment/87897013
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50441334
has text: Pass the list of characters you deem acceptable instead of using `string.printable`.

http://stackoverflow.com/comment/114525278
comment on: http://stackoverflow.com/a/64565019
type: AnswerComment
has text: you can even do `tf.reshape((), (0, n))`
score: 7
type: Comment

http://stackoverflow.com/q/50512797
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50513447
has answer: http://stackoverflow.com/a/50513447
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has body: I'm wondering about efficient and concise ways of passing nuisance columns through to the result of a pandas.DataFrame.groupby. I often have columns which I do not want to apply the groupby operation to, but I do want the values to propagate through to the result. An example of what I am trying to do is shown below import pandas as pd import numpy as np import random import string np.random.seed(43) random.seed(43) dates = pd.date_range("2015-01-01", "2017-01-02") types = "AAABBCCCDDDDEEFFFFGG" rtypes = list(types * len(dates)) rdates = dates.tolist() * len(types) data = np.random.randn(len(rtypes)) info1 = [''.join(random.choice(string.ascii_uppercase) for _ in range(5)) for i in range(len(rtypes))] info2 = [random.randint(100,1000) for i in range(len(rtypes))] df = pd.DataFrame({"date": rdates, "category": rtypes, "vals": data, "info1":info1, "info2": info2}) df = df.sort_values(["date", "category"]).reset_index(drop=True) df.head() category date info1 info2 vals 0 A 2015-01-01 BJWYE 990 0.257400 1 A 2015-01-01 ISQES 475 -0.867570 2 A 2015-01-01 KDEKE 214 1.683595 3 B 2015-01-01 TFOXR 203 0.575879 4 B 2015-01-01 HKTNF 992 -0.399677 Here I would like to group by the category and date and apply some function to vals but have the info1 and info2 columns passed through. Possible Solutions These are the possible solutions I have found, but both seem somewhat clunky and have quite different performance which made me wonder if there is possibly a more efficient or more concise solution. I'm applying the rank function in this example but am interested more broadly in functions that could return 1 value per group, all values per group or some values per group. Option 1 Stash all desired pass through columns in the index %%timeit (df.set_index(["date", "category", "info1", "info2"]) .groupby(axis=0, level=[0, 1]).rank().reset_index()) 2.64 s ± 47.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) with result sol1 = (df.set_index(["date", "category", "info1", "info2"]) …
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 2
has title: Efficient and concise GroupBy nuisance column pass through

http://stackoverflow.com/q/50522437
tagged with: numpy
has body: Saw couple of responses with the above mentioned error but culdn't figure out bug in my code. I am following tutorial at: https://pythonprogramming.net/unix-time-matplotlib-tutorial/?completed=/basic-customization-matplotlib-tutorial/ and ran into the above error. I am able to reproduce the issue with these three lines of code: import numpy as np L = ['2017-07-26,153.3500,153.9300,153.0600,153.5000,153.5000,12778195.00', '2017-07-25,151.8000,153.8400,151.8000,152.7400,152.7400,18714400.00', '2017-07-24,150.5800,152.4400,149.9000,152.0900,152.0900,21304700.00'] date, closep, highp, lowp, openp, adj_closep, volume = np.loadtxt(L, delimiter=',', unpack=True) The error trace is: ValueError Traceback (most recent call last) &lt;ipython-input-2-bae25d428491&gt; in &lt;module&gt;() 5 date, closep, highp, lowp, openp, adj_closep, volume = np.loadtxt(L, 6 delimiter=',', ----&gt; 7 unpack=True) /usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin) 1022 1023 # Convert each value according to its column and store -&gt; 1024 items = [conv(val) for (conv, val) in zip(converters, vals)] 1025 # Then pack it according to the dtype's nesting 1026 items = pack_items(items, packing) /usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in &lt;listcomp&gt;(.0) 1022 1023 # Convert each value according to its column and store -&gt; 1024 items = [conv(val) for (conv, val) in zip(converters, vals)] 1025 # Then pack it according to the dtype's nesting 1026 items = pack_items(items, packing) /usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in floatconv(x) 723 if b'0x' in x: 724 return float.fromhex(asstr(x)) --&gt; 725 return float(x) 726 727 typ = dtype.type ValueError: could not convert string to float: b'2017-07-26' Kindly let me know how to fix it.
has title: np.loadtxt giving ValueError: could not convert string to float: b'2017-07-26'
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50523016
has comment: http://stackoverflow.com/comment/88056910
tagged with: python
has comment: http://stackoverflow.com/comment/88056942
has answer: http://stackoverflow.com/a/50523016
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88057777
type: Question

http://stackoverflow.com/a/50502261
type: AcceptedAnswer
has body: I'm not entirely sure about your problem setup, but I imagine this could get you started. Suppose your collection of dictionaries is such: import math dict_list = { "water": { "ground": 1, "journey": 1, "longitude": 1, "main": 1, "contrary": 1, "cover": 1, "delaware": 1, "remarkable": 1 }, "mississippi": { "main": 1, "contrary": 1, "cover": 1, "delaware": 1, "remarkable": 1, "steamboats": 1, "germany": 1 } } If you want to apply the cosine rule to them, you need to setup vectors showing the occurrence of each word present in both dictionaries (i.e., if it shows up in one and not the other it needs to be zero in the other): def setup_vec(dict1, dict2): dict1_missing = list(set(dict2.keys() - set(dict1.keys()))) dict2_missing = list(set(dict1.keys() - set(dict2.keys()))) for i in dict1_missing: dict1[i] = 0 for i in dict2_missing: dict2[i] = 0 vec1 = [] vec2 = [] for i in dict1.keys(): vec1.append(dict1[i]) vec2.append(dict2[i]) return([vec1, vec2]) Note that the order of the vector elements is important. If you run this with "water" and "mississippi" you get: [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1]] After that, you just need to apply the rule: def dot_prod(p, q): return sum([p[x]*q[x] for x in range(0, len(p))]) def norm(p): return math.sqrt(dot_prod(p, p)) def cosine_metric(p, q): return dot_prod(p, q)/(norm(p) * norm(q)) And the function which computes them for a given dictionary against all others: def find_dict(word): if word in dict_list.keys(): for other_dicts in dict_list.keys(): if other_dicts != word: vecs = setup_vec(dict_list[word], dict_list[other_dicts]) print(other_dicts + " " + str(cosine_metric(vecs[0], vecs[1]))) The results here are: find_dict('water') 0.6681531047810609 The remaining task is to order the output, which shouldn't be hard to do.
has comment: http://stackoverflow.com/comment/88041287
has comment: http://stackoverflow.com/comment/88058840
has comment: http://stackoverflow.com/comment/88041476
has comment: http://stackoverflow.com/comment/88033451
accepted answer of: http://stackoverflow.com/q/50501238
has comment: http://stackoverflow.com/comment/88019392
has comment: http://stackoverflow.com/comment/88034564
has comment: http://stackoverflow.com/comment/88059698
answers question: http://stackoverflow.com/q/50501238
type: Answer
has comment: http://stackoverflow.com/comment/88040449
score: 0
has comment: http://stackoverflow.com/comment/88019656
has comment: http://stackoverflow.com/comment/88041033
has comment: http://stackoverflow.com/comment/88053068

http://stackoverflow.com/comment/87860959
comment on: http://stackoverflow.com/a/50422687
type: Comment
type: AnswerComment
has text: @zwer. To add on, I was going to suggest defining a custom label type like `class UserPressedCancel(Exception): pass` this would avoid any complications caused by catching unintended exception types.
score: 2

http://stackoverflow.com/comment/87988841
score: 0
has text: Can you show what you tried and describe how exactly it failed?
type: Comment
comment on: http://stackoverflow.com/q/50487995
type: QuestionComment

http://stackoverflow.com/a/50500484
accepted answer of: http://stackoverflow.com/q/50500453
has comment: http://stackoverflow.com/comment/88013797
has body: pd.concat pd.concat([d.iloc[[0, -1]] for _, d in df.groupby('ID')]) ID Date 0 A 1/1/2015 2 A 1/3/2017 3 B 1/3/2017 3 B 1/3/2017 4 C 1/5/2016 5 C 1/7/2016 Using agg df.groupby('ID').agg(['first', 'last']).stack().reset_index('ID') ID Date first A 1/1/2015 last A 1/3/2017 first B 1/3/2017 last B 1/3/2017 first C 1/5/2016 last C 1/7/2016
upvote count: 2
has comment: http://stackoverflow.com/comment/88013720
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88014140
answers question: http://stackoverflow.com/q/50500453
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88013781

http://stackoverflow.com/comment/87829058
has text: "This question was marked as an exact duplicate". It most certainly is not an exact duplicate: the other question is about parsing (binary vs text mode), while this one is about removing line endings from a string. Related perhaps, but not a duplicate IMO.
score: 0
comment on: http://stackoverflow.com/q/50406199
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88032301
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50510100
has text: This is not working. Showing error: } ^ SyntaxError: invalid syntax
type: Comment

http://stackoverflow.com/comment/88031308
type: AnswerComment
score: 0
has text: Works. Why the functions "T_scorer(cf, X, y)" and not "T_scorer(cf, X1, y1)"? In advance am asking understand, so as little experience)
type: Comment
comment on: http://stackoverflow.com/a/50509442

http://stackoverflow.com/q/50454630
tagged with: pandas
score: 1
has body: I'm trying to read in a tsv file using pandas read_table, but for some reason, the first line is being removed from the file. test.pln (File is here): Class index 0 0 0 1 1 1 2 2 2 3 3 3 fall spring summer fall spring summer fall spring summer fall spring summer 0 1 2 3 4 5 COMP 140 6 COMP 182 7 MATH 331 Then, running the command: pd.read_table("test.pln", header=[0,1],index_col=0) I get this result: Class index 0 1 2 \ fall spring summer fall spring summer fall spring summer 0 1 NaN NaN NaN NaN NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN 3 NaN NaN NaN NaN NaN NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN NaN NaN NaN NaN 5 COMP 140 NaN NaN NaN NaN NaN NaN NaN NaN 6 NaN COMP 182 NaN NaN NaN NaN NaN NaN NaN 7 MATH 331 NaN NaN NaN NaN NaN NaN NaN NaN Class index 3 fall spring summer 0 1 NaN NaN NaN 2 NaN NaN NaN 3 NaN NaN NaN 4 NaN NaN NaN 5 NaN NaN NaN 6 NaN NaN NaN 7 NaN NaN NaN As you can see, there is an empty row. When I try to access values from row 0, I get a KeyError. However, these values are present in the file, so the row should be full of NaNs. How can I fix this?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87922864
has title: Pandas read_table skips rows with MultiIndex
has comment: http://stackoverflow.com/comment/87922773
has comment: http://stackoverflow.com/comment/87922565
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87923301
accepted answer: http://stackoverflow.com/a/50455165
has comment: http://stackoverflow.com/comment/87922906
has answer: http://stackoverflow.com/a/50455165
has comment: http://stackoverflow.com/comment/87923040
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87923416
has comment: http://stackoverflow.com/comment/87923565
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87923237

http://stackoverflow.com/comment/88006050
has text: `Command|exited|with|status|0`: `|` is "or" not a word separator.
type: Comment
comment on: http://stackoverflow.com/q/50496586
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88004452
type: Comment
comment on: http://stackoverflow.com/a/50494478
type: AnswerComment
score: 0
has text: I do not see that in Python Wand. But threshold_local in Skimage looks similar, though I have not tried it. See http://scikit-image.org/docs/dev/api/skimage.filters.html#skimage.filters.threshold_local. There is also adaptive thresholding in OpenCV at https://docs.opencv.org/3.4.0/d7/d4d/tutorial_py_thresholding.html, though again I have not tried that.

http://stackoverflow.com/a/50513568
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50513399
type: Answer
answers question: http://stackoverflow.com/q/50513399
score: -1
has body: You should take a look at Scrapy. Scrapy is a fast high-level web crawling and web scraping framework, used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing. Here is a nice tutorial page from the documentation: Scrapy Tutorial
upvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50686849
has body: I found this answer which is similar to what I want to do I had to update my setup.py to include package_data and MANIFEST.in to include *.xlsx file (by providing the full directory path to excel file)
type: Answer
score: 0
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/50521626
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50521626

http://stackoverflow.com/comment/87801887
score: 0
type: Comment
has text: The problem is indeed the plot itself, not the data. 'plt.plot(timesteps, lp_heating_list)' sounds good and I tried it but I get: ValueError: x and y must have same first dimension, but have shapes (1,) and (1440,) ... =/
type: AnswerComment
comment on: http://stackoverflow.com/a/50392645

http://stackoverflow.com/q/50420548
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50420628
linked to: http://stackoverflow.com/q/10695139
has comment: http://stackoverflow.com/comment/87857032
tagged with: python
has title: How to sort 1 column of the csv file and print the line?
has body: My CSV file is like this. 0.0063,0.0121,band -&gt; mcr music 0.0061,0.0123,band -&gt; mcr 0.0062,0.0122,band -&gt; orchestra How can I sort the first column of the csv file and print the each line? So, in this case the final output should be 0.0061,0.0123,band -&gt; mcr 0.0062,0.0122,band -&gt; orchestra 0.0063,0.0121,band -&gt; mcr music
tagged with: http://stackoverflow.com/tag/csv
score: 0
has answer: http://stackoverflow.com/a/50420838
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: parsing
type: Question
answer count: 2

http://stackoverflow.com/q/50407189
score: 0
answer count: 2
has body: I have a timeseries data from which I am trying to build a stackedAreaChart with nvd3. Series look like this: xdata = ['2017-11-17', '2017-12-17', '2018-01-17', '2018-02-17', '2018-03-17', '2018-04-17'] ydata = [7277L, 9579L, 6291L, 6715L, 8743L, 9879L] I convert dates in xdata to unix format and it becomes like this: xdata = [1510873200000L, 1513465200000L, 1516143600000L, 1518822000000L, 1521241200000L, 1523916000000L] Then I create a chart: chart = stackedAreaChart(name='stackedAreaChart', height=400, width=400 ,x_is_date=True ) chart.add_serie(name = 'Chart1', y = ydata, x = xdata ) The problem is I want all xdata to be shown as ticks on x-axis or at least customize it in case of more data. I get output as on the picture below. As you can see, dates are not equally displayed. I would like it to be 17 Nov 2017, 17 Dec 2017, 17 Jan 2018... I haven't worked with js before, but everything I tried was unfortunate. I tried to add extra series to change x-axis format, but the problem us that extra series are added after plot is built and effect is not seen.
tagged with: nvd3.js
has answer: http://stackoverflow.com/a/50462914
possible better answer: http://stackoverflow.com/a/50462914
type: Question
has title: Equal x-axis ticks for time series data
has answer: http://stackoverflow.com/a/50470807
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50470807
linked to: http://stackoverflow.com/q/32321185
tagged with: python-nvd3
tagged with: python

http://stackoverflow.com/a/50415243
has comment: http://stackoverflow.com/comment/87846328
has comment: http://stackoverflow.com/comment/87846208
accepted answer of: http://stackoverflow.com/q/50415115
type: AcceptedAnswer
score: 6
type: Answer
answers question: http://stackoverflow.com/q/50415115
has body: You can use: df['Column2'].loc[pd.to_numeric(df['Column2'], errors='coerce').isnull()] Or if you want it in a list. list(df['Column2'].loc[pd.to_numeric(df['Column2'], errors='coerce').isnull()])
upvote count: 6
has comment: http://stackoverflow.com/comment/87846219
has comment: http://stackoverflow.com/comment/87846369
downvote count: 0

http://stackoverflow.com/q/50475847
has comment: http://stackoverflow.com/comment/87965901
tagged with: python
accepted answer: http://stackoverflow.com/a/50556899
has answer: http://stackoverflow.com/a/50556899
type: AnsweredQuestion
downvote count: 4
has title: Reformat text data convert from integer to time and concatenate with date using sed awk split
score: -4
answer count: 1
has body: I have input data file like this: (with column names not part of the data file. Date,Desc,Timestamp1, Timestamp2) --- 2016-01-01, AAA, 330, 1430 2016-01-02, ABA, 130, 930 I need to output is as (with column names not part of the data file. Date,Desc,Timestamp1, Timestamp2) --- 2016-01-01, AAA, 2016-01-01 03:30, 2016-01-01 14:30 2016-01-02, ABA, 2016-01-02 01:30, 2016-01-02 09:30 Please help. Thank you
tagged with: awk
favorite count: 0
type: Question
tagged with: apache-spark-sql
tagged with: linux
tagged with: sed
upvote count: 0

http://stackoverflow.com/q/50470735
score: 1
answer count: 1
tagged with: python
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am new in tensorflow and I am searching how to print a variable from a function in the main in Python. My function is the definition of a convolution which convolute an "image" with weights defined inside the function, this is it: def conv_fn(p_input): # Convolutional Layer #1 ------- weights1 = tf.get_variable("weights1", [3, 3, 3, 32], initializer=tf.random_normal_initializer()) conv1 = tf.nn.conv2d( input=p_input.astype(np.float32), filter=weights1, strides=[1, 1, 1, 1], padding="VALID") conv1_relu = tf.nn.relu(conv1) return conv1_relu In the main I want to do the convolution with an image and print it. I read that I have to define a session and eval the variable or feed it. I am lost in this part... This is my main: def main(argv): sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) im = [1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0,1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0, 1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0] image = np.reshape(im, [-1, 3, 3, 3]) con = conv_fn(image) print("This is image", image) print("This is con :", sess.run(con, feed_dict={p_input: image})) if __name__ == "__main__": tf.app.run() Can you please explain me how I can print: the weights from the function conv_fn the result of the convolution Thank you for your help.
has comment: http://stackoverflow.com/comment/132621932
has answer: http://stackoverflow.com/a/75154195
type: UnansweredQuestion
downvote count: 0
has title: How to print variable from function in main?
upvote count: 1
has comment: http://stackoverflow.com/comment/132621938

http://stackoverflow.com/q/50452934
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/50453292
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87919276
has answer: http://stackoverflow.com/a/50453292
has comment: http://stackoverflow.com/comment/87919603
favorite count: 0
linked to: http://stackoverflow.com/q/7129285
type: Question
has body: I have a regular expression that I want to apply to each line of a CSV file. Here's the function which basically removes all comma's encountered before a single digit number. The function is working perfectly fine for the string. Input : text = "52A, XYZ Street, ABC District, 2, M, Brown Function : re.sub('(?&lt;!\s[\dA-Z]),(?!\s+\d,?)', '', text) Output : '52A XYZ Street ABC District, 2, M, Brown' However, I have a CSV file containing hundreds of such lines. For instance 1, 5273249, 1061/72, 150-CF, S/O:XVZ, 1, ABX, 45, 0, Husband, 9213 1, 5272849, 1063/36, 150-AS, S/O:XVZ, 1, ABX, 45, 0, Wife, 9253 1, 5274549, 10626/12, 150-RT, S/O:XVZ, 1, ABX, 45, 0, Son, 9214 I tried to read it using CSV reader and apply the function but unfortunately, it's not producing any output. What did I do wrong here: def myFunction(text): return re.sub('(?&lt;!\s[\dA-Z]),(?!\s+\d,?)', '', text) import csv with open('temp1.csv', 'r') as csvfile: spamreader = csv.reader(csvfile, delimiter=',') for row in spamreader: l = ','.join(row) myFunction(l)
has comment: http://stackoverflow.com/comment/87919039
has comment: http://stackoverflow.com/comment/87919216
downvote count: 2
has comment: http://stackoverflow.com/comment/87919112
tagged with: data-cleaning
has comment: http://stackoverflow.com/comment/87919007
tagged with: python
score: -1
has title: Apply a function to each line of a CSV file in python
has comment: http://stackoverflow.com/comment/87919217
has comment: http://stackoverflow.com/comment/87919446
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/44564414
has comment: http://stackoverflow.com/comment/87919133
duplicate of: http://stackoverflow.com/q/7129285

http://stackoverflow.com/q/50439358
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87893113
has comment: http://stackoverflow.com/comment/87893523
upvote count: 1
has answer: http://stackoverflow.com/a/50455678
tagged with: macos
has body: I am using macOS High Sierra. In the past at some point I installed Python via brew however for some reason (that I don't know) pip failed to work: $ pip --version Traceback (most recent call last): File "/usr/local/opt/python2/libexec/bin/pip", line 6, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3195, in &lt;module&gt; @_call_aside File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3179, in _call_aside f(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3208, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 683, in _build_master return cls._build_from_requirements(__requires__) File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 696, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 885, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application Hence I issued: $ brew uninstall python@2 Uninstalling /usr/local/Cellar/python@2/2.7.14_1... (3,622 files, 50.6MB) After which I was left with what I assume is the default installation of python $ which python /usr/bin/python Unfortunately I can't run Python simply by typing python: $ python --version -bash: /usr/local/opt/python2/libexec/bin/python: No such file or directory however I can run that python interpreter by referring to it directly: $ /usr/bin/python --version Python 2.7.10 It bothered me that python --version didn't work and I wondered if it was a consequence of previously having had a brew installed version of python on here. Hence I decided to reinstall using brew install python@2, which succeeded. The supposed lo…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87924399
has comment: http://stackoverflow.com/comment/87912813
has title: Faulty python installation on macOS. How can I repair?
tagged with: python
has comment: http://stackoverflow.com/comment/87893407
has comment: http://stackoverflow.com/comment/87893595
has comment: http://stackoverflow.com/comment/87917693
type: AnsweredQuestion
score: 1
tagged with: homebrew
has comment: http://stackoverflow.com/comment/87909884
accepted answer: http://stackoverflow.com/a/50455678

http://stackoverflow.com/a/50494220
answers question: http://stackoverflow.com/q/50493886
type: Answer
upvote count: 4
score: 4
has body: Using mask x, y = df['barcode_x'], df['barcode_y'] y.mask(y.eq('') | y.isna(), x) 0 38927895 1 38927895 2 38927895 3 73094237 4 37645215 5 86972909 Name: barcode_y, dtype: object
accepted answer of: http://stackoverflow.com/q/50493886
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88001461
has comment: http://stackoverflow.com/comment/88001502

http://stackoverflow.com/a/50418949
has comment: http://stackoverflow.com/comment/87853963
accepted answer of: http://stackoverflow.com/q/50418785
downvote count: 0
has comment: http://stackoverflow.com/comment/87853475
has comment: http://stackoverflow.com/comment/87853654
has comment: http://stackoverflow.com/comment/87853538
type: AcceptedAnswer
type: Answer
has body: To solve this problem just add the line self.attr = self.attr inside the __init__ function of A. Since you don't want to change the attributes of A, you will have to make the following changes: class A(object): attr = None def __init__(self): assert self.attr is not None # Don't refer to A, but to self to get the correct value self.attr = self.attr class B(object): def __init__(self, attr): self.attr = attr # Don't edit A, just save the value in own instance def __getattribute__(self, item): # completely added, does some magic to ensure class.attr is set correctly if item in B.nested_classes: c = B.nested_classes[item] c.attr = self.attr return c return super().__getattribute__(item) class C(A): def __init__(self): super().__init__() class D(A): def __init__(self): super().__init__() nested_classes = {cls.__name__: cls for cls in {C, D}} first_class = B("first") first_sub_class = first_class.C() print(first_sub_class.attr) second_class = B("second") second_sub_class = second_class.C() print(second_sub_class.attr) print(first_sub_class.attr)
has comment: http://stackoverflow.com/comment/87853584
answers question: http://stackoverflow.com/q/50418785
has comment: http://stackoverflow.com/comment/87853758
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87853694
has comment: http://stackoverflow.com/comment/87854102

http://stackoverflow.com/a/50474536
type: Answer
answers question: http://stackoverflow.com/q/50472095
downvote count: 0
upvote count: 1
score: 1
has body: Here is a bit of improvised trickery that speeds up the computation quite a bit on random data of the indicated dimensions. I've no idea how numerically sound this is, though. import numpy as np from time import perf_counter def lstsq(A, b): AA = A.T @ A bA = b @ A D, U = np.linalg.eigh(AA) Ap = (U * np.sqrt(D)).T bp = bA @ U / np.sqrt(D) return np.linalg.lstsq(Ap, bp, rcond=None) # create random data A = np.random.random((150_000, 140)) b = np.random.random((150_000,)) # use solver directly t = perf_counter() x, *info = np.linalg.lstsq(A, b, rcond=None) s = perf_counter() print('direct method: ', s-t, 'seconds') # use equivalent reduced system t = perf_counter() x_acc, *info_acc = lstsq(A, b) s = perf_counter() print('accelerated method:', s-t, 'seconds') print('results equal:', np.allclose(x, x_acc)) Sample run: direct method: 3.032766239999546 seconds accelerated method: 0.20947745100056636 seconds results equal: True

http://stackoverflow.com/q/50481023
downvote count: 0
has comment: http://stackoverflow.com/comment/87975225
possible better answer: http://stackoverflow.com/a/50481331
tagged with: try-except
has answer: http://stackoverflow.com/a/50481118
has answer: http://stackoverflow.com/a/50481331
has comment: http://stackoverflow.com/comment/87975212
has comment: http://stackoverflow.com/comment/87976674
has title: Run individual python import statements which are stored in a list
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87975321
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50481118
tagged with: python
has body: I have a list of libraries i'd like to import, but some of them may not be in the filesystem. Basically, i want to do something like this: list_of_imports = ['from path1.path2.path3 import x', 'from path1.path2.path4 import y', 'from path1.path2.path3 import z', 'from path1.path2.path2 import a'] for statement in list_of_imports: try: execute statement except: ignore error and import the next statement The reason i want to do this, is because some of the libraries in the list may not be in the filesystem, and i don't want one failure to make the entire file to throw an import error. How do i do this?
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: python-2.7
answer count: 2
tagged with: python-import

http://stackoverflow.com/comment/88072743
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50530289
score: 0
has text: @Arne this attempt returns KeyError: 'SCORE_3'

http://stackoverflow.com/comment/87871343
score: 0
comment on: http://stackoverflow.com/q/50428033
type: Comment
has text: Aran, I know what you did was justified. But why would I search especially when it's a race to get the first answer in? Also, how does it hurt to have a similar question answered in a variety of ways? The titles to both are different, meaning a person searching for this answer later may only pick up one or the other with a google search. With only one, it's possible their search would miss the only available posting when it would have caught the other.
type: QuestionComment

http://stackoverflow.com/q/50468175
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: popen
has answer: http://stackoverflow.com/a/50468362
answer count: 1
has title: In Python 3, calculate a checksum on binary output from command line executable
has body: I'm using a tool called "exiftool" to extract a binary JPG from a file. I would like to then compute a sha512 sum from that file. What is a good way to do this? My function to extract the binary JPG is as follows: def getVisSig(filename): """ Calculates visual signature using imagemagick package. returns signature """ print("Calculating VisSig on %s" % filename) result = subprocess.Popen(["exiftool","-b","-PreviewImage", filename,], stdout=subprocess.PIPE) The output is binary. How should I handle this to compute a sha512 sum? I was thinking I could pipe the output to sha512sum in the command line and read the resulting string into Python, but not sure if there is a better way?
tagged with: checksum
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/88028492
type: Comment
score: 0
has text: @ypnos using imshow comes usually with the price of not having appropriate x- and y-ticks. I actually need them. Also, using imshow leads to storing the plot as png which is not really what I want to do since I started doing all this vector graphic stuff with the purpose of not using down-sampled png graphics. They usually look not that nice in pdf documents.
comment on: http://stackoverflow.com/q/50506076
type: QuestionComment

http://stackoverflow.com/comment/87849207
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50415140
has text: Follow-up question: Is there a similar way to construct a 3D-matrix if each coordinate corresponds to multiple values? @hpaulj
type: Comment

http://stackoverflow.com/q/50422187
has comment: http://stackoverflow.com/comment/87859435
type: Question
tagged with: file-handling
tagged with: python-3.x
has title: Python implantation of a while loop that checks if a file contains new data
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87859361
has answer: http://stackoverflow.com/a/50422352
tagged with: python
has answer: http://stackoverflow.com/a/50422598
has comment: http://stackoverflow.com/comment/87859273
score: 0
has body: I am trying to write a while true loop that checks the last line of a text file - TransactionFile.txt periodically (every 10 seconds) which contains data of the transactions being appended to the file. Basically I have two programs one that appends the users transaction into a file and the other the reads the transaction, both of which are running concurrently. What I'm having trouble with is is determining if the current transaction in TransactionFile.txt has changed or not. This is my function for doing so def transactionCheck(): threading.Timer(10.0, transactionCheck).start() fileSecLast = None while True: try: file = open('TransactionFile.txt', 'r') except FileNotFoundError: print('TransactionFile.txt could not found.') break else: file = open('TransactionFile.txt', 'r') global fileLast fileLast = file.readlines()[-1] file.close if fileLast == fileLast: print('New transaction data found.') print(fileLast) callfunctionNonce = calcNonce() elif fileLast == fileSecLast: print('No new transaction data found.') break break break Which gives output of this: TransactionFile.txt could not found. TransactionFile.txt could not found. TransactionFile.txt could not found. New transaction data found. MOWZ575728::max::sam::67890::2018-05-19 13:11:50.250116 New transaction data found. MOWZ575728::max::sam::67890::2018-05-19 13:11:50.250116 New transaction data found. MOWZ575728::max::sam::67890::2018-05-19 13:11:50.250116 New transaction data found. DOYU363556::geoff::tim::14515::2018-05-19 09:12:06.250116 What I would like to achieve is that if no new transactions have been written to TransactionFile.txt output No new transaction data found. instead of printing out the same transaction again. How should I go about doing this? My intended output should be something like this: TransactionFile.txt could not found. TransactionFile.txt could not found. New transaction data found. MOWZ575728::max::sam::67890::2018-05-19 09:11:50.250116 No new transaction data found. No new transacti…
answer count: 2
has comment: http://stackoverflow.com/comment/87859416
has comment: http://stackoverflow.com/comment/87859532
has comment: http://stackoverflow.com/comment/87859523

http://stackoverflow.com/q/50479969
upvote count: 1
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/51763917
has comment: http://stackoverflow.com/comment/87973313
has comment: http://stackoverflow.com/comment/87973334
has comment: http://stackoverflow.com/comment/87977824
has comment: http://stackoverflow.com/comment/87992309
score: 1
has comment: http://stackoverflow.com/comment/87973483
tagged with: http
tagged with: https
has title: Python requests giving error ('Connection aborted.', error("(104, 'ECONNRESET')",)) when attempting to post to gfycat.com
favorite count: 0
type: Question
has body: I am executing the code: import requests clientID = redacted secret =redacted filename = "temp2.gif" datakey = '{ "title":"random title"}' r = requests.post("https://api.gfycat.com/v1/gfycats", data = datakey) gfyname = r.json()["gfyname"] print(r.json()) print(gfyname) params_ = {'client_id': clientID, 'client_secret': secret, 'grant_type': 'client_credentials'} r = requests.post('https://api.gfycat.com/v1/oauth/token', data=str(params_)) access_token = r.json()['access_token'] headers = {'Authorization': 'Bearer {}'.format(access_token)} print(headers) data = {'key': gfyname} url = "https://filedrop.gfycat.com" files = {gfyname: open(filename, 'rb')} r = requests.post(url, data=data, files=files, headers=headers) print(r) It all executes fine until the very last request.post() call which is when I receive the error message: requests.exceptions.ConnectionError: ('Connection aborted.', error("(104, 'ECONNRESET')",)) I have verified the requests endpoints/params with the gfycat api documentation. I have checked the output of the headers and the access_token. I have read through the requests documentation and I did find a few things to which I fixed. and now I am stuck here, trying to figure out why the connection is aborting.
type: UnansweredQuestion
tagged with: gfycat
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88028160
has text: @Chris_Rands Could you please do that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50507990
score: 0

http://stackoverflow.com/a/50540485
downvote count: 0
type: Answer
has body: By all accounts, filter is lucky to be part of the standard library. IIUC, you just want to filter your dataframe to plot a histogram of values &gt; 0. Pandas has its own syntax for that: import numpy as np import pandas as pd import matplotlib.pyplot as plt data = np.random.randint(-50, 1000, 10000) df = pd.DataFrame({'some_data': data}) df[df['some_data'] &gt;= 0].hist(bins=100) plt.show() Note that this will run much faster than python builtins could ever hope to (it doesn't make much difference in my trivial example, but it will with bigger datasets). It's important to use pandas methods with dataframes wherever possible because, in many cases, the calculation will be vectorized and run in highly optimised C/C++ code.
answers question: http://stackoverflow.com/q/50540256
upvote count: 2
score: 2

http://stackoverflow.com/comment/88094456
type: Comment
comment on: http://stackoverflow.com/q/50532947
score: 0
has text: Many thanks for that @P.Tillmann, have reset the index and reassigned with: dfpiv3 = dfpiv2.reset_index(). This makes value_key appear again.
type: QuestionComment

http://stackoverflow.com/a/50529568
has comment: http://stackoverflow.com/comment/88071631
has comment: http://stackoverflow.com/comment/88071405
score: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/88071605
has comment: http://stackoverflow.com/comment/88071529
has comment: http://stackoverflow.com/comment/88070934
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50529504
has comment: http://stackoverflow.com/comment/88071485
has body: You should not assemble variable names this way, but you can place your variables in a collection (list), and print them: a0 = 3 a1 = 4 a2 = 5 a = [a0, a1, a2] for values in a: # this iterates over the values in a print(values)
has comment: http://stackoverflow.com/comment/88112102

http://stackoverflow.com/comment/88034067
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50510875
score: 1
has text: What's the file format?

http://stackoverflow.com/comment/88081227
type: QuestionComment
has text: Quick fix...create a hidden `a` element...on `$('#download-grades').on('click'` set the `href` attribute to your `grades_csv_url`...then trigger a click on that hidden `a` element....also read this https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50534439

http://stackoverflow.com/q/50474031
score: 1
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50474123
accepted answer: http://stackoverflow.com/a/50474173
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50474123
answer count: 2
has body: I have data like this. . I want to use pandas shift and subtract values between a column. This is the code which I am using. df['Difference'] = (df['A'] - df['A'].shift(-1)) This is the output I got ( as expected). How do I prevent pandas from subtracting between columns if the index ( Id) is different. I want to subtract only if the index is same. My desire output is something like this. Using of df.shift(-1, axis = 0) didn't solve either. Any Suggestions?
downvote count: 0
upvote count: 1
tagged with: python
has title: How do I stop Shifting column in Pandas if index is different
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50474173
tagged with: pandas

http://stackoverflow.com/a/50468009
has body: Here are some suggestions: import cv2 import numpy as np frame = cv2.imread('image.jpg') h, w = frame.shape[:2] mask_color = (0, 50, 255) # isolate a repeating constant # avoid setting a variable that is used only once, only if you REALLY need it to improve readability # that's why `upper_value` and `lower_value` were removed. # BTW, `lower_value` was unused in your code. upper_mask = cv2.rectangle(frame, (0, 0), (w, int(0.5 * h)), mask_color, -1) lower_mask = cv2.rectangle(frame, (0, h), (w, int(0.7 * h)), mask_color, -1)
type: Answer
accepted answer of: http://stackoverflow.com/q/50467436
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50467436
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/87951560
type: Comment
score: 0
has text: @Jack sounds like you may want to check https://stackoverflow.com/questions/71022/sql-max-of-multiple-columns and see if that offers anything you could use if your starting point is a SQL table...
type: AnswerComment
comment on: http://stackoverflow.com/a/50468140

http://stackoverflow.com/q/50432786
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49768770
score: 3
has title: Installing pip using easy_install on Mac OS
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50432830
tagged with: python
tagged with: easy-install
answer count: 4
has comment: http://stackoverflow.com/comment/87880682
linked to: http://stackoverflow.com/q/17271319
has body: I am trying to install pip through easy_install. I have tried the following command but no success: $ sudo /usr/bin/easy_install pip Result: Searching for pip Reading https://pypi.python.org/simple/pip/ Download error on https://pypi.python.org/simple/pip/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! Couldn't find index page for 'pip' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! No local packages or download links found for pip error: Could not find suitable distribution for Requirement.parse('pip') I have also tried simpler version sudo easy_install pip but getting same error. I have tried many online solutions but still no success.
has answer: http://stackoverflow.com/a/54191662
upvote count: 3
downvote count: 0
tagged with: pip
has answer: http://stackoverflow.com/a/52379531
has comment: http://stackoverflow.com/comment/87879846
has answer: http://stackoverflow.com/a/52358389

http://stackoverflow.com/q/50535703
type: Question
has title: Call newAPIHadoopFile from Python
upvote count: 0
type: UnansweredQuestion
has body: I want to read a large text file with Spark and change the textinputformat.record.delimiter to H. This code does NOT work: appName = "My Test" fname="myfile.txt" import operator from pyspark import SparkContext, SparkConf if __name__=="__main__": conf = SparkConf().setAppName(appName) conf.set("textinputformat.record.delimiter", "H") sc = SparkContext(conf=conf) sc.setLogLevel("ERROR") rdd1 = sc.textFile(fname) print("normal:",rdd1.collect()) It appears that the only way to do this is to use the sc.newAPIHadoopFile API call. However, I can't figure out how to do that from Python. This doesn't work: conf2 = SparkConf() conf2.set("textinputformat.record.delimiter", "H") rdd2 = sc.newAPIHadoopFile(fname, "org.apache.hadoop.mapreduce.lib.input.TextInputFormat", "org.apache.hadoop.io.LongWritable", "org.apache.hadoop.io.Text", conf2) print("improved:",rdd2.collect()) I get this error: AttributeError: 'SparkConf' object has no attribute '_get_object_id' Although this uses the same API as the question creating spark data structure from multiline record, it is a different use of the API. In that question, a function is created that allows multiple lines to be read at once. In this use, we change the textinputformat.record.delimiter
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/31227363
tagged with: apache-spark
duplicate of: http://stackoverflow.com/q/31227363
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50539063
favorite count: 0

http://stackoverflow.com/comment/87816201
has text: _When I want to get all records in table A, what would I use_ - `A.objects.all()`?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50399878

http://stackoverflow.com/a/50495779
has comment: http://stackoverflow.com/comment/88004447
score: 2
has comment: http://stackoverflow.com/comment/88004295
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/88004756
has comment: http://stackoverflow.com/comment/88004857
answers question: http://stackoverflow.com/q/50495686
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50495686
has body: From what I can tell from your code, you just print out whether the monster or person is dead. I would suggest making the Monster_Check_Dead and Person equivalent return True or False, as shown below. def Monster_check_dead(): if Monster.health &lt; 1 == True : print(Monster.name, "has been killed") return True else: print (Monster.name, "current health: ", Monster.health) return False def Player_check_dead(): if Player.health &lt; 1 == True : print(Player.name, "You have died") return True else: print (Player.name, "current health: ", Player.health) return False Then in the first part of the code you showed, add parenthesis at the end of each of the methods while Monster_check_dead() or Player_check_dead(): print ("Your fight is over") break else: fight_again() If that doesn't work, inform me and I can re-look at what I did wrong.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88004503

http://stackoverflow.com/comment/126634210
type: Comment
type: QuestionComment
has text: maybe i would (1) unstack the second level so they become columns, (2) group by the remaining level, and then (3) apply different aggregations to `v1` and `v2` with `agg(func={"v1": func1, "v2": func2})`.
comment on: http://stackoverflow.com/q/50397384
score: 0

http://stackoverflow.com/comment/87946596
comment on: http://stackoverflow.com/a/50465624
type: Comment
type: AnswerComment
score: 0
has text: @Kristjan I'm glad it works. As for learning material, I can't be much help there I'm afraid :/ Pandas is pretty huge and non-intuitive in some cases. Your best bet is probably to follow some of the bigger names here for a bit e.g. Jezrael, MaxU, Coldspeed, Wen, Unutbu, to name a few (and plenty that I missed out, sorry!). piRSquared seems to be using more pandas these days too.

http://stackoverflow.com/comment/88057683
type: AnswerComment
comment on: http://stackoverflow.com/a/50522276
score: 0
type: Comment
has text: Texts and images. I have to move 15gb blog contents from normal php website (which is impossible to export using sql) to wordpress.Wordpress has plugin html importer.So what I want to achieve is clean html with blog content.

http://stackoverflow.com/a/50472863
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: To perform multiple reductions at once, and for the problem dimensions you indicate, it will be important to understand whether your vectors are stored row-wise in memory or column-wise. For the row-wise storage method, a block-wise parallel reduction method should be pretty fast. Each block will perform a standard sweep-based parallel reduction for a single vector, then write the result as a single number to the output. For the column-wise storage method, for the problem dimensions you indicate (in particular, a "large" number of vectors), it will be efficient to have each thread perform the reduction across the vector using a simple loop traversing the column. Here is a worked example of both methods: # cat t7.py import numpy as np import numba as nb from numba import cuda,float32,int32 #vector length N = 1000 #number of vectors NV = 300000 #number of threads per block - must be a power of 2 less than or equal to 1024 threadsperblock = 256 #for vectors arranged row-wise @cuda.jit('void(float32[:,:], float32[:])') def vec_sum_row(vecs, sums): sm = cuda.shared.array(threadsperblock, float32) bid = cuda.blockIdx.x tid = cuda.threadIdx.x bdim = cuda.blockDim.x # load shared memory with vector using block-stride loop lid = tid sm[lid] = 0 while lid &lt; N: sm[tid] += vecs[bid, lid]; lid += bdim cuda.syncthreads() # perform shared memory sweep reduction sweep = bdim//2 while sweep &gt; 0: if tid &lt; sweep: sm[tid] += sm[tid + sweep] sweep = sweep//2 cuda.syncthreads() if tid == 0: sums[bid] = sm[0] #for vectors arranged column-wise @cuda.jit('void(float32[:,:], float32[:])') def vec_sum_col(vecs, sums): idx = cuda.grid(1) if idx &gt;= NV: return temp = 0 for i in range(N): temp += vecs[i,idx] sums[idx] = temp #peform row-test rvecs = np.ones((NV, N), dtype=np.float32) sums = np.zeros(NV, dtype=np.float32) d_rvecs = cuda.to_device(rvecs) d_sums = cuda.device_array_like(sums) vec_sum_row[NV, threadsperblock](d_rvecs, d_sums) d_sums.copy_to_host(sums) print(sums[:8]) #per…
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50462349
has comment: http://stackoverflow.com/comment/87960843
accepted answer of: http://stackoverflow.com/q/50462349

http://stackoverflow.com/comment/87829652
comment on: http://stackoverflow.com/q/50407089
has text: if __name__ == "__main__" : main()
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50457545
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has title: Scraping data from within multiple div classes into pandas data frame
answer count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: I am scraping some data off a dashboard and am stuck with trying to get some data within multiple div classes into a pandas data frame. How should I go about trying convert something like this : [ AAJ Marunda , Sari Dumai Sejati , Kutai Refinery Nusantara ] Into a data frame like this: no companyname country district latitude longitude millname province report 1 Apical Group INDONESIA Jakarta Utara -6.099396 106.951478 AAJ Marunda Jakarta http://naturalhealthytreat.com/sites/neste-daemeter.com/files/AAJ_Marunda.pdf 2 Apical Group INDONESIA Lubuk Gaung 1.754005 101.363532 Sari Dumai Sejati Riau http://naturalhealthytreat.com/sites/neste-daemeter.com/files/Kutai_Refinery_Nusantara_.pdf 3 Kutai Refinery Nusantara INDONESIA Balikpapan -1.179099 116.788274 Kutai Refinery Nusantara Penajam Paser Utara http://naturalhealthytreat.com/sites/neste-daemeter.com/files/Kutai_Refinery_Nusantara_.pdf So far, this is code I have put together to get the multiple div classes from the web page: from bs4 import BeautifulSoup import requests # Link of Neste dashboard url = 'http://nestetraceabilitydashboard.com/nestes-pfad-traceability-dashboard' page = requests.get(url).content soup = BeautifulSoup(page, "html.parser") divList = soup.findAll('div', attrs={ "class" : "map-item"})
tagged with: pandas
has answer: http://stackoverflow.com/a/50458057
accepted answer: http://stackoverflow.com/a/50458057

http://stackoverflow.com/comment/88039246
comment on: http://stackoverflow.com/q/50510479
type: Comment
type: QuestionComment
score: 0
has text: Another alternative: [**rpy2**](https://rpy2.bitbucket.io/)

http://stackoverflow.com/a/50516528
has comment: http://stackoverflow.com/comment/88994654
has comment: http://stackoverflow.com/comment/88609320
has comment: http://stackoverflow.com/comment/88993209
has comment: http://stackoverflow.com/comment/88828822
has comment: http://stackoverflow.com/comment/88688000
has comment: http://stackoverflow.com/comment/88610160
has comment: http://stackoverflow.com/comment/88744496
has comment: http://stackoverflow.com/comment/88617161
has comment: http://stackoverflow.com/comment/88580719
has comment: http://stackoverflow.com/comment/88760057
has comment: http://stackoverflow.com/comment/88105330
upvote count: 5
has comment: http://stackoverflow.com/comment/88665589
has comment: http://stackoverflow.com/comment/88826280
type: Answer
has comment: http://stackoverflow.com/comment/88143210
has comment: http://stackoverflow.com/comment/88625978
has comment: http://stackoverflow.com/comment/88049539
has comment: http://stackoverflow.com/comment/88124232
has comment: http://stackoverflow.com/comment/89171301
has comment: http://stackoverflow.com/comment/88734041
has comment: http://stackoverflow.com/comment/88766042
has comment: http://stackoverflow.com/comment/88140226
has comment: http://stackoverflow.com/comment/89009419
score: 5
has comment: http://stackoverflow.com/comment/88121164
answers question: http://stackoverflow.com/q/50515064
has comment: http://stackoverflow.com/comment/88616735
has comment: http://stackoverflow.com/comment/88987309
downvote count: 0
has comment: http://stackoverflow.com/comment/88150376
has comment: http://stackoverflow.com/comment/88627996
has comment: http://stackoverflow.com/comment/88093672
has comment: http://stackoverflow.com/comment/88650279
has comment: http://stackoverflow.com/comment/102588763
has comment: http://stackoverflow.com/comment/88578774
has comment: http://stackoverflow.com/comment/88079394
has body: When implementing this you should take care which version of IFC your import library works on - the version distributed by the IfcOpenShell-Website works with IFC2X3. For IFC4 you will probably need to compile a version yourself. (you can check your IFC version with ifcopenshell.schema_identifier) I am putting links up to the buildingSMART IFC 4 definition even if I am talking about IFC2X3. Differences to IFC2X3 are marked in red on the buildingSMART web page. And the IFC4 definition is nicer to read (IMO). Quantities aren't directly attached like an attribute. They are written as property sets and then related to the element or element type. So first you should ensure your IFC file contains quantities - otherwise you will not find any. Usually you start with a specific product - ifc_file.by_type('IfcSlab'). You can reach the property sets via inverse attributes - those are usually set up by the IFC library, they don't appear directly as attribute in the file. I took you example file and shortened it to about a third (so it's still a valid IFC2X3 file): ISO-10303-21; HEADER;FILE_DESCRIPTION(('ViewDefinition [Custom, QuantityTakeOffAddOnView, SpaceBoundary2ndLevelAddOnView]','Option [Drawing Scale: 100.000000]','Option [Global Unique Identifiers (GUID): Keep existing]','Option [Elements to export: Visible elements (on all stories)]','Option [Partial Structure Display: Entire Model]','Option [IFC Domain: All]','Option [Structural Function: All Elements]','Option [Convert Grid elements: On]','Option [Convert IFC Annotations and ARCHICAD 2D elements: Off]','Option [Convert 2D symbols of Doors and Windows: Off]','Option [Explode Composite and Complex Profile elements into parts: On]','Option [Export geometries that Participates in Collision Detection only: Off]','Option [Elements in Solid Element Operations: Extruded/revolved]','Option [Elements with junctions: Extruded/revolved without junctions]','Option [Slabs with slanted edge(s): Extruded]','Option [Use legacy geome…

http://stackoverflow.com/q/50464610
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: javascript
has body: This is a pretty simple thing to do I imagine, but I'm not sure how to do it. I have a data table with three columns. Two are numerical values that are plotted, and one is strings. I want the user to be able to input into a field, and the corresponding row in the DataTable and the point on the plot to be selected/highlighted. I think I need to use source.selected.indices, or possibly a CustomJS callback. Can anyone help? from random import randint from bokeh.io import output_file, show from bokeh.layouts import gridplot, row from bokeh.models import ColumnDataSource from bokeh.models.widgets import DataTable, TableColumn, TextInput search_words = TextInput(title="Search for country") data = dict( x=[randint(0, 100) for i in range(10)], y=[randint(0, 100) for i in range(10)], countries = ["France","Spain","Germany","Italy","Portugal","Poland","Russia","Bulgaria","Sweden","Belgium"] ) source = ColumnDataSource(data) columns = [ TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field="countries", title="Countries"), ] TOOLS = "pan,wheel_zoom,box_select,reset" fig = figure(plot_width=400, plot_height=400, tools=TOOLS) fig.circle('x', 'y', source=source,size=10,selection_color="red", hover_color="green") data_table = DataTable(source=source, columns=columns, width=400, height=280) p = gridplot([fig],[data_table], toolbar_location = "above") show(row(p, search_words))
score: 1
answer count: 1
tagged with: input
tagged with: slickgrid
tagged with: python
tagged with: bokeh
favorite count: 0
has answer: http://stackoverflow.com/a/50473169
type: Question
has title: Bokeh: Select row of ColumnDataSource using TextInput widget

http://stackoverflow.com/q/50489153
answer count: 2
has body: Does someone know the difference between those 2 keywords from Selenium: element.submit() element.submit I've some forms working with the first one, and others working with the second. For example, self.webdriver.find_element_by_xpath('//*[@id="search"]/input').submit return a result while self.webdriver.find_element_by_xpath('//*[@id="search"]/input').submit() returns another. Thanks!
has title: Python: Selenium submit
has comment: http://stackoverflow.com/comment/87991439
tagged with: submit
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/50489634
downvote count: 1
has comment: http://stackoverflow.com/comment/87992823
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50490706
accepted answer: http://stackoverflow.com/a/50489634
tagged with: python
has answer: http://stackoverflow.com/a/50490706
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87892822
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50439201
has text: @Jayjayyy Also, more generally—you may not have a use for everything you discover in SymPy. If `subs(…).evalf(…)` is always what you want, you can just use that. (Doing `evalf(…).subs(…)`, on the other hand, could be very different from either; it's more likely that you'll need both for different purposes, even though in this specific example it's identical.)

http://stackoverflow.com/comment/88085095
type: Comment
comment on: http://stackoverflow.com/a/50480107
type: AnswerComment
has text: @ArefRiant Sorry about that. Edited the code. Should work now.
score: 0

http://stackoverflow.com/q/50436259
type: AnsweredQuestion
has body: I just started to learn python and I created a calculator. I'm having troubles with doing 3 number operation with multiplication and division. I set the variable Number3 to zero so that if you don't have a third number it won't affect the operation, so it would be 1+1+0= 2, but if it's not + or - it will end up affecting the answer. So what I did was create a variable Number4 with a value of 1 and just add it to the elif statements for multiplication and division. However, I feel like it sloppy and there is a better way of getting the effect. What would be the best way to do this? print ("Python calculator") print (""" Select an operation below 1: Add 2: Sub 3: Mult 4: Div """) def add(x, y, z): return x + y + z def sub(x, y, z): return x - y - z def mult(x, y, z): return x * y * z def div(x, y, z): return x / y / z Operation = input ("Enter Operation Number") Number1 = int(input ("Enter Your First Number")) Number2 = int(input ("Enter your Second Number")) Number3 = (0) More = input ("Do you have more numbers? (Yes or No)") if More == "yes" or More == "Yes": Number3 =int(input ("What is your other number?")) print ("calculating") else: print ("calculating") if Operation == '1': print(add(Number1,Number2,Number3)) elif Operation == '2': print(sub(Number1,Number2,Number3)) elif Operation == '3'and More != "Yes": Number4 = 1 print(mult(Number1,Number2,Number4 )) elif Operation == '3': print(mult(Number1,Number2,Number3 )) elif Operation == '4'and More != "Yes": Number4 = 1 print(div(Number1,Number2,Number4 )) elif Operation == '4': print(div(Number1,Number2,Number3 )) else: print("Invalid inputs")
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50436473
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50436473
tagged with: python
has title: Python calculator - Having issues using 3 number

keras
tags question: http://stackoverflow.com/q/50409283
tags question: http://stackoverflow.com/q/50437095
tags question: http://stackoverflow.com/q/50436734
tags question: http://stackoverflow.com/q/50434710
tags question: http://stackoverflow.com/q/50437670
tags question: http://stackoverflow.com/q/50515409
tags question: http://stackoverflow.com/q/50524927
tags question: http://stackoverflow.com/q/50517934
tags question: http://stackoverflow.com/q/50447015
tags question: http://stackoverflow.com/q/50400765
tags question: http://stackoverflow.com/q/50536492
tags question: http://stackoverflow.com/q/50414117
tags question: http://stackoverflow.com/q/50448446
tags question: http://stackoverflow.com/q/50513505
tags question: http://stackoverflow.com/q/50504770
tags question: http://stackoverflow.com/q/50539213
tags question: http://stackoverflow.com/q/50518710
tags question: http://stackoverflow.com/q/50511689
tags question: http://stackoverflow.com/q/50539246
tags question: http://stackoverflow.com/q/50494396
tags question: http://stackoverflow.com/q/50487156
tags question: http://stackoverflow.com/q/50518563
tags question: http://stackoverflow.com/q/50469757
tags question: http://stackoverflow.com/q/50540668
tags question: http://stackoverflow.com/q/50525283
tags question: http://stackoverflow.com/q/50479021
tags question: http://stackoverflow.com/q/50402779
tags question: http://stackoverflow.com/q/50393014
tags question: http://stackoverflow.com/q/50488410
tags question: http://stackoverflow.com/q/50429004
tags question: http://stackoverflow.com/q/50467988
tags question: http://stackoverflow.com/q/50401466
tags question: http://stackoverflow.com/q/50388684
tags question: http://stackoverflow.com/q/50477826
tags question: http://stackoverflow.com/q/50512444
tags question: http://stackoverflow.com/q/50531732
tags question: http://stackoverflow.com/q/50442334
tags question: http://stackoverflow.com/q/50474336
tags question: http://stackoverflow.com/q/50455088
tags question: http://stackoverflow.com/q/50522400
tags question: http://stackoverflow.com/q/50387749
tags question: http://stackoverflow.com/q/50434183
tags question: http://stackoverflow.com/q/50525747
tags question: http://stackoverflow.com/q/50513422
tags question: http://stackoverflow.com/q/50392211
tags question: http://stackoverflow.com/q/50420559
tags question: http://stackoverflow.com/q/50458964
tags question: http://stackoverflow.com/q/50516541
tags question: http://stackoverflow.com/q/50428293
tags question: http://stackoverflow.com/q/50405655
tags question: http://stackoverflow.com/q/50512089
tags question: http://stackoverflow.com/q/50438308
tags question: http://stackoverflow.com/q/50483962
tags question: http://stackoverflow.com/q/50417088
tags question: http://stackoverflow.com/q/50456840
tags question: http://stackoverflow.com/q/50520306
tags question: http://stackoverflow.com/q/50510560
tag name: keras
tags question: http://stackoverflow.com/q/50432476
tags question: http://stackoverflow.com/q/50437579
tags question: http://stackoverflow.com/q/50410189
tags question: http://stackoverflow.com/q/50490514
tags question: http://stackoverflow.com/q/50400481
tags question: http://stackoverflow.com/q/50530100
tags question: http://stackoverflow.com/q/50398154
tags question: http://stackoverflow.com/q/50508154
tags question: http://stackoverflow.com/q/50396739
tags question: http://stackoverflow.com/q/50411612
tags question: http://stackoverflow.com/q/50508816
tags question: http://stackoverflow.com/q/50495161
tags question: http://stackoverflow.com/q/50393828
tags question: http://stackoverflow.com/q/50450512
tags question: http://stackoverflow.com/q/50515550
tags question: http://stackoverflow.com/q/50427893
tags question: http://stackoverflow.com/q/50441120
tags question: http://stackoverflow.com/q/50442416
type: Tag
tags question: http://stackoverflow.com/q/50474524
tags question: http://stackoverflow.com/q/50541409
tags question: http://stackoverflow.com/q/50479335

http://stackoverflow.com/q/50439178
tagged with: regression
has answer: http://stackoverflow.com/a/50439789
accepted answer: http://stackoverflow.com/a/50439789
has answer: http://stackoverflow.com/a/50441479
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/r
score: 3
upvote count: 3
has body: I am new to python I am trying to do a gamma regression, I hope to obtain similar estimations to R, but I can not understand the syntax of python and it generates an error, some idea of how to solve it. My R code: set.seed(1) y = rgamma(18,10,.1) print(y) [1] 76.67251 140.40808 138.26660 108.20993 53.46417 110.61754 119.11950 113.57558 85.82045 71.96892 [11] 76.81693 86.00139 93.62010 69.49795 121.99775 114.18707 125.43608 120.63640 # Option 1 model = glm(y~1,family=Gamma) summary(model) # Option 2 # x = rep(1,18) # summary(glm(y~x,family=Gamma)) Output: summary(model) Call: glm(formula = y ~ 1, family = Gamma) Deviance Residuals: Min 1Q Median 3Q Max -0.57898 -0.24017 0.07637 0.17489 0.34345 Coefficients: Estimate Std. Error t value Pr(&gt;|t|) (Intercept) 0.009856 0.000581 16.96 4.33e-12 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for Gamma family taken to be 0.06255708) Null deviance: 1.1761 on 17 degrees of freedom Residual deviance: 1.1761 on 17 degrees of freedom AIC: 171.3 Number of Fisher Scoring iterations: 4 Python Code y = [76.67251,140.40808,138.26660,108.20993,53.46417,110.61754, 119.11950,113.57558,85.82045,71.96892,76.81693,86.00139, 93.62010,69.49795,121.99775,114.18707,125.43608,120.63640] x = np.repeat(1,18) import numpy import statsmodels.api as sm model = sm.GLM(x,y, family=sm.families.Gamma()).fit() print(model.summary()) I expected an output similar to R
possible better answer: http://stackoverflow.com/a/50441479
tagged with: python
has title: Gamma regression only intercept
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: glm

http://stackoverflow.com/comment/87923638
has text: will this give the desired output?
comment on: http://stackoverflow.com/a/50455034
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88033789
has text: even if it's not raw data?
comment on: http://stackoverflow.com/q/50510642
score: 0
type: Comment
type: QuestionComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/50400038
tags question: http://stackoverflow.com/q/50385988
tags question: http://stackoverflow.com/q/50495232
tags question: http://stackoverflow.com/q/50504279
tags question: http://stackoverflow.com/q/50439309
tags question: http://stackoverflow.com/q/50435630
tags question: http://stackoverflow.com/q/50429004
tags question: http://stackoverflow.com/q/50421287
tags question: http://stackoverflow.com/q/50444939
tags question: http://stackoverflow.com/q/50465106
tags question: http://stackoverflow.com/q/50537908
tags question: http://stackoverflow.com/q/50497327
tags question: http://stackoverflow.com/q/50479258
tags question: http://stackoverflow.com/q/50404640
tags question: http://stackoverflow.com/q/50439165
type: Tag
tags question: http://stackoverflow.com/q/50457501
tags question: http://stackoverflow.com/q/50449196
tags question: http://stackoverflow.com/q/50389613

http://stackoverflow.com/q/50403610
type: Question
has body: the reboot function of virdomain class from libvirt-domain : def reboot(self, flags=0): """Reboot a domain, the domain object is still usable thereafter, but the domain OS is being stopped for a restart. Note that the guest OS may ignore the request. Additionally, the hypervisor may check and support the domain 'on_reboot' XML setting resulting in a domain that shuts down instead of rebooting. If @flags is set to zero, then the hypervisor will choose the method of shutdown it considers best. To have greater control pass one or more of the virDomainRebootFlagValues. The order in which the hypervisor tries each shutdown method is undefined, and a hypervisor is not required to support all methods. To use guest agent (VIR_DOMAIN_REBOOT_GUEST_AGENT) the domain XML must have &lt;channel&gt; configured. Due to implementation limitations in some drivers (the qemu driver, for instance) it is not advised to migrate or save a guest that is rebooting as a result of this API. Migrating such a guest can lead to a plain shutdown on the destination. """ ret = libvirtmod.virDomainReboot(self._o, flags) if ret == -1: raise libvirtError ('virDomainReboot() failed', dom=self) return ret and my qemu/kvm vm doesn't response to the request to reboot or to shutdown , while it responds to request of reset. i want to know why and what can i do. thank you~
tagged with: python
has answer: http://stackoverflow.com/a/50414595
tagged with: kvm
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50414595
answer count: 1
has title: why libvirt virdomain guest os mayignore the request to reboot or shutdown?
tagged with: libvirt

http://stackoverflow.com/comment/87925830
score: 0
type: Comment
has text: Why do you set `blank=True`? Looks to me that this has impact on the fact that they add a "blank" option.
type: QuestionComment
comment on: http://stackoverflow.com/q/50456101

http://stackoverflow.com/comment/87824325
comment on: http://stackoverflow.com/q/50404234
type: QuestionComment
has text: I request to "https://groupon.com/" worked. But with this link it didn't
type: Comment
score: 0

http://stackoverflow.com/a/50513681
type: Answer
has body: You forgot the self. def in_order_traversal(self): if self.root != None: self.in_order_traversal(self.root.left) print(root.data) self.in_order_traversal(self.root.right)
accepted answer of: http://stackoverflow.com/q/50513658
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50513658
upvote count: 1

http://stackoverflow.com/q/50517454
possible better answer: http://stackoverflow.com/a/50521539
tagged with: python
has body: I'm asking you guys if there's any way to create a two-dimensional Array as a class. I'm trying to complete a task and I couldn't find any research about this on google. If someone knows any solution with extra interpretation and/or explanation, please hit me up. (something like this:) class Array (object): def __init__ (self, row = 0, col = 0, el = 0): self.row = row self.col = col self.el = el
accepted answer: http://stackoverflow.com/a/50517633
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88047713
tagged with: arrays
has answer: http://stackoverflow.com/a/50521539
has comment: http://stackoverflow.com/comment/88047558
has answer: http://stackoverflow.com/a/50517633
has title: Two-dimensional Array as an object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88047610
has comment: http://stackoverflow.com/comment/88047572

http://stackoverflow.com/q/50527953
has title: Dataframe join on multiple columns with some conditions on columns in pyspark
type: Question
tagged with: apache-spark-sql
linked to: http://stackoverflow.com/q/34041710
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50531683
tagged with: pyspark
tagged with: python
duplicate of: http://stackoverflow.com/q/34041710
score: 0
has body: df = sqlContext.sql("select d1.a, d1.b, d1.c as aaa, d2.d, d2.e, d2.f, d2.g, d2.h, d2.i, d2.j as length, '{1}' as month_end from df1 d1 join df2 d2 on concat(substr(upper(trim(d1.a)),0,d1.j),' ') = substr(upper(trim(d2.j)),0,(d2.j+1)) and upper(trim(d1.c)) = upper(trim(d2.f)) where length(upper(trim(d2.i))) &gt; d2.j and length(upper(trim(d1.a))) = (d1.j+3)".format(dataBase, month_end)) can someone please help me to convert the above join to dataframe join instead of sql join. Tried: joinDf = df1.join(df2,on=[(concat(substring(upper(trim(df1["a"])),0,df1["j"]),' ')) == substring(upper(trim(df2["j"])),0,(df2["j"]+1)) and upper(trim(df1["c"])) == upper(trim(df2["f"]))]) (without select) Getting error : Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/opt/cloudera/parcels/CDH-5.10.2-1.cdh5.10.2.p2667.3017/lib/spark/python/pyspark/sql/functions.py", line 1180, in substring return Column(sc._jvm.functions.substring(_to_java_column(str), pos, len)) File "/opt/cloudera/parcels/CDH-5.10.2-1.cdh5.10.2.p2667.3017/lib/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 798, in __call__ File "/opt/cloudera/parcels/CDH-5.10.2-1.cdh5.10.2.p2667.3017/lib/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 785, in _get_args File "/opt/cloudera/parcels/CDH-5.10.2-1.cdh5.10.2.p2667.3017/lib/spark/python/lib/py4j-0.9-src.zip/py4j/java_collections.py", line 512, in convert TypeError: 'Column' object is not callable
tagged with: apache-spark
answer count: 1

http://stackoverflow.com/q/50408796
type: Question
has title: VSCode ImportError: No module named web3
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/50409021
type: UnansweredQuestion
answer count: 1
tagged with: pip
has body: I have Python3 and Python2 in my ubuntu 16.04. naturally, I install pip3 and pip. But When I use VScode to run my python3 code, it can't find my package! I don't find where to set the package path. I need help, thanks! [Running] python "source/pyweb3.py" Traceback (most recent call last): File "source/pyweb3.py", line 5, in &lt;module&gt; import web3 ImportError: No module named web3 [Done] exited with code=1 in 0.059 seconds Here are the package information of my pip and pip3 : ubuntu:/source$ pip list Package Version ----------------------------- ---------------------- … virtualenv 15.2.0 Werkzeug 0.14.1 wheel 0.29.0 wrapt 1.10.11 … ubuntu:/source$ pip3 list Package Version ----------------------------- ---------------------- … virtualenv 15.2.0 web3 4.2.1 websockets 4.0.1 … Here are the information of my pip and pip3 : ubuntu:/source$ pip3 --version pip 10.0.1 from /home/username/.local/lib/python3.5/site-packages/pip (python 3.5) ubuntu:/source$ pip --version pip 10.0.1 from /home/username/.local/lib/python2.7/site-packages/pip (python 2.7)
score: 0
tagged with: python

aes
tag name: aes
tags question: http://stackoverflow.com/q/50425623
tags question: http://stackoverflow.com/q/50429603
type: Tag

http://stackoverflow.com/comment/87963423
score: 0
has text: You can use regex module which supports overlapping pattern matching. print(len(regex.findall("ana", str,overlapped=True)))
comment on: http://stackoverflow.com/q/50474751
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87873226
score: 0
has text: https://stackoverflow.com/questions/27315592/csrf-exempt-does-not-work-on-generic-view-based-class csrf exempt your view
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50429243

http://stackoverflow.com/q/50460930
tagged with: numpy
has body: I am applying OneHotEncoder on numpy array. Here's the code print X.shape, test_data.shape #gives 4100, 15) (410, 15) onehotencoder_1 = OneHotEncoder(categorical_features = [0, 3, 4, 5, 6, 8, 9, 11, 12]) X = onehotencoder_1.fit_transform(X).toarray() onehotencoder_2 = OneHotEncoder(categorical_features = [0, 3, 4, 5, 6, 8, 9, 11, 12]) test_data = onehotencoder_2.fit_transform(test_data).toarray() print X.shape, test_data.shape #gives (4100, 46) (410, 43) where both X and test_data are &lt;type 'numpy.ndarray'&gt; X is my train set while test_data my test set. How come the no. of columns different for X &amp; test_data. they should be 46 or either 43 for both after applying onehotencoder. I am applying OnehotEncoder on specific attributes as they are categorical in nature in both X and test_data Can someone point out what is wrong here?
type: AnsweredQuestion
upvote count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/50461140
tagged with: scikit-learn
answer count: 1
has answer: http://stackoverflow.com/a/50461140
favorite count: 0
type: Question
tagged with: one-hot-encoding
has title: applying onehotencoder on numpy array
tagged with: python
score: -2

http://stackoverflow.com/q/50488066
has title: How to sort and separate an array in a special way
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/50488787
tagged with: python
tagged with: pseudocode
has body: I have a table with three columns and it has this structure: Date | Hour | Status | --------------------------- 23/05 | 12:00 | Stop | 23/05 | 12:20 | Stop | 23/05 | 12:40 | Running | 23/05 | 13:00 | Running | 23/05 | 13:06 | Stop | 23/05 | 13:15 | Running | 23/05 | 13:20 | Running | 23/05 | 13:40 | Running | 23/05 | 14:00 | Running | 23/05 | 14:01 | Other | 23/05 | 14:20 | Other | 23/05 | 14:40 | Other | 23/05 | 15:00 | Other | ... I would like to sandwich all the status in one hour and end up with a table like so: Date | Hour | Status | --------------------------- 23/05 | 12:00 | Stop | 23/05 | 13:00 | Running | 23/05 | 14:00 | Other | The criteria would be by taking the average of times that a status has spent the most time on. The problem I have is that for each hour we could have either 3 rows or we could have several, there is no way of knowing so we have to calculate it... How could I do this?
favorite count: 0
type: Question

http://stackoverflow.com/q/50427896
has comment: http://stackoverflow.com/comment/87870868
has comment: http://stackoverflow.com/comment/87870467
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87870782
type: UnansweredQuestion
has title: Python 3 - Are "from __future__ import xyz" statements necessary/beneficial (emphasis on TensorFlow)?
downvote count: 0
score: 6
has body: As I'm getting further into TensorFlow and the finer points of Python, I've noticed these 3 statements at the top of many (perhaps most) .py files in the TensorFlow repository: from __future__ import absolute_import from __future__ import division from __future__ import print_function Here are two examples: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_deep.py#L25 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/word2vec/word2vec_basic.py#L17 I should clarify that I have no interest or need to support Python 2 or substantially older versions of Python 3 in any projects I'm undertaking currently. After reading about from __future__ import xyz statements, for example from these sources: What is __future__ in Python used for and how/when to use it, and how it works https://docs.python.org/2/library/future.html https://docs.python.org/3/library/future.html http://python-future.org/imports.html I'm able to understand most of this documentation but I'm left with the following questions: If only using Python 3, is there any need for these statements or can they safely be removed entirely in all cases? More specifically, if I put the following statement in the beginning of a program: # check Python version is at least 3.6, if not, show an error and bail if sys.version_info.major &lt; 3 or sys.version_info.minor &lt; 6: print("ERROR: currently running Python version " + sys.version + ", at least version 3.6 is required") return # end if Can the above statements be removed with no possibility of ill effects? Would these statements matter in an older version of Python 3 vs a newer version of Python 3, ex. Python 3.1 vs Python 3.6? Since TensorFlow requires Python version 3.5 or later, if these statements only matter if Python 2 (or possibly an older version of Python 3? see the previous question) is being used, why are these included in the TensorFlow codebase? If removing these could ever cause…
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/87871720
has comment: http://stackoverflow.com/comment/87871945
linked to: http://stackoverflow.com/q/7075082
answer count: 0

http://stackoverflow.com/comment/88244084
has text: @Mouad: Rule based approach would take much time. So leave it for now. you can try to store keys having multiple words as word1\s+word2. Then chk for the same.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50387023

http://stackoverflow.com/comment/109604818
type: Comment
score: 0
type: AnswerComment
has text: How does this work in a query set? This is what I'm stuck on https://stackoverflow.com/questions/61951419/django-get-queryset-return-custom-variables?noredirect=1#comment109577359_61951419
comment on: http://stackoverflow.com/a/50393519

http://stackoverflow.com/q/50434784
tagged with: python
has answer: http://stackoverflow.com/a/50474757
favorite count: 0
linked to: http://stackoverflow.com/q/50322704
tagged with: date-histogram
score: 1
tagged with: matplotlib
has title: Python: Plot month-wise normalised histogram
has comment: http://stackoverflow.com/comment/87896960
has comment: http://stackoverflow.com/comment/87887129
has body: I have a CSV file with data that look like this: Time Pressure 1/1/2017 0:00 5.8253 ... ... 3/1/2017 0:10 4.2785 4/1/2017 0:20 5.20041 5/1/2017 0:30 4.40774 6/1/2017 0:40 4.03228 7/1/2017 0:50 5.011924 12/1/2017 1:00 3.9309888 I want to make a month-wise histogram (NORMALIZED) on the pressure data and finally write the plots into PDF. I understand that I need to use Groupby and Numpy.hist option,but I'm not sure how to use them. (I'm a newbie to Python). Please help! CODE 1: n = len(df) // 5 for tmp_df in (df[i:i+n] for i in range(0, len(df), n)): gb_tmp = tmp_df.groupby(pd.Grouper(freq='M')) ax = gb_tmp.hist() plt.setp(ax.xaxis.get_ticklabels(),rotation=90) plt.show() plt.close() This gives me the following error message: ValueError: range() arg 3 must not be zero CODE 2: df1 = df.groupby(pd.Grouper(freq='M')) np.histogram(df1,bins=10,range=None,normed=True) This returns another error message: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I tried the above codes, but got these errors. Not sure if I'm using it right.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87887218
upvote count: 3
tagged with: seaborn
type: UnansweredQuestion
downvote count: 2
answer count: 1

http://stackoverflow.com/a/50559635
has body: A simple solution that still allows you to use progress callback is: Use BytesIO file-like object to store a downloaded file to memory; You have to seek file pointer back to file start after downloading it, before you start reading it. with io.BytesIO() as fl: sftp.getfo(file_name, fl, callback=printTotals) fl.seek(0) df = pd.read_csv(fl, sep=' ') Though with this solution, you will end up having the file loaded to memory twice. Better solution is to implement a custom file-like object. It will even allow you to download and parse the file at the same time. class FileWithProgress: def __init__(self, fl): self.fl = fl self.size = fl.stat().st_size self.p = 0 def read(self, blocksize): r = self.fl.read(blocksize) self.p += len(r) print(str(self.p) + " of " + str(self.size)) return r And use it like: with sftp.open(file_name, "rb") as fl: fl.prefetch() df = pd.read_csv(FileWithProgress(fl), sep=' ') For the SFTPFile.prefetch call, refer to: Reading file opened with Python Paramiko SFTPClient.open method is slow. If you do not need the progress monitoring, simple code like this will do: with sftp.open(file_name, "rb") as fl: fl.prefetch() df = pd.read_csv(fl, sep=' ')
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/136578736
answers question: http://stackoverflow.com/q/50531631
upvote count: 15
type: Answer
accepted answer of: http://stackoverflow.com/q/50531631
score: 15
has comment: http://stackoverflow.com/comment/88143203

http://stackoverflow.com/comment/87835914
type: QuestionComment
comment on: http://stackoverflow.com/q/50410304
has text: use csv.writer or [DictWriter](https://docs.python.org/2/library/csv.html#csv.DictWriter) from [CSV module](https://docs.python.org/2/library/csv.html)
score: 1
type: Comment

http://stackoverflow.com/comment/88061900
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50524915
has text: thanks ! problem solved :)
score: 0

http://stackoverflow.com/q/50500930
has answer: http://stackoverflow.com/a/50508532
type: Question
tagged with: python-3.x
tagged with: python
has body: how can one alter the appearance of a marker within a trace? e.g. in the example below how could the opacity for each marker be set to a specific value (e.g based on the opacity_data list) Seems like this should be possible but I haven't had any success. Thanks in advance for any help, dusiod import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go app = dash.Dash() x_data = list(range(1,11)) y_data = [i**2 for i in x_data] opacity_data = [i / i**2 for i in x_data] app.layout = html.Div([ dcc.Graph(id='test', figure=go.Figure( data=[go.Scatter( x=x_data, y=y_data, mode='markers', opacity=1)] )) ]) app.run_server()
type: AnsweredQuestion
score: 0
tagged with: plotly
has title: plotly - how to modify markers within a trace
accepted answer: http://stackoverflow.com/a/50508532
answer count: 1

http://stackoverflow.com/a/50714964
answers question: http://stackoverflow.com/q/50530158
score: 2
upvote count: 2
downvote count: 0
has body: Update: (Inspired by sacul) Create an empty dok_matrix and modify only D's nonzero part with nonzero. (This should work for sparse matrices other than dok_matrix as well.) F = scipy.sparse.dok_matrix(E.shape) F[D.nonzero()] = E[D.nonzero()] / D[D.nonzero()] You can try the update + nonzero method for dok_matrix. nonzero_idx = [tuple(l) for l in np.transpose(D.nonzero())] D.update({k: E[k]/D[k] for k in nonzero_idx}) First, we use nonzero to nail down the indices in the matrix D that is not 0. Then, we put the indices in the update method where we supply a dictionary {k: E[k]/D[k] for k in nonzero_idx} such that the values in D will be updated according to this dictionary. Explanation: What D.update({k: E[k]/D[k] for k in nonzero_idx}) does is for k in {k: E[k]/D[k] for k in nonzero_idx}.keys(): D[k] = E[k]/D[k] Note that this changes D in place. If you want to create a new sparse matrix rather than modifying D in place, copy D to another matrix, say ret. nz = [tuple(l) for l in np.transpose(D.nonzero())] ret = D.copy() ret.update({k: E[k]/D[k] for k in nz})
type: Answer

http://stackoverflow.com/comment/103995001
comment on: http://stackoverflow.com/a/50389564
type: AnswerComment
score: 0
has text: @variable it's hard to debug this without context, could you create a question and define what you've tried exactly?
type: Comment

http://stackoverflow.com/q/50530444
tagged with: python
has body: I'm writing a script for scrape the website "yelp.fr" but to scrap the number of stars the class is generating automaticly: class="i-stars i-stars--regular-4 rating-large" ==> 4 starts class="i-stars i-stars--regular-3-half rating-large" ==> 3.5 My question how i can do this? and how can i etst if class exist or not on the html page CITIES = "la rochelle(17000)" places = "Bars" driver = webdriver.Chrome() driver.get("https://www.yelp.fr/search?find_desc="+places+"&find_loc="+CITIES+"") page = driver.page_source soup = BeautifulSoup(page,"lxml") etoiles=soup.find_all("div",{"class":"biz-rating biz-rating-large clearfix"}) etoiles.get_attribute("title") if etoiles: print "ok" else: print "not " some times class biz-rating biz-rating-large clearfix not exist as bellow
tagged with: selenium-webdriver
type: Question
tagged with: selenium-chromedriver
score: 0
has answer: http://stackoverflow.com/a/50588757
upvote count: 1
type: UnansweredQuestion
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50622102
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50532845
answer count: 3
has title: Check if a specific class and value exist in HTML using beautifulsoup Python

http://stackoverflow.com/comment/87883168
type: Comment
type: QuestionComment
has text: What would be the desired outcome if the line wasn't straight but curved? It seems the spacing between markers would then need to depend not only on the markersize but also on the curvature?
comment on: http://stackoverflow.com/q/50385463
score: 0

http://stackoverflow.com/comment/87859534
comment on: http://stackoverflow.com/q/50406779
has text: @user26472 Yes, the answer to my question was to close when pressed out of the popup.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87962758
score: 1
has text: I doubt you can use strings to fit anything. The page you link to may not be the most reliable source. Better look at respective questions like e.g. [ths one](https://stackoverflow.com/questions/41838037/python-matplotlib-axis-is-blank-for-date-with-trend-line).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50474104

http://stackoverflow.com/a/66456158
type: Answer
has body: Initially, I tried with only pip. It didn't work in colab. Then I tried with git. And it worked perfectly. !git clone https://github.com/google/seq2seq.git !pip install -e seq2seq Then import it and use it according to your need. import seq2seq
score: 0
answers question: http://stackoverflow.com/q/50513493

http://stackoverflow.com/a/50529443
type: AcceptedAnswer
upvote count: 2
has comment: http://stackoverflow.com/comment/88071174
downvote count: 0
has comment: http://stackoverflow.com/comment/88070963
type: Answer
answers question: http://stackoverflow.com/q/50529336
has body: You could use list() to force the queryset to be evaluated. try: dossiersdb = list(Person.objects.using('dbn').all()) except OperationalError as exp : logger.warning("Got %s", exp) return HttpResponse(' OperationalError ')
score: 2
accepted answer of: http://stackoverflow.com/q/50529336

http://stackoverflow.com/a/50513194
has body: I think this question answers your question: Anchor link to Firefox about:config?. Give it a try. Basically, you are not allowed to reference a local resource due to security issues (like the post says).
answers question: http://stackoverflow.com/q/50513128
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87955481
has text: try https://codereview.stackexchange.com for help with working code.
score: 2
comment on: http://stackoverflow.com/q/50470991
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51065013
answers question: http://stackoverflow.com/q/50494654
score: 0
has body: If it happens to me and not to BPL with almost the same setup. It could be that it works on 32 bit python and doesn't work on 64 bit python.
type: Answer

http://stackoverflow.com/q/50485291
upvote count: 2
downvote count: 0
has title: Django queryset of articles by authors the user is following
tagged with: django
accepted answer: http://stackoverflow.com/a/50485427
has answer: http://stackoverflow.com/a/50485487
favorite count: 0
has answer: http://stackoverflow.com/a/50485427
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/87984178
has body: I have two models class Account(AbstractBaseUser, PermissionsMixin): followers = models.ManyToManyField( 'Account', related_name='followers', blank=True, ) following = models.ManyToManyField( 'Account', related_name='following', blank=True, ) and class Article(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) I'm writing an application where users subscribe to each other and create articles. How can I make a request to receive all the articles from those to whom I am subscribed? I'm trying to do something like: (pseudo-code) user = self.get_object() articles = Article.objects.filter(author=user.followers.all()) But I know that this is not right
tagged with: python
possible better answer: http://stackoverflow.com/a/50485487
type: Question
score: 2
has answer: http://stackoverflow.com/a/50486822
tagged with: django-queryset

http://stackoverflow.com/a/58198755
answers question: http://stackoverflow.com/q/50396282
type: Answer
score: 0
has body: There's also a user has_perm check going on which will return False, because permissions aren't handled the normal way. You can MonkeyType around it, in my case there's a check if the user is staff and is active, but you can offcourse always return True def override_user_has_perm(self, *args): return self.is_staff and self.is_active User.add_to_class('has_perm', override_user_has_perm)

http://stackoverflow.com/comment/87811201
has text: Since this question was closed, I can't suggest this as the official answer, but if you *need* your container to be a dictionary with arbitrary order, you "can" subclass Dict and then implement logic that would **dict**ate the algorithm by which you wish to represent the keys/values when interacting with the Dict. I'd probably just make a decorator and decorate functions that delegate to super(); unfortunately, the comment section is a little too small for a proper example.
score: 0
comment on: http://stackoverflow.com/q/50386332
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88207068
score: 0
type: Comment
type: QuestionComment
has text: Then you don't have to slice
comment on: http://stackoverflow.com/q/50500181

http://stackoverflow.com/comment/88077846
type: Comment
has text: Thanks for reply! The virtual environments, py27 and py36 are in my home folder which is /Users/myname/ The VScode folder is in my home folder.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50518765

http://stackoverflow.com/q/50503904
favorite count: 0
type: Question
has title: cntk import Error /usr/local/lib/python2.7/dist-packages/cntk/libs/libCntk.Math-2.5.1.so: undefined symbol: LAPACKE_dgesvd
type: UnansweredQuestion
tagged with: python
has body: While importing cntk in python the following error is coming: File "&lt;string&gt;", line 1, in &lt;module&gt; File "/home/ubuntu/src/cntk/bindings/python/cntk/__init__.py", line 10, in &lt;module&gt; from . import cntk_py File "/home/ubuntu/src/cntk/bindings/python/cntk/cntk_py.py", line 21, in &lt;module&gt; _cntk_py = swig_import_helper() File "/home/ubuntu/src/cntk/bindings/python/cntk/cntk_py.py", line 20, in swig_import_helper return importlib.import_module('_cntk_py') File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: /usr/local/lib/python2.7/dist-packages/cntk/libs/libCntk.Math-2.5.1.so: undefined symbol: LAPACKE_dgesvd Installation procedure: sudo apt-get install openmpi-bin sudo pip3 install cntk-gpu
has comment: http://stackoverflow.com/comment/88023347
answer count: 0
tagged with: cntk
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87952084
comment on: http://stackoverflow.com/a/50455673
type: Comment
score: 0
type: AnswerComment
has text: i put my solve as an edit above. your code though pretty much loses readability...

http://stackoverflow.com/a/50486409
has comment: http://stackoverflow.com/comment/87985690
type: Answer
answers question: http://stackoverflow.com/q/50485438
upvote count: 3
has body: It may be tempting to use str.extract but it only matches the first match as per the docs. On the other hand, str.extractall outputs a bit too complex dataframe to work with. We will resort to df.apply. import re regex = re.compile(r'(class\d+)-(\d+)') def func(x): data = regex.findall(x[0]) for class_name, value in data: df.loc[x.name, class_name] = value df.apply(func, axis=1) print(df) # overall class1 class2 class3 # 0 class1-10/class2-11/class3-13 10 11 13 # 1 class3-31/class2-22/class1-23 23 22 31 # 2 abc/def/xyz/prq NaN NaN NaN
score: 3
has comment: http://stackoverflow.com/comment/87985659
downvote count: 0

http://stackoverflow.com/a/50495604
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/88004439
has comment: http://stackoverflow.com/comment/88008811
has body: Check the input format and convert to numerator/denominator as needed before performing the necessary math operation to convert it from a fraction to a decimal value. chance = "3/4" # verify that format is valid, then proceed to conversion tokens = chance.split("/") numer = int(tokens[0]) denom = int(tokens[1]) value = numer / denom print(value) If you're using an older version of python (eg 2.x) you will need to convert one of the parts to a float because python discards floating point during int/int division.
downvote count: 2
upvote count: 1
answers question: http://stackoverflow.com/q/50495408
has comment: http://stackoverflow.com/comment/88042849
has comment: http://stackoverflow.com/comment/88008780

http://stackoverflow.com/comment/88089559
type: Comment
comment on: http://stackoverflow.com/q/50528833
type: QuestionComment
has text: The second table is a groupby them aggregate (you summed `quantity`).
score: 0

http://stackoverflow.com/a/50536004
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50535941
score: 2
answers question: http://stackoverflow.com/q/50535941
type: Answer
has body: With os.system, you're composing your argument string yourself. It works, but it's ugly, liable to code injection, and not robust to some arguments with spaces if you forget to quote them. So subprocess is the right choice. Now, there are requirements to use subprocess with an argument list. Here your argument splitting is wrong. You're including 2 arguments as one (space separated) for example here: '-xc {:.4e}'.format(loc[0]), this "argument" is issued to the system like "-xc .4555" (yes, with quotes), and that confuses the argument parsing. fix: separate the arguments properly: result = subprocess.check_output(['./get_cpus', '-inp','./output_00076', '-xc','{:.4e}'.format(loc[0]), '-yc','{:.4e}'.format(loc[1]), '-zc','{:.4e}'.format(loc[2]), '-rad','{:.4e}'.format(rad)], stdin = subprocess.PIPE) you don't need shell=True either. It's almost never useful except for quick hacks. Often doesn't solve anything, and is a security liability (code injection)
has comment: http://stackoverflow.com/comment/88084201
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88084157

http://stackoverflow.com/a/50540994
has comment: http://stackoverflow.com/comment/88093258
upvote count: 2
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/50540876
type: Answer
has body: Make use of default parameters. def func(config, a = None, b = None, c = None): pass func(config, b="B") Use dictionary params = {"config": myConfig, "b": valB} # you want b here def func(**params): config = params["config"] a = params.get("a") b = params.get("b") c = params.get("c") func(params) Edit: If you want config should always be the last, use it as def func(a=None, b=None, c=None, config=None): pass func(b=valB, config=myConfig)
has comment: http://stackoverflow.com/comment/88093283

http://stackoverflow.com/a/50450638
type: Answer
has comment: http://stackoverflow.com/comment/87919243
accepted answer of: http://stackoverflow.com/q/50448837
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50448837
downvote count: 0
has body: Your calculations of tstep and fstep produce float numbers, but scipy expects integers. You could for instance change your code to arr_f, arr_t, fft = signal.spectrogram(data, Fs, nperseg=window_length.astype(int), noverlap=noverlap.astype(int), nfft=nfft.astype(int), window='hanning') and scipy should work without problems. The .astype(int) just tweaks the numpy datatype, so instead of the float number 2000.0 scipy receives the integer number 2000. You can find more information about numpy data types in the official documentation. A better way is of course to change your calculations, so that they produce integers numbers right away.
score: 1
upvote count: 1

exec
tags question: http://stackoverflow.com/q/50516591
type: Tag
tag name: exec

http://stackoverflow.com/comment/87876107
comment on: http://stackoverflow.com/q/50430795
has text: As a rule of thumb, the earlier you know that there is something wrong with your command line, the better. Knowing that a critical command line argument is missing will let you avoid doing unnecessary, potentially costly computations whose results will be discarded in the future, anyway.
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88058147
type: QuestionComment
comment on: http://stackoverflow.com/q/50522464
has text: [Scipy docs say](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) that the Levenberg-Marquardt algorithm (lm) doesn't work when the number of observations is less than the number of variables. I don't know astropy, but it is probably the same problem. Does astropy have any other fitting algorithms?
score: 1
type: Comment

http://stackoverflow.com/comment/88089254
score: 0
type: Comment
type: QuestionComment
has text: It means that the particular index triangle has no neighbours.
comment on: http://stackoverflow.com/q/50537967

http://stackoverflow.com/a/50437974
type: Answer
answers question: http://stackoverflow.com/q/50436479
has comment: http://stackoverflow.com/comment/87897927
upvote count: 3
downvote count: 0
has body: You can use pandas together with collections.defaultdict. It is good practice to use a dictionary for a variable number of variables. Solution from collections import defaultdict # initialise defaultdict of lists d = defaultdict(list) # iterate list of dictionaries and append to appropriate value for item in [df1, df2, df3]: d[item['Method'].iloc[0]].append(item) # convert to integer def formatter(df): df.iloc[:, 2:] = df.iloc[:, 2:].apply(pd.to_numeric, downcast='integer') return df # use dictionary comprehension to process results for each Method res = {k: formatter(pd.concat(v).fillna(0)) for k, v in d.items()} print(res['Soil']) ID Method a1 a10 a11 a2 a3 a4 a5 a6 a7 a8 a9 0 1 Soil 2 0 0 3 4 5 0 3 6 4 8 1 2 Soil 6 0 0 9 2 7 0 4 3 4 4 2 3 Soil 5 0 0 2 4 9 0 1 1 2 3 0 1 Soil 5 3 4 0 0 0 4 7 8 2 1 1 2 Soil 4 2 1 0 0 0 6 3 8 7 2 Setup You can replace strings with file1.csv, file2.csv, etc. from io import StringIO df1_str = StringIO("""ID Method a1 a2 a3 a4 a6 a7 a8 a9 01 Soil 2 3 4 5 3 6 4 8 02 Soil 6 9 2 7 4 3 4 4 03 Soil 5 2 4 9 1 1 2 3""") df2_str = StringIO("""ID Method a1 a5 a6 a7 01 Datas 5 4 7 8 02 Datas 4 6 3 8 03 Datas 6 3 2 8""") df2_str = StringIO("""ID Method a1 a5 a6 a7 a8 a9 a10 a11 01 Soil 5 4 7 8 2 1 3 4 02 Soil 4 6 3 8 7 2 2 1""") df3_str = StringIO("""ID Method a1 a5 a6 a7 a8 a9 01 Datas 5 4 7 8 2 1 02 Datas 4 6 3 8 7 2 03 Datas 6 3 2 8 9 9 03 Datas 5 3 2 2 7 7""") df1 = pd.read_csv(df1_str, delim_whitespace=True) df2 = pd.read_csv(df2_str, delim_whitespace=True) df3 = pd.read_csv(df3_str, delim_whitespace=True)
score: 3

http://stackoverflow.com/comment/87920060
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50453048
has text: This could help [to save tables as temporary in memory](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.registerTempTable) and this [to unpersist](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.unpersist) dataframes. A new dataframe is created when you make a change inside `for` block. So, maybe, save it, unpersist and read help
score: 3

http://stackoverflow.com/comment/87896559
score: 0
type: Comment
has text: iloc[:,1:] will not get the first columns , since that is irrelevant @Liquidity
type: AnswerComment
comment on: http://stackoverflow.com/a/50441015

http://stackoverflow.com/comment/88137456
type: QuestionComment
score: 0
has text: Basically you want to debug it remotely? You are ok to debug it in a telnet session or so?
type: Comment
comment on: http://stackoverflow.com/q/50509148

http://stackoverflow.com/q/50408941
possible better answer: http://stackoverflow.com/a/52518512
linked to: http://stackoverflow.com/q/46288847
has answer: http://stackoverflow.com/a/52124900
tagged with: python
score: 44
tagged with: python-3.6
has answer: http://stackoverflow.com/a/50410256
has body: I am interrested in knowing the recommended way to install pip3 for python3.6 (as of today, may 2018) on current version of centos7 (7.5.1804) and the accepted answer of How to install pip in CentOS 7? seems to be outdated because: yum search -v pip outputs (among other things): python2-pip.noarch : A tool for installing and managing Python 2 packages Repo : epel python34-pip.noarch : A tool for installing and managing Python3 packages Repo : epel and python34-pip seems to be a (newer?) simpler way than the accepted answer of How to install pip in CentOS 7? : sudo yum install python34-setuptools sudo easy_install-3.4 pip But since the versions of python installed on my machine are 2.7.5 and 3.6.3 why is it python34-pip and not python36-pip ? Is pip the same for 3.4+ (up to current 3.6.3) ?
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 45
has answer: http://stackoverflow.com/a/54731630
has answer: http://stackoverflow.com/a/52518512
downvote count: 1
tagged with: centos7
linked to: http://stackoverflow.com/q/32618686
has answer: http://stackoverflow.com/a/55732519
tagged with: pip
accepted answer: http://stackoverflow.com/a/50410256
has answer: http://stackoverflow.com/a/52278528
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/60369267
has comment: http://stackoverflow.com/comment/97693886
has title: Recommended way to install pip(3) on centos7
answer count: 8
has answer: http://stackoverflow.com/a/55560339

http://stackoverflow.com/comment/87914929
comment on: http://stackoverflow.com/a/50450826
score: 0
type: Comment
has text: This works, also df.as_matrix() works but accepting this answer as it came first.
type: AnswerComment

http://stackoverflow.com/comment/88038216
score: 0
type: Comment
has text: @MarkTolonen The DLL was indeed compiled by the other person with `extern "C"`, `EXPORTED_FUNCTION` already in the header file. Using `dumpbin /exports aa_Function.dll` I could see the function names, which match the names shown in Dependency Walker. I am making function calls in Python using the same function names in Python - unsuccessfully. Your point about `LOAD_LIBRARY_AS_DATAFILE` not loading the DLL function table is interesting. Couldn't find anything in the documentation about this method of loading. This would make sense as the DLLS are loaded, but functions can't be called.
type: QuestionComment
comment on: http://stackoverflow.com/q/50497472

http://stackoverflow.com/q/50404273
has comment: http://stackoverflow.com/comment/87824087
has answer: http://stackoverflow.com/a/56286367
has comment: http://stackoverflow.com/comment/87824191
has answer: http://stackoverflow.com/a/54088527
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50405197
tagged with: rabbitmq
answer count: 6
has body: Edit: I had the wrong version of the pika package installed on my device. It works fine after I updated from pip. I just started learning the usage of RabbitMQ (using Python) by following their tutorial. The send.py code works works fine but when I try to run receive.py, I see this error: Traceback (most recent call last): File "receive.py", line 15, in &lt;module&gt; no_ack=True) TypeError: basic_consume() got multiple values for keyword argument 'queue' Here's the code inside receive.py: #!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume(callback, queue='hello', no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() Any idea what I am doing wrong?
has comment: http://stackoverflow.com/comment/87824147
has answer: http://stackoverflow.com/a/55414934
has comment: http://stackoverflow.com/comment/87824240
downvote count: 0
has comment: http://stackoverflow.com/comment/87824723
favorite count: 0
upvote count: 17
has comment: http://stackoverflow.com/comment/87823987
score: 17
has comment: http://stackoverflow.com/comment/87824541
has title: Python tutorial code from RabbitMQ failing to run
has comment: http://stackoverflow.com/comment/87824260
type: Question
has comment: http://stackoverflow.com/comment/87825323
has answer: http://stackoverflow.com/a/68530182
has answer: http://stackoverflow.com/a/56325223

http://stackoverflow.com/a/50535901
accepted answer of: http://stackoverflow.com/q/50535879
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50535879
has body: You can use multiple |s: import re print(re.findall('foo bar|foo|bar', 'foo bar bar foo')) Output: ['foo bar', 'bar', 'foo']
score: 2
type: Answer

http://stackoverflow.com/q/50440497
tagged with: artificial-intelligence
type: AnsweredQuestion
score: 0
answer count: 2
has title: Neural Network - Test Trained Network
has answer: http://stackoverflow.com/a/50440776
upvote count: 1
has body: I've programmed (Java) my own feed-forward network learning by back propagation. My network is trained to learn the XOR problem. I have an input matrix 4x2 and target 4x1. Inputs: {{0,0}, {0,1}, {1,0}, {1,1}} Outputs: {0.95048} {-0.06721} {-0.06826} {0.95122} I have this trained network and now I want to test it on new inputs like: {.1,.9} //should result in 1 However, I'm not sure how to implement a float predict(double[] input) method. From what I can see, my problem is that my training data has a different size than my input data. Please suggest. EDIT: The way I have this worded, it sounds like I want a regression value. However, I'd like the output to be a probability vector (classification) which I can then analyze.
tagged with: java
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50440776
has answer: http://stackoverflow.com/a/50440763
possible better answer: http://stackoverflow.com/a/50440763
tagged with: neural-network
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/88061116
comment on: http://stackoverflow.com/a/50524384
score: 0
type: Comment
type: AnswerComment
has text: :-) You're new around here - if I've answered your question then please consider accepting and upvoting my answer.

http://stackoverflow.com/q/50516591
tagged with: local-variables
tagged with: variables
has comment: http://stackoverflow.com/comment/88046565
has body: I have 2 Python scripts: ScriptSmall.py: a=9 ScriptBig.py: a=5 print(a) f=open('ScriptSmall.py') exec(f.read()) f.close print(a) When I run ScriptBig.py in the terminal as python3 ScriptBig.py, the terminal prints out: $python3 ScriptBig.py 5 5 I would like it to print out 5 and then 9. What I am doing wrong?
type: Question
has comment: http://stackoverflow.com/comment/88045718
linked to: http://stackoverflow.com/q/1463306
has comment: http://stackoverflow.com/comment/88046895
has comment: http://stackoverflow.com/comment/88051358
has comment: http://stackoverflow.com/comment/88046513
has comment: http://stackoverflow.com/comment/88046420
has comment: http://stackoverflow.com/comment/88045694
has comment: http://stackoverflow.com/comment/88046466
tagged with: python
duplicate of: http://stackoverflow.com/q/1463306
tagged with: exec
has comment: http://stackoverflow.com/comment/88046499
has title: How to keep the values defined in `exec()` in Python
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/88045733
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50520297
type: Answer
score: 0
has body: So – Regex101 is a fantastic tool for building and debugging regular expressions. In this instance, you probably want to use a capture group to get the text within the square brackets at the start of your string. The best way I can think of would be like this: ^\[(.*)\]. Regex101 explains this better than I can at this link: https://regex101.com/r/LfrbL2/1/ This regular expression basically looks for a [ at the start of the input text, and then captures everything after that [ until it hits a ].
answers question: http://stackoverflow.com/q/50520255

http://stackoverflow.com/comment/87954205
comment on: http://stackoverflow.com/q/50470419
type: QuestionComment
type: Comment
has text: You need to do `import math` in `sinner.py`. Every module is its own namespace. When the main module imports `sinner.py`, it gets access to `sinner.py`'s namespace: not the other way around.
score: 2

http://stackoverflow.com/comment/87860002
comment on: http://stackoverflow.com/q/50422593
has text: So a acts as a pointer to the class, and not a member actual class, right?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87977199
type: Comment
score: 0
type: AnswerComment
has text: Thanks for this suggestion, and after I try it found that this solution is great
comment on: http://stackoverflow.com/a/50476518

http://stackoverflow.com/comment/87907226
has text: It is clear, but how to get it solved definitely? I mean, how to get Harmonized Index Current Price data correctly from Eurostat?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50410397

http://stackoverflow.com/comment/87864868
has text: Sorry, I'm just curious: what module are you using to do this?
score: 1
comment on: http://stackoverflow.com/q/50424902
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87923617
has text: @roganjosh The variable summary in method 1 contains some text that needs to be written to a file. The file writing method is in method 2. So I need to access the variable summary and write it to the file, which I have tried in filehandle.write(x.summary).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50454861

http://stackoverflow.com/comment/87959947
type: QuestionComment
score: 0
has text: @s3n0 question post edited to included the detail you request. Check was ok.
comment on: http://stackoverflow.com/q/50472440
type: Comment

http://stackoverflow.com/q/50420017
downvote count: 0
has title: Python not reading japanese characters
tagged with: character-encoding
has comment: http://stackoverflow.com/comment/87856057
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87856124
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87856067
linked to: http://stackoverflow.com/q/10923086
tagged with: python
has body: I have a script that reads all mp3 files in a folder, gets all the tags and arrange it as json objects. I'm using id3-py-1.2 library to get the tags. It works wonderfully. Except when reading japanese songs, I can't find a way to make it read properly the japanese characters. Here is my code: #!/usr/bin/env python import os import json from ID3 import * extension = '.mp3' result = [] def getFiles(): for path, subdirs, files in os.walk(r'.'): for filename in files: f = os.path.join(path, filename)[2:] f = f.replace('\\', '/') if f[-4:] == extension: result.append(f) return result files = getFiles() def arrangeSong(files): songs = [] for file in files: data = ID3(file) song = {} song['path'] = file song['artist'] = data.get('ARTIST', '') song['title'] = data.get('TITLE', '') song['album'] = data.get('ALBUM', '') song['trackNumber'] = data.get('TRACKNUMBER', '') songs.append(song) return songs print "Content-type: text/html" print print json.dumps(arrangeSong(files), encoding="ISO-8859-1") When it tries to read files with japanese characters on the filename, it gives me this error: IOError: [Errno 22] invalid mode ('rb') or filename: '0.8 Byou to Shougeki - Hakai Pop/02 - ?????.mp3' It stops when the file "0.8 Byou to Shougeki - Hakai Pop\02 - 虹色の言葉.mp3" appears I've tried to change the os.walk to this: for path, subdirs, files in os.walk(ur'.'): for filename in files: f = os.path.join(path, filename)[2:] f = f.replace('\\', '/') if f[-4:] == extension: result.append(f) return result Then it successfully reads the file, but still can't figure the japanese characters properly, giving me this result with question marks instead of the characters: [{"album": "??POP", "path": "0.8 Byou to Shougeki - Hakai Pop/01 - The Killing M oon.mp3", "title": "The Killing Moon", "trackNumber": "", "artist": "0.8?????"}, {"album": "??POP", "path": "0.8 Byou to Shougeki - Hakai Pop/02 - \u8679\u8272\ u306e\u8a00\u8449.mp3", "title": "?????", "trackNumber": "", "artist": "0.8????? "}, {"al…
has comment: http://stackoverflow.com/comment/87855985
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/87856009

http://stackoverflow.com/q/50455504
has comment: http://stackoverflow.com/comment/87953750
has comment: http://stackoverflow.com/comment/87953443
tagged with: inverse
has body: Alright, so I have 3 numpy matrices : m1 = [[ 3 2 2 ... 2 2 3] [ 3 2 2 ... 3 3 2] [500 501 502 ... 625 626 627] ... [623 624 625 ... 748 749 750] [624 625 626 ... 749 750 751] [625 626 627 ... 750 751 752]] m2 = [[ 3 2 500 ... 623 624 625] [ 3 2 500 ... 623 624 625] [ 2 3 500 ... 623 624 625] ... [ 2 2 500 ... 623 624 625] [ 2 2 500 ... 623 624 625] [ 3 2 500 ... 623 624 625]] m3 = [[ 813 827 160500 ... 199983 200304 200625] [ 830 843 164000 ... 204344 204672 205000] [ 181317 185400 36064000 ... 44935744 45007872 45080000] ... [ 221046 225867 43936000 ... 54744256 54832128 54920000] [ 221369 226196 44000000 ... 54824000 54912000 55000000] [ 221692 226525 44064000 ... 54903744 54991872 55080000]] m1, m2 and m3 are very large square matrices (those examples are 128x128, but they can go up to 2048x2048). Also m1*m2=m3. My goal is to obtain m2 by using only m1 and m3. Someone told me this was possible, as m1*m2=m3 implies that (m1**-1) * m3 = m2 (I believe it was that, please correct me if I'm wrong) ; so I calculated the inverse of m1 : m1**-1 = [[ 7.70884284e-01 -8.13188394e-01 -1.65131146e+13 ... -2.49697170e+12 -7.70160676e+12 -4.13395320e+13] [-3.38144598e-01 2.54532610e-01 1.01286404e+13 ... -3.64296085e+11 2.60327813e+12 2.41783491e+13] [ 1.77721050e-01 -3.54566231e-01 -5.00564604e+12 ... 5.82415184e+10 -5.98354744e+11 -1.29817153e+13] ... [-6.56772812e-02 1.54498025e-01 3.21826474e+12 ... 2.61432526e+11 1.14203762e+12 3.61036457e+12] [ 5.82732587e-03 -3.44252762e-02 -4.79430664e+11 ... 5.10855381e+11 -1.07679881e+11 -1.71485373e+12] [ 6.55360708e-02 -8.24446025e-02 -1.19618881e+12 ... 4.45713678e+11 -3.48073716e+11 -4.89344092e+12]] The result looked rather messy so I ran a test and multiplied m1**-1 and m1 to see if it worked : (m1**-1)*m1 = [[-125.296875 , -117.34375 , -117.390625 , ..., -139.15625 , -155.203125 , -147.25 ], [ 483.1640625 , 483.953125 , 482.7421875 , ..., 603.796875 , 590.5859375 , 593.375 ], [-523.22851562, -522.36328125, -523.49804688, ..., …
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87941298
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87954642
has comment: http://stackoverflow.com/comment/87953144
tagged with: matrix
has comment: http://stackoverflow.com/comment/87955716
tagged with: python
has title: Python numpy : Matrix Inverses give unprecise results when multiplied
accepted answer: http://stackoverflow.com/a/50455643
has comment: http://stackoverflow.com/comment/87953527
has comment: http://stackoverflow.com/comment/87953207
tagged with: numpy
has answer: http://stackoverflow.com/a/50455643
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87978853
comment on: http://stackoverflow.com/a/50471214
type: AnswerComment
has text: This solved it! For reference, 1.2GB file went from 14 hours down to 7 minutes. I extracted the groups I wanted as lists by using for example `time = grouped.get_group(visitorId).timestamp.tolist()`
score: 0
type: Comment

pymodbus3
tags question: http://stackoverflow.com/q/50472613
tags question: http://stackoverflow.com/q/50461048
type: Tag
tag name: pymodbus3

http://stackoverflow.com/a/50389135
has comment: http://stackoverflow.com/comment/87798558
answers question: http://stackoverflow.com/q/50388627
has comment: http://stackoverflow.com/comment/87805038
type: Answer
has comment: http://stackoverflow.com/comment/87809328
has comment: http://stackoverflow.com/comment/87797505
downvote count: 0
upvote count: 1
score: 1
has body: For example: df_set = df.apply(lambda x: str(sorted(set(x))), 1) In: df[~df_set.duplicated()] Out: seq_sp1 seq_sp2 cluster 1 seq20 seq56 2 seq3 seq5 3 seq9 seq5 3 seq7 seq4

http://stackoverflow.com/comment/88084283
type: QuestionComment
has text: I've noticed you are quite new on SO. If one of the answers below answered your question, the way this site works works, you'd "accept" the answer, more here: [What should I do when someone answers my questions?](https://stackoverflow.com/help/someone-answers). But only if your question really has been answered.
comment on: http://stackoverflow.com/q/50527661
type: Comment
score: 0

http://stackoverflow.com/a/50585733
answers question: http://stackoverflow.com/q/50491930
has body: You are correctly accessing the variable values through the X attribute. The reason why you get confused by the zero solution is an error in the method constraint1: lhs1 = self.model.getVarByName("y_") lhs1 = 2 rhs1 = self.model.getVarByName("q_") rhs1 = 3 self.model.update() self.model.addConstr(lhs1, GRB.LESS_EQUAL, rhs1) First you assign to lhs1 and rhs1 references to the created variables, but then you overwrite them with numbers. Effectively you are adding the constraint 2 &lt;= 3, which is satisfied independently of y_ and q_. Hence, setting y_ and q_ to zero is an optimal solution.
type: Answer
score: 0

http://stackoverflow.com/q/50476732
has answer: http://stackoverflow.com/a/50498676
tagged with: python
has title: Python - How to receive WMI events asynchronously
type: AnsweredQuestion
answer count: 1
downvote count: 0
tagged with: events
has body: I want to receive WMI events asynchronously and handle them with a SWbemSink object. Microsoft instructs to call IWbemServices.ExecNotificationQueryAsync passing it a SWbemSink instance. When an event occurs it is delivered to the OnObjectReady method of the SWbemSink object so that the client can handle it. Below is an example of how to do this in js. How can we do this in Python? I know how to interact with WMI using win32com.client but how can a Python script be implemented so that it executes in this event-driven fashion? //Connects to default namespace (HKEY_LOCAL_MACHINE\Software\Microsoft\WBEM\Scripting\Default Namespace). var wbemServices = GetObject("WinMgmts:{impersonationLevel=impersonate,(security)}"); //Create an event sink object. var sink = WScript.CreateObject("WbemScripting.SWbemSink", "SINK_"); //Register an event query describing which events the client would like //to receive. wbemServices.ExecNotificationQueryAsync( sink, "Select * From __InstanceOperationEvent within 0.5 Where TargetInstance ISA 'Win32_Process' and TargetInstance.Caption='explorer.exe'"); //Show a msg box to allow user to stop receiving events. var wshShell = WScript.CreateObject("WScript.Shell"); wshShell.Popup("Click OK to stop listening for events..."); sink.Cancel(); //SWbemSink function called every time an event is ready. function SINK_OnObjectReady(wbemObject, asyncContext) { WScript.Echo("Event received: " + wbemObject.GetObjectText_()); }
score: 1
upvote count: 1
tagged with: asynchronous
accepted answer: http://stackoverflow.com/a/50498676
tagged with: wmi
favorite count: 0
type: Question

http://stackoverflow.com/comment/87813108
comment on: http://stackoverflow.com/q/50398344
has text: @tdelaney YOUR A LIFESAVER!!!!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50461620
answer count: 2
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/87937306
has comment: http://stackoverflow.com/comment/87936440
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50461788
score: -2
has answer: http://stackoverflow.com/a/50461788
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/87937354
accepted answer: http://stackoverflow.com/a/50461660
has title: Parse none uniform JSON Python
has body: I have trouble getting "remoteAddress" only when I need it. This output is generated by another API so I can't edit it. Just to be clear I want to split up the data of the 2 processes. Sorry if it's a repost, I couldn't find a similar post. { "family": "INET6", "pid": 835, "localAddress": { "ip": "127.0.0.1", "port": 44082 }, "processName": "avahi-daemon", "state": "NONE", "type": "SOCK_DGRAM" }, { "family": "INET", "pid": 22624, "localAddress": { "ip": "0.0.0.0", "port": 631 }, "remoteAddress": { "ip": "x.x.x.x", "port": 443 }, "processName": "gitkraken", "state": "ESTABLISHED", "type": "SOCK_STREAM" } Edit: It needs to be dynamic so I can't just search for "remoteAddress". I'm parsing GRR flows, diffirent flows have diffirent keys that can be missing.
has answer: http://stackoverflow.com/a/50461660
type: AnsweredQuestion

http://stackoverflow.com/q/50538447
has comment: http://stackoverflow.com/comment/88088833
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88088814
has answer: http://stackoverflow.com/a/50538503
has comment: http://stackoverflow.com/comment/88088978
has comment: http://stackoverflow.com/comment/88088867
accepted answer: http://stackoverflow.com/a/50538503
downvote count: 0
has title: AttributeError: module 'zbar' has no attribute 'ImageScanner'
has comment: http://stackoverflow.com/comment/88088784
has comment: http://stackoverflow.com/comment/88088944
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88088995
has comment: http://stackoverflow.com/comment/88088760
has comment: http://stackoverflow.com/comment/88088834
linked to: http://stackoverflow.com/q/34577710
favorite count: 0
has comment: http://stackoverflow.com/comment/88088894
has comment: http://stackoverflow.com/comment/88088897
has comment: http://stackoverflow.com/comment/88088819
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88088848
has comment: http://stackoverflow.com/comment/88088925
has comment: http://stackoverflow.com/comment/88088950
has comment: http://stackoverflow.com/comment/88088904
has comment: http://stackoverflow.com/comment/88088999
tagged with: zbar
has comment: http://stackoverflow.com/comment/88089016
has comment: http://stackoverflow.com/comment/88088792
tagged with: python
has comment: http://stackoverflow.com/comment/88088879
has body: I try to run this code import pyqrcode from qrtools import qrtools from PIL import Image import zbar qr = pyqrcode.create("She got two litle horns and they get me a litle bit") qr.png("horn.png", scale=6) qr = qrtools.QR() scanner = zbar.Scanner() qr.decode("horn.png") print(qr.data) And it says to me AttributeError: module 'zbar' has no attribute 'ImageScanner' Im running the latest ubuntu x64 and have all dependencies installed mayby is because im trying on python3

http://stackoverflow.com/q/50538118
tagged with: pandas
has comment: http://stackoverflow.com/comment/88088201
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88088191
has answer: http://stackoverflow.com/a/50580684
has answer: http://stackoverflow.com/a/50582231
favorite count: 0
has body: Given the following DataFrame: d = {'A': [1,2,np.nan, -2, -1], 'B':[5,-1,np.nan,2,-1], 'C':[1,2,3,4,-1]} df = pd.DataFrame(d) I need to replace all values less then 0 from column B by np.nan (for instance); I've tried: df = df.apply(lambda x: fillna(value = np.nan) if x &lt; 0) but it gives me the following error: File "&lt;ipython-input-157-2d34a150c603&gt;", line 1 df = df.apply(lambda x: fillna(value = np.nan) if x &lt; 0) SyntaxError: invalid syntax
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88088156
upvote count: 1
tagged with: dataframe
tagged with: kaggle
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88088202
tagged with: fillna
has title: Cannot use fillna when a condition is introduced - SyntaxError: invalid syntax

http://stackoverflow.com/comment/88074514
comment on: http://stackoverflow.com/a/50508722
type: AnswerComment
type: Comment
has text: Thank you for your help. I feel I am close but I am getting an 'random_url' did not receive value(s) for the argument(s): 'format_string' error message. I created the _init__.py file within the templatetags folder and I have 3 basic view.html pages set up and connected via urls.py and views.py as suggested.
score: 0

http://stackoverflow.com/comment/87888520
comment on: http://stackoverflow.com/q/50437194
type: QuestionComment
has text: By saying that you want to get '13 and '46' as well, do you mean that you want it to work for strings like 'ABC 13' or that you want to remove the middle digit?
type: Comment
score: 0

http://stackoverflow.com/comment/87971472
type: Comment
has text: Your question is Too Broad. Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the [How to Ask](https://stackoverflow.com/help/how-to-ask) page for help clarifying this question.
type: QuestionComment
comment on: http://stackoverflow.com/q/50478832
score: 0

http://stackoverflow.com/a/50458223
type: Answer
accepted answer of: http://stackoverflow.com/q/50457394
has body: The logger in util doesn't generate output because Python logging is set to log warnings and higher by default, and info is lower than warning. Configure Python's logging with the level and handlers you want. If logging isn't configured, Flask adds a handler for its own logger and sets the level to debug in debug mode, which is why the app.logger message shows up. Flask's docs show how to configure logging the way it does and other examples. from logging.config import dictConfig dictConfig({ 'version': 1, 'formatters': {'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', }}, 'handlers': {'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' }}, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] } }) app = Flask(__name__) from project import util util.test() If you import util before calling dictConfig, you'll notice that the logging still doesn't work. This is because Python will disable existing loggers when configuring. You can prevent that by adding 'disable_existing_loggers': False to the config, but this comes with the tradeoff that you might see duplicate logs if a logger was already configured. Alternatively, don't get logger at the module level, get it inside the function when it's needed. If you specifically want to use the app's logger elsewhere, you need to import the app. Since this is prone to circular import errors, or even impossible when using an app factory, use current_app instead to access the app during requests. from flask import current_app def test(): current_app.logger.info('info message from util')
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50457394
upvote count: 5
score: 5

http://stackoverflow.com/comment/88013520
comment on: http://stackoverflow.com/q/50500429
type: Comment
type: QuestionComment
score: 0
has text: Can you show us an image? (Input/output) It's hard to do image processing without one. :)

http://stackoverflow.com/comment/88068274
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50528027
has text: `.split()` splits a string into a list

http://stackoverflow.com/comment/87863574
comment on: http://stackoverflow.com/q/50410065
has text: @PM2Ring Yes! this is exactly what I need, thanks! The input is just what I specify a couple of function calls earlier, so it is completely controlled. The variations would include strings or JSON objects.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50493515
score: 0
has comment: http://stackoverflow.com/comment/88001894
answer count: 1
has comment: http://stackoverflow.com/comment/88005829
has answer: http://stackoverflow.com/a/53868013
type: Question
has comment: http://stackoverflow.com/comment/88002329
has comment: http://stackoverflow.com/comment/88002679
has title: Trouble getting video stream from Bebop 2 (python, open cv and ffmpeg)
tagged with: ffmpeg
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88001351
has body: I'm currently working with the Bebop 2 drone from parrot and I would like to get the video stream from the bebop and to use the frame I get. To control the bebop I'm using this library : https://github.com/amymcgovern/pyparrot. First I've tried to use opencv by opening the sdp file used by the bebop to stream the video with this code : capture = cv2.VideoCapture('./bebop.sdp') while True : rt,img = capture.read() cv2.imshow("cam",img) cv2.waitKey(10) here is the content of the sdp file : c=IN IP4 192.168.42.1 m=video 55004 RTP/AVP 96 a=rtpmap:96 H264/90000 but I got this error [rtp @ 0000020b890b3300] Protocol 'rtp' not on whitelist 'file,crypto'! warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:808) warning: ./bebop.sdp (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:809) False OpenCV Error: Assertion failed (size.width&gt;0 &amp;&amp; size.height&gt;0) in cv::imshow, file C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp, line 331 Traceback (most recent call last): File "pilotage.py", line 109, in &lt;module&gt; _main_(args) File "pilotage.py", line 56, in main cv2.imshow('drone view',im) cv2.error: C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:331: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow I've seen that this is due to the ffmpeg command used by opencv that does not include the option -protocol_whitelist So I tried to get the image directly with ffmpeg by using this command "ffmpeg -protocol_whitelist \"file,rtp,udp\" -i ./bebop.sdp -r 30 -b:v 800k image_%03d.png &amp;" But the images I got were awful and useless. Like this one : So I tried different options to improve the quality but I can't get it to work. Thanks for your help. I'm on windows 10 and using latest python version
tagged with: python
tagged with: opencv

http://stackoverflow.com/a/50536584
score: 4
has comment: http://stackoverflow.com/comment/88085306
has body: arr.sort is syntactically valid. It's just not the syntax you wanted. Syntactically, arr.sort is an attribute access expression for the sort attribute of whatever arr evaluates to; semantically, when arr is a list, arr.sort evaluates to a method object for arr's sort method, so it's perfectly fine at runtime too. It's kind of like method references in Java, but since Python is dynamically typed and has method objects, it doesn't need to go through all the functional interface and poly expression stuff Java 8 had to add to support list::sort syntax. Syntax errors are only for outright invalid syntax.
type: Answer
has comment: http://stackoverflow.com/comment/88085339
accepted answer of: http://stackoverflow.com/q/50536527
upvote count: 4
answers question: http://stackoverflow.com/q/50536527
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50441346
has body: When open an editor within Ipython, I usually issue commands In [13]: subprocess.run('vim Person.py', shell=True) Out[13]: CompletedProcess(args='vim Person.py', returncode=0) How to do it in a straight-forwards method?
tagged with: ipython
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50443101
favorite count: 0
type: Question
has title: Invoke the editor in the interactive mode
accepted answer: http://stackoverflow.com/a/50443101
tagged with: python

http://stackoverflow.com/q/50389974
accepted answer: http://stackoverflow.com/a/50390036
tagged with: python
has answer: http://stackoverflow.com/a/50390036
type: AnsweredQuestion
tagged with: frozenset
upvote count: 3
tagged with: set
answer count: 1
downvote count: 0
has body: Suppose I generate a frozenset with A = frozenset(frozenset([element]) for element in [1,2,3]) And I have the empty set E = frozenset(frozenset()) Now I want to have the union of both sets: U = A | E This gives me frozenset({frozenset({2}), frozenset({3}), frozenset({1})}) this assumes, that a frozenset, containing an empty frozenset is itself empty. However, I'd like to have frozenset({frozenset({}), frozenset({2}), frozenset({3}), frozenset({1})}) So, I'd like to add the empty set explicitly to the set. This is, for example, necessary in my opinion when constructing a power set? So: Is a family of sets that only contains the empty set itself empty? Is there a way, in Python, to explicitly include an empty set into a family of sets using the variable types set and frozenset?
favorite count: 0
type: Question
score: 3
has title: Add the empty set to a family of sets in a frozenset in python

http://stackoverflow.com/comment/87811376
comment on: http://stackoverflow.com/a/50397733
score: 0
type: Comment
has text: @TimJohns I interpret `rows` as that mask. But added in case others interpret it differently.
type: AnswerComment

graph-tool
tag name: graph-tool
type: Tag
tags question: http://stackoverflow.com/q/50478853

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/50497472
tags question: http://stackoverflow.com/q/50539213
tags question: http://stackoverflow.com/q/50531699

http://stackoverflow.com/a/50411668
score: 0
has body: One way is convert this problematic values to NaTs: df.datetime = pd.to_dtaetime(df.datetime, errors='coerce')
answers question: http://stackoverflow.com/q/50411641
has comment: http://stackoverflow.com/comment/87935158
has comment: http://stackoverflow.com/comment/87838967
has comment: http://stackoverflow.com/comment/87937374
has comment: http://stackoverflow.com/comment/87841750
type: Answer
has comment: http://stackoverflow.com/comment/87839308
has comment: http://stackoverflow.com/comment/88133746
has comment: http://stackoverflow.com/comment/87937323
has comment: http://stackoverflow.com/comment/87937502

http://stackoverflow.com/comment/87910479
has text: You are not redefining `doc` inside the `while` loop so presumably it's all going to be written to the same document object. I assume you need something like `doc = Document()` just after `os.chdir("C:\\Users\\user\\Desktop\\" +FolderName)` and pass it a new file name
comment on: http://stackoverflow.com/q/50448598
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/87893282
type: Comment
comment on: http://stackoverflow.com/q/50439540
type: QuestionComment
has text: To look up many values quickly, use a set or dict instead of a list. When that isn't appropriate (e.g., the keys can't be hashed), use a sorted list and `bisect`. Or, if you need to modify the list between searches, use a logarithmic data structure like a red-black tree, b-tree, skiplist, etc. (there are many options on PyPI).
score: 0

http://stackoverflow.com/comment/87845813
comment on: http://stackoverflow.com/a/50396467
has text: @IsharaMadhawa is the recommended edit in the code actually working?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88033810
has text: Thank you - after posting this question I figured out the answer. How can I execute a hiveql script in python. example - I have a .hql script load_emp_table.hql which contains a series of queries:
type: Comment
comment on: http://stackoverflow.com/a/50509781
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88045407
type: QuestionComment
comment on: http://stackoverflow.com/q/50515177
score: 0
has text: I demonstrate how to encode a basic `loop` function using python in [this answer](https://stackoverflow.com/a/46268042/633183) – and `unfold` in [this answer](https://stackoverflow.com/a/49398922/633183)
type: Comment

http://stackoverflow.com/a/60689649
answers question: http://stackoverflow.com/q/50395044
has body: I believe the answer to your main question lies in the difference between Anaconda vs Miniconda. Anaconda includes a long list of packages that get installed automatically into each environment that you create. Miniconda creates barebone conda virtual environments (which don't contain many packages at all). Switching to Miniconda should substantially reduce the size/number of packages in your environments. Anaconda is about 2GB, while Miniconda is closer to 100MB. Conda also uses hardlinks for packages installed vs conda install. A good description of hardlinks can be found here. They basically link dependencies across multiple environments like you've described above. Packages installed via pip are not hardlinked, so they cannot take advantage of the space savings that conda packages offer.
downvote count: 0
has comment: http://stackoverflow.com/comment/135469864
upvote count: 10
has comment: http://stackoverflow.com/comment/139264988
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/134535515

http://stackoverflow.com/q/50421340
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87857992
type: Question
has comment: http://stackoverflow.com/comment/87858017
has body: If I don't use the function 'threshold (iar3)' the code works perfectly, but in the moment I add the function, the code presents an error, but the code is OK (I guess). The code is: from PIL import Image from matplotlib import pyplot as plt import numpy as np import time np.seterr(over='ignore') def threshold(imageArray): balanceAr = [] newAr = imageArray for eachRow in imageArray: for eachPix in eachRow: avgNum = reduce(lambda x, y: x + y, eachPix[:3]) / len(eachPix[:3]) balanceAr.append(avgNum) balance = reduce(lambda x, y: x + y, balanceAr) / len(balanceAr) for eachRow in newAr: for eachPix in eachRow: if reduce(lambda x, y: x + y, eachPix[:3]) / len(eachPix[:3]) &gt; balance: eachPix[0] = 255 eachPix[1] = 255 eachPix[2] = 255 eachPix[3] = 255 else: eachPix[0] = 0 eachPix[1] = 0 eachPix[2] = 0 eachPix[3] = 255 return newAr i=Image.open(open('images/User.1.10.jpg','rb')) iar=np.array(i) i2=Image.open(open('images/User.1.9.jpg','rb')) iar2=np.array(i2) i3=Image.open(open('images/User.1.11.jpg','rb')) iar3=np.array(i3) i4=Image.open(open('images/User.1.12.jpg','rb')) iar4=np.array(i4) threshold(iar3) fig=plt.figure() ax1=plt.subplot2grid((8,6),(0,0),rowspan=4,colspan=3) ax2=plt.subplot2grid((8,6),(4,0),rowspan=4,colspan=3) ax3=plt.subplot2grid((8,6),(0,3),rowspan=4,colspan=3) ax4=plt.subplot2grid((8,6),(4,3),rowspan=4,colspan=3) ax1.imshow(iar) ax2.imshow(iar2) ax3.imshow(iar3) ax4.imshow(iar4) plt.show() And I have the problem: Traceback (most recent call last): File "C:\Users\Lucas Diehl\Desktop\matplotlibgg.py", line 44, in &lt;module&gt; threshold(iar3) File "C:\Users\Lucas Diehl\Desktop\matplotlibgg.py", line 29, in threshold eachPix[3] = 255 IndexError: index 3 is out of bounds for axis 0 with size 3 Traceback (most recent call last): File "C:\Users\Lucas Diehl\Desktop\matplotlibgg.py", line 44, in &lt;module&gt; threshold(iar3) File "C:\Users\Lucas Diehl\Desktop\matplotlibgg.py", line 29, in threshold eachPix[3] = 255 IndexError: index 3 is out of bounds for …
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87857922
tagged with: python
type: UnansweredQuestion
has title: New-> IndexError: index 3 is out of bounds for axis 0 with size 3
tagged with: image
tagged with: numpy
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87862396

http://stackoverflow.com/a/50510423
accepted answer of: http://stackoverflow.com/q/50505347
type: Answer
answers question: http://stackoverflow.com/q/50505347
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: It looks like you have forgotten to include the namespace. The URL tag should be something like: {% url 'users:user-list' pk=gym.id status='deactivated' %}

http://stackoverflow.com/a/50458381
accepted answer of: http://stackoverflow.com/q/50458339
score: 1
has comment: http://stackoverflow.com/comment/87930231
answers question: http://stackoverflow.com/q/50458339
type: Answer
has body: You can try this : sample_data = [ { "hostname": "a.example.com", "Id": "1" }, { "hostname": "b.example.com", "Id": "2" }, { "hostname": "c.example.com", "Id": "1" }, { "hostname": "d.example.com", "Id": "1" } ] for item in sample_data: if item['hostname'] == "c.example.com": item['Id'] = 10 print(sample_data) Explanation: Using for-loop iterate over the elements and using if search for c.example.com. If it matches using = operator assign a new value to Id Output: [{'hostname': 'a.example.com', 'Id': '1'}, {'hostname': 'b.example.com', 'Id': '2'}, {'hostname': 'c.example.com', 'Id': 10}, {'hostname': 'd.example.com', 'Id': '1'}]
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50526552
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
score: 1
has title: Pandas get integer keys after groupby
has answer: http://stackoverflow.com/a/50526748
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50526830
has answer: http://stackoverflow.com/a/50526830
possible better answer: http://stackoverflow.com/a/50526748
has body: I have a groupby with multiple columns and the keys contain all columns which makes the output hard to read... Here's an example import pandas as pd import numpy as np from pandas import Series df = pd.DataFrame({'A': [1, 1, 2, 2], 'B': [1, 2, 2, 2], 'C': np.random.randn(4), 'D': ['one', 'two', 'three', 'four']}) def aggregate(x): return Series(dict(C=round(x['C'].mean()), D=' '.join(x['D']))) print(df.groupby(['A', 'B']).apply(aggregate)) C D A B 1 1 0.0 one 2 -1.0 two 2 2 -0.0 three four How can I get 'normal' keys? Like C D 0 0.0 one 1 -1.0 two 2 -0.0 three four

http://stackoverflow.com/comment/87897470
comment on: http://stackoverflow.com/q/50441612
type: Comment
has text: Much, much easier to write a new file and then rename it to the original name.
type: QuestionComment
score: 0

http://stackoverflow.com/a/54140019
upvote count: 1
has body: I agree with @MrE, as he says: I think it makes sense: 5 is not a datetime object, so pandas is parsing the data and find that you have both a number and a datetime object, and it parses both as 'object' string, because the dtype needs to be consistent across all data in the Series. The string representation of a datetime is the date string, not timestamp. When you then add to it, you can modify the dtype of a cell I really agree, it has to find a dtype and found int, if you drop the 'a' index, it will work (this is basically checking if the above is true or not): g = pd.Series(dict(b =datetime(2018, 1,1))) g['datetime'] = pd.Timestamp('2018-01-02') print(g) Output: b 2018-01-01 datetime 2018-01-02 dtype: datetime64[ns] So it is true. To solve the issue: Simply add an extra line at the end: g['datetime']=pd.to_datetime(g['datetime']) And now: print(g) Is: a 5 b 2018-01-01 00:00:00 datetime 2018-01-02 00:00:00 dtype: object
answers question: http://stackoverflow.com/q/50431592
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/87927416
comment on: http://stackoverflow.com/a/50456906
has text: Even after "Successfully installed beautifulsoup4-4.6.0 google-2.0.1" in terminal
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88060218
type: QuestionComment
score: 2
has text: you have used time.time in image ( not used `()`), that's why it is giving error there, but here this code is working fine
type: Comment
comment on: http://stackoverflow.com/q/50524141

http://stackoverflow.com/q/50458339
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
possible better answer: http://stackoverflow.com/a/50458377
favorite count: 0
has answer: http://stackoverflow.com/a/50458388
type: Question
has title: Update a value when matched in array
tagged with: for-loop
has body: I'd like to change a value when the hostname is c.example.com Sample data: [ { "hostname": "a.example.com", "Id": "1" }, { "hostname": "b.example.com", "Id": "2" }, { "hostname": "c.example.com", "Id": "1" }, { "hostname": "d.example.com", "Id": "1" } ] I can match the item data=[{"hostname":"a.example.com","Id":"1"},{"hostname":"b.example.com","Id":"2"},{"hostname":"c.example.com","Id":"1"},{"hostname":"d.example.com","Id":"1"}] for item in data: if item['hostname'] == 'c.example.com': # how to update its id to 10 and write it back to data How to update its id to 10 and write it back to data?
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50458377
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50458381
score: 0
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50458381

http://stackoverflow.com/comment/88046294
type: QuestionComment
comment on: http://stackoverflow.com/q/50516864
has text: Have you seen [this](https://stackoverflow.com/a/47116576/2286337)?
score: 2
type: Comment

http://stackoverflow.com/q/50474233
score: 0
answer count: 1
type: Question
tagged with: serial-port
tagged with: python
has comment: http://stackoverflow.com/comment/87986367
has answer: http://stackoverflow.com/a/50515245
type: UnansweredQuestion
has body: I am using a raspberry pi to send data through TCP/IP where the raspberry pi is the server and my local windows machine is the client. When I try to read data in python 3, I am getting weird characters for example: send 20 decimal I receive @4 send 21 decimal I receive @5 send 22 decimal I receive @6 Below is the code running on my local machine: import socket host = '192.168.1.100' port = 25000 mySocket = socket.socket() mySocket.connect((host,port)) data = mySocket.recv(4).decode() print (data) Using python 2 is no problem and characters received with no decoding needed. I know I need to do some decoding on the data but not sure what. Any advise will be very helpful.
has title: python3 serial read v/s python 2
tagged with: tcp

http://stackoverflow.com/a/50425533
score: 3
upvote count: 3
has body: You can specify a destination cell, and then pass those values to the Left and Top properties of the OLEObject like this: import win32com.client as win32 xl = win32.gencache.EnsureDispatch('Excel.Application') wb = xl.Workbooks.Open('file_name') ws = wb.Worksheets("sheet_name") dest_cell = ws.Range("C2") #change to your wanted location obj = ws.OLEObjects() obj.Add(ClassType=None, Filename='file_path', Link=False, DisplayAsIcon=True, Left=dest_cell.Left, Top=dest_cell.Top, Width=50, Height=50) wb.Save() xl.Application.Quit()
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50409440
type: Answer
accepted answer of: http://stackoverflow.com/q/50409440

http://stackoverflow.com/q/50409414
duplicate of: http://stackoverflow.com/q/8009882
tagged with: python
score: -2
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/50409595
upvote count: 0
has answer: http://stackoverflow.com/a/50409548
downvote count: 2
has comment: http://stackoverflow.com/comment/87834205
linked to: http://stackoverflow.com/q/8009882
has body: Hello so i am trying to read lines from a txt file. My code is the following: import sys accFiletypes = '.txt' f = None filnavn = None correctFiletype = False while (correctFiletype == False): filnavn = input("Filename (Type exit to leave):") if (filnavn.endswith(accFiletypes) == True): try: f = open(filnavn, 'r') correctFiletype = True print("File successfully opened!") except IOError: print("File is not existing") elif (filnavn == "exit"): sys.exit("Program closed") else: print("Accepted filetypes: " + accFiletypes) line = f.readline print(line()) print(line(2)) print(line(3)) print(line(4)) print(line(5)) print(line(6)) f.close() This prints the following: Filename (Type exit to leave):test.txt File successfully opened! 0000 00000000 00 00 0000 1 0000 0 The first 10 lines in "test.txt" 0000 00000000 0000 00001 0000 00001111 0000 000099 0000 00009999 0000 0000w 0000 5927499 0000 634252 0000 6911703 0000 701068 I want it to print out the lines in the txt file but i prints something completely different. What do i do?
has answer: http://stackoverflow.com/a/50409595
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python 3 readline not working
has comment: http://stackoverflow.com/comment/87834150
possible better answer: http://stackoverflow.com/a/50409548

http://stackoverflow.com/comment/87900399
comment on: http://stackoverflow.com/q/50436798
type: Comment
type: QuestionComment
has text: ok, so I will get the geckodriver, same directory as my script? If I am just testing from terminal, what would that be ?
score: 0

http://stackoverflow.com/q/50515651
accepted answer: http://stackoverflow.com/a/50515847
answer count: 1
downvote count: 0
score: 6
has body: Consider the following Python program: code = """ def test(): 1/0 """ filename = "&lt;test&gt;" c = compile(code, filename, 'exec') exec(c) import linecache linecache.cache[filename] = (len(code), None, code.splitlines(keepends=True), filename) import traceback print("Traceback from the traceback module:") print() try: test() except: traceback.print_exc() print() print("Regular traceback:") print() test() I am dynamically defining a function that raises an exception and adding it to the linecache. The output of the code is Traceback from the traceback module: Traceback (most recent call last): File "test.py", line 20, in &lt;module&gt; test() File "&lt;test&gt;", line 3, in test 1/0 ZeroDivisionError: division by zero Regular traceback: Traceback (most recent call last): File "test.py", line 28, in &lt;module&gt; test() File "&lt;test&gt;", line 3, in test ZeroDivisionError: division by zero If I then get a traceback from that function using the traceback module, the line of code from the function is shown (the 1/0 part of the first traceback). But if I just let the code raise an exception and get the regular traceback from the interpreter, it doesn't show the code. Why doesn't the regular interpreter traceback use the linecache? Is there a way to make the code appear in regular tracebacks?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50515847
upvote count: 6
tagged with: python
has title: Why does the Python linecache affect the traceback module but not regular tracebacks?
tagged with: traceback
type: AnsweredQuestion

http://stackoverflow.com/comment/87799337
score: 0
has text: @Benjamin - Glad can help!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50388962

http://stackoverflow.com/a/50488227
type: AcceptedAnswer
downvote count: 1
has body: I've solved it in a really simple way, assuming that views are made with class based views or viewsets: The serializer_class propriety it's actually the serializer, it's a class, so you can access to the depth value with serializer_class.Meta.depth, and assign it a value from the self.request.GET array Example serializer: class ItemSerializer(ModelSerializer): class Meta: model = Item fields = '__all__' Example view: class ItemList(generics.ListCreateAPIView): queryset = Item.objects.all() serializer_class = serializers.ItemSerializer def get_serializer_class(self): if(self.request.GET.get('depth')): if (10 &gt;= int(self.request.GET.get('depth')) &gt;= 0): self.serializer_class.Meta.depth = int( self.request.GET.get('depth')) return self.serializer_class
accepted answer of: http://stackoverflow.com/q/50487145
has comment: http://stackoverflow.com/comment/87993083
type: Answer
score: -1
answers question: http://stackoverflow.com/q/50487145
upvote count: 0

http://stackoverflow.com/q/50517818
downvote count: 0
has title: Pandas: return index values for first instance and last instance of value
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have the following DataFrame: df = pd.DataFrame({'index':[0,1,2,3,4,5,6,7,8,9,10], 'X':[0,0,1,1,0,0,1,1,1,0,0]}) df.set_index('index', inplace = True) X index 0 0 1 0 2 1 3 1 4 0 5 0 6 1 7 1 8 1 9 0 10 0 What I need is to return a list of tuples showing the index value for the first and last instances of the 1s for each sequence of 1s (sorry if that's confusing). i.e. Want: [(2,3), (6,8)] The first instance of the first 1 occurs at index point 2, then the last 1 in that sequence occurs at index point 3. The next 1 occurs at index point 6, and the last 1 in that sequence occurs at index point 8. What I've tried: I can grab the first one using numpy's argmax function. i.e. x1 = np.argmax(df.values) y1 = np.argmin(df.values[x1:]) (x1,2 + y1 - 1) Which will give me the first tuple, but iterating through seems messy and I feel like there's a better way.
has answer: http://stackoverflow.com/a/50517962
linked to: http://stackoverflow.com/q/24885092
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50517962
has answer: http://stackoverflow.com/a/50518010
possible better answer: http://stackoverflow.com/a/50518010
has answer: http://stackoverflow.com/a/50519475
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/88087943
comment on: http://stackoverflow.com/q/50537595
type: Comment
type: QuestionComment
has text: Thank you for the comment, I just gave an example.
score: 0

http://stackoverflow.com/comment/87908592
type: QuestionComment
score: 0
has text: we are not allowed to load the file to memory sadly, i know the running time will be long. that's what they asked us to do =\. thanks for that post. il'l read it now since its long. so i guess i need to work with seek and not as i did above...
type: Comment
comment on: http://stackoverflow.com/q/50446908

http://stackoverflow.com/comment/88046496
has text: I tried that and it didn't work. I'll play around with it a bit more and move on soon if I can't get it working. There is a lot left to get through in that book!
comment on: http://stackoverflow.com/q/50478758
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87999819
has text: Then work through the “getting started” tutorial for Flask. To explain it, I’d have to essentially rewrite that tutorial, and I wouldn’t do nearly as good a job.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50493309
type: Comment

http://stackoverflow.com/q/50524050
possible better answer: http://stackoverflow.com/a/50530536
downvote count: 0
accepted answer: http://stackoverflow.com/a/50524121
favorite count: 0
has body: I have a dask dataframe with an index on one of the columns. The issue is if I do a df.head() it always treturns an empty df, whereas df.tail always returns the correct df. I checked df.head always checks for the first n entries in the first partition. So if i do df.reset_index(), it should work but thats not the case Below is the code to reproduce this: import dask.dataframe as dd import pandas as pd data = pd.DataFrame({ 'i64': np.arange(1000, dtype=np.int64), 'Ii32': np.arange(1000, dtype=np.int32), 'bhello': np.random.choice(['hello', 'Yo', 'people'], size=1000).astype("O") }) daskDf = dd.from_pandas(data, chunksize=3) daskDf = daskDf.set_index('bhello') print(daskDf.head())
score: 9
type: Question
has answer: http://stackoverflow.com/a/50524121
tagged with: dask
upvote count: 9
has comment: http://stackoverflow.com/comment/88060364
has answer: http://stackoverflow.com/a/50530536
tagged with: python
has title: dask dataframe head() returns empty df
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88060220
answer count: 2

http://stackoverflow.com/comment/87973302
has text: In my example, I have the indexes on the x axis.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50479526
type: Comment

http://stackoverflow.com/comment/87987636
type: Comment
comment on: http://stackoverflow.com/q/50487431
type: QuestionComment
has text: Floating point numbers does not guarantee to be precise.
score: 0

http://stackoverflow.com/q/50448447
type: AnsweredQuestion
answer count: 2
has title: Extract content between two tags at same sibling level
has answer: http://stackoverflow.com/a/50448545
score: 0
has body: I'm trying to collect the content between two tags at the same level, in this case the content between the two h2 tags below: Learning Outcomes On successful completion of this unit, you will beable to: Plan for and be active in your own learning... Reflect on your knowledge of yourself.... Articulate your informed understanding of the foundations... Demonstrate information literacy skills Communicate in writing for an academic audience Prior knowledge Ideally, I would like the output as below (i.e., ideally the text in the would be ignored, but I'm ok with it sticking around): Plan for and be active in your own learning... Reflect on your knowledge of teaching and yourself... Articulate your informed understanding of the foundations... Demonstrate information literacy skills Communicate in writing for an academic audience This is what I have so far; soup = BeautifulSoup(text) output = "" unitLO = soup.find(id="learning-outcomes") tagBreak = unitLO.name if unitLO: # we will loop until we hit the next tag with the same name as the # matched tag. eg if unitLO matches an H3, then all content up till the # next H3 is captured. for tag in unitLO.next_siblings: if tag.name == tagBreak: break else: output += str(tag) print(output) Which gives the following output, which is a string; >>> type(output) <class 'str'> >>> On successful completion of this unit, you will beable to: Plan for and be active in your own learning... Reflect on your knowledge of yourself.... Articulate your informed understanding of the foundations... Demonstrate information literacy skills Communicate in writing for an academic audience Which is somewhat different from what I want... The only solution I've come up with is to push output through another round of BeautifulSoup parsing: >>> moresoup = BeautifulSoup(output) >>> for str in moresoup.strings: ... print(str) ... On successful completion of this unit, you will beableto: Plan for and be active in your own learning... Reflect on your knowledge o…
tagged with: beautifulsoup
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/50448528
accepted answer: http://stackoverflow.com/a/50448545
has answer: http://stackoverflow.com/a/50448528

http://stackoverflow.com/a/50402791
type: Answer
answers question: http://stackoverflow.com/q/50402446
accepted answer of: http://stackoverflow.com/q/50402446
score: 3
has body: You can explicitly define type field inside serializer, and use source argument to map it to msg_type field: class TruRouteRequestSerializer(serializers.ModelSerializer): type = serializers.CharField(source='msg_type') class Meta: model = TruRouteRequest fields = ['type', ...]
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87835027
has comment: http://stackoverflow.com/comment/87834955

http://stackoverflow.com/q/50499475
has body: Only compare 3 columns, homePhone, workPhone,CellPhone, how to select the first non null column value, in 'I want' column, use Python Pandas name homePhone workPhone CellPhone I want 1 Tom 888 666 null 888 2 John null 777 null 777 3 Lily null null 333 333
has answer: http://stackoverflow.com/a/50499600
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: dataframe
tagged with: python
has title: Compare and select the first non-null column value Python Dataframe
upvote count: 0
downvote count: 2
tagged with: pandas
answer count: 1

ubuntu
tags question: http://stackoverflow.com/q/50518622
tags question: http://stackoverflow.com/q/50442675
tags question: http://stackoverflow.com/q/50481691
tag name: ubuntu
tags question: http://stackoverflow.com/q/50504502
tags question: http://stackoverflow.com/q/50409623
tags question: http://stackoverflow.com/q/50398145
tags question: http://stackoverflow.com/q/50480639
tags question: http://stackoverflow.com/q/50404731
tags question: http://stackoverflow.com/q/50515960
tags question: http://stackoverflow.com/q/50493132
type: Tag
tags question: http://stackoverflow.com/q/50537296

http://stackoverflow.com/a/50575370
score: 2
downvote count: 0
type: AcceptedAnswer
has body: With help from the comment below the question, here's how I got my custom form field to get the default help text back from the model: class EventForm(forms.ModelForm): category = CategoryModelChoiceField( queryset=Category.objects.all(), help_text=Event._meta.get_field('category').help_text, )
answers question: http://stackoverflow.com/q/50496895
type: Answer
accepted answer of: http://stackoverflow.com/q/50496895
upvote count: 2

http://stackoverflow.com/comment/88051205
type: AnswerComment
has text: @Anthony If it helps : what you are saying in your question is exactly what happens ("I'm thinking `bear_moved = False` Therefore : `not bear_moved == True`").
comment on: http://stackoverflow.com/a/50516230
score: 1
type: Comment

http://stackoverflow.com/q/50529779
tagged with: python
tagged with: flask-restful
has answer: http://stackoverflow.com/a/50529827
score: 0
tagged with: heroku-api
answer count: 3
has title: passing arguments to API created by flask in python
tagged with: api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88071538
upvote count: 1
tagged with: flask
downvote count: 1
has body: I am a complete newbie to API and python. actually, after getting disappointed to find a free host supporting plumber in R I decided to try it by python. The simple problem is that I have a simple function which takes two numeric arguments and using a given CSV file do some calculations and returns a number (I have simply made this in R by the plumber in localhost). now for a test in python have written below code: from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "hello world!" if __name__ == '__main__': app.run(debug=True) well, this correctly works. but when I try to make a function to take arguments like this: from flask import Flask app = Flask(__name__) @app.route("/") def hello(a): return a + 2 if __name__ == '__main__': app.run(debug=True) I get this page which says I have not passed the arguments. my main question is that how I can pass the arguments? (in API created by R plumber, for example, I call it like: localhost/5000/?a=2 ) my another question is, could be this kind of API host and request in something like Heroku?
has answer: http://stackoverflow.com/a/50530041
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50530073

http://stackoverflow.com/a/50396157
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50396027
answers question: http://stackoverflow.com/q/50396027
has body: Just use the absolute form, since an absolute byte offset is what you have. The work of actually reading from the correct location after using seek is buried in the file system driver used by your OS. seek itself does little more than set a variable. You would use f.seek(d, 1) if you don't already know your current position, but know that you need to skip ahead by d bytes.
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/121359379
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50402794
type: AnswerComment
has text: Comon man, don't you think I didn't do that. I just don't understand after I ran the same code on my browser i.e. what is the page that is being loaded during the function's run time and what is being show after the completion

http://stackoverflow.com/a/50538936
has body: You have one float element instead of two integers in your list. Change [90.50] to [90, 50]. self.body=[[100,50], [90.50], [80,50]]
score: 0
answers question: http://stackoverflow.com/q/50538826
type: Answer

http://stackoverflow.com/comment/87804624
score: 0
has text: What determines the placement of the dots in the top and bottom edges?
comment on: http://stackoverflow.com/q/50394197
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50446131
accepted answer of: http://stackoverflow.com/q/50445847
has comment: http://stackoverflow.com/comment/87906170
has comment: http://stackoverflow.com/comment/87905887
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50445847
downvote count: 0
has body: This will give you your zigzag: np.concatenate([np.diagonal(a[::-1,:], i)[::(2*(i % 2)-1)] for i in range(1-a.shape[0], a.shape[0])])
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139546929
has comment: http://stackoverflow.com/comment/87906206
type: Answer

http://stackoverflow.com/q/50461657
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: wsgi
tagged with: python
tagged with: gevent
tagged with: python-3.6
has body: I'm getting the following error while running a flask app: from gevent.wsgi import WSGIServer ModuleNotFoundError: No module named 'gevent.wsgi' gevent is already installed and the requirement is satisfied. Pip version is 10.11 and Python 3.6. OS: Windows 10 x64 Using Anaconda VM This same code worked in another machine, so somewhere I am missing configuration, but I can't track/find it. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import json from pprint import pprint from rasa_core.channels import HttpInputChannel from rasa_core import utils from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter from rasa_core.channels.channel import UserMessage from rasa_core.channels.direct import CollectingOutputChannel from rasa_core.channels.rest import HttpInputComponent from flask import Blueprint, request, jsonify, abort def run(serve_forever=True): #path to your NLU model interpreter = RasaNLUInterpreter("models/nlu/default/current") # path to your dialogues models agent = Agent.load("models/dialogue", interpreter=interpreter) #http api endpoint for responses input_channel = SimpleWebBot() if serve_forever: agent.handle_channel(HttpInputChannel(5004, "/chat", input_channel)) return agent if __name__ == '__main__': utils.configure_colored_logging(loglevel="INFO") run()
has answer: http://stackoverflow.com/a/52046930
has title: ModuleNotFoundError: No module named 'gevent.wsgi'
downvote count: 0
tagged with: rasa-core
has answer: http://stackoverflow.com/a/50465220
score: 17
upvote count: 17

http://stackoverflow.com/q/50539721
type: AnsweredQuestion
has body: i'm working on two csv files that contain date column, the first csv file worked fine with my codes but i got error on the second file showing as " ValueError: unconverted data remains: 09". see below for my codes and screenshots, can anyone help me?? codes: with open(source_csv,newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(csvreader, None) # skip the headers for row in csvreader: dictList.append([datetime.strptime(row[0],'%b-%d').strftime('%m%d%Y'),row[1], row[0]]) mmyy = row[0].split("-") month.append(str(mmyy[0])) total += int(row[1]) error: csv file:
score: 1
has title: Python - ValueError: unconverted data remains: 09
has comment: http://stackoverflow.com/comment/88091134
downvote count: 1
tagged with: python
tagged with: valueerror
accepted answer: http://stackoverflow.com/a/50539788
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88091327
tagged with: python-3.x
answer count: 1
has answer: http://stackoverflow.com/a/50539788

http://stackoverflow.com/q/50540458
has answer: http://stackoverflow.com/a/50540509
has comment: http://stackoverflow.com/comment/88092348
favorite count: 0
type: Question
answer count: 2
downvote count: 4
linked to: http://stackoverflow.com/q/931092
tagged with: python
score: -2
has body: def reverse(text): for i in range(1, len(text) + 1): a += text[len(text) - i] return a print(reverse("Hello World!")) #error local variable 'a' referenced before assignment
accepted answer: http://stackoverflow.com/a/50540486
has answer: http://stackoverflow.com/a/50540486
has comment: http://stackoverflow.com/comment/88092841
type: AnsweredQuestion
has title: Reversing a string - local variable referenced before assignment
upvote count: 2
possible better answer: http://stackoverflow.com/a/50540509
has comment: http://stackoverflow.com/comment/88092324

http://stackoverflow.com/comment/88026090
type: QuestionComment
has text: Apparently after a reboot of the whole system I cannot reproduce the error anymore either. I didn't understand what triggered it, but not being able to reproduce it, I'm afraid I cannot investigate it any further. The strange part is that I used the same exact script to test it, but the behaviour changed... I'll come again here if it happens again
comment on: http://stackoverflow.com/q/50389613
score: 0
type: Comment

http://stackoverflow.com/q/50504590
has comment: http://stackoverflow.com/comment/88021285
has comment: http://stackoverflow.com/comment/88021402
has title: Slicing List items in python
downvote count: 5
score: -2
possible better answer: http://stackoverflow.com/a/50504740
has body: I have ordered list of string elements which I need to iterate.. starting from specific element/item from the list until the end. The list that I have: ip_list = ['input1','input2','input3',....,'input10'] I wanted to iterate from any given element (which would be dynamic on each run) for example consider input3 currently till the end of List. So I wanted to achieve something like this: for item in ip_list[input3:]: # my logic base I have searched out that, in Python, we can slice the list with positional base but not on value base.
tagged with: python
has answer: http://stackoverflow.com/a/50504740
linked to: http://stackoverflow.com/q/231767
linked to: http://stackoverflow.com/q/176918
accepted answer: http://stackoverflow.com/a/50504734
has comment: http://stackoverflow.com/comment/88021261
type: AnsweredQuestion
upvote count: 3
tagged with: list
has answer: http://stackoverflow.com/a/58333782
linked to: http://stackoverflow.com/q/509211
has answer: http://stackoverflow.com/a/50505002
has comment: http://stackoverflow.com/comment/88021270
answer count: 4
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50504734

http://stackoverflow.com/q/50472448
score: 0
answer count: 0
upvote count: 1
tagged with: plotly
tagged with: matplotlib
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87958721
type: UnansweredQuestion
tagged with: seaborn
has comment: http://stackoverflow.com/comment/87989103
has comment: http://stackoverflow.com/comment/87988706
tagged with: python
has title: Python Plotly: Visualizing and plotting normal distribution
has body: To plot Normal distribution curve for error data, I currently plot it like this, mymean = np.mean(mydata) mystd = np.std(mydata) mypd = scipy.stats.norm.pdf((mydata), mymean, mystd) plt.plot(mydata, mypd) The result of my code The result is very bad, Is there any alternative to effectively visualize curves in PLOTLY or matplotlib, like the one shown in image below (at-least with sigma values). Any solution better than the my result would be great! Thanks Normal distribution curve edit1 :new result Sorted using: df.sort_values('mydata', inplace=True) But still not a good visualization like normal distribution curve(sigma values)

http://stackoverflow.com/comment/87880267
type: AnswerComment
has text: @Neil No worries. I've added a few more remarks to my answer.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50432935

http://stackoverflow.com/comment/87935777
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50459664
has text: You superuser_id when calling report from py. That may be help you out here.

http://stackoverflow.com/comment/87938922
score: 0
comment on: http://stackoverflow.com/a/50460828
type: Comment
type: AnswerComment
has text: Thank you for the timely response!

selenium-chromedriver
tags question: http://stackoverflow.com/q/50456783
tags question: http://stackoverflow.com/q/50452087
tags question: http://stackoverflow.com/q/50443955
tags question: http://stackoverflow.com/q/50530444
tags question: http://stackoverflow.com/q/50424654
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/50427972
tags question: http://stackoverflow.com/q/50413206
tags question: http://stackoverflow.com/q/50400666
tags question: http://stackoverflow.com/q/50455943
tags question: http://stackoverflow.com/q/50430290
tags question: http://stackoverflow.com/q/50403711
tags question: http://stackoverflow.com/q/50505169
tags question: http://stackoverflow.com/q/50434065
tags question: http://stackoverflow.com/q/50522769
type: Tag
tags question: http://stackoverflow.com/q/50389926
tags question: http://stackoverflow.com/q/50498809

http://stackoverflow.com/comment/87930636
comment on: http://stackoverflow.com/q/50457569
score: 0
has text: Do you have a sample `json2` you could post here?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50419987
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
favorite count: 0
has title: Ladon auto-refresh module/code
type: Question
has body: I have a Ladon service that currently uses one service module named register, behind that is code in services/register.py. Other frameworks, such as .NET and Java, will automatically compile &amp; reload code/classes when the underlying physical file changes on disk without requiring a restart of the application server. In this case I have the Ladon app server running on port 8080, if I make changes to services/register.py I have to stop and restart the app server. It's not critical, the app isn't go to be in a highly available environment, it's annoying more than anything (and I'm curious). Does Ladon offer any similar feature? I've had no luck finding a way to do this. Code used to start up the app server: scriptdir = dirname(abspath(__file__)) service_modules = ['register'] # Create the WSGI Application application = LadonWSGIApplication( service_modules, [join(scriptdir, 'services'), join(scriptdir, 'appearance')], catalog_name='Serisma web services', catalog_desc='All web services', logging=31) if __name__ == '__main__': port = 8080 print("\nServices running on localhost:%(port)s\n" % {'port': port}) server = wsgiref.simple_server.make_server('', port, application) server.serve_forever() Environment details: Darwin hostname 17.5.0 Darwin Kernel Version 17.5.0: Mon Mar 5 22:24:32 PST 2018; root:xnu-4570.51.1~1/RELEASE_X86_64 x86_64 Python 2.7.13 :: Anaconda 4.3.1 (x86_64) ladon 1.0.2
score: 1
tagged with: ladon
tagged with: python
tagged with: python-2.7

http://stackoverflow.com/comment/87998202
type: QuestionComment
type: Comment
has text: Can you show the call to gradient_descent. Because this is where the error occured. You forgot to pass in some argument, not kwargs.
comment on: http://stackoverflow.com/q/50492607
score: 0

http://stackoverflow.com/q/50417851
tagged with: interpreter
tagged with: list
has answer: http://stackoverflow.com/a/50417958
has title: python flow control functioning weird
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50418007
favorite count: 0
type: Question
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87851494
type: UnansweredQuestion
has body: I was trying to solve a knapsack problem using DP. Basically, the goal is to see if we can have certain elements in the list sum up to half of the total sum. def canPartition(nums): """ :type nums: List[int] :rtype: bool """ run_sum = 0 for num in nums: run_sum += num if run_sum &amp; 1 == 1: return False run_sum //= 2 n = len(nums) dp = [[False] * (run_sum+1)] * (n+1) for i in range(n+1): dp[i][0] = True for j in range(1, run_sum+1): dp[0][j] = False print("initial stage") print(dp) for i in range(1, 2): for j in range(1, run_sum+1): dp[i][j] = dp[i-1][j] print("inner loop after operation 1:") print(dp) if j &gt;= nums[i-1]: print("inner loop after operation 2:") print(i, j) dp[i][j] |= dp[i-1][(j - nums[i-1])] print(dp) print(" ") return dp[n][run_sum] nums = [1, 2, 5] canPartition(nums) The goal itself is not so important here. But the flow control of the last nested loop behaves really strange. Below is the printed result. initial stage [[True, False, False, False, False], [True, False, False, False, False], [True, False, False, False, False], [True, False, False, False, False]] inner loop after operation 1: [[True, False, False, False, False], [True, False, False, False, False], [True, False, False, False, False], [True, False, False, False, False]] inner loop after operation 2: 1 1 [[True, True, False, False, False], [True, True, False, False, False], [True, True, False, False, False], [True, True, False, False, False]] inner loop after operation 1: [[True, True, False, False, False], [True, True, False, False, False], [True, True, False, False, False], [True, True, False, False, False]] inner loop after operation 2: 1 2 [[True, True, True, False, False], [True, True, True, False, False], [True, True, True, False, False], [True, True, True, False, False]] inner loop after operation 1: [[True, True, True, False, False], [True, True, True, False, False], [True, True, True, False, False], [True, True, True, False, False]] inner loop after operation 2: 1 3 [[True,…
tagged with: python

http://stackoverflow.com/q/50403292
upvote count: 0
answer count: 1
has body: h = np.array([1, 1, 1, 0, 0]) x = np.array([0.5, 2, 0, 0, 0]) length = len(h)+len(x)-1 h_conv, h_rev, x_conv, y_conv = np.zeros(length), np.zeros(length), np.zeros(length), np.zeros(length) x_conv[:len(x)] = x h_rev[length-len(h):] = h[::-1].copy() for t in range(length): h_conv[:t+1] = h_rev[length-t-1:] y_conv[t] = np.sum(x_conv * h_conv) &gt;&gt;&gt; y [0.5, 2.5, 2.5, 2., 0., 0., 0., 0., 0.] How do I write the three lines for the for-loop without using pre-defined methods? I tried: for i in range(length): y[i]=0; for j in range(length): y[i] += x[i-j]*h[j]; Error index 0 is out of bounds for axis with size 0
has title: Python questions(Convolution)
downvote count: 1
favorite count: 0
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50403337
type: Question
tagged with: numpy
type: UnansweredQuestion

http://stackoverflow.com/comment/87890251
type: Comment
score: 4
has text: This does work when the key you are searching for is in the dictionary, but this will fail and cause undefined behavior if the key isn't in the dictionary. This is because there is no return value for when the key isn't already in the dictionary.
type: AnswerComment
comment on: http://stackoverflow.com/a/50437320

http://stackoverflow.com/q/50447940
has title: Error while building a basic web crawler
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/51498688
has body: I am trying to run the following code for web crawling. import requests from bs4 import BeautifulSoup def function1(): url = "http://www.iitg.ac.in/" source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text) for link in soup.findALL('a', {'target' : '_blank'} ): href = link.get(href) print(href) function1() but it is showing the following error: File "C:/Users/HP/.spyder-py3/temp.py", line 9, in function1 for link in soup.findALL('a', {'target' : '_blank'}): TypeError: 'NoneType' object is not callable I also checked for its solution on this platform already, but according to that there seems no un-callable object inside the function findALL. Please help.
has answer: http://stackoverflow.com/a/50448170
has answer: http://stackoverflow.com/a/50448156
answer count: 3
upvote count: 0
tagged with: python-requests
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

data-visualization
tags question: http://stackoverflow.com/q/50414406
tags question: http://stackoverflow.com/q/50518090
tags question: http://stackoverflow.com/q/50417528
tags question: http://stackoverflow.com/q/50504053
tags question: http://stackoverflow.com/q/50458563
tags question: http://stackoverflow.com/q/50461615
tags question: http://stackoverflow.com/q/50509481
tags question: http://stackoverflow.com/q/50472921
type: Tag
tag name: data-visualization
tags question: http://stackoverflow.com/q/50421549

http://stackoverflow.com/a/50446092
has comment: http://stackoverflow.com/comment/88035029
upvote count: 1
has comment: http://stackoverflow.com/comment/88054701
score: 1
has body: a bit correction in @Prakash answer. You need to call function inside from if __name__== "__main__" Here, explained well !! from multiprocessing import Process import time def func1(): print('test1') time.sleep(10) def func2(): print('test2') time.sleep(5) def test_multiprocessing(): p_func1 = Process(target=func1) p_func2 = Process(target=func2) p_func1.start() p_func2.start() p_func1.join() p_func2.join() print('done') if __name__== "__main__": test_multiprocessing() Another way is you can bound method to a class because functions are only picklable if they are defined at the top-level of a module. as below: from multiprocessing import Process import time class Foo: def func1(self): print('test1') time.sleep(10) def func2(self): print('test2') time.sleep(5) def test_multiprocessing(self): p_func1 = Process(target=self.func1) p_func2 = Process(target=self.func2) p_func1.start() p_func2.start() p_func1.join() p_func2.join() print('done') if __name__== "__main__": f=Foo() f.test_multiprocessing()
answers question: http://stackoverflow.com/q/50445730
downvote count: 0
type: Answer

http://stackoverflow.com/a/50566337
answers question: http://stackoverflow.com/q/50464551
type: Answer
accepted answer of: http://stackoverflow.com/q/50464551
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Since you are using Python 3 please install the library using the right command: sudo python3 setup.py install

http://stackoverflow.com/comment/88047626
score: 0
type: Comment
type: AnswerComment
has text: This is what I'm having a hard time grasping. It makes a lot more sense to me to write it as "... and bear_moved == False" instead of "... and not bear_moved". It's driving me insane that I can't intuitively understand this - like I KNOW this is a simple concept but it just won't click.
comment on: http://stackoverflow.com/a/50516230

http://stackoverflow.com/comment/87858924
type: Comment
comment on: http://stackoverflow.com/q/50421933
score: 0
has text: I get the save error message with the linked example code and a Linux machine, too. i assume these two problems are unrelated and you should ask those two questions separately.
type: QuestionComment

http://stackoverflow.com/a/50440119
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50439661
has body: flipped_label = tf.gather([0, 3, 2, 1], label)
accepted answer of: http://stackoverflow.com/q/50439661
score: 1
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/comment/87914058
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50450322
type: AnswerComment
has text: Welcome to StackOverflow, when you get a moment please read our [help] and take the [tour]. When you have enough reputation you will be able to comment on a question. As it stands, while your answer may provide a a solution, it's not really an answer to the question.

http://stackoverflow.com/comment/87953585
score: 0
has text: @ImportanceOfBeingErnest, but is there any possibility simply to create a point (XYZ) and than set a value to this point from 4th column ? after that color all points and in best case connect nearest points or smth like this to the surface?
comment on: http://stackoverflow.com/q/50467393
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87974651
has text: From your path it looks like you are running Python 3.7. Is that the case? mysqlclient might not yet work with this pre-release development version
score: 0
comment on: http://stackoverflow.com/q/50480583
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87993547
score: 0
type: Comment
has text: Eliminating the else statement works because your `found` starts at False, and once at least one line is found, it becomes True, and it will stay that way even if nothing else matches again. Before hand, if something didn't match after it had matched, `found` would become False again, ignoring the fact that something had actually been found previously.
type: AnswerComment
comment on: http://stackoverflow.com/a/50489489

http://stackoverflow.com/comment/87860821
has text: How are you triggering this error? Please show the complete traceback.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50422076

http://stackoverflow.com/a/50456988
has body: Your logic seems overcomplicated. You can create a name to age mapping from df1 and iterate df2.iterrows. There is no need to access indices, unless you have repeated names. In the latter case, you can use the index. s = df1.set_index('name')['age'] for _, row in df2.iterrows(): print('{0} who is {1} lives in {2}'.format(row['name'], s.get(row['name']), row.city)) Bobby who is 17 lives in Lakeside Sally who is 23 lives in Carlstown John who is 19 lives in Wallsburg
has comment: http://stackoverflow.com/comment/87928950
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50456633
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87928964

kivy
tags question: http://stackoverflow.com/q/50518977
tags question: http://stackoverflow.com/q/50415281
type: Tag
tags question: http://stackoverflow.com/q/50448131
tag name: kivy
tags question: http://stackoverflow.com/q/50416284
tags question: http://stackoverflow.com/q/50534767
tags question: http://stackoverflow.com/q/50462200
tags question: http://stackoverflow.com/q/50433534
tags question: http://stackoverflow.com/q/50433301
tags question: http://stackoverflow.com/q/50397890
tags question: http://stackoverflow.com/q/50428342
tags question: http://stackoverflow.com/q/50441390
tags question: http://stackoverflow.com/q/50518645
tags question: http://stackoverflow.com/q/50483687
tags question: http://stackoverflow.com/q/50515109
tags question: http://stackoverflow.com/q/50412552
tags question: http://stackoverflow.com/q/50426097
tags question: http://stackoverflow.com/q/50508949
tags question: http://stackoverflow.com/q/50429891
tags question: http://stackoverflow.com/q/50464674
tags question: http://stackoverflow.com/q/50455760
tags question: http://stackoverflow.com/q/50425726
tags question: http://stackoverflow.com/q/50503899
tags question: http://stackoverflow.com/q/50426891
tags question: http://stackoverflow.com/q/50526939
tags question: http://stackoverflow.com/q/50525029
tags question: http://stackoverflow.com/q/50391698
tags question: http://stackoverflow.com/q/50473732

http://stackoverflow.com/q/50456885
has answer: http://stackoverflow.com/a/50457228
possible better answer: http://stackoverflow.com/a/50457228
has comment: http://stackoverflow.com/comment/87927510
has comment: http://stackoverflow.com/comment/88076161
tagged with: python
has title: concatenate files in python 3
has comment: http://stackoverflow.com/comment/87927586
has body: Let's say I have two files, file1.txt, file2.txt. file1.txt is the following TITLE MEARA Repeatv2 Run2 DATA TYPE ORIGIN JASCO OWNER DATE 18/03/08 TIME 22:07:45 SPECTROMETER/DATA SYSTEM JASCO Corp., J-715, Rev. 1.00 RESOLUTION DELTAX -0.1 XUNITS NANOMETERS YUNITS CD[mdeg] HT[V] FIRSTX 260 LASTX 200 NPOINTS 601 FIRSTY -4.70495 MAXY -4.70277 MINY -41.82113 XYDATA 260.0 -4.70495 443.669 259.9 -4.70277 443.672 259.8 -4.70929 443.674 259.7 -4.72508 443.681 259.6 -4.72720 443.69 file2.txt is this: TITLE MEARA Repeatv2 Run2 DATA TYPE ORIGIN JASCO OWNER DATE 18/03/08 TIME 22:30:34 SPECTROMETER/DATA SYSTEM JASCO Corp., J-715, Rev. 1.00 RESOLUTION DELTAX -0.1 XUNITS NANOMETERS YUNITS CD[mdeg] HT[V] FIRSTX 260 LASTX 200 NPOINTS 601 FIRSTY -4.76564 MAXY -3.51295 MINY -41.95971 XYDATA 260 -4.76564 443.152 259.9 -4.77382 443.155 259.8 -4.78663 443.156 259.7 -4.8017 443.162 259.6 -4.83604 443.174 I have written the following Python script to concatenate the two files. def catFiles(names, outName): with open(outName, 'w') as outfile: for fname in names: fileName=('/'+str(fname)) with open(fname) as infile: outfile.write(infile.read()) while this script works to concatenate the two files, it stacks the files on top of each other, so that one file comes after another. I was wondering how I can modify this or rewrite it, such that the files are stacked next to each other; such that I get the following output TITLE MEARA Repeatv2 Run2 TITLE MEARA Repeatv2 Run2 DATA TYPE DATA TYPE ORIGIN JASCO ORIGIN JASCO OWNER OWNER DATE 18/03/08 DATE 18/03/08 TIME 22:07:45 TIME 22:30:34 SPECTROMETER/DATA SYSTEM JASCO Corp., J-715, Rev. 1.00 SPECTROMETER/DATA SYSTEM JASCO Corp., J-715, Rev. 1.00 RESOLUTION RESOLUTION DELTAX -0.1 DELTAX -0.1 XUNITS NANOMETERS XUNITS NANOMETERS YUNITS CD[mdeg] YUNITS CD[mdeg] HT[V] HT[V] FIRSTX 260 FIRSTX 260 LASTX 200 LASTX 200 NPOINTS 601 NPOINTS 601 FIRSTY -4.70495 FIRSTY -4.76564 MAXY -4.70277 MAXY -3.51295 MINY -41.82113 MINY -41.95971 XYDATA XYDATA 260.0 -4.70495 4…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50456956
accepted answer: http://stackoverflow.com/a/50456956
has comment: http://stackoverflow.com/comment/87927319
answer count: 2
tagged with: concatenation
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87927369
has comment: http://stackoverflow.com/comment/87927341
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50438675
type: Answer
score: 0
has body: Eventually I assumed it wasn't possible in pure plotly. It's simple enough in Dash. app = dash.Dash() func_map = {'cos': np.cos, 'sin': np.sin, None: np.cos} app.layout = html.Div([ html.Div( [ dcc.Dropdown( id='function-select', options=[{'label': 'cos', 'value': 'cos'}, {'label': 'sin', 'value': 'sin'}], value='cos' ) ], style={'width': '20%', 'display': 'inline-block'} ), html.Div( [ dcc.Dropdown( id='arg-select', options=[{'label': 'x', 'value': 1}, {'label': '2x', 'value': 2}], value=1 ) ], style={'width': '20%', 'display': 'inline-block'} ), dcc.Graph(id='sinusoid-graph') ]) @app.callback( dash.dependencies.Output('sinusoid-graph', 'figure'), [ dash.dependencies.Input('function-select', 'value'), dash.dependencies.Input('arg-select', 'value') ] ) def update_graph(func_name, omega): func = func_map[func_name] xx = np.linspace(0, 10, 100) yy = func(omega*xx) data = [go.Scatter(x = xx, y = yy)] layout = go.Layout( title = '{}({}x)'.format(func_name, omega), hovermode = 'closest' ) return {'data': data, 'layout': layout}
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50430578
answers question: http://stackoverflow.com/q/50430578

memory
tags question: http://stackoverflow.com/q/50477582
tag name: memory
tags question: http://stackoverflow.com/q/50490955
type: Tag
tags question: http://stackoverflow.com/q/50397067
tags question: http://stackoverflow.com/q/50497280
tags question: http://stackoverflow.com/q/50408842
tags question: http://stackoverflow.com/q/50439859

http://stackoverflow.com/comment/87979343
type: Comment
comment on: http://stackoverflow.com/q/50468074
score: 0
type: QuestionComment
has text: Please don't add an answer in the question. Just write a (short) answer to your own question.

http://stackoverflow.com/q/50475989
has comment: http://stackoverflow.com/comment/87978173
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87976099
downvote count: 0
has answer: http://stackoverflow.com/a/50591431
has comment: http://stackoverflow.com/comment/87968409
score: 2
has comment: http://stackoverflow.com/comment/87969817
has title: Efficiency of Numpy wheels and simple benchmark for Numpy installations
has body: Some months (or years?) ago, I installed a Numpy wheel which was very inefficient. Since, I avoid wheels for the computational packages and prefer to build them or to use conda. By " very inefficient", I mean that a code using this wheel was something like 10 times slower than usual. I guess this Numpy did not manage to use correctly the Blas and/or Lapack implementations installed on the system (Debian). See https://docs.scipy.org/doc/numpy/user/building.html Note that for Linux, the wheels are built on an old CentOS (https://github.com/pypa/manylinux). But a generically compiled Numpy (a wheel) can also be less efficient than a Numpy compiled on the machine because it is not compiled with options like march=native, so I guess it uses only the most generic processor instructions. This is why I think when we really care about performance, one needs to be able to check how fast is the installed Numpy. Now I try to use pyenv and pipenv, which seem very convenient but using pipenv without wheels would be very slow and inconvenient. I'm wondering how efficient are the wheels of Numpy (and other computational packages). Note that I found nothing about the efficiency of the wheels in the installation pages of Numpy and Scipy (https://docs.scipy.org/doc/numpy/user/install.html and https://scipy.org/install.html#installing-via-pip) I'm also wondering how to bench the Numpy installations. I can benchmark with a very simple code like import numpy as np a = np.random.rand(1000) %timeit a @ a which already gives a good idea but it only benchmark one Numpy function. I didn't find anything very simple. For example there is https://github.com/numpy/numpy/tree/master/benchmarks but one needs to download the Numpy source. I guess that there are commands using only the installed Numpy. There are bench functions (for example np.lib.bench() or np.random.bench()) but the documentation is not so clear and I don't understand how to use them. To summarize, my questions are (yes, 2 question…
answer count: 1
tagged with: python
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy

http://stackoverflow.com/a/50518641
has comment: http://stackoverflow.com/comment/88050063
type: Answer
has comment: http://stackoverflow.com/comment/88049973
has comment: http://stackoverflow.com/comment/88055449
has comment: http://stackoverflow.com/comment/88056326
has comment: http://stackoverflow.com/comment/88049883
has comment: http://stackoverflow.com/comment/88053188
score: 1
answers question: http://stackoverflow.com/q/50518607
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88049918
has body: You can use the condition (and its negation) for logical indexing: has_abc = cntnt.str.contains("abc") cntnt[ has_abc].apply(do_thing) cntnt[~has_abc].apply(do_other_thing)

http://stackoverflow.com/q/50427134
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25537028
has comment: http://stackoverflow.com/comment/87872173
upvote count: 0
downvote count: 2
answer count: 1
has title: Python, simple compression/encoding algorithm
accepted answer: http://stackoverflow.com/a/50428782
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50428782
score: -2
has body: I have a string which contains only 0 and 1. I need to encode it in a form of ranges of 1's. Example input: 01101110 Example output: [[1,2], [4,6]] Update: Need to produce [begin,end] array of 1's sequence indexes. As per example: First sequence of 1's starts at index 1 and finishes at index 2. Second sequence starts at index 4 and finishes at index 6 Minimum length of sequence is 1. So "1" input produces [[0,0]] output How should I do it?
tagged with: python
has comment: http://stackoverflow.com/comment/87872097
has comment: http://stackoverflow.com/comment/87872162
has comment: http://stackoverflow.com/comment/87869018

http://stackoverflow.com/comment/87921459
type: AnswerComment
score: 0
type: Comment
has text: ok there is no inplace on csv :(, i'll use pandas with this great optimization to my for loop
comment on: http://stackoverflow.com/a/50453590

http://stackoverflow.com/comment/88055294
type: Comment
comment on: http://stackoverflow.com/a/50500951
type: AnswerComment
has text: @Ethan http://www.pythonforbeginners.com/regex/regular-expressions-in-python and https://www.programcreek.com/python/example/21/re.sub
score: 0

http://stackoverflow.com/comment/115849809
score: 0
comment on: http://stackoverflow.com/a/64855389
type: Comment
has text: Note: This requires pandas >= 1.1
type: AnswerComment

http://stackoverflow.com/q/50437406
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87888966
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87888820
upvote count: 3
has title: Need modified version of Python Dictionary
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50437500
has comment: http://stackoverflow.com/comment/87889015
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87896961
has answer: http://stackoverflow.com/a/50437500
has body: What methods need to be altered if want to change the default behaviour of the dictionary? Some of the methods I am aware of like __getitem__(), __missing__(), __iter__() etc. I am trying to implement the dictionary in such a way that if I tried to assign the value to key(already existed) then the old value should not go away while should be kept in some list and when we try to remove the key like pop(key), it should remove older value. What methods need to be modified to override the dict class to achieve this behaviour?
tagged with: python

http://stackoverflow.com/q/50424138
has title: OpenCV Python View webcam feed before it takes a snap?
tagged with: python
has body: So my code should detect an object with opencv and once it detects it it should take a snap of it. Which it does fine....However it simply goes to the webcam and doesn't show me the webcam feed. When it detects the object it takes a snap and show the image. What I want is to see the webcam feed until it detects the object....How can I do that? Here's my code: import cv2 cascade = cv2.CascadeClassifier('xcascade.xml') cap = cv2.VideoCapture(1) num = 0 while num&lt;1000: ret, img = cap.read() gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cas = cascade.detectMultiScale(gray, 10, 10) for(x,y,w,h) in cas: font = cv2.FONT_HERSHEY_SIMPLEX cv2.rectangle(img,(x,y), (x+w,y+h),(255,255,0),5) cv2.putText(img, 'Something',(x,y-120), font, 1.5, (0,255,255),5, cv2.LINE_AA) num = num+1 cv2.imshow('img',img) cv2.waitKey(1000) cap.release() cv2.desrtoyAllWindows() break
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50434282
accepted answer: http://stackoverflow.com/a/50434282
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: opencv

http://stackoverflow.com/q/50473598
has title: Parkingspot corners coordinates gather through OpenCV in Python 3.6
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87961780
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87960871
tagged with: opencv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87961041
tagged with: python
has body: I want to make a parkingspots detector with OpenCV and Python and I got stucked at finding the coordinates of each parking spot. So, my idea was to apply hughlines function to detect the lines and then track the corners and then apply a function which determine if the spot is empty or not. Here's what I got until now: Function to detect if the spot is empty: def f(img,a,b,c,d): sub_img=img[a:b, c:d] edg= cv2.Canny(sub_img,100,150) pix=cv2.countNonZero(edg) if pix&gt;1400: cv2.rectangle(img,(d,b),(c,a),(0,0,255),3) else:cv2.rectangle(img,(d,b),(c,a),(0,255,),3) The part where I'm tryin to detect the spots: import cv2 import numpy as np import csv from matplotlib import pyplot as plt img = cv2.imread('parking.jpg',1) im_gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) (thresh, im_bw)= cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY| cv2.THRESH_OTSU) tresh=127 im_bw= cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1] cv2.imshow('binary',im_bw) edges = cv2.Canny(im_bw,300,350) imagem = cv2.bitwise_not(im_bw) height, width = im_bw.shape[:2] contours=np.zeros((height, width,3),np.uint8) lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=0.1,maxLineGap=30) for line in lines: x1,y1,x2,y2 = line[0] cv2.circle(im_bw,(x1,y1),3,(0,255,0),3) cv2.circle(im_bw,(x2,y2),3,(0,0,255),3) cv2.line(contours,(x1,y1),(x2,y2),255,2) gray = cv2.cvtColor(contours,cv2.COLOR_BGR2GRAY) gray = np.float32(gray) dst = cv2.cornerHarris(gray,2,3,0.04) #result is dilated for marking the corners, not important dst = cv2.dilate(dst,None) # Threshold for an optimal value, it may vary depending on the image. contours[dst&gt;0.1*dst.max()]=[0,0,255] # Printing corners coords gray = np.float32(gray) dst = cv2.cornerHarris(gray,2,3,0.04) dst = cv2.dilate(dst,None) ret, dst = cv2.threshold(dst,0.01*dst.max(),255,0) dst = np.uint8(dst) ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001) corners = cv2.cor…
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/50491761
downvote count: 0
has comment: http://stackoverflow.com/comment/87960798
answer count: 1

http://stackoverflow.com/comment/87875749
has text: That was not clear to me from your answer, you might consider expanding the answer to make that more clear.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50430552
type: Comment

http://stackoverflow.com/comment/88038540
type: QuestionComment
comment on: http://stackoverflow.com/q/50497472
has text: I'm using Python 3.6.4 64-bit, (built using MSC v.1900 on win32, which is Visual Studio 2013 ver 14.0) through module Ctypes to try and load DLLs compiled using Visual Studio 2013. The person who compiled the DLLs said this difference in compiler versions should not cause any conflicts... Unsure what next steps should be...
type: Comment
score: 0

http://stackoverflow.com/a/50470214
answers question: http://stackoverflow.com/q/50469721
score: 1
has body: You are using both pack and grid with widgets that are directly in root (for example, LabelCodeDDL = Label(root, text="Petrel Code").grid(row=2, column=0, sticky=W) and toolbar.pack(side=TOP, fill=X)). You cannot mix them like that. All widgets that have the same parent or master must use one or the other.
type: Answer
has comment: http://stackoverflow.com/comment/87987760
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87968476
comment on: http://stackoverflow.com/a/50474387
score: 0
type: AnswerComment
has text: @ Julien Spronck Thanks! I figured out what my problem was... 1) I did need to adjust my code a bit by removing the single quotation marks from file_path. However, my biggest issue was for some reason whenever I start a new project in IntelliJ IDEA, it doesnt carry over my settings and so my SDK was not configured for the project through the Jupyter Notebook GUI in IntelliJ. Ughhh.... such a headache. Thanks again all!
type: Comment

http://stackoverflow.com/comment/88031346
comment on: http://stackoverflow.com/a/50509252
type: Comment
has text: Thank you very much @Elad for your help. Thanks to this, I advance in the resolution of my problem! Now I will use it to understand the main issue, keeping you inform if solved the main problem. Also, a small thing by curiosity, I dont understand why their is the error before this number can not reached 3000... would you have any idea?
score: 0
type: AnswerComment

http://stackoverflow.com/q/50475337
tagged with: google-python-api
type: Question
has body: When removing an attendee via the patch method: https://developers.google.com/calendar/v3/reference/events/patch the attendee's calendar view in the browser does not refresh showing they're no longer invited to the meeting. How does one trigger a UI refresh so that the meeting is removed from their calendar in the browser.
type: UnansweredQuestion
tagged with: python
answer count: 1
score: 0
tagged with: google-calendar-api
has answer: http://stackoverflow.com/a/50475338
has title: how to trigger UI refresh when removing attendee with google calendar api

http://stackoverflow.com/comment/88047789
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50510090
score: 0
has text: right now, i can get it from point a to point b, which is just a straight line, I would like to be able to move it along a curved path.

http://stackoverflow.com/a/53710346
answers question: http://stackoverflow.com/q/50539729
has comment: http://stackoverflow.com/comment/94283091
type: Answer
has body: the error it´s in the "success" quotes: Feature: ... - Then I should see "success" ... Step implementation: ... @then('I should see {txt}') def step_impl(context, txt): if txt not in ['success', 'error']: ... It should be: Feature: ... - Then I should see success ... Or change the step implementation to: ... @then('I should see {txt}') def step_impl(context, txt): if txt not in ['"success"', 'error']: ... The error is in the quotes used in "success". The step implementation use the text: "success" (including the quotes) and assigne it to the txt variable and so, in the if statement, txt is NOT equal to success without the quotes.
upvote count: 1
has comment: http://stackoverflow.com/comment/94317386
downvote count: 0
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50539729

http://stackoverflow.com/comment/87849488
type: Comment
comment on: http://stackoverflow.com/a/50415766
type: AnswerComment
has text: One last thing. How would I add a colorbar? I see that colorbar is an available method of fig.subplot(111).pcolormesh using the dir command. So would I just add a .colorbar() to the end of fig.add_subplot(111).pcolormesh(X, Y, Z, cmap = get_cmap('BuPu'))?
score: 0

http://stackoverflow.com/comment/91627712
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50473832
has text: In Windows system, CTRL+C interrupt is only sent to the affected program **after** it has processed data (such as from coroutines or transport). This is a Python bug on signal handling in Windows system.

http://stackoverflow.com/q/50396786
downvote count: 0
has answer: http://stackoverflow.com/a/69588179
has title: 404 Error on Google OAuth API Token Request
favorite count: 0
tagged with: google-oauth
upvote count: 4
has body: I am trying to get a token from the Google OAuth api. I have already successfully been able to get the temporary auth code. However, my requests are returning a 404 error, with the normal Google "That's an error" 404 page. Here is my Python code: data = { "code":auth_code, "client_id":client_id, "client_secret":client_secret, "redirect_uri":redirect_uri, "grant_type":"authorization_code" } headers = {"Content-Type":"application/x-www-form-urlencoded"} r = requests.post("https://googleapis.com/oauth/v4/token",data=data,headers=headers) I get the same error no matter if I url-encode my parameters or not (I think the requests library does it anyway). Here are the data I am sending in more detail (censored of course) 'client_id':'2-------------------------------------------0.apps.googleusercontent.com', 'client_secret': '5----------------------p', 'code': '4/A-------------------------- ... ------------------------------------fGE#', 'grant_type': 'authorization_code', 'redirect_uri': 'https://localhost' I understand the question here is very similar to mine but all the solutions provided either don't work (url encoding) or don't apply (everything else). I am using this official documentation for reference. This is probably very obvious, like most of the questions I ask here. Edit - I tried data = "code="+auth_code+"&amp;client_id="+client_id+"&amp;client_secret="+client_secret+"&amp;redirect_uri="+redirect_uri+"&amp;grant_type=authorization_code" ...which returned a 400. With or without url-encoding.
answer count: 4
tagged with: oauth
type: Question
linked to: http://stackoverflow.com/q/42828358
tagged with: google-api
has answer: http://stackoverflow.com/a/60267124
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/50438931
has answer: http://stackoverflow.com/a/50431206
has answer: http://stackoverflow.com/a/50438931
possible better answer: http://stackoverflow.com/a/60267124
type: AnsweredQuestion

http://stackoverflow.com/comment/88186881
has text: Pubnub works for me on my windows pc and raspberry pi too. But I am unable to get it going on the onion omega 2 plus board. My python version is 3.6
score: 0
comment on: http://stackoverflow.com/a/50588724
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87890878
has text: Edited the post, thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50437443
type: QuestionComment

http://stackoverflow.com/q/50530759
tagged with: http://stackoverflow.com/tag/json
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50532183
upvote count: 2
has answer: http://stackoverflow.com/a/50532183
downvote count: 0
tagged with: python
has body: I'm writing data from dataframe to json file using pandas function .to_json like this: xx.to_json('file_path',orient='records',lines=True) The output of this looks like this: {"speed":null,"state":4.0,"stop_trigger":null,"t":1527237121263,"target_speed":null} {"speed":null,"state":null,"stop_trigger":null,"t":1527237121264,"target_speed":400.0} How is it possible to get rid of columns in the output if there are null values?: {"state":4.0,"t":1527237121263} {"t":1527237121264,"target_speed":400.0}
score: 2
has title: Get rid of columns with null value in json output
possible better answer: http://stackoverflow.com/a/50531123
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50531943
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50531123

http://stackoverflow.com/q/50440947
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/87896250
has comment: http://stackoverflow.com/comment/87896381
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: jupyter
has body: I have tried joining 2 Web-scraped lists into one list together but, all it does is show one instance. (I already have the list of names and a list of addresses made, I just want to join them). from bs4 import BeautifulSoup import urllib.request def get_HTML(url): response = urllib.request.urlopen(url) html = response.read() return html FIRST LIST: venues_html = get_HTML('http://www.cxra.com/venues/new-york/') soup = BeautifulSoup(venues_html, "lxml") for venue in soup('a', attrs={'href' : '#', 'onclick' : 'return false;'}): display (venue.text) Output: 'Manhattan Center Studios' 'Ellis Island' 'The TimesCenter' 'The Altman Building' 'NYIT Auditorium on Broadway' SECOND LIST for info in soup.findAll('div', attrs={'class' : 'infoUnit col-md-6'}): display (info.text) Output: '\n \n311 West 34th Street\r\nNew York City, 94710\n\n212.613.5536\n' '\n \nEllis Island\r\nNew York, NY 10004\n\n212.613.5535\n' '\n \n242 W 41st St\r\nNew York, NY 10036\n\n212.613.5535\n' '\n \n135 W 18th St\r\nNew York, NY 10011\n\n212.613.5535\n' '\n \n1871 Broadway\r\nNew York, NY 10023\n\n212.613.5536\n' Attempt of joining the two: print ("Venue: " + venue.text + info.text) output: Venue: NYIT Auditorium on Broadway 1871 Broadway New York, NY 10023 212.613.5536 I want it to do that for all of the different venues, not just one. I have tried loops, but they just seem to show that one instance repeatedly.
has comment: http://stackoverflow.com/comment/87896607
type: Question
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/50441250
accepted answer: http://stackoverflow.com/a/50441250
has title: How to join 2 Webscraped lists together as one
score: -3
tagged with: web-scraping
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87896539

http://stackoverflow.com/q/50388349
linked to: http://stackoverflow.com/q/50383997
has comment: http://stackoverflow.com/comment/87792981
has comment: http://stackoverflow.com/comment/87792942
has title: How to write a customized processor in Nifi using Python?
type: Question
has comment: http://stackoverflow.com/comment/87793746
answer count: 1
has comment: http://stackoverflow.com/comment/87792461
tagged with: kafka-consumer-api
tagged with: python
has comment: http://stackoverflow.com/comment/87793736
tagged with: apache-kafka
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50392867
accepted answer: http://stackoverflow.com/a/50392867
has body: I have a kafka queue running and receiving messages. I have connected Nifi with that topic(of kafka) using ConsumeKafka api. I want to have a processor which would read this messages and apply some operations over them. Based on these needs, what would be the best way by being within Nifi?
tagged with: apache-nifi

http://stackoverflow.com/q/50440664
upvote count: 1
score: 1
answer count: 1
has body: #!/usr/bin/python import socket import argparse import os.path parser = argparse.ArgumentParser(description='Scan for open ports on given hostname or ip address') parser.add_argument('-H','--HOST', help ="Enter a hostname or Ip Address") args = parser.parse_args() def find_port(PORT,HOST): data = ('\r\nSuccessful Connections were made at host {} on port {}'.format(HOST, PORT)) originalfile = ("Data Log.txt") s = socket.socket() socket.setdefaulttimeout(1) try: s.connect((HOST, PORT)) print '[+] Successful connection on ',PORT except: print '[+] Connection failure on port ',PORT if os.path.exists(originalfile) is True: if s.connect((HOST, PORT)): with open (originalfile, "w") as currentfile: currentfile.write(data) currentfile.close() elif os.path.exists(originalfile) is False: if s.connect((HOST, PORT)): with open("Data Log.txt","w+") as newfile: newfile.write(data) newfile.close() if __name__=='__main__': for i in range(1024): find_port(i, args.HOST) i keep getting these errors. All im trying to do is capture the instance of a successful connection on the port and for it to log it inside of a text file but i keep getting these errors. [+] Connection failure on port 0 Traceback (most recent call last): File "./poo2.py", line 44, in find_port(i, args.HOST) File "./poo2.py", line 30, in find_port if s.connect((HOST, PORT)): File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 99] Cannot assign requested address
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50442203
tagged with: network-programming
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has title: Python Socket errors
tagged with: ports
downvote count: 0

http://stackoverflow.com/a/67498943
answers question: http://stackoverflow.com/q/50454857
score: 0
has body: You can perform sentence segmentation using trainable pipeline component in Spacy. https://spacy.io/api/sentencerecognizer Additionally, if you can come up with some pattern in the text string then use python regex lib re https://docs.python.org/3/library/re.html.
type: Answer

http://stackoverflow.com/a/50477570
has body: I see you're trying to put a string in "input_str". Have you already tried?: input_str = raw_input('Enter location: ') This type of method recieves a string as a input. The input of the method "input" must be a number Regards!
answers question: http://stackoverflow.com/q/50477528
type: Answer
score: -3
has comment: http://stackoverflow.com/comment/87968732
downvote count: 4
has comment: http://stackoverflow.com/comment/87970084
upvote count: 1

http://stackoverflow.com/a/56749504
downvote count: 1
has body: Full steps including file operations for beginners like me Assuming you have a .jsonl file like: {"reviewerID": "A2IBPI20UZIR0U", "asin": "1384719342", "reviewerName": "cassandra tu \"Yeah, well, that's just like, u...", "helpful": [0, 0], "reviewText": "Not much to write about here, but it does exactly what it's supposed to. filters out the pop sounds. now my recordings are much more crisp. it is one of the lowest prices pop filters on amazon so might as well buy it, they honestly work the same despite their pricing,", "overall": 5.0, "summary": "good", "unixReviewTime": 1393545600, "reviewTime": "02 28, 2014"} {"reviewerID": "A14VAT5EAX3D9S", "asin": "1384719342", "reviewerName": "Jake", "helpful": [13, 14], "reviewText": "The product does exactly as it should and is quite affordable.I did not realized it was double screened until it arrived, so it was even better than I had expected.As an added bonus, one of the screens carries a small hint of the smell of an old grape candy I used to buy, so for reminiscent's sake, I cannot stop putting the pop filter next to my nose and smelling it after recording. :DIf you needed a pop filter, this will work just as well as the expensive ones, and it may even come with a pleasing aroma like mine did!Buy this product! :]", "overall": 5.0, "summary": "Jake", "unixReviewTime": 1363392000, "reviewTime": "03 16, 2013"} This code should work: import json with open('./data/my_filename.jsonl', 'r') as json_file: json_list = list(json_file) for json_str in json_list: result = json.loads(json_str) print(f"result: {result}") print(isinstance(result, dict)) About .jsonl files: http://jsonlines.org/
score: 87
type: Answer
upvote count: 88
answers question: http://stackoverflow.com/q/50475635

http://stackoverflow.com/comment/87966162
score: 2
has text: A minimal working data set would be helpful. It sounds like your question is more complicated than you are stating. I am assuming that each admission date can have more than one drug administered during it. Depending on how your data is structured you can end up with all kinds of things going on. Definitely will need an example for this.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50476265

http://stackoverflow.com/q/50507735
duplicate of: http://stackoverflow.com/q/47152691
tagged with: pivot-table
tagged with: reshape
tagged with: python
accepted answer: http://stackoverflow.com/a/50508221
has body: I was looking for a while but i didn't find a solution for my problem ... I have a csv with the following structure: date_time, country, temp, dc 2018-01-01 00:00:00, Germany, 12, 0 ... 2018-01-01 00:00:00, Austria, 13, 3 ... 2018-01-01 00:00:00, France, 4, 9 ... as you can see, date_time will repeat. I want to use python pandas to get the following structure: | | Germany | Austria | France | | temp, dc | temp, dc | temp, dc ________________________________________________________ | 2018-01-01 00:00:00 | 12 , 0 | 13 , 3 | 4 , 9 I want to get two headers .. first separates the countries, second the attributes temp and dc. My index should be the date_time attribute. Thank you for help!!!
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50508221
tagged with: pandas
has title: Pandas rearrange DataFrame from long-form to wide-form
upvote count: 2
tagged with: pivot
possible better answer: http://stackoverflow.com/a/50507876
linked to: http://stackoverflow.com/q/47152691
downvote count: 2
has answer: http://stackoverflow.com/a/50507876
favorite count: 0
type: Question

http://stackoverflow.com/comment/87822012
has text: python is interpreted language and you called `sorting` function before it defined
comment on: http://stackoverflow.com/q/50403205
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87913894
has text: Edited, using four frames added to the questionnaire frame?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50449810

http://stackoverflow.com/a/50508902
has comment: http://stackoverflow.com/comment/88030513
type: Answer
has comment: http://stackoverflow.com/comment/88029777
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50508732
downvote count: 0
has body: You're calling write with a list, the error message is pretty straightforward. To make this work simply (but not necessarily correctly), you could convert the list to a string like so: database = open('database.csv', 'a') linetowrite = ['username', 'password', 'forename', 'surname', 'dob', 'artist', 'genre'] database.write(",".join(linetowrite)) database.close() Better would be to use a proper CSV library, e.g.: https://docs.python.org/3/library/csv.html . Otherwise you're likely to end up with escaping errors (what if one of your fields contains a comma?).

http://stackoverflow.com/a/50444295
has comment: http://stackoverflow.com/comment/87902487
downvote count: 1
has comment: http://stackoverflow.com/comment/87904063
type: Answer
has comment: http://stackoverflow.com/comment/87902727
answers question: http://stackoverflow.com/q/50444190
has body: Here's an example of finding words that appear more than once in a sentence: tokens = 'the quick brown fox jumps over the lazy dog'.split() print(set(filter(lambda x: tokens.count(x) &gt; 1, tokens))) # Output is 'the', which appears twice
has comment: http://stackoverflow.com/comment/87902676
score: 0
upvote count: 1

http://stackoverflow.com/comment/88030423
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50506175
has text: Maybe of interest: https://stackoverflow.com/questions/45026920/when-will-memory-get-freed-after-completing-the-request-on-app-engine-backend-in/45061554#45061554. Since then I switched all the way to the F4 class (similar app usage pattern) and couldn't be happier: app's faster, no memory worries and still well in the free instance hours quota (you'd be using ~12 instance h/day at the same usage pattern). Maybe worth a try.

http://stackoverflow.com/comment/88033722
has text: Just create a new environment in Anaconda and install the versions you need. You can then switch between the environments without having to downgrade.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50510560

http://stackoverflow.com/comment/136813182
type: Comment
comment on: http://stackoverflow.com/a/77546878
type: AnswerComment
has text: `location = loads(policeStation.location)` - where does the `loads` method come from here?
score: 0

http://stackoverflow.com/comment/88018337
type: Comment
type: QuestionComment
has text: refer to this solution: https://stackoverflow.com/a/45860443/2545197
comment on: http://stackoverflow.com/q/50503033
score: 0

http://stackoverflow.com/comment/88024110
score: 2
type: Comment
has text: I suggest to go with DB
type: QuestionComment
comment on: http://stackoverflow.com/q/50506046

http://stackoverflow.com/comment/88074126
has text: in my case i will predict tow classes 0 (negatif) and 1 (postive), so the target is the sentiment column and I have MultinomialNB().fit(X_train_counts, train['sentiment'])
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50518315
type: Comment

pendulum
tag name: pendulum
type: Tag
tags question: http://stackoverflow.com/q/50539215

http://stackoverflow.com/q/50519237
score: 0
has body: I have coded an authentication and I get an access token, but when I use it to grab an object I just end up getting 'NoneType' object is not callable. Exception Location: googleads\adwords.py in GetService, line 365 Exception Type: Type Error Exception Value: Internal Server Error: /oauth2callback I get the same result whether calling for Customer or CampaignService. I don't understand what I am doing wrong. I am following the code in Googleads. def getAdwordsFlow(): FLOW.redirect_uri = 'http://localhost/oauth2callback' # Generate URL for request to Google's OAuth 2.0 server. authorization_url, state = FLOW.authorization_url( access_type='offline', include_granted_scopes='true') return authorization_url def getAdwordsTokens(request): auth_code = request.GET.get('code') FLOW.fetch_token(code=auth_code) credentials = FLOW.credentials oauth2_client = oauth2.GoogleAccessTokenClient( FLOW.credentials.token, FLOW.credentials.expiry) adwords_client = adwords.AdWordsClient( "DEVELOPER-TOKEN", oauth2_client, "USER-AGENT", "CLIENT-CUSTOMER-ID") customer = adwords_client.GetService('CustomerService').getCustomers()[0] print('You are logged in as customer: %s' % customer['customerId']) return HttpResponseRedirect("/") url.py urlpatterns = [ re_path(r'^oauth2callback', queries.getAdwordsTokens, name='auth_calledback'),] #How view.py def index(request): return redirect(getAdwordsFlow()) Terminal output: "GET /oauth2callback?state=XXXXXXXXX&amp;code=4/XXXXXXXXXXX&amp;scope=https://www.googleapis.com/auth/adwords+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email HTTP/1.1" 500 80213 Why is it 500? I notice my access token has a different value when I call for it. So I am assuming it's working.
tagged with: oauth-2.0
tagged with: django
has answer: http://stackoverflow.com/a/50530661
tagged with: google-ads-api
answer count: 1
type: UnansweredQuestion
type: Question
tagged with: google-api-python-client
tagged with: python
has title: Basic Google API Oauth2 Authentication Setup Fails To Give Objects?

progress-bar
tags question: http://stackoverflow.com/q/50390838
tag name: progress-bar
tags question: http://stackoverflow.com/q/50496347
tags question: http://stackoverflow.com/q/50410327
type: Tag
tags question: http://stackoverflow.com/q/50455516

http://stackoverflow.com/comment/88083587
type: Comment
comment on: http://stackoverflow.com/q/50535733
has text: @mad_: That's the new-ish matrix multiplication operator.
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88347598
comment on: http://stackoverflow.com/q/50477638
score: 0
has text: What in-built queries are you referring to? Assuming custom SQL is not in use, then all queries are generated by Tableau and logged at run-time when the workbook is opened - they are not present in the workbook XML itself
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87857279
type: Comment
type: QuestionComment
has text: This isn't exactly what you asked for, but jsonschema might be helpful? https://pypi.org/project/jsonschema/
comment on: http://stackoverflow.com/q/50420987
score: 0

http://stackoverflow.com/comment/88046776
type: Comment
comment on: http://stackoverflow.com/a/50515847
type: AnswerComment
has text: If I read that C source correctly, it just opens the file and reads it each time (no line caching). So I guess your solution is the only reasonable fix.
score: 0

http://stackoverflow.com/comment/88046921
type: Comment
comment on: http://stackoverflow.com/a/50517155
type: AnswerComment
has text: OP provided no information or code on his backend, nor how the processing happens. Generalized questions can only receive generalized answers
score: 0

http://stackoverflow.com/a/50393218
answers question: http://stackoverflow.com/q/50393189
downvote count: 0
type: Answer
score: 4
has body: Use loc with : for select from start point to end: df = df.loc['cc':] print (df) a b c d cc 1 0 1 0 dd 0 0 0 0 ee 1 1 1 1 If possible duplicated values and need select by first value: print (df) a b c d aa 1 1 1 1 bb 0 0 0 0 cc 1 0 1 0 dd 0 0 0 0 cc 1 1 1 1 pos = df.index.get_loc('cc').argmax() #alternative #pos = df.index.searchsorted('cc') df = df.iloc[pos:] print (df) a b c d cc 1 0 1 0 dd 0 0 0 0 cc 1 1 1 1
accepted answer of: http://stackoverflow.com/q/50393189
type: AcceptedAnswer
upvote count: 4

http://stackoverflow.com/comment/87878255
has text: You should always create JSON using a JSON library, not do it by hand. This will ensure that it's in correct format.
comment on: http://stackoverflow.com/q/50431585
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50482110
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has title: How to get text of selected node using beautifulsoup
has answer: http://stackoverflow.com/a/50482808
has answer: http://stackoverflow.com/a/50482216
upvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/50482216
score: 2
type: AnsweredQuestion
has body: Using BeautifulSoup for the first time and not able to get the idea about how I can extract the text from some specific node. Here is my code html: ... ... once as the adjective abdrea (groups) twice as the noun shokdia (techs) ... python: current_page = urlopen(url) current_soup = BeautifulSoup(current_page, 'html.parser') derivative_list = current_soup.select('p.dsm + ul.also li') for li in derivative_list: print(li) output: once as the adjective abdrea (groups) twice as the noun shokdia (techs) Its outputting the correct list items, but what I want to get is text values of i.ab and span.at, something like desired output: abdrea, groups shokdia, techs
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50482808

http://stackoverflow.com/a/50401998
has comment: http://stackoverflow.com/comment/87896899
score: 11
has comment: http://stackoverflow.com/comment/87904684
has body: Yes, you can use the HTTP header Authorization: Bearer &lt;access_token&gt; with requests or any library you want. Service account from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file( 'services.json', scopes=['https://www.googleapis.com/auth/devstorage.read_only'], ) # Copy access token bearer_token = credentials.token User account credentials import json from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow flow = InstalledAppFlow.from_client_secrets_file( 'test.json', 'https://www.googleapis.com/auth/devstorage.read_only' ) # Construct cache path for oauth2 token oauth2_cache_path = 'test-oauth2.json' credentials = None try: # Try to load existing oauth2 token with open(oauth2_cache_path, 'r') as f: credentials = Credentials(**json.load(f)) except (OSError, IOError) as e: pass if not credentials or not credentials.valid: credentials = flow.run_console() with open(oauth2_cache_path, 'w+') as f: f.write(json.dumps({ 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes, })) # Copy access token bearer_token = credentials.token Use requests lib import requests # Send request response = requests.get( 'https://www.googleapis.com/storage/v1/&lt;endpoint&gt;?access_token=%s' % bearer_token) # OR response = requests.get( 'https://www.googleapis.com/storage/v1/&lt;endpoint&gt;', headers={'Authorization': 'Bearer %s' % bearer_token}) Use googleapiclient lib I recommend you to use build() method and not requests directly because the google library do some checks before sending your API call (like checking params, endpoint, auth and the method you use). This library also raise exceptions when error is detected. from googleapiclient.discovery import build storage = build('storage', 'v1', credentials=credentials…
has comment: http://stackoverflow.com/comment/87967122
has comment: http://stackoverflow.com/comment/87976663
has comment: http://stackoverflow.com/comment/87968763
type: Answer
has comment: http://stackoverflow.com/comment/87968821
has comment: http://stackoverflow.com/comment/87969020
upvote count: 11
downvote count: 0
answers question: http://stackoverflow.com/q/50401755

http://stackoverflow.com/a/50442995
accepted answer of: http://stackoverflow.com/q/50442803
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/87900768
has body: You can go for udf import pyspark.sql.functions as F df = sqlContext.sql('select * from --db--.vt_prof_test') REQUEST = 'STRING' request_bc = sc.broadcast(REQUEST) def check_value(val): if request_bc.value == 'STRING': try: val = int(val) return None except: return val if request_bc.value == 'INTEGER': try: val = int(val) return val except: return None check_udf = F.udf(lambda x: check_value(x)) df = df.select(check_udf(F.col('col_str_1').alias('col_str_1')).dropna() Set the REQUEST parameter according to the need.
answers question: http://stackoverflow.com/q/50442803
score: 0

http://stackoverflow.com/comment/87918565
type: Comment
has text: This is absolutely what I was looking for. Thanks a lot @WiktorStribiżew and the others
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50450985

http://stackoverflow.com/comment/88031964
type: QuestionComment
has text: If you really need a widget common to all tabs, did you consider putting the widget outside of the Tabs object?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50499390

http://stackoverflow.com/comment/87948704
score: 0
has text: I know that issue is because of I am not instantiating the Class object ,
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50467804

http://stackoverflow.com/comment/87793925
comment on: http://stackoverflow.com/q/50388366
score: 0
type: Comment
type: QuestionComment
has text: without any argument i m just doing `pd.read_csv('sample.csv')`

http://stackoverflow.com/comment/88118654
comment on: http://stackoverflow.com/a/50540242
score: 0
type: Comment
has text: I'm referring to df1 = pd.DataFrame([9337, 2953, 8184], index=[49, 127, 84], columns=['Tot']) If I were to use slicing how would I accomodate for it? Refer to my slicing iloc data in my question. Cheers
type: AnswerComment

http://stackoverflow.com/comment/87962248
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50473197
has text: @WillemVanOnsem That's in the case that the variable is assigned a model instance of the parent class. In which case, _set is used to get a reverse relationship and directly access the model field. In the case of a lookup, which is what I'm doing, you don't need _set, you simply include the names of the classes https://docs.djangoproject.com/en/2.0/topics/db/queries/#lookups-that-span-relationships
score: 0

http://stackoverflow.com/comment/88051391
has text: Thank you that is the answer that solved it. Thank you so much for your quick reply.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50519373
type: AnswerComment

http://stackoverflow.com/a/50394085
accepted answer of: http://stackoverflow.com/q/50392783
upvote count: 8
type: Answer
has body: In SGD, if you use 'epsilon_insensitive' with epsilon=0 it should work as if you used MAE. You could also take a look at statsmodels quantile regression (using MAE is also called median regression, and median is a quantile).
score: 8
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50392783

http://stackoverflow.com/q/50474674
accepted answer: http://stackoverflow.com/a/50480107
score: 0
has body: I really like to have 2D representation of activation functions in tensor flow. for example, plotting : (tf.nn.sigmoid( for a range of inputs, something like the image: plot
answer count: 1
upvote count: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0
tagged with: plot
type: Question
type: AnsweredQuestion
tagged with: representation
has title: How to plot Tensor flow activation functions in a range of inputs
tagged with: python
has answer: http://stackoverflow.com/a/50480107

http://stackoverflow.com/a/50538421
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50538248
has body: You assign top inside the function main which means it doesn't exist outside that function and therefore the function secondary can not find it. You can change the scope of top with global: def main(): global top ... Also; you sholuld take a look at Best way to structure a tkinter application

http://stackoverflow.com/a/50451354
has comment: http://stackoverflow.com/comment/87990603
has comment: http://stackoverflow.com/comment/101698462
upvote count: 14
has comment: http://stackoverflow.com/comment/122663730
has comment: http://stackoverflow.com/comment/101697564
has comment: http://stackoverflow.com/comment/101707795
has comment: http://stackoverflow.com/comment/101697781
has comment: http://stackoverflow.com/comment/101681204
answers question: http://stackoverflow.com/q/50410037
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/122654497
score: 14
has body: Scikit-learn does not allow such constraints on the coefficients. But you can impose any constraints on coefficients and optimize the loss with coordinate descent if you implement your own estimator. In the unconstraint case, coordinate descent produces the same result as OLS in reasonable number of iterations. I've written a class that imposes upper and lower bounds on LinearRegression coefficients. You can extend it to use Ridge or evel Lasso penalty if you want: from sklearn.linear_model.base import LinearModel from sklearn.base import RegressorMixin from sklearn.utils import check_X_y import numpy as np class ConstrainedLinearRegression(LinearModel, RegressorMixin): def __init__(self, fit_intercept=True, normalize=False, copy_X=True, nonnegative=False, tol=1e-15): self.fit_intercept = fit_intercept self.normalize = normalize self.copy_X = copy_X self.nonnegative = nonnegative self.tol = tol def fit(self, X, y, min_coef=None, max_coef=None): X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], y_numeric=True, multi_output=False) X, y, X_offset, y_offset, X_scale = self._preprocess_data( X, y, fit_intercept=self.fit_intercept, normalize=self.normalize, copy=self.copy_X) self.min_coef_ = min_coef if min_coef is not None else np.repeat(-np.inf, X.shape[1]) self.max_coef_ = max_coef if max_coef is not None else np.repeat(np.inf, X.shape[1]) if self.nonnegative: self.min_coef_ = np.clip(self.min_coef_, 0, None) beta = np.zeros(X.shape[1]).astype(float) prev_beta = beta + 1 hessian = np.dot(X.transpose(), X) while not (np.abs(prev_beta - beta)&lt;self.tol).all(): prev_beta = beta.copy() for i in range(len(beta)): grad = np.dot(np.dot(X,beta) - y, X) beta[i] = np.minimum(self.max_coef_[i], np.maximum(self.min_coef_[i], beta[i]-grad[i] / hessian[i,i])) self.coef_ = beta self._set_intercept(X_offset, y_offset, X_scale) return self You can use this class, for example, to make all coefficients non-negative from sklearn.datasets import load_boston from sklearn.linear_…

http://stackoverflow.com/a/50418446
has body: I solved my problem. Here the code: from selenium import webdriver from selenium.webdriver.firefox.options import Options as FirefoxOptions from selenium.webdriver.chrome.options import Options as ChromeOptions def connectChrome(): options = ChromeOptions() options.add_argument("--headless") chromeDriverPath = "/usr/bin/chromedriver" driver = webdriver.Chrome(chromeDriverPath, chrome_options=options) print("Chrome Headless Browser Invoked") return driver def connectFirefox(): options = FirefoxOptions() options.add_argument("--headless") driver = webdriver.Firefox(firefox_options=options) print("Firefox Headless Browser Invoked") return driver def main(): #driver = connectChrome() driver = connectFirefox() driver.get("https://www.archlinux.org/") print("Headless Browser closing") driver.quit() #------------------------------------------------------------------------# main()
upvote count: 16
type: Answer
answers question: http://stackoverflow.com/q/50414007
downvote count: 0
score: 16

http://stackoverflow.com/q/50414338
tagged with: telegram
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64014093
has title: Python3 ERROR:no module named telebot after pip installed it
tagged with: python
has body: python 3.5.2 // Ubuntu 16.04 LTS I've installed pyTelegramBotAPI to code bots for telegram using this command: pip instal pyTelegramBotAPI Result: Collecting pyTelegramBotAPI Requirement already satisfied: six in /home/username/.local/lib/python2.7/site-packages (from pyTelegramBotAPI) (1.11.0) Collecting requests (from pyTelegramBotAPI) Using cached https://files.pythonhosted.org/packages/49/df/50aa1999ab9bde74656c2919d9c0c085fd2b3775fd3eca826012bef76d8c/requests-2.18.4-py2.py3-none-any.whl Collecting certifi&gt;=2017.4.17 (from requests-&gt;pyTelegramBotAPI) Using cached https://files.pythonhosted.org/packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl Collecting chardet&lt;3.1.0,&gt;=3.0.2 (from requests-&gt;pyTelegramBotAPI) Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl Collecting idna&lt;2.7,&gt;=2.5 (from requests-&gt;pyTelegramBotAPI) Using cached https://files.pythonhosted.org/packages/27/cc/6dd9a3869f15c2edfab863b992838277279ce92663d334df9ecf5106f5c6/idna-2.6-py2.py3-none-any.whl Collecting urllib3&lt;1.23,&gt;=1.21.1 (from requests-&gt;pyTelegramBotAPI) Using cached https://files.pythonhosted.org/packages/63/cb/6965947c13a94236f6d4b8223e21beb4d576dc72e8130bd7880f600839b8/urllib3-1.22-py2.py3-none-any.whl Installing collected packages: certifi, chardet, idna, urllib3, requests, pyTelegramBotAPI Then, I imported it into my source code: import telebot However, when I run the code I get the following error: Traceback (most recent call last): File "firstBot.py", line 1, in &lt;module&gt; import telebot ImportError: No module named 'telebot'
tagged with: py-telegram-bot-api
has comment: http://stackoverflow.com/comment/87845201
tagged with: bots
upvote count: 2
score: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87847869
downvote count: 0
has comment: http://stackoverflow.com/comment/87844656
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87841898
comment on: http://stackoverflow.com/q/50413021
type: Comment
type: QuestionComment
has text: I am sorry.I forgot to show what happens when I run my script.My script is just create a simple graph with two nodes and try to get the list of them.What I received is:TypeError:unhashable type: 'slice'
score: 0

http://stackoverflow.com/comment/87967290
comment on: http://stackoverflow.com/q/50475815
has text: @PaulMcG Thank you for your help, but still, I am not getting the expected result.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88069924
type: QuestionComment
has text: Could you please share an example of your input data before groupby?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50528833

http://stackoverflow.com/comment/87800540
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50392272
has text: Something wrong with arguments of `doc = word.Documents.Open(in_file, 'rb')`... Is `'rb'` really needed?
score: 0

bipartite
type: Tag
tags question: http://stackoverflow.com/q/50397442
tag name: bipartite

http://stackoverflow.com/comment/87858884
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50421623
type: QuestionComment
has text: The definition is inside another definition. The definition that it is inside of it is basically just a definition to hold all of the buttons, labels and images for a Toplevel() window.

http://stackoverflow.com/a/50500373
type: Answer
has comment: http://stackoverflow.com/comment/88034781
downvote count: 0
upvote count: 1
has body: cumcount c = 'Customer Number' df.set_index([c, df.groupby(c).cumcount() + 1]).unstack().sort_index(1, 1) Date Salaries Date Salaries Date Salaries 1 1 2 2 3 3 Customer Number 1 2013.0 100.0 2014.0 200.0 2015.0 200.0 2 2016.0 300.0 2017.0 300.0 NaN NaN 3 2013.0 4000.0 2014.0 5000.0 2015.0 5000.0
answers question: http://stackoverflow.com/q/50500057
score: 1

http://stackoverflow.com/q/50536967
favorite count: 0
type: Question
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/1419046
tagged with: python
type: AnsweredQuestion
has body: I have the following user model, class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=False, unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) is_bot = models.BooleanField(default=False) I want to create a custom command which could work like createsuperuser and creates a bot. I have created a management package in the relevant app and added a command package inside that and a file createbot.py inside of that. This is my code inside createbot.py class Command(BaseCommand): def handle(self, email, username=None, password=None): user = User.objects.create(email, username=username, password=password, is_staff=True, is_superuser=True, is_active=True, is_bot=True ) self.stdout.write(self.style.SUCCESS('Successfully create user bot with id: {}, email: {}'.format(user.id, user.email))) I want this to work exactly like createsuper user giving me prompts to enter email, name and the works. But when I run it, I get the following, TypeError: handle() got an unexpected keyword argument 'verbosity' How can I get this to work?
has answer: http://stackoverflow.com/a/50537033
has title: Creating custom commands in django
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88086091
tagged with: django
has comment: http://stackoverflow.com/comment/88086322
accepted answer: http://stackoverflow.com/a/50537033

http://stackoverflow.com/comment/87811151
type: QuestionComment
comment on: http://stackoverflow.com/q/50394519
type: Comment
has text: You may have to use an image editor to show desired result as it is not clear.
score: 0

http://stackoverflow.com/comment/88424757
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50478637
has text: I should clarify that my previous comment incorrectly mentions iSeriesPython. OP was using the term "iSeriesPython" without realizing that it means something other than IBM's Python for PASE. The rest of my comment still stands.
type: AnswerComment

http://stackoverflow.com/q/50412290
has comment: http://stackoverflow.com/comment/87840518
has answer: http://stackoverflow.com/a/50412569
has comment: http://stackoverflow.com/comment/87840584
tagged with: excel
tagged with: iterable
type: Question
has title: How to handle another Excel file in Python
has comment: http://stackoverflow.com/comment/87840862
tagged with: nonetype
possible better answer: http://stackoverflow.com/a/50587426
tagged with: python
has answer: http://stackoverflow.com/a/50587426
has comment: http://stackoverflow.com/comment/87840686
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87840160
answer count: 2
tagged with: pandas
has body: Good Morning. I'm starting with Python and I have a problem. I need to find all .xls files (all have the same header) and merge all into a single DataFrame, so I need to say that the first line of the file should be ignored. The current code I'm using is this: os.chdir("file folder path") fileLista = glob.glob('*.xls') df = list() for arquivo in fileLista: df = df.append(pd.read_excel(arquivo)) Company= pd.concat(df) Company.columns = Company.columns.str.strip() I am using Glob to return all the .xls extension files, df.append is to merge all the files that have been returned and put inside a DataFrame, Company concat is to form a single file, Company strip is to remove the spaces that it has in the column header. When I run the code it returns me this error: "erro NoneType' object is not iterable" Can anyone help me with this mistake?
accepted answer: http://stackoverflow.com/a/50412569

http://stackoverflow.com/comment/87791837
type: QuestionComment
score: 2
has text: You say by the end: *I'm getting:*: can you provide the original text to test?
comment on: http://stackoverflow.com/q/50387231
type: Comment

http://stackoverflow.com/q/50440398
has title: Why does `numpy.ndarray.view` ignore a previous call to `numpy.ndarray.newbyteorder`?
has comment: http://stackoverflow.com/comment/87895362
favorite count: 0
type: Question
tagged with: numpy
tagged with: binary
has body: I have a NumPy array with one element of data type uint32: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([123456789], dtype=np.uint32) &gt;&gt;&gt; a.dtype.byteorder '=' Then, I can choose to interpret the data as little-endian: &gt;&gt;&gt; a.newbyteorder("&lt;").dtype.byteorder '&lt;' &gt;&gt;&gt; a.newbyteorder("&lt;") array([123456789], dtype=uint32) Or as big-endian: &gt;&gt;&gt; a.newbyteorder("&gt;").dtype.byteorder '&gt;' &gt;&gt;&gt; a.newbyteorder("&gt;") array([365779719], dtype=uint32) Where the latter returns a different number 365779719 as my platform is little-endian - and therefore has been written to the memory in little-endian order. Now, what's unexpected for me is the fact that a following appended call to view seems to be unaffected by this interpretation: &gt;&gt;&gt; a.newbyteorder("&lt;").view(np.uint8) array([ 21, 205, 91, 7], dtype=uint8) &gt;&gt;&gt; a.newbyteorder("&gt;").view(np.uint8) array([ 21, 205, 91, 7], dtype=uint8) I would have expected the numbers to be the other way round for the big-endian byte order. Why doesn't this happen? Doesn't view view the data "through" the newbyteorder method? By the way: if I use byteswap instead of newbyteorder and therefore copy and change the bytes in the memory, I obviously get the desired result: &gt;&gt;&gt; a.byteswap("&lt;").view(np.uint8) array([ 21, 205, 91, 7], dtype=uint8) &gt;&gt;&gt; a.byteswap("&gt;").view(np.uint8) array([ 7, 91, 205, 21], dtype=uint8) However, I don't want to copy the data.
tagged with: python
has answer: http://stackoverflow.com/a/50493713
tagged with: endianness
accepted answer: http://stackoverflow.com/a/50493713
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50440560
has answer: http://stackoverflow.com/a/50440455
possible better answer: http://stackoverflow.com/a/50440455
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87895382

http://stackoverflow.com/q/50433378
tagged with: multidimensional-array
has body: I'm quite new to programming in general, but I could not figure this problem out until now. I've got a two-dimensional numpy array mask, lets say mask.shape is (3800,3500)which is filled with 0s and 1s representing a spatial resolution of a 2D image, where a 1 represents a visible pixel and 0 represents background. I've got a second two-dimensional array data of data.shape is (909,x) where x is exactly the amount of 1s in the first array. I now want to replace each 1 in the first array with a vector of length 909 from the second array. Resulting in a final 3D array of shape(3800,3500,909) which is basically a 2D x by y image where select pixels have a spectrum of 909 values in z direction. I tried mask_vector = mask.flatten ones = np.ones((909,1)) mask_909 = mask_vector.dot(ones) #results in a 13300000 by 909 2d array count = 0 for i in mask_vector: if i == 1: mask_909[i,:] = data[:,count] count += 1 result = mask_909.reshape((3800,3500,909)) This results in a viable 3D array giving a 2D picture when doing plt.imshow(result.mean(axis=2)) But the values are still only 1s and 0s not the wanted spectral data in z direction. I also tried using np.where but broadcasting fails as the two 2D arrays have clearly different shapes. Has anybody got a solution? I am sure that there must be an easy way...
upvote count: 1
tagged with: python
has title: Numpy 2D spatial mask to be filled with specific values from a 2D array to form a 3D structure
type: AnsweredQuestion
tagged with: array-broadcasting
has comment: http://stackoverflow.com/comment/87881325
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50433680
score: 1
has answer: http://stackoverflow.com/a/50433680
has comment: http://stackoverflow.com/comment/87881306
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/q/50477800
downvote count: 0
has comment: http://stackoverflow.com/comment/87969290
tagged with: python
has comment: http://stackoverflow.com/comment/87969564
has body: I'm following the directions Spacy gives to install for Windows, Python 3, and from source (pip and conda have both given me errors that I've still been unable to resolve, directly from source seems to get the closest to actually installing). However, when I get to step 3 and enter export PYTHONPATH = pwd in the command line (with the quotes around pwd like it wants, it just messes up the formatting here), I get this error message: export is not recognized as an internal or external command, operable program, or batch file. I've read that how to fix this error in the past is to add a path through the environmental variables option, however I'm not sure what that would look like here. I'm not sure what pwd is on my computer or how to get a path to it. I have the newest version of python 3 (just downloaded today), as well as microsoft visual studio, which is apparently needed for using Spacy. Any help would be greatly appreciated. Thanks!
has comment: http://stackoverflow.com/comment/87969318
has comment: http://stackoverflow.com/comment/87969337
answer count: 1
has comment: http://stackoverflow.com/comment/87969529
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87969522
has answer: http://stackoverflow.com/a/50478036
favorite count: 0
type: Question
has title: Installing Spacy for NLP with Python 3 & Windows gives error when installing from source
tagged with: python-3.x
tagged with: spacy
type: UnansweredQuestion

http://stackoverflow.com/comment/87806982
type: Comment
type: QuestionComment
has text: The first answer you linked to worked for me (Python v3.6.1). What exactly didn't work for you with the code in the first answer? What does _". . . fewer modules are printed . . ."_ mean?
comment on: http://stackoverflow.com/q/50395556
score: 1

http://stackoverflow.com/a/50440296
has comment: http://stackoverflow.com/comment/87907742
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87903396
has body: Here's a different approach that you can dismiss if you believe if differs from your pixel movement method. Since there is a maximum of eight possible movements to neighboring pixels in a 2-dimensional pixel array, you can define a constant list of movements and pair them up with an index that refers to the pixel resulting from said movement. From my interpretation of your code, this is something you could define in the __init__ method of your pixel class. Set up: changes_1d = (-1, 0, 1) changes_2d = [(i,j) for j in changes_1d for i in changes_1d if i or j] self.movements = tuple(enumerate(changes_2d)) # Assign pixel index to each movement Contents of self.movements: 0 (-1, -1) 1 (0, -1) 2 (1, -1) 3 (-1, 0) 4 (1, 0) 5 (-1, 1) 6 (0, 1) 7 (1, 1) Why set this up? Now we can make use of random.choice() to quickly select a random 2-D pixel movement, and we can check whether this move is valid by using the index returned alongside the (dx, dy) movement pair: def move(self): s = self.surrounding() surroundingBool = [i is not None for i in s] pixel, movement = random.choice(self.movements) if surroundingBool[pixel]: self.x += movement[0] self.y += movement[1] NOTE: This assumes that there is an equal probability of moving to any one of the eight surrounding pixels. However, I believe that there may also be a great deal of inefficiency with the self.surrounding() function, particularly in this line: PAI = allPixels[(self.x + x) % width][(self.y + y) % height] if allPixels[(self.x + x) % width][(self.y + y) % height] != None else None You are checking whether the pixel is not None, then assigning it to PAI. Although if it is None, you assign None to PAI, making the if else check redundant. The following statement is equivalent: PAI = allPixels[(self.x + x) % width][(self.y + y) % height] I would offer more recommendations, but there is plenty of code there to make sense of. Keep searching for ways to make improvements!
accepted answer of: http://stackoverflow.com/q/50439611
has comment: http://stackoverflow.com/comment/87926460
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87903684
upvote count: 1
answers question: http://stackoverflow.com/q/50439611

http://stackoverflow.com/a/54542874
has body: Actually, there is no need to downgrade the MYSQL Server. Follow these two steps and it should work: Step 1: Change MYSQL configuration to use mysql_native_password. Edit one of ini files that mysqld is using. You can see which one my using the command mysqld --verbose --help and make sure this line is added - default-authentication-plugin=mysql_native_password Step 2: Create an new or alter the existing user. To create a new with mysql_native_password password: CREATE USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password'; and to alter user ALTER USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password'; By the way, this step is also pointed out by @Kol_ya
answers question: http://stackoverflow.com/q/50469587
downvote count: 1
score: 9
has comment: http://stackoverflow.com/comment/114458503
type: Answer
has comment: http://stackoverflow.com/comment/97078630
upvote count: 10

http://stackoverflow.com/comment/88053902
has text: There is also `float('inf')`
comment on: http://stackoverflow.com/a/50520829
type: Comment
type: AnswerComment
score: 1

dynamic-class-creation
type: Tag
tag name: dynamic-class-creation
tags question: http://stackoverflow.com/q/50394083

http://stackoverflow.com/q/50533472
tagged with: django
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50533680
type: UnansweredQuestion
tagged with: django-authentication
tagged with: python
has body: I have a django server which acts as an API (i.e. listens to requests and returns data ONLY), and I want this API to be accessible only to authenticated users. I read about the django authentication system, and tried to implement it according to the documentation (https://docs.djangoproject.com/en/2.0/topics/auth/default/). I wrote a small web-page just to test the authentication - login was successful (server was able to authenticate and login the user), but when attempting to reach a restricted view I have no access, and the request.user received is an AnonymousUser instead of the logged in user. I am using Python 3.6.5 and Django 2.0.4 Server code: @csrf_exempt def dologin(request): username = request.POST.get('username') password = request.POST.get('password') if not username or not password: return HttpResponse('missing username or password', status=400) user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponse(user) else: return HttpResponse('bad credentials', status=422) def dologout(request): logout(request) return HttpResponse('success') @login_required() def testAccess(request): return HttpResponse('ok') def checkUser(request): u = "anonymous" if not request.user.is_authenticated else request.user.username return HttpResponse(u) Client code: username: username: login logout test access check user (I'm running everything locally, that's why I use 10.0.0.9 which is my pc's ip) As i wrote before - after a successful login, clicking 'test access' results in a 404 response, and clicking 'check user' returns 'anonymous' (and by debugging the server I know the user is indeed AnonymousUser)
has title: python - django autentication - anonymous user after login
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88082489
has comment: http://stackoverflow.com/comment/88079191
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50539277
answer count: 0
score: 1
upvote count: 1
has body: I am a beginner of deep learning programmer. I have been having problems for two days. I've seen a lot of similar problems, but I have not solved my problems. I need your help. I tried to debug the dimensions of the tensor, but the following error message appears. (Network layer) with self._model_variable_scope(): if self.data_format == 'channels_first': # Convert the inputs from channels_last (NHWC) to channels_first (NCHW). # This provides a large performance boost on GPU. See # https://www.tensorflow.org/performance/performance_guide#data_formats self.input_imgs = tf.transpose(self.input_imgs, [0, 3, 1, 2]) self.input_imgs = conv2d_fixed_padding( inputs=self.input_imgs, filters=self.num_filters, kernel_size=self.kernel_size, strides=self.conv_stride, data_format=self.data_format) self.input_imgs = tf.identity(self.input_imgs, 'initial_conv') # We do not include batch normalization or activation functions in V2 # for the initial conv1 because the first ResNet unit will perform these # for both the shortcut and non-shortcut paths as part of the first # block's projection. Cf. Appendix of [2]. if self.resnet_version == 1: self.input_imgs = batch_norm(self.input_imgs, self.training, self.data_format) self.input_imgs = tf.nn.relu(self.input_imgs) if self.first_pool_size: self.input_imgs = tf.layers.max_pooling2d( inputs=self.input_imgs, pool_size=self.first_pool_size, strides=self.first_pool_stride, padding='SAME', data_format=self.data_format) self.input_imgs = tf.identity(self.input_imgs, 'initial_max_pool') for i, num_blocks in enumerate(self.block_sizes): num_filters = self.num_filters * (2 ** i) self.input_imgs = block_layer( inputs=self.input_imgs, filters=num_filters, bottleneck=self.bottleneck, block_fn=self.block_fn, blocks=num_blocks, strides=self.block_strides[i], training=self.training, name='block_layer{}'.format(i + 1), data_format=self.data_format) # Only apply the BN and ReLU for model that does pre_activation in each # building/bottleneck block, eg re…
tagged with: tensorflow
favorite count: 0
has title: tensorflow , feed_dict error , ValueError: Cannot feed value of shape
has comment: http://stackoverflow.com/comment/88097251
has comment: http://stackoverflow.com/comment/88155934
type: Question
has comment: http://stackoverflow.com/comment/88358997
tagged with: python
type: UnansweredQuestion
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/88091905
downvote count: 0

pytorch
tags question: http://stackoverflow.com/q/50471886
tags question: http://stackoverflow.com/q/50435310
tags question: http://stackoverflow.com/q/50420168
tags question: http://stackoverflow.com/q/50440391
tags question: http://stackoverflow.com/q/50412235
tags question: http://stackoverflow.com/q/50438738
tags question: http://stackoverflow.com/q/50425739
tags question: http://stackoverflow.com/q/50432506
tags question: http://stackoverflow.com/q/50424167
tags question: http://stackoverflow.com/q/50539641
tags question: http://stackoverflow.com/q/50391703
tags question: http://stackoverflow.com/q/50450800
tags question: http://stackoverflow.com/q/50414900
tags question: http://stackoverflow.com/q/50532286
tags question: http://stackoverflow.com/q/50511212
tags question: http://stackoverflow.com/q/50405832
tags question: http://stackoverflow.com/q/50454645
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/50475094
tags question: http://stackoverflow.com/q/50495053
tags question: http://stackoverflow.com/q/50463975
tags question: http://stackoverflow.com/q/50488869

http://stackoverflow.com/comment/87891228
type: Comment
type: QuestionComment
has text: I don't think you need to use `.encode` if you specify the encoding of the whole file.
comment on: http://stackoverflow.com/q/50438606
score: 1

http://stackoverflow.com/q/50515397
tagged with: flask
has title: Python Flask - avoid posting on dynamic table return to render template
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25983603
has body: I have this python app using flask having this core routes: @app.route('/test_limit', defaults={'page':1}) @app.route('/test_limit/page/<int:page>') def test_results_limit(page): perpage=10 startat=page*perpage results = [] cursor = db.cursor() cursor.execute('SELECT * from pi_fb_limit limit %s, %s;', (startat,perpage)) table = list(cursor.fetchall()) return render_template('results_limits.html', table=table) @app.route('/infringement/FB/<int:id>') def infringement(id): cursor = db.cursor() cursor.execute('UPDATE p_test_search SET infringement = ''TRUE'' WHERE ID = %s', (id)) db.commit() return render_template('results_limits.html') In my HTML file "result_limits.html" I have this HTML code iterating MySQL resoult: {% for tab in table %} {{tab[0]}} {{tab[9]}} Infringement {% endfor %} All is working fine but my problem is that when the button above dinamically call the route @app.route('/infringement/FB/'), browser is redirected to result_limits.html. Instead I'd like to avoid any redirection and remain on the same page each row button is creating post (to update records). Any suggestion? Thank you Regs SL
upvote count: 0
answer count: 1
tagged with: mysql
downvote count: 1
duplicate of: http://stackoverflow.com/q/25983603
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50515782
has answer: http://stackoverflow.com/a/50515782
tagged with: python
score: -1

http://stackoverflow.com/q/50417148
favorite count: 0
type: Question
has title: django admin: exclude not working in change_form
answer count: 0
upvote count: 2
tagged with: django-admin
type: UnansweredQuestion
has body: I have the following admin class: from django.contrib import admin class CommandAdmin (admin.ModelAdmin): list_display = ('name','status','get_requester', 'justification') readonly_fields = ('name','status','get_requester', 'request', 'justification') exclude = ('request',) def get_requester(self,obj): return obj.request.requester get_requester.command_order_field = 'requester' #Allows column order sorting get_requester.short_description = 'Who Requested' #Renames column head def get_form(self, request, obj=None, **kwargs): self.exclude = ['request'] form = super(CommandAdmin, self).get_form(request, obj, **kwargs) return form def get_queryset(self, request): print request qs = super(CommandAdmin, self).get_queryset(request).select_related('request') return qs.filter(status='pending', request__isnull=False) The Command model looks like this ... class Command(models.Model): ... bunch of fields ... justification = models.CharField(max_length=2000, blank=True, null=True) request = models.ForeignKey('sudorequests.Request', blank=True, null=True) When I get to the change form the 'Request' object still appears on the form. Here's a screen shot:
downvote count: 0
tagged with: django
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/87850207
has comment: http://stackoverflow.com/comment/87850172

http://stackoverflow.com/a/50406447
downvote count: 0
answers question: http://stackoverflow.com/q/50406312
upvote count: 3
score: 3
has body: Using a simple for-loop Demo: authors_firstName = [] authors_lastName = [] with open(filename, "r") as infile: for i in infile.readlines(): val = i.strip().split("-")[-1].strip().split(",") #str.strip to remove any leading or trailing space, split by "-" authors_firstName.append(val[0]) authors_lastName.append(val[1]) print(authors_firstName) print(authors_lastName) Output: ['Jordan', 'Thomson', 'Einstein', 'Tesla', 'Agassi', 'Herbert', 'Agut'] [' M.', ' J.J.', ' A.', ' N.', ' A.', ' P.H.', ' R.B.']
type: Answer

http://stackoverflow.com/a/50403647
answers question: http://stackoverflow.com/q/50403549
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: Using map df.income=df.income.map({'&lt;=50':0,'&gt;50':1}) df Out[328]: age gender edu income 0 15 m MS 0 1 16 f BS 1 2 17 m BS 0
has comment: http://stackoverflow.com/comment/87823505

http://stackoverflow.com/comment/87817215
has text: There's just one possible flaw with the way you read your file. If there is a comma next to a word, it would process it as a different word because of `.split()`. i.e. if you have `Word1 Word2 Word1,`, this would yield `['Word1', 'Word2', 'Word1,']`
type: AnswerComment
comment on: http://stackoverflow.com/a/50399642
score: 0
type: Comment

http://stackoverflow.com/comment/87946832
comment on: http://stackoverflow.com/a/50406708
score: 0
has text: Thanks for this elegant, versatile solution. Works like a charm!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87866452
type: QuestionComment
type: Comment
score: 0
has text: why DAG? it is a binary tree and i want to find all the paths in the binary tree( root to leaf, leaf to leaf, etc.)
comment on: http://stackoverflow.com/q/50425656

http://stackoverflow.com/comment/126777286
type: QuestionComment
has text: https://stackoverflow.com/a/61084589/7508077
comment on: http://stackoverflow.com/q/50461779
score: 0
type: Comment

http://stackoverflow.com/q/50490569
has answer: http://stackoverflow.com/a/50490607
tagged with: python
accepted answer: http://stackoverflow.com/a/50490607
linked to: http://stackoverflow.com/q/3819449
tagged with: macos
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/3819449
has body: I have install python 3.6.5 (With brew) and when I execute python command in a shell, it is always python 2.7 that come. I have executed these command see in an other post but nothing work: Remove the third-party Python 2.7 framework sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7 Remove the Python 2.7 applications directory sudo rm -rf "/Applications/Python 2.7" Remove the symbolic links in /usr/local/bin that point to this Python version see ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' and then run the following command to remove all the links: cd /usr/local/bin/ ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
answer count: 1
downvote count: 0
upvote count: 1
has title: How to uninstall definitely python 2.7 on MacOS
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87994032
score: 1

http://stackoverflow.com/comment/87882343
comment on: http://stackoverflow.com/a/50434107
type: Comment
score: 0
has text: @Tomble: It is added according to your code and tested it worked. Let me know if it solves your issue. ?
type: AnswerComment

http://stackoverflow.com/q/50428429
has body: I'm working on a school project and it specifically asks for a while not end-of-file loop which I don't know how to do in Python. I'm taking in user input (not from an external file) and computing some math in this infinite loop until they CTRL+C to break the loop. Any thoughts would really help me out. I've added part of the instruction if that helps clarify. Thanks.
has answer: http://stackoverflow.com/a/50428889
tagged with: loops
has title: While(!EOF()) equivalent in Python
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/10140281
has answer: http://stackoverflow.com/a/50428502
score: 0
has comment: http://stackoverflow.com/comment/87871623

http://stackoverflow.com/a/50416957
type: AcceptedAnswer
downvote count: 0
has body: DRF's GenericAPIView has a get_queryset method that you can override to perform custom filtering: def get_queryset(self): qs = super(YourView, self).get_queryset() return self.filter_queryset_for_user(qs, request.user) def filter_queryset_for_user(self, qs, user): pass # Your logic here This is not necessarily a bad idea; DRF docstrings recommend overriding this: You may want to override this if you need to provide different querysets depending on the incoming request.
score: 2
has comment: http://stackoverflow.com/comment/87893097
accepted answer of: http://stackoverflow.com/q/50414750
type: Answer
answers question: http://stackoverflow.com/q/50414750
has comment: http://stackoverflow.com/comment/87904362
upvote count: 2

http://stackoverflow.com/q/50447533
accepted answer: http://stackoverflow.com/a/50448356
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87908543
has answer: http://stackoverflow.com/a/50448356
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87908577
tagged with: algorithm
score: -2
tagged with: python
has body: I am trying to solve this HackerRank problem. https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem The general idea in this problem is that as Alice progresses up the leaderboard, I need to output her rank after each game. My code is working against all test except for TestCase 6,7,8,9 and it's because it's getting RunTime Error. This is my code: from itertools import count #Hackerrank Code scores_count = int(input()) scores = list(map(int, input().rstrip().split())) alice_count = int(input()) alice = list(map(int, input().rstrip().split())) #My Code Starts from here main_list = [sorted(scores+[i], reverse=True) for i in alice] track = [] for sub in main_list: seen = {} c = count() next(c) ss = [] for j in sub: try: ind = seen[j] except KeyError: ind = seen[j] = next(c) ss.append((j, ind)) track.append(ss) flicker = [] for x in track: gatter = dict(x) flicker.append(gatter) trackstar = [d.get(key) for key, d in zip(alice, flicker)] for m in trackstar: print(m) I did like to know where's the flaw in my code that's showing Runtime Error and how can I fix it. I am using Python 3.x
has comment: http://stackoverflow.com/comment/87908381
has title: My code is showing runtime error
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87908441
upvote count: 0
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/88087319
comment on: http://stackoverflow.com/q/50522480
type: QuestionComment
has text: Networkx doesn't draw self-edges. See other related questions on this.
score: 0
type: Comment

http://stackoverflow.com/comment/106578797
type: Comment
comment on: http://stackoverflow.com/a/59131407
type: AnswerComment
has text: Hi @mBrice1024, this is not the right way to do pagination with PRAW. PRAW will paginate any listing for you "under the hood." To get more posts, just change the `limit` parameter. If you set `limit=None`, PRAW will pull as many posts from the listing as Reddit's API offers (right around 1000).
score: 1

http://stackoverflow.com/a/50390681
answers question: http://stackoverflow.com/q/50389886
score: 0
has body: You can try manually drawing the rectangles using a loop: import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np idx = np.linspace(0, 12, 12) x = np.random.random(12) y = [0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1] fig, ax = plt.subplots(1) ax.plot(idx, x) rect_height = np.max(x) rect_width = 1 for i, draw_rect in enumerate(y): if draw_rect: rect = patches.Rectangle( (i, 0), rect_width, rect_height, linewidth=1, edgecolor='grey', facecolor='grey', fill=True ) ax.add_patch(rect) plt.show()
accepted answer of: http://stackoverflow.com/q/50389886
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50444141
upvote count: 3
downvote count: 0
answer count: 1
has body: There're already several solutions on StackOverflow to decode and encode image and base64 string. But most of them need IO between disk which is time wasted. Are there any solutions to encode and decode just in memory?
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50444142
score: 3
has answer: http://stackoverflow.com/a/50444142
tagged with: base64
tagged with: scikit-image
tagged with: python
has title: How to encode and decode between base64 string and numpy array?
tagged with: image

http://stackoverflow.com/a/50466346
upvote count: 12
has comment: http://stackoverflow.com/comment/87947411
answers question: http://stackoverflow.com/q/50465966
type: Answer
has comment: http://stackoverflow.com/comment/87946969
score: 12
downvote count: 0
type: AcceptedAnswer
has body: If you were to create a generator each time you loop, that would solve everything, because you could reuse that multiple times. For that, convert L_RANGES from a simple generator to a lambda creating generators, but don't forget to "call" it each time with (): L_RANGES = lambda: zip(range(10, 20), range(11, 21)) for a, b in L_RANGES(): print(a, b) for a, b in L_RANGES(): print(a, b) #works as many times as you want Compared to the other answers this doesn't take up memory (which is the downside of converting to a list) and doesn't require multiple variables for each time you want to loop (by using tee) which makes this way more flexible (you can iterate 1000 times if necessary, without creating L_RANGES_1...L_RANGES_999) for example: for i in range(1000): for a, b in L_RANGES(): print(a, b)
accepted answer of: http://stackoverflow.com/q/50465966

http://stackoverflow.com/comment/88025413
type: Comment
score: 0
has text: There are no braces in my answer.. This is a representation of tuples..
type: AnswerComment
comment on: http://stackoverflow.com/a/50492029

http://stackoverflow.com/comment/88051264
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50518825
score: 0
has text: I've worked through the notebook to learn how to do individual heatmaps and then researched how to stack them but without progress. I didn't know where to start on the tree diagram as I didn't know what it was called.

http://stackoverflow.com/comment/87950756
score: 0
comment on: http://stackoverflow.com/a/50468742
type: Comment
type: AnswerComment
has text: usong `r.json()` I get this error: `simplejson.errors.JSONDecodeError: Expecting property name enclosed in double quores: line 1 column 3 (char 2)`

http://stackoverflow.com/comment/87911089
type: Comment
has text: The code is working, clearly, you have entered the wrong path of the file!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50440724

http://stackoverflow.com/a/50438423
type: AcceptedAnswer
has body: The numexpr docs list the supported functions, and, alas, Bessel functions are not in it. http://numexpr.readthedocs.io/projects/NumExpr3/en/latest/user_guide.html You can try looking around for alternative implementations, e.g. from GSL or boost, but frankly I doubt the speed difference is going to be non-trivial, if any at all. What might be relevant is avoiding the loops over the points on the python side. Either just use array-valued arguments to scipy.special.kv or drop to Cython and use the cython_special version with looping in Cython.
answers question: http://stackoverflow.com/q/50438054
type: Answer
accepted answer of: http://stackoverflow.com/q/50438054
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87937758
comment on: http://stackoverflow.com/q/50456149
has text: thank you martineau! i will try it on a different system, maby it's just my computer
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50494124
score: 1
type: Answer
has body: You cannot add a string and an integer, this is why the following segment of code raises an exception. # Trying to add a string and an int raises a TypeError '\t\t' + int(my_quantity) * int(price) One solution is to cast your int to a str like so. # This will now work '\t\t' + str(int(my_quantity) * int(price)) Although, there exist cleaner syntax for string generation that implicitly cast objects to str for you. Using str.format '{} {}\t\t{}\t\t{}\n'.format( No, my_text, my_quantity, int(my_quantity) * int(price) ) Using literal string interpolation The best approach, if you are using Python 3.6+, is to use f-strings. f'{No} {my_text}\t\t{my_quantity}\t\t{int(my_quantity) * int(price)}\n'
downvote count: 0
answers question: http://stackoverflow.com/q/50494000
upvote count: 1

http://stackoverflow.com/comment/88071693
comment on: http://stackoverflow.com/q/50529991
score: 1
type: QuestionComment
has text: You would usually use the ORM, e.g. `rows = Location.objects.all()`, but apart from that your code looks ok. Maybe the problem is in the rest of the view or the urls.
type: Comment

http://stackoverflow.com/comment/88093869
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50540962
score: 0
has text: Login view logic inside the project: https://github.com/pinax/django-user-accounts/blob/be8a10a93613e45502a57f8769044c2b3129bd48/account/views.py#L355

http://stackoverflow.com/comment/87973371
comment on: http://stackoverflow.com/q/50479949
score: 0
type: Comment
type: QuestionComment
has text: Your code just reads and prints the `english.txt` - I don't see how you are getting the output described.

web-scraping
tags question: http://stackoverflow.com/q/50487815
tags question: http://stackoverflow.com/q/50438903
tags question: http://stackoverflow.com/q/50479820
tags question: http://stackoverflow.com/q/50417842
tags question: http://stackoverflow.com/q/50527882
tags question: http://stackoverflow.com/q/50477634
tags question: http://stackoverflow.com/q/50527790
tags question: http://stackoverflow.com/q/50457043
tags question: http://stackoverflow.com/q/50442391
tags question: http://stackoverflow.com/q/50519924
tags question: http://stackoverflow.com/q/50422110
tags question: http://stackoverflow.com/q/50493548
tags question: http://stackoverflow.com/q/50443463
tag name: web-scraping
tags question: http://stackoverflow.com/q/50441385
tags question: http://stackoverflow.com/q/50518634
tags question: http://stackoverflow.com/q/50482796
tags question: http://stackoverflow.com/q/50458326
tags question: http://stackoverflow.com/q/50425704
tags question: http://stackoverflow.com/q/50508759
tags question: http://stackoverflow.com/q/50440209
tags question: http://stackoverflow.com/q/50472985
tags question: http://stackoverflow.com/q/50453603
tags question: http://stackoverflow.com/q/50454896
tags question: http://stackoverflow.com/q/50493039
tags question: http://stackoverflow.com/q/50467085
tags question: http://stackoverflow.com/q/50446485
tags question: http://stackoverflow.com/q/50515260
tags question: http://stackoverflow.com/q/50433349
tags question: http://stackoverflow.com/q/50459154
tags question: http://stackoverflow.com/q/50418044
tags question: http://stackoverflow.com/q/50430237
tags question: http://stackoverflow.com/q/50400301
tags question: http://stackoverflow.com/q/50437085
type: Tag
tags question: http://stackoverflow.com/q/50434065
tags question: http://stackoverflow.com/q/50534813
tags question: http://stackoverflow.com/q/50513399
tags question: http://stackoverflow.com/q/50470658
tags question: http://stackoverflow.com/q/50537982
tags question: http://stackoverflow.com/q/50396393
tags question: http://stackoverflow.com/q/50482770
tags question: http://stackoverflow.com/q/50422477
tags question: http://stackoverflow.com/q/50534249
tags question: http://stackoverflow.com/q/50398344
tags question: http://stackoverflow.com/q/50505573
tags question: http://stackoverflow.com/q/50436791
tags question: http://stackoverflow.com/q/50411520
tags question: http://stackoverflow.com/q/50427865
tags question: http://stackoverflow.com/q/50506025
tags question: http://stackoverflow.com/q/50514217
tags question: http://stackoverflow.com/q/50501595
tags question: http://stackoverflow.com/q/50502617
tags question: http://stackoverflow.com/q/50492428
tags question: http://stackoverflow.com/q/50397474
tags question: http://stackoverflow.com/q/50501778
tags question: http://stackoverflow.com/q/50480530
tags question: http://stackoverflow.com/q/50418432
tags question: http://stackoverflow.com/q/50502476
tags question: http://stackoverflow.com/q/50512534
tags question: http://stackoverflow.com/q/50440430
tags question: http://stackoverflow.com/q/50476999
tags question: http://stackoverflow.com/q/50423262
tags question: http://stackoverflow.com/q/50401977
tags question: http://stackoverflow.com/q/50493703
tags question: http://stackoverflow.com/q/50514919
tags question: http://stackoverflow.com/q/50501203
tags question: http://stackoverflow.com/q/50500210
tags question: http://stackoverflow.com/q/50452087
tags question: http://stackoverflow.com/q/50518447
tags question: http://stackoverflow.com/q/50440947
tags question: http://stackoverflow.com/q/50523197
tags question: http://stackoverflow.com/q/50479547
tags question: http://stackoverflow.com/q/50486567
tags question: http://stackoverflow.com/q/50525017
tags question: http://stackoverflow.com/q/50429282

http://stackoverflow.com/q/50387368
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Storage transfer job from one google cloud storage region to another with Python "Failed to rewrite object."
score: 1
has body: I am trying to run a storage transfer job to copy files from a starting location bucket to a bucket in a destination location. The following code fails to rewrite starting bucket files to destination bucket. import datetime import sys import time import googleapiclient.discovery from google.cloud import bigquery, storage import json import pytz PROJECT_ID = 'myproject_id' # TODO: set this to your project name FROM_BUCKET = 'source_bucket' TO_BUCKET = 'destination_bucket' # Construct API clients. bq_client = bigquery.Client(project=PROJECT_ID) transfer_client = googleapiclient.discovery.build('storagetransfer', 'v1') def transfer_buckets(): # Transfer files from one region to another using storage transfer service. print('Transferring bucket {} to {}'.format(FROM_BUCKET, TO_BUCKET)) now = datetime.datetime.now(pytz.utc) transfer_job = { 'description': '{}-{}-{}_once'.format( PROJECT_ID, FROM_BUCKET, TO_BUCKET), 'status': 'ENABLED', 'projectId': PROJECT_ID, 'transferSpec': { 'transferOptions': { 'overwriteObjectsAlreadyExistingInSink': True, }, 'gcsDataSource': { 'bucketName': FROM_BUCKET, }, 'gcsDataSink': { 'bucketName': TO_BUCKET, }, }, # Set start and end date to today (UTC) without a time part to start # the job immediately. 'schedule': { 'scheduleStartDate': { 'year': now.year, 'month': now.month, 'day': now.day, }, 'scheduleEndDate': { 'year': now.year, 'month': now.month, 'day': now.day, }, }, } transfer_job = transfer_client.transferJobs().create( body=transfer_job).execute() print('Returned transferJob: {}'.format( json.dumps(transfer_job, indent=4))) # Find the operation created for the job. job_filter = { 'project_id': PROJECT_ID, 'job_names': [transfer_job['name']], } # Wait until the operation has started. response = {} while ('operations' not in response) or (not response['operations']): time.sleep(1) response = transfer_client.transferOperations().list( name='transferOperations', filter=json.dumps(job_filter)).execute() operation = response['operations…
answer count: 1
has answer: http://stackoverflow.com/a/50412489
tagged with: google-cloud-storage
favorite count: 0
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/50412489

http://stackoverflow.com/a/50465077
type: Answer
has body: If using csv library is an option you can try: import pandas as pd import requests import csv url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt" raw_data = requests.get(url).content file = open("raw_data.txt","w") file.write(raw_data) data = list(csv.reader(open('raw_data.txt', 'rb'), delimiter='\t')) df = pd.DataFrame.from_records(data) print df
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50464149

server
tags question: http://stackoverflow.com/q/50441592
tags question: http://stackoverflow.com/q/50446707
tags question: http://stackoverflow.com/q/50457085
tags question: http://stackoverflow.com/q/50528274
type: Tag
tags question: http://stackoverflow.com/q/50476505
tags question: http://stackoverflow.com/q/50474314
tags question: http://stackoverflow.com/q/50535964
tag name: server
tags question: http://stackoverflow.com/q/50501820

http://stackoverflow.com/a/50438727
downvote count: 0
answers question: http://stackoverflow.com/q/50438704
has body: &gt;&gt;&gt; dict(zip(year, value)) {2007: 1, 2008: 123, 2009: 8765, 2010: 987, 2011: 182735, 2012: 3459, 2013: 9, 2014: 0, 2015: 2, 2016: 835, 2017: 874}
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/88374038
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50526122
type: Comment
has text: I am seeing something similar. I even see the exact same byte value (262144 bytes), though I'm using scala. Have you had any luck debugging this?

http://stackoverflow.com/comment/87962243
score: 0
comment on: http://stackoverflow.com/a/50473952
type: Comment
type: AnswerComment
has text: Curious. I don't know why `super().__new__(cls, value)` doesn't work, but [using `__init__` definitely does](https://repl.it/repls/UnwieldySelfassuredClimate).

http://stackoverflow.com/comment/88078580
comment on: http://stackoverflow.com/a/50530295
type: Comment
has text: Thank you! Happy Friday!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88100587
type: Comment
has text: Not an answer just the current code, it still doesn't work
type: AnswerComment
comment on: http://stackoverflow.com/a/50544734
score: 1

http://stackoverflow.com/comment/88187356
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50469157
has text: @JRsz What is the error? Does it crash after you send the bytes, or before?
score: 0

http://stackoverflow.com/a/50492227
upvote count: 2
downvote count: 0
has body: If you want to create a new dict that has the desired order, you can create an OrderedDict from the result of sorting the original dict's items. OrderedDict stores its items in the order in which they were inserted (whereas the built-in dict which has no internal ordering). from collections import OrderedDict newDict = OrderedDict(sorted(oldDict.items(), key=lambda x: x[1]['width'])) largest = list(newDict.items())[-1] # {'ISIC_0013861.jpg', {'width': 4288, 'heigth': 2848})
type: Answer
answers question: http://stackoverflow.com/q/50492042
score: 2

http://stackoverflow.com/q/50521709
score: 0
tagged with: pandas
answer count: 1
has title: How to suppress warnings when using boxplot()?
type: Question
accepted answer: http://stackoverflow.com/a/50521790
tagged with: python
has body: When I use the boxplot(), I get 2 warnings. The chart is displayed correctly, but 2 warnings appear. Here is my code: import pandas as pd pd.options.display.mpl_style = 'default' df.boxplot() Here are the 2 warnings. Warning 1: /home/nbuser/anaconda3_501/lib/python3.6/site-packages/IPython/core/ interactiveshell.py:2910: FutureWarning: mpl_style had been deprecated and will be removed in a future version. Use `matplotlib.pyplot.style.use` instead. Warning 2: /home/nbuser/anaconda3_501/lib/python3.6/site-packages/matplotlib/ font_manager.py:1320: UserWarning: findfont: Font family ['monospace'] not found. Falling back to DejaVu Sans Is there anything I can do to suppress these 2 warning?
tagged with: plot
has answer: http://stackoverflow.com/a/50521790
type: AnsweredQuestion

http://stackoverflow.com/q/50464507
has title: Do I benefit from the 96 vCPUs of a gcloud Compute Engine if in python multiprocessing.cpu_count() returns 64?
downvote count: 0
has body: I am running a python parallel CPU intensive task on Google Compute Engine. Hence, the greater the number of vCPUs I can run it on, the greater the speed. I've read that there is no point in creating a multiprocessing pool with greater size than the number of available vCPUs, which makes sense, so I determine the size of my multiprocessing.dummy.Pool pool using multiprocessing.cpu_count(). I am running this script in a Pod, using gcloud Kubernetes Engine, and tested on machines with less than 96 vCPUs during development. The pool size automatically determined seemed always to match to the number of vCPUs. However, running it on a machine with 96 vCPUs, multiprocessing.cpu_count() returns 64 and not 96. I don't care setting that size manually to 96 but the question is, will I benefit from those extra 32 vCPUs if python is not "aware" of them? The machine is a n1-highcpu-96 (96 vCPUs, 86.4 GB memory) running the Container-Optimized OS (cos). Python version is 3.6.3.
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/88906585
has comment: http://stackoverflow.com/comment/88924681
tagged with: docker
type: AnsweredQuestion
tagged with: google-kubernetes-engine
tagged with: kubernetes
answer count: 1
favorite count: 0
tagged with: multiprocessing
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/57300284
has answer: http://stackoverflow.com/a/57300284

http://stackoverflow.com/a/50515475
downvote count: 0
has body: You need to turn each list value in the dictionary into a string of tab-separated values that also have a '\n' newline character at the end of each one of them: value1, value2 = 'key1', 'key2' dict_with_lists = {} dict_with_lists[value1] = ['word1', 'word2', 'word3', 'word4'] dict_with_lists[value2] = ['word1', 'word2', 'word3'] fname = 'dict_list_values.tsv' with open(fname, 'w') as file: file.writelines( '\t'.join(values)+'\n' for values in dict_with_lists.values() )
score: 3
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/50514973

http://stackoverflow.com/a/50432992
has comment: http://stackoverflow.com/comment/87880359
answers question: http://stackoverflow.com/q/50432901
has comment: http://stackoverflow.com/comment/87880214
score: 2
has body: You can write a function that tests whether an index is in range for a list: def validIndex(l, i): try: _ = l[i] except IndexError: return False return True I got this code from If list index exists, do X Then you can use this in your loop: def length_itr_whl(list): total = 0 index = 0 while validIndex(list, index): total += 1 index += 1 return total You could also use while True: and catch the index error in the loop. def length_itr_whl(list): total = 0 index = 0 try: while True: _ = list[index] total += 1 index += 1 except IndexError: pass return total
type: Answer
has comment: http://stackoverflow.com/comment/87880339
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/88034927
comment on: http://stackoverflow.com/q/50511275
type: Comment
score: 1
has text: what's your index, document and expected field set?
type: QuestionComment

http://stackoverflow.com/q/50402446
tagged with: django
tagged with: django-rest-framework
answer count: 1
favorite count: 0
type: Question
score: 3
tagged with: python
has body: I have a Request model and follows class TruRouteRequest(models.Model): msisdn = models.CharField('Subscriber international MSISDN ', max_length=25) sessionid = models.CharField(max_length=100, unique=True) msg_type = models.CharField(max_length=255) msg = models.CharField(max_length=255) I failed to write the name of the model field as 'type' so i wrote 'msg_type'. I have a ModelSerializer for the above model. Data I am receiving have field 'type' which is required. How do I map type from serializer data to msg_type to avoid this error when calling is valid &gt;&gt; serializer = TruRouteRequestSerializer(data=request.data) &gt;&gt; serializer.data &gt;&gt; {'msisdn': 'M', 'sessionid': 'S', 'msg': 'MSG'} &gt;&gt; request.data &gt;&gt; {'msisdn': 'M', 'type': 'T', 'sessionid': 'S', 'msg': 'MSG'} # there is type &gt;&gt; serializer.is_valid() &gt;&gt; False &gt;&gt; serializer.errors &gt;&gt; {'msg_type': [ErrorDetail(string='This field is required.', code='required')]}
accepted answer: http://stackoverflow.com/a/50402791
has answer: http://stackoverflow.com/a/50402791
type: AnsweredQuestion
upvote count: 3
has title: Set serializer field from data value having different names (Custom field Mapping for ModelSerizer)
downvote count: 0

http://stackoverflow.com/comment/87916571
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50427754
has text: @trozz `<botocore.client.CloudWatch.Paginator.ListMetrics object at 0x7f7293f2afd0>`
score: 0

http://stackoverflow.com/a/50434777
accepted answer of: http://stackoverflow.com/q/50434266
has body: You can use np.concatenate to build each row of your matrix of matrices. B, I = matrix(size) A = np.zeros((size, size)) M = [] for i in range(size): if i == 0: M.append(np.concatenate([ B, I, np.tile(A, (1, size-2)) ], axis = -1 )) elif i == size-1: M.append(np.concatenate([ np.tile(A, (1, size-2)), I, B ], axis = -1)) else: M.append(np.concatenate([ np.tile(A, (1, i-1)), I, B, I, np.tile(A, (1, size-i-2))], axis = -1)) M = np.concatenate(M, axis = 0) Using list comprehension: M = np.concatenate([ np.concatenate([ B, I, np.tile(A, (1, size-2)) ], axis = -1 ) if i == 0 else np.concatenate([ np.tile(A, (1, size-2)), I, B ], axis = -1) if i == size-1 else np.concatenate([ np.tile(A, (1, i-1)), I, B, I, np.tile(A, (1, size-i-2))], axis = -1) for i in range(size)], axis = 0)
score: 1
answers question: http://stackoverflow.com/q/50434266
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50469587
tagged with: mysql
has answer: http://stackoverflow.com/a/76076546
favorite count: 0
tagged with: python-3.x
has body: I am trying to connect my django project 'mysite' to mysql. I made a user in mysql and granted it all privileges to access the project. These are the changes I made to settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysitedb', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } Now when I try to migrate the database using python3 manage.py makemigrations, I get the following error: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: /usr/lib/mysql/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory")&lt;/code&gt;&lt;/pre&gt; The complete stack trace is as follows: Traceback (most recent call last): File "/home/prabhjeet/.local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/prabhjeet/.local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/prabhjeet/.local/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "/usr/lib/python3/dist-packages/MySQLdb/__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "/usr/lib/python3/dist-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: /usr/lib/mysql/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/prabhjeet/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_…
type: Question
has answer: http://stackoverflow.com/a/53463299
tagged with: django
tagged with: python
type: UnansweredQuestion
score: 6
upvote count: 6
linked to: http://stackoverflow.com/q/54633968
answer count: 6
has answer: http://stackoverflow.com/a/54542874
has title: django.db.utils.operationalError: (2059,"Authentication Plugin 'caching_sha2_password'")
has answer: http://stackoverflow.com/a/53867541
has answer: http://stackoverflow.com/a/59961086
has answer: http://stackoverflow.com/a/50838395
tagged with: mysql-python
downvote count: 0

http://stackoverflow.com/a/50413323
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Since you don't appear to have actual foreign-keys, you'll need to tell peewee how to reconstruct the model graph by providing aliases in your join predicates: .join(age, pw.JOIN.LEFT_OUTER, on=(cit.AGE_ID == age.AGE_ID).alias('agecitas')) .join(per, pw.JOIN.LEFT_OUTER, on=(age.PER_ID == per.PER_ID).alias('sktpersona'))
has comment: http://stackoverflow.com/comment/87847250
has comment: http://stackoverflow.com/comment/87847421
answers question: http://stackoverflow.com/q/50411547

http://stackoverflow.com/a/70467955
type: Answer
has body: In java, there appears not to be a direct way to do this. You can, however, use the result of a model dump to get the actual number of trees. Using a trained Booster: int numberOfTrees = booster.getModelDump("", false, "text").length;
score: -1
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/50426248

http://stackoverflow.com/q/50534579
has title: How to filter one dataframe's columns with another dataframe's MultiIndex
tagged with: indexing
score: 0
tagged with: pandas
tagged with: dataframe
type: Question
has body: How should I take a set of columns of one dataframe that take values in another set of columns of a different dataframe? Basically, what I am trying to achieve is like the following: df.loc[ df'c1','c2'.isin(df2.index), : ] = [1,2,3,4,5] But this code does not work. How should I achieve this?
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/50585914
favorite count: 0

http://stackoverflow.com/a/58479159
has body: If you are a Visual Studio Code user who wants to ignore this, you can add python.linting.pylintArgs to .vscode/settings.json: { ... "python.linting.pylintArgs": [ "--disable=C0103" ] ... }
upvote count: 23
type: Answer
answers question: http://stackoverflow.com/q/50434026
downvote count: 0
score: 23

http://stackoverflow.com/comment/88048892
score: 0
has text: Not sure why this is down voted. It is what the guy asked for. A loading gif would be better however
type: Comment
comment on: http://stackoverflow.com/a/50517155
type: AnswerComment

http://stackoverflow.com/a/50495916
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You're using time.sleep(1). But time.sleep is a blocking function, that means it will stop the whole server and nothing else will be able to run during that time. This has also been mentioned in Tornado FAQs page. What you need is an asynchronous sleep function. Tornado has gen.sleep. Use it like this: async def my_func(): ... await gen.sleep(1)
answers question: http://stackoverflow.com/q/50488084
type: Answer
accepted answer of: http://stackoverflow.com/q/50488084

http://stackoverflow.com/comment/137670203
score: 0
comment on: http://stackoverflow.com/a/70702327
type: Comment
type: AnswerComment
has text: this solved my issue, my credential had a special character in it.

http://stackoverflow.com/comment/87840987
score: 0
has text: Don't know what editor you're using but that throws an error in IDLE... the default python editor
type: Comment
comment on: http://stackoverflow.com/a/50412603
type: AnswerComment

http://stackoverflow.com/comment/87971448
comment on: http://stackoverflow.com/a/50478367
has text: @abarnert: That said, none of the features of `defaultdict` or `Counter` would be used when implicitly accessed via `__dict__` (their hooks are bypassed too), so it's not a huge benefit (unless you're doing something terrible like alternating direct access to the instance stored `__dict__` and indirect access via attribute lookups).
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87975113
has text: The issue was resolved. Apparently, when you use regex in the 'sep' argument, read_csv() ignores the 'quotechar' argument. I had used '\s*,\s*' in the sep argument and hence, the issue. However, I still don't get why is that so or how does one proceed when both the regex in the sep argument and the quotechar are required? Thank you for your time!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50437222
score: 0

http://stackoverflow.com/comment/88042412
type: Comment
comment on: http://stackoverflow.com/a/50514724
type: AnswerComment
has text: @ViVi if you are splitting a string, you will probably receive a list with words. If that is the case, can you show us the value of the `words` variable ?
score: 0

http://stackoverflow.com/q/50456233
has answer: http://stackoverflow.com/a/50456384
tagged with: python
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: z3py
has title: Is it possible to query z3's Python API on whether a timeout occured?
favorite count: 0
type: Question
tagged with: z3
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50456384
has body: I want to limit the time z3 can spend on some problem, which works by setting a timeout with: from z3 import * solver = Solver() solver.set(timeout=60000) # add constraints to solver result = solver.check() However, I'd like to check whether a timeout actually occurred. result is unknown in that case, but that might afaik also occur because the issue is not decidable (I'm using theories which are in general not decidable). So, is there a way to find out whether a timeout has occurred?

http://stackoverflow.com/comment/89757052
type: Comment
comment on: http://stackoverflow.com/a/50688333
type: AnswerComment
score: 1
has text: Thanks, that was a great tip. `retry_count` and `ValueError` made it work for me.

http://stackoverflow.com/a/50456326
has comment: http://stackoverflow.com/comment/87926614
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87927257
accepted answer of: http://stackoverflow.com/q/50455829
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50455829
has body: Internally, pandas represents each series, or column, of data with a specific data type, or dtype: df = pd.DataFrame([[2, True, 3.5, 'hello'], [4, False, 5.12, 'again']]) print(df) 0 1 2 3 0 2 True 3.50 hello 1 4 False 5.12 again print(df.dtypes) 0 int64 1 bool 2 float64 3 object dtype: object When you ask for a row of data which contains mixed types, pandas performs an explicit conversion to create a series of dtype=object. Such a series can hold virtually anything: # extract first row print(df.iloc[0]) 0 2 1 True 2 3.5 3 hello Name: 0, dtype: object Notice that there are many different types in this object series. For efficiency, you should aim to perform operations on series which are held in contiguous memory blocks. This is the case with int, float, datetime and bool series, but will not be the case for object series which contain pointers to data rather than the data itself. You can get a numpy array from your series: print(df.iloc[0].values) array([2, True, 3.5, 'hello'], dtype=object) But this is not the same as a regular series: Creating an array with dtype=object is different. The memory taken by the array now is filled with pointers to Python objects which are being stored elsewhere in memory (much like a Python list is really just a list of pointers to objects, not the objects themselves).
score: 2

http://stackoverflow.com/q/50476206
has comment: http://stackoverflow.com/comment/87966877
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: openpyxl
tagged with: python
has comment: http://stackoverflow.com/comment/87966917
has answer: http://stackoverflow.com/a/50485424
tagged with: excel
has title: How do I extract cell values from column object in openpyxl?
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87966958
has body: In Python, printing a column from the spreadsheet just returns &lt;Cell 'File Name' .A000&gt; but what I want is the singular value that is in the cell. I can not figure out from openpyxl's documentation how to do this for the whole column the same way you can a singular cell.
has comment: http://stackoverflow.com/comment/87966604
favorite count: 0
type: Question

http://stackoverflow.com/comment/88006731
comment on: http://stackoverflow.com/a/50496644
type: AnswerComment
score: 0
has text: Thanks for your answer. Could you explain what is happening in the loading function and why files should be an iter of the numpy array?
type: Comment

http://stackoverflow.com/a/50449952
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/99005195
downvote count: 0
has body: I solved the issue by following this link: https://software.ecmwf.int/wiki/display/WEBAPI/Web-API+Troubleshooting#Web-APITroubleshooting-3.2.1.3WARNING:httplib2.URLErrorreceivedNone%3Curlopenerror[SSL:CERTIFICATE_VERIFY_FAILED]certificateverifyfailed The problem may be that the SSL library used in the Python version doesn't look in the correct certificate path. In my case, ca-certificates have to be updated The QuoVadis Root CA 2 G3 is the Root CA for api.ecmwf.int and can be downloaded from https://www.quovadisglobal.com/QVRepository/DownloadRootsAndCRL.aspx and installed locally. For Windows it can be done in the following steps: 1.Type mmc.exe on search bar of the windows menu 2.Go to File > Add / Remove Snap In > Select Certificates > Click Add > Click OK 3.Expand Certificates - Current User 4.Right Click on Trusted Root Certification Authorities > All Tasks > Import 5.Follow the steps alternatively certutil -addstore -f "ROOT" new-root-certificate.crt In the command prompt
type: Answer
answers question: http://stackoverflow.com/q/50446888
has comment: http://stackoverflow.com/comment/115817094

http://stackoverflow.com/comment/88061711
score: 2
type: Comment
type: QuestionComment
has text: Well, it's true. There's no `word_tokenize` function in your code or in your imports.
comment on: http://stackoverflow.com/q/50524915

http://stackoverflow.com/a/50538166
downvote count: 0
answers question: http://stackoverflow.com/q/50536721
score: 3
type: Answer
has body: Solution with tf.meshgrid() and some reshaping: import tensorflow as tf import numpy as np t = tf.placeholder(tf.int32, [None, 2]) num_rows, size_row = tf.shape(t)[0], tf.shape(t)[1] # actual dynamic dimensions # Getting pair indices using tf.meshgrid: idx_range = tf.range(num_rows) pair_indices = tf.stack(tf.meshgrid(*[idx_range, idx_range])) pair_indices = tf.transpose(pair_indices, perm=[1, 2, 0]) # Finally gathering the rows accordingly: res = tf.reshape(tf.gather(t, pair_indices), (-1, size_row * 2)) with tf.Session() as sess: print(sess.run(res, feed_dict={t: np.array([[1,2], [3,4], [5,6]])})) # [[1 2 1 2] # [3 4 1 2] # [5 6 1 2] # [1 2 3 4] # [3 4 3 4] # [5 6 3 4] # [1 2 5 6] # [3 4 5 6] # [5 6 5 6]] Solution using cartesian product: import tensorflow as tf import numpy as np t = tf.placeholder(tf.int32, [None, 2]) num_rows, size_row = tf.shape(t)[0], tf.shape(t)[1] # actual dynamic dimensions # Getting pair indices by computing the indices cartesian product: row_idx = tf.range(num_rows) row_idx_a = tf.expand_dims(tf.tile(tf.expand_dims(row_idx, 1), [1, num_rows]), 2) row_idx_b = tf.expand_dims(tf.tile(tf.expand_dims(row_idx, 0), [num_rows, 1]), 2) pair_indices = tf.concat([row_idx_a, row_idx_b], axis=2) # Finally gathering the rows accordingly: res = tf.reshape(tf.gather(t, pair_indices), (-1, size_row * 2)) with tf.Session() as sess: print(sess.run(res, feed_dict={t: np.array([[1,2], [3,4], [5,6]])})) # [[1 2 1 2] # [1 2 3 4] # [1 2 5 6] # [3 4 1 2] # [3 4 3 4] # [3 4 5 6] # [5 6 1 2] # [5 6 3 4] # [5 6 5 6]]
accepted answer of: http://stackoverflow.com/q/50536721
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/87912326
has text: @piRSquared Thank you.
type: Comment
comment on: http://stackoverflow.com/a/50449490
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88046895
comment on: http://stackoverflow.com/q/50516591
score: 0
has text: @Barmar Yes but the answer is still there. `exec` has its own scope and changing an immutable variable inside its scope doesn't affect the global namespace.
type: Comment
type: QuestionComment

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/50498950
type: Tag

http://stackoverflow.com/comment/88084035
type: Comment
type: QuestionComment
score: 0
has text: the for loop includes the, actually just two, lines just after the for declaration and before the 3 empty rows...
comment on: http://stackoverflow.com/q/50535733

http://stackoverflow.com/a/50415840
score: 0
answers question: http://stackoverflow.com/q/50415567
has body: I solved converting to HSV, setting saturation equal to 0 and re-converting back to rgb: # http://mkweb.bcgsc.ca/colorblind rgbs = [(213/255, 94/255, 0/255), (86/255, 180/255, 233/255), (.9, .9, .9)] cblind = [mpl.colors.to_hex(r) for r in rgbs] cblind_gray = [mpl.colors.to_hex( mpl.colors.hsv_to_rgb(mpl.colors.rgb_to_hsv(r) * (1,0,1))) for r in rgbs] pal = sns.color_palette(cblind) sns.palplot(pal) pal = sns.color_palette(cblind_gray) sns.palplot(pal) Is this the right way to do it? Update Apparently it does not work (the second color is different when put in grayscale - I checked with Color Oracle). Do you know what would it be the reason for this and how to fix it?
type: Answer

http://stackoverflow.com/q/50427969
has answer: http://stackoverflow.com/a/50450322
type: Question
has body: as part as my homework one of the tasks is to update a specific line, but we are not allowed to load the whole file into the memory, but only 1 line at a time the problem is, it writes all the info to the end of file instead of replace the same line. i tried using seek, but kept getting errors, this is the closest i got it to somehow working. what i want to do is take for example: heap.update('currency', 'PKR', '123') that will keep all the lines and just change PKR into 123 in all lines. but stay the same order. hope someone can tell me what is my mistake. thanks! # update a value in heap def update(self, col_name, old_value, new_value, ): if self.is_empty() == 0: #check if file is empty return i = self.findIndex(col_name) #find what column im comparing to if i == -1: #if column out of bound return with open(self.name, "r") as f: #open file for read mode while True: temp='' line = f.readline() #read line if line == '': #if line is empty, we are done break #split line into the 4 columns keep1 = line.split(',', 3)[0]; keep2 = line.split(',', 3)[1]; keep3 = line.split(',', 3)[2]; keep4 = line.split(',', 3)[3]; x = line.split(',')[i]; if (x == old_value): #compare value and check if its equle, if it is: #create a new string with value if i == 0: temp = new_value + "," + keep2 + "," + keep3 + "," + keep4; elif i == 1: temp = keep1 + "," + new_value + "," + keep3 + "," + keep4; elif i == 2: temp = keep1 + "," + keep2 + "," + new_value + "," + keep4; elif i == 3: temp = keep1 + "," + keep2 + "," + keep3 + "," + new_value; with open(self.name, "a") as ww: #write value into file ww.write(temp) self def __init__(self, file_name): self.name = file_name; f = open(self.name, "w"); f.close(); findIndex function def findIndex(self, col_name): if self.is_empty() == 0: return -1 elif col_name == 'lid': return 0 elif col_name == 'loan_amount': return 1 elif col_name == "currency": return 2 elif col_name == "sector": return 3 example of txt to read lid,loan_amount,currency,sector 653…
linked to: http://stackoverflow.com/q/49732826
has title: python updating a line without readlines command
type: UnansweredQuestion
tagged with: python
answer count: 2
linked to: http://stackoverflow.com/q/16208206
score: 0
has comment: http://stackoverflow.com/comment/87873438
has answer: http://stackoverflow.com/a/50428596

http://stackoverflow.com/comment/87857637
type: AnswerComment
comment on: http://stackoverflow.com/a/50421203
has text: why apply is less recommended? or there is an error for the apply solution:TypeError: ('my_function() takes exactly 7 arguments (13 given)', u'occurred at index deviation')
score: 0
type: Comment

http://stackoverflow.com/q/50398344
tagged with: web-scraping
answer count: 1
has comment: http://stackoverflow.com/comment/87813108
has body: Writing a basic scraping script. I fail to comprehend where I keep going wrong. I faced the same issue when I was using python 2.7. I use Sublime 3 as my text editor I use macOS I run python3.6 Here is what I have so far: import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'http://wbsite.com' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") #loop starts here #base of the script, one = page_soup.findAll("div",{"class":"large-7 medium-9 columns"}) two = page_soup.findAll("div",{"body field"}) three = page_soup.findAll("div",{"field-ingredients-data field-wrapper"}) four = page_soup.findAll("div",{"field-how-to-use-data field-wrapper"}) onito = (one[0].h1) docito = two[1] trincipito = (three[0].p) cuatrocinto= (four[0].p) filename = "insertfilehere.cvs" f = open(filename, "w") headers = "onito, docito, trincipito, cuatrocinto\n" f.write(headers) un = str(onito.text) deux = str(docito.text) trois = str(trincipito.text) quatre = str(cuatrocinto.text) base = (un + "," + deux + "," + trois + "," + quatre + "\n") encoding_base = base.encode("utf-8)") finito = encoding_base.decode("utf-8)") f.write(finito) f.close() Please help me understand why i am so stupid that i can't figure this small problem out. error: Traceback (most recent call last): File "/Users/user/Downloads/scrape.py", line 74, in&lt;module&gt; f.write(un + "," + deux + "," + trois + "," + quatre + "\n") UnicodeEncodeError: 'ascii' codec can't encode character '\u2022' in position 30: ordinal not in range(128) [Finished in 0.8s] *tears Here is my updated script. Thank you all for the help!!! import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://www.insertsitehere.com/' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") one = page_soup.findAll("div",{"class":"large-7 medium-9 columns"}) two =…
favorite count: 0
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87812443
has comment: http://stackoverflow.com/comment/87812560
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87812894
has comment: http://stackoverflow.com/comment/87812438
has answer: http://stackoverflow.com/a/50398396
has title: A basic UnicodeEncodeError issue
has comment: http://stackoverflow.com/comment/87812796
has comment: http://stackoverflow.com/comment/87812550
downvote count: 2
has comment: http://stackoverflow.com/comment/87812930
upvote count: 1

http://stackoverflow.com/q/50416872
has comment: http://stackoverflow.com/comment/87849647
has comment: http://stackoverflow.com/comment/87849661
has title: Matplotlib pyplot: plotting array mixes up y axis labels
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87849392
tagged with: plot
has answer: http://stackoverflow.com/a/50417445
tagged with: list
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/87849817
has body: I'm making a simple program in Python to plot two lists of integers, one data one the time axis. The time list goes from 0 to 3 in increments of 1, while the data list consists of: 5,10, 3,12. I used print statements to verify that the lists do have the values mentioned above. plt.plot(time_axis,data_array, 'ro') plt.axis([0, 20, 0, 20]) plt.show() However, as shown in the image, the plot y axis is labeled in the order that my data list is processed, not in ascending order: 5,10,3,12 Is there a way to make the y axis go in equal increasing increments upto 20? EDIT: I noticed that this mixup only happens when i use the list as a parameter: eg, plt.plot([0,1,2,3],[5,10,3,12],'bo') #gives the correct graph while plt.plot(time_axis,data_array,'bo') #gives the incorrect graph, Even though the two lists time_axis and data_array contain the same values. Tracing back my error, I was importing my data values from a text file, and the parsing was done incorrectly, so the data values were not ints. The char values were in the format '5\n',etc so numplot was getting confused. Fixing that solved the issue!
favorite count: 0
has comment: http://stackoverflow.com/comment/87849478
score: -1
type: Question
has comment: http://stackoverflow.com/comment/87850273
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/87892648
type: AnswerComment
comment on: http://stackoverflow.com/a/50438431
type: Comment
has text: i tried implementing this emthod but i get this error: `TypeError: list indices must be integers or slices, not tuple`
score: 0

http://stackoverflow.com/q/50489525
tagged with: python
score: -1
downvote count: 4
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/20056548
has title: Python - Printing Integer variable inside double quote
answer count: 2
has comment: http://stackoverflow.com/comment/87991868
duplicate of: http://stackoverflow.com/q/20056548
has answer: http://stackoverflow.com/a/50489553
has body: I have an integer variable in Python:: var = 10 I want to print it like this : "10" Tried many things like ' "var" ' but did not really work. Any help would really be appreciated. Thanks in advance.
has comment: http://stackoverflow.com/comment/87992044
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50489553
has answer: http://stackoverflow.com/a/50489583
accepted answer: http://stackoverflow.com/a/50489583

http://stackoverflow.com/a/50422739
answers question: http://stackoverflow.com/q/50421459
has comment: http://stackoverflow.com/comment/88432524
has body: This is a classic use case for topological sorting. If you treat your prerequisites like a directed graph where there is an edge from prerequisite to another course you can simply find the topological sort of the graph and you will have your answer. A topological sort is not defined when the graph has cycles and similarly, your courses shouldn't have cycles because you would never be able to take those courses. In python you can do topological sorting with a simple depth-first search keeping track of when you enter and exit nodes. As you exit the nodes (after you've looked at all the children) you add that node to the from of the list. For example: from collections import defaultdict graph = defaultdict(set) def getCourses(prereq): for p in prereq: # build a simple graph structure: keys are node value is a set of children graph[p[1]] graph[p[0]].add(p[1]) visited = set() seen = set() courses = [] def dfs(node): # depth-first search if node in visited: return if node in seen: raise ValueError("Error cycle in prerequisites") seen.add(node) for e in graph[node]: dfs(e) #recurse on children seen.remove(node) visited.add(node) courses.insert(0, node) for k in graph.keys(): if k in visited: continue try: dfs(k) except ValueError: # in case of cycle return [] return courses print(getCourses([[1,2],[3,2],[2,4]]))
accepted answer of: http://stackoverflow.com/q/50421459
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50415115
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50415243
has answer: http://stackoverflow.com/a/50415226
score: 2
upvote count: 2
has title: Pandas: Select rows containing only strings?
downvote count: 0
has answer: http://stackoverflow.com/a/50415329
accepted answer: http://stackoverflow.com/a/50415243
type: AnsweredQuestion
has body: I have a data-frame that looks like this: [Column1] [Column2] 0 16155.22300 1.246982 1 16193.009 BMS1P17,BMS1P18,BMS1P22,DUXAP8 2 16231.289 LINC01297 5 16265.05300 2.156268 6 16287.937 POTEH,POTEH-AS1 7 16288.53800 2.156268 10 17645.92500 44.765792 11 17646.335 HDHD5,HDHD5-AS1 12 17646.44400 44.765792 15 18073.59200 103.154877 16 18073.656 LOC101929372,SLC25A18 17 18073.84300 103.154877 I'd like to make list containing only strings from the column2. My solution to this is something like this: my_list=list(i for i in ndf['LDU'] if isinstance(i, basestring)) For some reason it is not working and it returns all values. Any suggestion is much appreciated!
answer count: 3
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/50415226

http://stackoverflow.com/q/50431490
has comment: http://stackoverflow.com/comment/87878067
tagged with: jinja2
has comment: http://stackoverflow.com/comment/87877868
type: Question
has comment: http://stackoverflow.com/comment/87877842
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87877893
tagged with: django
tagged with: python
has title: Upload image and show it on template - Django 2.0
has comment: http://stackoverflow.com/comment/87877816
has comment: http://stackoverflow.com/comment/87877972
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87877674
has body: I have this code on my template: {% extends "base.html" %} {% block content %} picture {% csrf_token %} {{form}} {% for img in images %} {{forloop.counter}}.{{ img.pic.name }} ({{img.upload_date}}) {% endfor %} {% endblock content %} Although I have doubts with the form action but anyways. The problem is that when I click on submit button, it takes me to a blank page, no pop-up to actually upload the image, nothing. Is there some example I should follow to accomplish this? Also, this is just a proof test, but I'd like to know if a model and/or form is actually needed for it to work? EDIT Okay, by editing the input line like this it actually opens the file pop-up, but obviously it doesn't upload anything, it needs like a submit button or something, so, now it looks like this: {% extends "base.html" %} {% block content %} picture {% csrf_token %} {{form}} {% for img in images %} {{forloop.counter}}.{{ img.pic.name }} ({{img.upload_date}}) {% endfor %} {% endblock content %} But when I click on submit, it keeps sending me to a blank page, so, the value on submit, which is Upload, comes from this model: from django.db import models from django.forms import ModelForm class Upload(models.Model): pic = models.FileField(upload_to="static/") upload_date=models.DateTimeField(auto_now_add =True) class UploadForm(ModelForm): class Meta: model = Upload fields = ('pic',) And on my views.py: from django.shortcuts import render from uploader.models import UploadForm,Upload from django.http import HttpResponseRedirect from django.urls import reverse def home(request): if request.method=="POST": img = UploadForm(request.POST, request.FILES) if img.is_valid(): img.save() return HttpResponseRedirect(reverse('imageupload')) else: img=UploadForm() images=Upload.objects.all() return render(request,'image_upload.html',{'form':img,'images':images}) And in my urls.py: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from dj…
has comment: http://stackoverflow.com/comment/87877969

http://stackoverflow.com/comment/88063904
type: QuestionComment
score: 0
has text: Thanks @revo that worked like a charme. You should put that as an answer.
comment on: http://stackoverflow.com/q/50525652
type: Comment

http://stackoverflow.com/q/50531077
tagged with: indexoutofrangeexception
has answer: http://stackoverflow.com/a/50539427
type: Question
has title: I'm getting an error when i delete value in a array Python
has body: `i am getting an error when i run the following code: dosya=open("a.txt","r").read() dosya=dosya.split(" ") uzun=len(dosya) sayac=[0 for i in range(len(dosya))] for i in range(uzun): for j in range(i+1,uzun): if(dosya[i]==dosya[j]): del dosya[j] sayac[i]+=1 sayac[i]+=1 del dosya[i] i+=1 print sayac ` Erorr : IndexError: list index out of range why ? and how can i fix it
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50531945
has comment: http://stackoverflow.com/comment/88074146
has comment: http://stackoverflow.com/comment/88074759
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88074890

http://stackoverflow.com/q/50416935
has comment: http://stackoverflow.com/comment/87849925
has comment: http://stackoverflow.com/comment/87850829
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87849731
tagged with: tkinter
type: UnansweredQuestion
tagged with: modal-dialog
has answer: http://stackoverflow.com/a/50417675
has comment: http://stackoverflow.com/comment/87850068
tagged with: python
has comment: http://stackoverflow.com/comment/87850803
has comment: http://stackoverflow.com/comment/87850731
score: 2
has title: Creating a modal dialog box in tkinter
has comment: http://stackoverflow.com/comment/87850945
linked to: http://stackoverflow.com/q/31892015
downvote count: 0
tagged with: dialog
answer count: 1
has body: This question is not a duplicate: see below. I want to create a modal dialog box in tkinter. In other words, a dialog box which, while it is active, prevents the user from interacting with the parent window. There is an existing question on SO answering this, and there is a full example illustrating the concept. However, making the dialog box a Toplevel and calling grab_set() on it simply doesn't work, on either Windows 7 or Ubuntu 16.04.4 LTS. The user is still able to close, resize, and in general interact with the parent window. Is there a way of creating a modal dialog box in Tkinter that actually works? Here is a minimal usage example of dialog.grab_set() failing to prevent interaction with the parent window: import os try: import Tkinter as tkinter except ImportError: import tkinter class MyToplevel(tkinter.Toplevel, object): def __init__(self, parent): tkinter.Toplevel.__init__(self, parent) self.title("Main window") MyDialog(self) self.protocol("WM_DELETE_WINDOW", parent.destroy) class MyDialog(tkinter.Toplevel, object): def __init__(self, parent): tkinter.Toplevel.__init__(self, parent) self.transient(parent) self.title("Dialog") self.grab_set() self.protocol("WM_DELETE_WINDOW", self.destroy) if __name__ == "__main__": root = tkinter.Tk() root.withdraw() app = MyToplevel(root) app.mainloop() I should point out that using grab_set_global() (as in this answer) does work, but is not a viable solution because it blocks access to all windows, for the entire system.
has comment: http://stackoverflow.com/comment/87871417
tagged with: python-2.x
linked to: http://stackoverflow.com/q/16803686
has comment: http://stackoverflow.com/comment/87849697

http://stackoverflow.com/a/62166129
has body: See this answer to a very similar question: by design, fixture values can not be used as lists of parameters to parametrize tests. Indeed parameters are resolved at pytest collection phase, while, fixtures are resolved later, during pytest nodes execution. The best that you can do with lazy_fixture or with pytest_cases.fixture_ref is to use a single fixture value as a parameter. With lazy_fixture you have limitations (if I remember correctly, the fixture cannot be parametrized) while with pytest_cases you can do pretty much anything (using the fixture_ref in a parameter tuple, using several fixture_refs each with different parametrization, etc.). I'm the author of pytest_cases by the way ;) See also this thread.
has comment: http://stackoverflow.com/comment/132479331
answers question: http://stackoverflow.com/q/50482416
downvote count: 0
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/125124688

http://stackoverflow.com/a/50421205
upvote count: 1
has body: Did you edit or create core-site.xml in $SPARK_HOME/conf (Must be /dsvm/tools/spark/current/conf) with add the config property as specified in the reference article you linked with the ADLS access tokens and adl schema details? (Pasted here for convenience). dfs.adls.oauth2.access.token.provider.type ClientCredential dfs.adls.oauth2.refresh.url YOUR TOKEN ENDPOINT dfs.adls.oauth2.client.id YOUR CLIENT ID dfs.adls.oauth2.credential YOUR CLIENT SECRET fs.adl.impl org.apache.hadoop.fs.adl.AdlFileSystem fs.AbstractFileSystem.adl.impl org.apache.hadoop.fs.adl.Adl The ADLS connectivity JAR files are already prebuilt into the DSVM.
answers question: http://stackoverflow.com/q/50399751
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/50454576
downvote count: 0
has body: Let me open a new answer in response to the renewed question. After trying some methods with just requests and urllib, I think it is better to use the selenium webdriver controller. The following code will grab the table rows as you want. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup url = 'https://parivahan.gov.in/rcdlstatus/' # Optional: Getting "Headless" browser, ie suppressing the browser window from showing chrome_options = Options() chrome_options.add_argument("--headless") # Let the driver open, fill and submit the form driver = webdriver.Chrome(chrome_options=chrome_options) driver.get(url) driver.delete_all_cookies() wait = WebDriverWait(driver, 10) wait.until(EC.element_to_be_clickable((By.NAME, 'form_rcdl:j_idt34'))) input1 = driver.find_element_by_name('form_rcdl:tf_reg_no1') input1.send_keys('GJ03KA') input2 = driver.find_element_by_name('form_rcdl:tf_reg_no2') input2.send_keys('0803') driver.find_element_by_name('form_rcdl:j_idt34').click() wait = WebDriverWait(driver, 10) # Get the result table try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "form_rcdl:j_idt63")) ) result_html = driver.page_source #print(result_html) soup = BeautifulSoup(result_html, 'lxml') print(soup.findAll('tr')) except TimeoutException: driver.quit() print('Time out.') Below demonstrates the result of printing out the table html tags in soup. I hope the government does not find out and block this way before you try out lol Hope this helps! You may refer to the following references if interested: Selenium manual: http://selenium-python.readthedocs.io/ Driving headless Chrome with Python: https://duo.com/decipher/driving-headless-chrome-with-python Submitting form with selenium: Selenium/Python - Extract dynamica…
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87932925
has comment: http://stackoverflow.com/comment/87933218
has comment: http://stackoverflow.com/comment/87936684
has comment: http://stackoverflow.com/comment/87936675
has comment: http://stackoverflow.com/comment/87934886
has comment: http://stackoverflow.com/comment/87934985
has comment: http://stackoverflow.com/comment/87935676
type: Answer
answers question: http://stackoverflow.com/q/50452625
has comment: http://stackoverflow.com/comment/87936064

http://stackoverflow.com/a/50443410
has comment: http://stackoverflow.com/comment/87904904
has body: The problem is in first two line. pd.get_dummies() will return different columns for train and test if the data is different in them. For example if in train, a column has 3 cateogories , 3 columns will be made for them, but it may happen that the test data only contains 2 categories in that specific column, in that you will get 2 columns after the pd.get_dummies(). Which then will lead to different number of columns. There are a couple of things you can do here: 1) Easiest Use pd.get_dummies() on the whole data before train test split and then split the data. But its not recommended because it leaks the information of testing data to the model. 2) If you can use the development version of scikit, use CategoricalEncoder to perform the one hot encoding. 3) Use a combination of LabelEncoder + OneHotEncoder in the current scikit version to achieve the same. See my other answer for example. Note Also only call transform() on the test data, never fit(). Do this:- # If you call fit_transform(), the imputer will again learn the # new mean from the test data # Which will lead to differences and data leakage. imp_test_X = pd.DataFrame(imputer.transform(test_X))
has comment: http://stackoverflow.com/comment/87904541
has comment: http://stackoverflow.com/comment/87905314
accepted answer of: http://stackoverflow.com/q/50441669
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87904646
has comment: http://stackoverflow.com/comment/87905444
has comment: http://stackoverflow.com/comment/87905068
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50441669
upvote count: 2
has comment: http://stackoverflow.com/comment/87993642

http://stackoverflow.com/comment/87797358
comment on: http://stackoverflow.com/q/50390255
type: Comment
type: QuestionComment
score: 0
has text: @eqperes it's the ` _id': u'en.wikipedia.org/wiki/William_Cowper `

pca
tag name: pca
tags question: http://stackoverflow.com/q/50527117
tags question: http://stackoverflow.com/q/50514783
type: Tag

http://stackoverflow.com/a/53657006
type: Answer
answers question: http://stackoverflow.com/q/50385480
downvote count: 0
score: 1
upvote count: 1
has body: I was able to get around this issue by doing the following, some steps may not be necessary, but so far, this has worked in my case. I found this github issue helpful and put me on the right track. First, excessive importing in my script: import pypylon import pathlib from pypylon import pylon from pypylon import genicam from pypylon import _genicam from pypylon import _pylon I'd advise against the way you imported pypylon in your example, refering to a package simply as "py" will be confusing for other developers. Next, I modified my spec file's binaries, pathex, and hiddenimports. I added all of the pylon dll and pyd files to binaries, appended the pypylon directory to pathex, and added all of the possibilities to hiddenimports: import pypylon pypylon_dir = pathlib.Path(pypylon.__file__).parent pypylon_dlls = [(str(dll), '.') for dll in pypylon_dir.glob('*.dll')] pypylon_pyds = [(str(dll), '.') for dll in pypylon_dir.glob('*.pyd')] _binaries = list() _binaries.extend(pypylon_dlls) _binaries.extend(pypylon_pyds) _pathex = list() _pathex.append(str(pypylon_dir)) _hiddenimports = list() _hiddenimports.extend(['pypylon', 'pypylon.pylon', 'pypylon.genicam', 'pypylon._pylon', 'pypylon._genicam']) a = Analysis(... pathex=_pathex, binaries=_binaries, ... hiddenimports=_hiddenimports, I'm not sure all of that is strictly necessary, but it's working for me with Python 3.4, PyInstaller 3.3, and pypylon 1.3.1. Good luck!

http://stackoverflow.com/comment/87930113
has text: Well, it does have a "bytes" but it's just an alias to `str`, which is not helpful.
type: Comment
comment on: http://stackoverflow.com/a/50458246
score: 2
type: AnswerComment

http://stackoverflow.com/comment/87920415
has text: Please read my answer below. It answers the new question you have asked too
comment on: http://stackoverflow.com/q/50409623
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50389428
type: Question
has comment: http://stackoverflow.com/comment/87794399
answer count: 0
type: UnansweredQuestion
has body: I am trying to plot a bunch of dots on a map: these are my Latitudes (AX,BX,CX,...) and Longitudes (AY,BY,CY,...) and my code: Xpos=[AX, BX, CX, DX, EX,SouXposJun,LonXposJun,ImmXposJun,LeiXposJun,FelXposJun,ZeelXposJun,RotXposJun,AmsXposJun]) Ypos=[AY, BY, CY, DY, EY,SouYposJun,LonYposJun,ImmYposJun,LeiYposJun,FelYposJun,ZeelYposJun,RotYposJun,AmsYposJun]) #%% map ax=plt.figure(figsize=(20,10)) #colors color=[] color[0:7500]=np.tile('red',7500)#A color[7500:92400]=np.tile('orange',84900)#B color[92400:288600]=np.tile('green',196200)#C color[288600:752400]=np.tile('darkred',463800)#D color[752400:775920]=np.tile('gold',23520)#E color[775920:800000]=np.tile('darkgrey',24080)#Ports plt.subplot(231)#Start of release m= Basemap(width=1000000,height=1000500,projection='lcc', resolution='h',lat_0=52.25,lon_0=1) m.drawmapscale(lon=6.5, lat=48.5, lon0=0, lat0=48.5, length=50) m.drawmapboundary(fill_color='turquoise') m.fillcontinents(color='white',lake_color='aqua') m.drawcountries(linestyle='--') plt.title("17/02/2013",size=15) x,y = m(XposFeb[33],YposFeb[33]) scatter = m.scatter([], [], s=0.1, c=color, marker='o', label = 'Aurelia aurita', zorder=2) scatter.set_offsets(np.c_[x,y]) The problem is this first plots the dots A,B,C.. and over these the rest. Since they overlap, I can no longer see A, B, C, ... Is there a way to plot the first values of Xpos and Ypos over the last values? So I can see A, B, C better than the rest? Preferably without me having to completely reorganise my code. Any help is appreciated!
tagged with: python
tagged with: scatter
has comment: http://stackoverflow.com/comment/87797878
score: 0
has comment: http://stackoverflow.com/comment/87797069
has title: Change the plot order in scatter
has comment: http://stackoverflow.com/comment/87794663
tagged with: matplotlib