python,python-3.x,vim,pylint,syntastic
In the docs under 4.2. Q. The python checker complains about syntactically valid Python 3 constructs...: A. Configure the python checker to call a Python 3 interpreter rather than Python 2, e.g: let g:syntastic_python_python_exec = '/path/to/python3' ...
This is a bug with how the arguments are being parsed. See issue #1259 and issue #11828 for the same bug with string methods, and issue #13340 for lists. Yes, the documentation implies that the indices are used in roughly the same way as a slice, and the internal utility...
#!/usr/bin/env python3 # coding: utf-8 s = """00 1f [email protected] 00c 00e 00N 00> 00E 00O 00F 002 00& 00* 00/ 00) 00 1f 00 1c 00 00 00 17 00\r 00 08 00 03 00 f8 ff ea ff e1 ff e1 ff e0 ff da ff d2 ff...
function,python-3.x,random,dice
this line if die == 'a' or 'A': will always return True. That is because the way the items are grouped, it is the same as if (die == 'a') or ('A'): and 'A' (along with any string except "") is always True. Try changing all those lines to if...
python,python-3.x,scipy,integration,quad
The reason here is that your function is only very strongly peaked in a very small region of your integration region and is effectively zero everywhere else, quad never finds this peak and thus only see's the integrand being zero. Since in this case you know where the peaks are,...
Pass end='' to your print function to suppress the newline character, viz: for l in line.split(): print(l[0].upper(), end='') print() ...
A partialmethod object will only handle descriptor delegation for the function object, no for any arguments that are descriptors themselves. At the time the partialmethod object is created, there is not enough context (no class has been created yet, let alone an instance of that class), and a partialmethod object...
Note that the bz2.open defaults to binary mode. This is in contrast to the regular Python built-in open which defaults to text mode. To solve your error, you simply need to open the file in text mode, not the default binary mode. Change the with bz2.open(... mode='w'...) to with bz2.open(......
python,django,python-3.x,django-models,django-1.8
primary_key implies unique=True. So, as the warning says, you should probably be using a OneToOneField.
Your function does not return a value so it returns None as all python functions that don't specify a return value do: def whois(k, i): k = str(k[i]) print (k) whois = subprocess.Popen(['whois', k], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ou, err = whois.communicate() who = str(ou) print (who.find('NetName:')) who = re.split('NetName:', who)[1] who...
QMainWindow comes with its default QMenuBar, but you cant set a new one with QMainWindow.setMenuBar() More informations in the Qt Documentation...
Try something like this instead of creating a new label every time: import Tkinter as tk class Window(): def __init__(self, root): self.frame = tk.Frame(root) self.frame.pack() self.i = 0 self.labelVar = tk.StringVar() self.labelVar.set("This is the first text: %d" %self.i) self.label = tk.Label(self.frame, text = self.labelVar.get(), textvariable = self.labelVar) self.label.pack(side = tk.LEFT)...
Sounds like you're looking for exceptions https://docs.python.org/2/tutorial/errors.html # checkError: becomes try # some test if x > 0: raise AssertionError("Something failed...") print("The block of code works!") except: print("The block of code does not work!") Something like that...
Use range and format for i in range(1,5): contentA = tree.xpath("//table[@class='yfnc_tabledata1']/tr[1]/td/table/tr[2]/td[{i}]".format(i=i))[0].text_content().strip() print(contentA) Output Total Revenue 31,821,000 30,871,000 29,904,000 for i in range(1,5): contentB = tree.xpath("//table[@class='yfnc_tabledata1']/tr[1]/td/table/tr[3]/td[{i}]".format(i=i))[0].text_content().strip() print(contentB) Output Cost of Revenue 16,447,000 16,106,000 15,685,000 EDIT In [22]: d = {} In [23]: d.setdefault('Revenue', []) Out[23]: [] In [24]: for i in...
if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Quoting the documentation for the round function. Hope this helps :) On a side note, I would suggest always read the doc when...
python,django,python-3.x,django-models
You shouldn't use this method to set your default value, rather than override the save method of the model and use it there. For example: class User(models.Model): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, default=uuid.uuid1) def make_slug(self): return self.first_name + self.last_name[0] def save(self, *args, **kwargs): self.slug =...
python,python-3.x,numpy,pandas,datetime64
If you call set_index on pdata to date_2 then you can pass this as the param to map and call this on tdata['date_1'] column and then fillna: In [51]: tdata['TBA'] = tdata['date_1'].map(pdata.set_index('date_2')['TBA']) tdata.fillna(0, inplace=True) tdata Out[51]: TBA date_1 0 0 2010-01-04 1 2 2010-01-05 2 0 2010-01-06 3 0 2010-01-07...
Python already has the wrapper you describe, it's called functools.cmp_to_key
python,python-3.x,command-line-interface,argparse
You can do this with nargs='?': One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string...
python,windows,batch-file,python-3.x
May be changing / to \\ in Popen can help.
The code works fine in Python 2. If you are using Python 3, there is an issue with last line, because print is a function. So, because of where you've put the close parenthesis, only the first part is actually passed to print. Try this instead print("len(list6[1]):", len(list6[1])) ...
python,json,django,python-3.x,serialization
You have to serialize your student objects list, try something like this: from django.http import HttpRequest,HttpResponse from django.http import JsonResponse from json import dumps from django.core import serializers def get_stats(request): if request.method == "POST": srch_dropV = request.POST['srch_dropAJ'] else: srch_dropV = '' if(srch_dropV == 'Green'): students = GreenBased.objects.all() if(srch_dropV == 'Yellow'):...
python,list,python-3.x,dictionary
You can use unpacking operation within a dict comprehension : >>> my_dict={i:j for i,*j in [l[i:i+4] for i in range(0,len(l),4)]} >>> my_dict {'Non Recurring': ['-', '-', '-'], 'Total Other Income/Expenses Net': [33000, 41000, 39000], 'Selling General and Administrative': [6469000, 6384000, 6102000], 'Net Income From Continuing Ops': [4956000, 4659000, 4444000], 'Effect...
I don't know if the Tcl interpreter in your system is recent. If it is, you should be able to use python $python_app_name {*}$python_app_args to get the arguments as separate strings. The {*} prefix is a syntactic modifier that splices the items in a list as separate arguments. Example: list...
Change n = words.count(x) to n = i.count(x) does the trick. Reason You are saying i is your one word in each iteration.So you have to use i.count(x) to get count of x in i ...
python,string,python-3.x,double-quotes
In Python you can create multiline strings with """...""". Quoting the documentation for strings, String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. In your first case, ""s"" is parsed like this "" (empty string literal) s "" (empty string literal) Now, Python doesn't know...
python,python-2.7,python-3.x,command-line,pip
Based on your error log, the main issue is that apt-get is interpreting your attempt to install separate packages with the comma as part of the name of python-dev. To install multiple packages with apt-get just separate them with a space. However, based upon the continued discussion in the chat...
python,python-3.x,gsm,at-command,modem
I found the origin of the error : The syntax is ATD+98xxxxxxxxxx; followed by terminating string. I was forgotten to put semicolon at the end after the number. So I replace phone.write(b'ATD"'+recipient.encode() +b'"\r') with phone.write(b'ATD"'+recipient.encode() +b';"\r') And now it works fine. Based on the brackets in this documents, I thought...
Python 3.3.5 installation fixed this issue for me. Downloaded from - https://www.python.org/downloads/release/python-335/
You are calling the script wrong Bring up a cmd (command line prompt) and type: cd C:/Users/user/PycharmProjects/helloWorld/ module_using_sys.py we are arguments And you will get the correct output....
According to the Django documentation regarding static/: This should be an initially empty destination directory for collecting your static files from their permanent locations into one directory for ease of deployment; it is not a place to store your static files permanently. You should do that in directories that will...
Python 3's map returns a map object. You need to convert it to list explicitly: f1_b = list(map(lambda x: list(map(lambda t:t.strip(), x.split(',', 1))), lst)) Though in most cases you should prefer list comprehensions to map calls: f1_a = [[t.strip() for t in x.split(',', 1)] for x in lst] Keep in...
Your problem starts here: frame.bind('<Configure>', self.OnFrameConfigure(parent=canvas)) You are immediately calling the OnFrameConfigure function. That is not how you use bind. You must give a reference to a callable function. Since you're using a class, you don't need to pass parent in, unless you have this one function work for multiple...
python,regex,validation,python-3.x,isnumeric
try: float(w.get()) except ValueError: # wasn't numeric ...
list.remove() removes the first occurrence of the value, not all such values. As a result you'll first add both 1 values to sort, remove one of the two 1 values, then add the remaining 1 value to sort again: >>> lst = [4,5,5,1,6,1] >>> copy = lst.copy() >>> sort =...
Try this: from pandas import read_csv data = read_csv('country.csv') print(data.iloc[:,1].mean()) This code will convert your csv to pandas dataframe with automatic type conversion and print mean of the second column. ...
python-3.x,tkinter,messagebox,tkmessagebox
from Tkinter import * from tkMessageBox import showerror Tk().withdraw() showerror(title = "Error", message = "Something bad happened") Calling Tk().withdraw() before showing the error message will hide the root window. Note: from tkinter import * for Python 3.x...
You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8'). See Convert bytes to a Python String...
re.sub(r"^[^.-]*[.-]\s*","",some_string) You can try this....
python,authentication,python-3.x,hash,salt
You can do salt = salt.decode("utf-8") after salt is encoded to convert it to string.
The line: randgend = random.choice(gend) makes randgend a single random choice from [ 'male', 'female' ], you're basically writing: randgend = 'male' # or female, whichever gets picked first If you want it to be a function that returns a different random choice each time, you need: randgend = lambda:...
Regular expression functions in Python return None when the regular expression does not match the given string. So in your case, match is None, so calling match.groupdict() is trying to call a method on nothing. You should check for match first, and then you also don’t need to catch any...
python,python-3.x,contextmanager
The problem is probably due to buffering of stdout. You need to manually flush it for the message to be displayed. In Python 3.3+, the print function has a flush argument: from contextlib import contextmanager import time @contextmanager def msg(m): print(m + "... ", end='', flush=True) t_start = time.time() yield...
python-3.x,scroll,tkinter,scrollbar
I don't think Frames support scrolling (there is no .yview method.) You could put a canvas which does support scrolling in place of or inside the frame to hold the contents of your page and get the scrolling you are after. This is a very good, comprehensive tkinter resource that...
Two issues (apart from the messed-up indentation which probably just happened when pasting your code): The frame was bound to the returned value of a function rather than to a function itself. You can fix this with a lambda function. You're trying to create a complex layout with pack(). Try...
This is nothing special about import statements. It's just how the scoping works in Python. If you're assigning a value to a label, it is local to the scope unless explicitly defined global. Try this code - a = 2 def start(): print a a = 3 start() This also...
There are essentially two parts of your code to consider separately: The nested loop where you build `dic`. The loop where you build `count`. For 1. there are two loops to consider. The i loop will run n times and j loop will run n-i times each time. This means...
Magic number is the term for the first two bytes of an executable file. It is used to determine how the executable should be loaded. The magic number is also used in *.pyc files that are compiled from the *.py files. It says what version of bytecode is used inside....
I am not sure if you did give out your real API key, but I urge you to change it ASAP. In any case, in Python, top level variables/names do not come from thin air - they're introduced either by import or the assignment statement (x = 123), (or some...
python,sockets,python-3.x,serversocket
There are two issues in your server/client programs. You server has two accept() calls, before the while loop and inside the while loop , this causes the server to actually wait for two connections before it can start receiving any messages from any client. The socket.sendall() function takes in bytes...
You need to unpack the list in the function call with the * operator: foo.accept(*values) ...
You need to convert your converted string grades to floats (or int) average =(float(grade_1) + float(grade_2)+ float(grade_3))/3.0 average = str(average) ...
Indeed, as Andreus correctly answered, %.1e would give you what I would understand as scientific formatting of the tick values as printed on the axes. However, setting a FormatStrFormatter switches off what is called the scientific formatting feature of the default formatter, where the exponent is not formatted with each...
Roll it into a function, since it's reusable. import random def roll_die(): return random.randint(1,6) then just test. result = roll_die() if result == 1: # forfeit attack however you're doing that else: # roll between 2-6 # do whatever your game logic has you doing. ...
There are couple problems in your code, You always re-assign fileSizeStr. You need to concatenate new values. You need to check if fileSize greater than or equal to 1024, not smaller. New fileSize should be remainder of the first calculation, not the result of it. Also, checking from larger one...
python,python-3.x,multiprocessing,pid
You need to also specify chunksize=1 in the call to pool.map. Otherwise, multiple items in your iterable get bundled together into one "task" from the perception of the worker processes: import multiprocessing import time import os def f(x): print("PID: %d" % os.getpid()) time.sleep(x) complex_obj = 5 #more complex axtually return...
python,python-3.x,datatables,lxml
Rather than use a huge long XPath as generated by Chrome, you can just search for a table with the yfnc_tabledata1 class; there is just the one: >>> tree.xpath("//table[@class='yfnc_tabledata1']") [<Element table at 0x10445e788>] Get to your <td> from there: >>> tree.xpath("//table[@class='yfnc_tabledata1']//td[1]")[0].text_content() 'Period EndingDec 31, 2014Dec 31, 2013Dec 31, 2012\n \n...
As suggested by tobias_k, you should add the contents of choices() into a while loop. I also found some other problems: False does not equal "False", so your while loop never runs. You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and...
I think the problem is with your start.py file. You have a function refreshgui which re imports start.py import will run every part of the code in the file. It is customary to wrap the main functionality in an ''if __name__ == '__main__': to prevent code from being run on...
qt,user-interface,python-3.x,dialog,qt-creator
use setModal() like so; dialog.setModal(1); Or; dialog.setModal(true); ...
Below is how I get my trouble solved. Using array to append all the processed data and use executemany to save them at once. In beforehand, have to modify mysql config max_allowed_packet = 500M A pain but valuable lesson. Answer: - import base64 import struct import pymysql.cursors import sys import...
python,csv,datetime,python-3.x
Once you have both the values in two variables, new_date and new_time, you could simply combine them to get the datetime, like this, >>> new_date = dt.datetime.strptime(row[0], "%Y.%m.%d") >>> new_time = dt.datetime.strptime(row[1], "%H:%M").time() >>> >>> dt.datetime.combine(new_date, new_time) datetime.datetime(2005, 2, 28, 17, 38) Note:- Avoid using date and time as variable...
python,django,osx,python-2.7,python-3.x
Recommended: Try using virtualenv and initiate your environment with Python3. Or a quicker solution is to use python interpreter directly to execute django-admin: <path-to-python3>/python /usr/local/bin/django-admin startproject mysite ...
For printing all display names , You should try - dnames = entry.findall(".//DisplayName") for x in dnames: print(x.text) For getting the specific display name under <Scalar> , you can do the below- name = entry.find('./Scalar/DisplayName').text print(name) ...
The operator module has operator.attrgetter() and operator.itemgetter() that do just that: from operator import attrgetter, itemgetter sorted(some_dict.items(), key=itemgetter(1)) sorted(list_of_dicts, key=itemgetter('name')) map(attrgetter('name'), rows) These functions also take more than one argument, at which point they'll return a tuple containing the value for each argument: # sorting on value first, then on...
count returns how many times an object occurs in a list, so if you count occurrences of '' you get 6 because the empty string is at the beginning, end, and in between each letter. Use the len function to find the length of a string....
You may be right... I think the error may actually be in Music21, with the way it handles importing StringIO Python 2 has StringIO.StringIO, whereas Python 3 has io.StringIO ..but if you look at the import statement in music21\midi\realtime.py try: import cStringIO as stringIOModule except ImportError: try: import StringIO as...
python,python-3.x,multiple-columns
For Python3 , You can try this function if you need column wise printing - def listPrinter(lst, cols): l = len(lst) rs = int(l/cols) for i in range(rs): for j in range(cols): print(lst[i + rs*j] , end='\t') print('') Please note, the argument lst to the above function is the list...
Yes, I believe the author could have used super() . The main advantage of super comes with multiple inheritance, this may interest you...
python-3.x,matplotlib,histogram
with your data, cases = list(set(actions)) fig, ax = plt.subplots() ax.hist(map(lambda x: times[actions==x], cases), bins=np.arange(min(times), max(times) + binwidth, binwidth), histtype='bar', stacked=True, label=cases) ax.legend() plt.show() produces ...
python-3.x,primes,sieve-of-eratosthenes,number-theory
Always try to measure empirical complexity of your code at several ranges. Your code is slow because of how you find the set difference, and that you always convert between set and list and back. You should be using one set throughout, and updating it in place with sete.difference_update(range(p*p,n,p*2)) To...
This problem occurs only with Python on Windows. In Python v3, you need to add newline='' in the open call per: Python 3.3 CSV.Writer writes extra blank rows On Python v2, you need to open the file as binary with "b" in your open() call before passing to csv Changing...
python,list,python-2.7,python-3.x,reduce
First, given the list and the index range, we can get the sublist A[i : j + 1] [66, 77, 88] For positive integers a and b, a * b is no less than a or b. So you don't need to do multiplying, it's not possible that multiplying of...
As I see from your error you have Python 3.5 install Try insatalling Python 3.3 or Python 3.4 because Djagno 1.8 not supporting Python 3.5 see this link for table that gives version compatibility with difrrent version of Python and Django...
read() will read the entire file. Try with readline(). with open('keys', 'r') as f: key = f.readline().rstrip() secret = f.readline().rstrip() print(key) print(secret) # ewjewej2j020e2 # dw8d8d8ddh8h8hfehf0fh or splitting read: with open('keys', 'r') as f: key, secret = f.read().split() print(key) print(secret) # ewjewej2j020e2 # dw8d8d8ddh8h8hfehf0fh with open('keys', 'r') as f: key,...
python,python-3.x,amazon-web-services,docker
You should install python3-pip in your Dockerfile and then run pip3 install -r requirements.txt
python,python-3.x,set-comprehension
You misunderstood; the set comprehension is a distinct expression, separate from the assignment. The expression produces a new set() object that then will be assigned to newSet, replacing the old set() object you had. As such, as you iterate and build the set, the previous and separate set() object bound...
python,function,python-3.x,tkinter
You are looking for the lambda keyword: from tkinter import * index={'Food':['apple', 'orange'], 'Drink':['juice', 'water', 'soda']} Names=['Food', 'Drink'] def display(list): for item in list: print(item) mon=Tk() app=Frame(mon) app.grid() for item in Names: Button(mon, text=item, command= lambda name = item: display(index[name])).grid() mon.mainloop() You have to use name = item so that...
It should suffice to set your item flags to include ItemIsEditable: self.item.setFlags(self.item.flags() | Qt.ItemIsEditable) You can also configure the EditTriggers to start editing as you like, e.g. upon double-clicking an item: treeView.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked) Double-clicking an item in your treewidget should now bring up an editor - which by default is simply...
Your function never returns the values, so they are discarded again. Add a return statement: def main(): infile = open("studentinfo.txt", "r") return infile.read() Also, in the interactive interpreter, all expression results are echoed automatically unless the result is None. In regular scripts, you'll have to print results explicitly: print(main()) ...
A common approach in Python is to initialize a variable to None if it is not being used yet. This is a signal to the future readers of your code that you want that variable to exist, but it won't be until later that it is used. infile = None...
The issue is in the line - grade_1, grade_2, grade_3, average = 0.0 and fName, lName, ID, converted_ID = "" In python, if the left hand side of the assignment operator has multiple items to be allocated, python would try to iterate the right hand side that many times and...
python,python-3.x,if-statement,condition
When you call getSrc a second time, the value of source that was created the first time has long since gone out of scope and been garbage collected. To prevent this, try making source an attribute of the function the same way you did for has_been_called. def getSrc(): if getSrc.has_been_called...
Taking the original code from the itertools man page copy the code for the combinations_with_replacement code but replace line 7 with new indices starting from your entered word. inputStr='acc' indices=[pool.index(l) for l in inputStr] And then run the rest of the code from the man page. EDIT: For a complete...
python,user-interface,python-3.x,model-view-controller,tkinter
You have two mistakes here: 1 - In your Counter.py file and in your Convert class methods, you are not return the right variables, instead of return celsius you should return self.celsius and same goes for self.fahrenheit 2 - In Controller.py file: self.view.outputLabel["text"] = self.model.convertToFahrenheit(celsius) This will not update the...
python,python-2.7,python-3.x,numpy,shapely
Without downloading shapely, I think what you want to do with lists can be replicated with strings (or integers): In [221]: data=['one','two','three'] In [222]: data1=['one','four','two'] In [223]: results=[[],[]] In [224]: for i in data1: if i in data: results[0].append(i) else: results[1].append(i) .....: In [225]: results Out[225]: [['one', 'two'], ['four']] Replace...
Normal string formatting cannot be used for bytes. I think the way to go about it is - you'd have to first generate a string, format it and then convert it to bytes with appropriate encoding. So the following changes should work change sock.send(b'Hello %s!' % data) to reply =...
Remove the if not len(key) != len(aDict) and the break. What you probably wanted to do is stopping the loop after iterating all the keys. However key is one of 'OG_1', 'OG_2', 'OG_XX', it's not a counter or something like that. Replace open("key", "w") with open(key + ".txt", "w")....
python,regex,python-3.x,directory,filtering
import os import re result = [] reg_compile = re.compile("test\d{8}") for dirpath, dirnames, filenames in os.walk(myrootdir): result = result + [dirname for dirname in dirnames if reg_compile.match(dirname)] As advised I will explain (thanks for the -1 btw :D) the compile("test\d{8}) will prepare a regex that matches any folder named test...
What about something like this? This is basically what you're doing in your "I'd like to do something like..." example. Attributes on scope objects default to None, and then get set using the attribute/xpath dictionary xmlPaths. There's some stuff going on in your code that I'm not sure about (for...
You should have a look at how floats are handled, and what limitations they have. https://docs.python.org/3/tutorial/floatingpoint.html is a Python specific explanation. In your particular example, Python chooses to use a representation that has a limited number of digits (depends on the Python version). Internally, different float values may share the...
python,python-2.7,variables,python-3.x,pygame
You are confusing the event KEYUP with the UP key. The event KEYUP occurs when a key (any key) is released. The event KEYDOWN occurs when any key is pressed down. In you code, this means that when the UP key is pressed down, the speed is set to 0.1,...
python,python-3.x,for-loop,flask,jinja2
As pointed out by Peter Wood in the comments, points is a generator: You need to turn it into a list: list(graph.find()) Thanks!...
python,python-3.x,for-loop,file-io
In python3, the 'for line in file' construct is represented by an iterator internally. By definition, a value that was produced from an iterator cannot be 'put back' for later use (http://www.diveintopython3.net/iterators.html). To get the desired behaviour, you need a function that chains together two iterators, such as the chain...