w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » PYTHON » Page 2
Python Input 0 automatically
I think this is what you are looking for: n1 = raw_input('Εισάγετε Λεφτά :') or 0 n2 = raw_input('Εισάγετε Πλυσίματα Μέσα - Έξω :') or 0 n3 = raw_input('Εισάγετε Πλυσίματα Μηχανών :') or 0 n4 = raw_input('Εισάγετε Πλυσίματα Εξωτερικά :') or 0 n5 = raw_input('Εισάγετε Τι Ποσό Πήρε ο Σπύρο

Categories : Python

How can I specify the server where an egg is?
It is possible indicate where to retrieve the egg from including the full path to it in the find-lings parameter. The following example is taken from the pip docs: eggs = PILwoTk find-links = http://dist.plone.org/thirdparty/PILwoTk-1.1.6.4.tar.gz

Categories : Python

What is the difference between contiguous and non-contiguous arrays?
A contiguous array is just an array stored in an unbroken block of memory: to access the next value in the array, we just move to the next memory address. Consider the 2D array arr = np.arange(12).reshape(3,4). It looks like this: In the computer's memory, the values of arr are stored like this: This means arr is a C contiguous array because the rows are stored as contiguous blocks of memor

Categories : Python

How to perform HTTPS Calls in Pycurl?
According to the pycURL documentation, your post data needs to be key value pairs and url encoded: post_data = {'field': 'value'} # Form data must be provided already urlencoded. postfields = urlencode(post_data) # Sets request method to POST, # Content-Type header to application/x-www-form-urlencoded # and data to send in request body. c.setopt(c.POSTFIELDS, postfields)

Categories : Python

Error: Maximum recursion depth on using flask-babel method with Nereid
Finally I got the solution and here is how I reach there. Problem with recursion depth error with flask is its not easy to get root cause of problem, so with hit and trial approach I got tail of the problem. Method call flow is like this: dateformat filter > format_date() > to_user_timezone() > get_timezone() Now get timezone method is overridden here as: def get_timezone(): """ Retur

Categories : Python

Python - Monkey Patching weird bug
The issue was not having the right signature for one of the functions. It was resolved by changing the argument passed to the MonkeyPatch function as en empty dictionary {} instead of 'None' value which is kind of specific to my code. The reason the I was initially hitting the issue was, as the current function's call(cli.port_register) was failing when the parameters where passed to port_registe

Categories : Python

Execute bash file from Python
The program is executed in the current working directory as reported by os.getcwd(). For a command line program, its typically the directory you are in when you run the program. To run a command in the same directory as your python script, use the __file__ variable to figure out where you are: import os import envoy my_path = os.path.dirname(os.path.abspath(__file__)) envoy.run('./scripts.sh', c

Categories : Python

Writing a CSV from Flask framework
You need to add newlines. Anyway, your method of making csvs (printing the list and removing brackets from it) is not the best way to do it. Try this instead: csvList = ' '.join(','.join(row) for row in csvList) Or use the csv module: import io, csv dest = io.StringIO() writer = csv.writer(dest) for row in csvList: writer.writerow(row) # Now dest is a file-like object containing your cs

Categories : Python

Python 3 email body encoding
The problem is that many email clients (including Gmail) send non-ascii emails in base64. stdin on the other hand passes everything into a string. If you parse that with Parser.parse(), it returns a string type with base64 inside. Instead the optional decode argument should be used on the get_payload() method. When that is set, the method returns a bytes type. After that you can use the builtin d

Categories : Python

Get colorbar ticklabels
This gives you the ticks on the scale of the y-axis of the colorbar, which has limits (0.0, 1.0) cbar.ax.get_yticks() This is what you need: np.interp(cbar.ax.get_yticks(), cbar.ax.get_ylim(), cbar.get_clim()) The result is: array([ 10., 20., 30., 40., 50., 60., 70., 80., 90.])

Categories : Python

defining a function which calls another function for a variety of strings python
It only "works on the first string in the list" because you return from inside the loop. Keep track of your result outside of the loop. def test_find_anagrams(): stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')] result = [] for str1 in stringlist: result.extend(word for word in get_dictionary_word_list() if anagram(word,str1)) return re

Categories : Python

Python check if force closed
You can't. A process can't read it's own exit code. That would not make much sense. But in order to force process shutdown the OS has to send a signal to that process. As long as it is not SIGKILL and/or SIGSTOP then you can intercept it via signal library. SIGKILL and SIGSTOP cannot be blocked, e.g. if someone does kill -9 then there's nothing you can do. To use signal library: import signal im

Categories : Python

Python local class leak
Neither method will lead to leaks. The lifetime of Python objects is governed by reference counting; if there are no references left, the object is removed. In all cases here are the instances and classes in your Outer.AppendToMenu() method only referenced by locals, and will not lead to leaks. In both your cases, the counts for the class and instance are as follows: class _Inner creates the c

Categories : Python

Python3 Django -> HTML to PDF
You could use Weasyprint. You could easily render directly. You could do something like that: html = HTML(string=htmlstring) main_doc = html.render() pdf = main_doc.write_pdf() return HttpResponse(pdf, content_type='application/pdf') To render your Django view to HTML, you could simply use the shortcut render_to_string(self.template_name, context, context_instance=RequestConte

Categories : Python

Create a map using pymongo
You can approach like this, for itm in db.collection.find(): print {itm.pop('b'): itm} Here collection is the name of your collection in the database. If you iterate over the pymongo cursor object you will get dict type object which you can modify like normal python dict.

Categories : Python

Take In Input from User and Display the same input on the same page
First off you aren't passing the form to the template in articles(). You need to have something along the lines of: args['form'] = YourForm() In your first view function. Also, in your create view you do this: a.user = User.objects.get(username = request.user.username) Which does an unnecessary database lookup of the user again, you can just do this to be clearer and faster: a.user = requ

Categories : Python

Python GUI using tkinter and db connection
ttk.Label(mainframe, text = notice).grid(column = 1, row = 6) Changing the value of the string notice won't update the text in this label. You need to use a StringVar for this. notice = Tkinter.StringVar() ttk.Label(mainframe, textvariable = notice).grid(column = 1, row = 6) Then, instead of doing notice = "whatever" in your functions, do notice.set("whatever"). Alternatively, don't have a

Categories : Python

Monty Hall-Not Running
To many brackets and you do not need brackets in python. Try changing: if ((not(i == car) and not(i == guess1)): to if i != car and i != guess1:

Categories : Python

Remove all rows of lines between two stings from xml file using python
Use a SAX parser such as xml.sax. This gives you callbacks as it scans the XML file for each of the various xml tags or 'events' (ie opening a tag, closing a tag, seeing an attribute, seeing some data, etc). Keep track of whether you are in part of the XML file you do or do not want to keep (or delete) as you get these callbacks. Stream the data into a new file if you are in "keeping" mode, and do

Categories : Python

Can't go back to wxpython main frame after creating and destroying Dialogue using ShowModal via Pubsub
try changing secondaryReciever as follows class secondaryReceiver(object): def __init__(self): pub.subscribe(self.__OnShowDialog, 'add.item') def __OnShowDialog(self, message): dlgParent = message.data[0] dlgGrandParent = message.data[1] self.variableList = message.data[2] editParameterDialog = editParamDlg(dlgParent, dlgGrandParent, self.variableL

Categories : Python

Ploting the same numerical relationship in multiple units / representations
Try this # Plot the normalized chart (the one on the right) f, ax = plt.subplots(figsize=(3,3)) ax.plot(x,y) ax1 = ax.twinx().twiny() ax1.plot(x*len(ar), y*np.sum(ar), 'r')

Categories : Python

how do i combine the children of a node into one cell of a csv cell using elementtree in python?
Iterate text tags, and find p tags inside the text tags. Combine them using str.join: .... for content in root.iter('text'): writer.writerow([' '.join(p.text for p in content.iter('p'))]) UPDATE According to OP's commnet, to handle TypeError, UnicodeEncodeError OP should use the following: writer.writerow([' '.join(p.text for p in content.iter('p') if p.text is not None

Categories : Python

Issue saving a matplotlib figure
This is nothing to do with matplotlib really, and is instead because of how operating systems handle directories. / is often used for separating directories, i.e. my file is stored here /path/to/my/file.py. As such, it is unlikely that you're allowed to use the symbol / in a filename as it would confuse matters far too much. This is definitely not allowed in Windows and Ubuntu, not sure about OS

Categories : Python

Instantiation fails in a python object
map is a class attribute (shared between all instances of the class), not an instance attribute. If that's not the behavior you want, change it so that it's an instance attribute -- that is, move the map = list() part to inside __init__. You'll probably want to do the same to width, height and dictLine.

Categories : Python

Image warping with scikit-image and transform.PolynomialTransform
There are a couple of things wrong here, mainly they have to do with coordinate conventions. For example, if we examine the code where you plot the original image, and then put the clicked point on top of it: plt.imshow(orig, cmap='gray', interpolation='nearest') plt.plot(source[:,0],source[:,1],'+r') plt.xlim(0,orig.shape[1]) plt.ylim(0,orig.shape[0]) (I've taken out the destination points to

Categories : Python

Python destroying content to save memory
The html will be held in memory for as long as the object that references it exists. If your for loop does not assign the B object to any other variable, then each time you re-assign page the previously created B object will become eligible for garbage collection, and the html will be removed from memory at the same time. If you are retaining references to each of your B objects you will slowly

Categories : Python

Python client disconnect if server closes connection
When you have a loop with recv or anything that reads from a socket or a pipe, you should stop reading as soon as you get a buffer with len 0 : while True: data=the_socket.recv(8192) if len(data) == 0: break ...

Categories : Python

how to mock internal calls (xlwt)?
I don't know why you're trying to patch xlwt.Workbook.Workbook, but these two work for me: @patch.object(xlwt.Workbook, 'save', return_value=None) def test_patch_object(mock): wb = xlwt.Workbook() assert wb.save() == None @patch('xlwt.Workbook.save', return_value=None) def test_patch(mock): wb = xlwt.Workbook() assert wb.save() == None

Categories : Python

Python how to assert that a method has been called
Maybe you want to check if the method add_dns_analysis was call by parse_har(): Rewrite your test as def test_parse_har(self): with patch.object(rules, 'add_dns_analysis', return_value=None) as dns_mock: result = rules.parse_har(self.data,[self.rule],RulesTest.url) self.assertEqual(result[RULES.TOTAL_REQUESTS], 484) self.assertEqual(result[RULES.HTML_SIZE], 2

Categories : Python

urllib2 Error 403: Forbidden
Actually the problem is that they block everyone who doesn't have a user-agent import urllib2 request = urllib2.Request("http://www.cmegroup.com/trading/energy/natural-gas/natural-gas.html", None, {'User-Agent': 'Mozilla/5.0'}) content = urllib2.urlopen(request).read() splitted_page = content.split("<span class="cmeSubHeading">", 1); splitted_page = splitted_page[1].split("</span>",

Categories : Python

How to loop a whole python quiz without using def's?
If you break your code up into functions, it is easier to control the flow of code, for example: Let's make a function whos purpose is to ask a single question and determine if they were right or wrong def askQuestion(): import random num1 = random.randint(1,20) num2 = random.randint(1,20) answer = int(input('What is {} + {}'.format(num1, num2))) if (num1 + num2) == answer:

Categories : Python

django form not validating the datefield
You have declared form AppointmentForm1, but didn't use it appointment_date = request.GET.get('appointment_date') And use POST when you trying to create/update data in your database <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> So in your views should be something like this if request.POST: my_form = Appointme

Categories : Python

TKInter - The text in the label changes window's width
You can use the columnspan argument to let the label stretch over top all of your columns, instead of stretching out the first one. Add to your grid method: calculationsLabel.grid(row=0, column=1, columnspan=7 **gridStyle) (replacing 7 with however many columns you actually have)

Categories : Python

Accessing a python script in a different folder, using a python script
If you have some "global" variables I think is a good idea to have them in a separated module and import that module from each place you need them. This way you only have to do it as cdarke has commented.

Categories : Python

Pandas: Feeding index values to apply
You can reset the index, then it will be an ordinary column: df2.reset_index(level='id1') Or provide as_index=False to the groupby call: df2.groupby(['id2', 'id1'], as_index=False).sum()

Categories : Python

Adding up all pairs of columns of two matrices
It's not pretty but this line uses broadcasting to do the same thing: (A[:, np.newaxis, :] + B[np.newaxis, :, :]).reshape(nrow_A * nrow_B, ncol) Example import numpy as np ncol = 3 nrow_A = 5 nrow_B = 10 A = np.random.random_sample((nrow_A,ncol)) B = np.random.random_sample((nrow_B,ncol)) C = np.empty((nrow_A*nrow_B,ncol)) k = 0 for i in range(nrow_A): for j in range(nrow_B): C[k,

Categories : Python

Query multiple values at a time pymongo
You're making one call to the DB for each of your titles. The roundtrip is going to significantly slow the process down (the program and the DB will spend most of their time doing network communications instead of actually working). Try the following (adapt it to your program's structure, of course): # Build a list of the 1000 titles you're searching for. titles = [w["title"] for w in json_works

Categories : Python

Format a python list and search for patterns
If you want to call a function for each case, I would do it this way: def stub1(elem): #do something for match of type '-1' return def stub2(elem): #do something for match of type 'SD4' return def stub3(elem): #do something for match of type 'OPEN15' return sg = [500782, u'BMOU9015488', u'SD4', u'CLOSED', -1, '', '', -1] sg = map(unicode, sg) patterns = {u"-1":st

Categories : Python

Get data from a huge text file to replace data in another huge text file, efficiently (Python)
here is my contribution to your problem. First of all, here is what I understand about your problem, just to check I'm correct : You have two files, each are tabulation separated values file. The first, dbSNP, contains data, whose the third columns are identifiers corresponding to the gene's chromosome number (column 1) and the gene's position on the chromosome (column 2). The task so consist of

Categories : Python




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.