w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » PYTHON » Page 3
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

How do I read a integer from a file? Python help needed
Edited my answer because it was a wrong assumption that '3 ' is an invalid int literal. What's really happening here is that with f.readline(1) you are reading exactly 1 symbol from file. First you read '3' then you read ' ' and THIS is an invalid string literal. Use 'f.readline()' instead.

Categories : Python

How do you get Python to open a text file using print and input? I have the code I am using below
Python 3.x filename = input("What is the text file's name?") with open(filename) as f: for line in f: print(line) Python 2.x filename = raw_input("What is the text file's name?") with open(filename) as f: for line in f: print line Note that you may either use: A file name if the file is in the current working directory, e.g. data.txt A relative path from you

Categories : Python

Printing a list to a Tkinter Text widget
Append newline (' ') manually: from Tkinter import * # from tkinter import * lst = ['a', 'b', 'c', 'd'] root = Tk() t = Text(root) for x in lst: t.insert(END, x + ' ') t.pack() root.mainloop() BTW, you don't need to use index to iterate a list. Just iterate the list. And don't use list as a variable name. It shadows builtin function/type list.

Categories : Python

Multiple updating plot with pyqtgraph in Python
One problem is that you are appending to lists. This gets to be very slow when the lists grow large, as Python has to copy the full list to a new location that is one cell larger than the previous one. You could test this by running your code again with the appends removed, but continuing to read the data (which you throw away for that test). If that is the problem, there are several solutions:

Categories : Python

SyntaxError when running with Python 2
It appears that your script controlled_biomass_exp.py overwrites run in your current namespace. This toy example will produce a similar problem: # file: test.py run = "hello world!" print(run) Calling run in IPython is just a shortcut for %run which is a built-in magic function. Once you overwrite run (e.g. as shown in my toy example) you cannot use the shortcut anymore. However, %run control

Categories : Python

GUI not updating when adding a call to an external EM simulation program
I would imagine that you are interrupting the mainloop whilst running your simulation. If you want to do both at the same time, you may need to look into making your program multi threaded so that both the mainloop and your simulation can run concurrently.

Categories : Python

Websocket connection with autobahn and twisted in python
reactor.connectTCP accepts as its first argument an IP address (or a hostname). You passed it a URI. It got confused and decided this must be a hostname, tried to resolve it, failed, and stopped the client factory. Try passing real.okcoin.com instead of the full URI. This can be resolved to an IP address (I assume) and the connection attempt will be able to proceed further.

Categories : Python

How can I create an Exception in Python minus the last stack frame?
You can get the current frame and any other level using the inspect module. For instance, here is what I use when I'd like to know where I'm in my code : from inspect import currentframe def get_c_frame(level = 0) : """ Return caller's frame """ return currentframe(level) ... def locate_error(level = 0) : """ Return a string containing the filename, function name and lin

Categories : Python

Writing to csv error handling
The first obvious thing to do would be to check the HTTP status code for the response object. It's not an explicit part of the Google API documentation but obviously something else than a 200 ("Found") HTTP status code means you have a problem and you cannot even expect to get anything useful in the response's body. HTTP response codes are documented in the HTTP RFC. Then if you read the API's d

Categories : Python

Beautfiul Soup 3: convert two-byte Unicode sequences to actual Unicode characters
The characters you are looking at look like double-encoded UTF-8. If the input is hosed, there really isn't anything BeautifulSoup can do to rectify it. BeautifulSoup basically returns Unicode always, which is just as it should be (unless you are actually into manipulating encodings, in which case it's a hopeless hassle). It is possible, though unlikely, that BeautifulSoup is the source for the

Categories : Python

Error in Recursion
Your function Reduce() is not returning anything when it recurses. You'd want to change def Reduce(n) : if Check_Prime(n) : Reduce(n-1) else : return n into def Reduce(n) : if Check_Prime(n) : return Reduce(n-1) else : return n That way, each code path in Reduce returns a value.

Categories : Python

Joining the numbers to form a new number
Use str.join with for loop l = [1, 2, 3] In [75]: int(''.join(str(i) for i in l)) Out[75]: 235 Or use simple math:- In [77]: s = 0 In [78]: for x in l: ....: s = s*10 + x ....: In [79]: s Out[79]: 235

Categories : Python

BeautifulSoup splitting scrapped string into three rows
You could do simply like in the below example, In [23]: from bs4 import BeautifulSoup In [24]: s = """<td>1</td> ...: <td>2</td> ...: <td>3</td> ...: <td>4</td> ...: <td>5</td> ...: <td>6</td>""" In [4]: soup = BeautifulSoup(s) In [25]: td = [i.string for i in soup.find_all("td")] In [26]: td Out[26]:

Categories : Python

Python conditional block within try block
There is nothing wrong with your code. As @Tomo said, you can use any code within the try block. You said: I have run the test where module1 cannot be imported and the file module2.py exists This means permissions are not granted to perform os.stat() on your file module2.py. So all what you have to do is to chmod your file with the needed permissions (you can chmod it in 777 as a first test

Categories : Python

Twisted Could not accept new connection (EMFILE)
You are running out of available file descriptors, either on a per-user, per-process or per-computer basis. You may need to change some ulimit or sysctl parameters to increase these limits. Depending on your operating system this may be slightly different. For example, here's the relevant chapter of the FreeBSD handbook about tuning limits with sysctl.

Categories : Python

Multi-threading with Class and without class in python using join
target should be a function, not the result of a function (unless that result is a function). eg. target=printer. Note the absence of brackets. What you have effectively done is run printer three times. Then started three threads which have nothing to do. Then printed bye bye.

Categories : Python

Where to find the file after uploading via Flask/Python/Heroku?
The file is at filename = secure_filename(file.filename) file.save(os.path.join("/tmp/", filename)) which means whatever filename is, in the /tmp/ directory. No. It should be in /tmp/ filename. Although I don't think this is a valid location for heroku. I suspect you have to upload content to someplace else, like Amazon S3 or direct via node. The online location, such as S3 will have a

Categories : Python

Hashed password authentication in Python not working
linecache.getline returns ' ' character. https://docs.python.org/2/library/linecache.html This code should work: salt = linecache.getline(userin + '.userdat', 2).strip() saltin = newin + salt hashed_newin = (hashlib.sha256(saltin.encode()).hexdigest()) realin = linecache.getline('file.dat', 1).strip() if hashed_newin == realin: return True

Categories : Python

Join unicode u with non-ASCII value in python
The prefix only works for literal values; the syntax with prefix creates a different object type from the syntax without. To convert already created str objects, you need to decode them to Unicode, and in the other direction unicode objects can be converted to str objects by encoding them to bytes. If you don't explicitly decode bytes to Unicode, Python does this for you, implicitly, with the AS

Categories : Python

cv.COLOR_BGR2LAB gives wrong range
You are correct, the LAB values returned from OpenCV will never lie outside the range 0-100, 0-255, 0-255. But: the LAB color space's gamut exceeds the one of RGB color spaces, see for example the second paragraph in the wikipedia article on LAB. Thus, when you convert from RGB/BGR to LAB, you will never get the full LAB range, as LAB contains colors that can't be represented in RGB.

Categories : Python




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