spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » PYTHON » Page 34
RGB to HSV Python, change Hue continuously
Use colorsys.hsv_to_rgb to convert the (H,S,V) tuple back to RGB: import os import colorsys import Image def hueChange(img, hue): # It's better to raise an exception than silently return None if img is not # an Image. img.load() r, g, b = img.split() r_data = [] g_data = [] b_data = [] for rd, gr, bl in zip(r.getdata(), g.getdata(), b.getdata()): h, s, v

Categories : Python

Python / read a specific part in a log file
You'll need to parse the entire file. with open(logfile) as f: for line in f: if line.startswith('**** start logging'): l = [] else: l.append(line) print(' '.join(l[:-1])) The last entry in l will be the line end logging, so I explicitly remove it. Alternatively, you could use file.seek(n, -2), where n is a guess for how many characters each logging

Categories : Python

How to display without [' '] in python
It's printing ['Matthew'] because it is a list which contains a single element, the string 'Matthew'. You can remove it from the list by simple indexing it. name = tree.xpath(xpath)[0] which will remove the first element. Note that if the list is empty, this will return an IndexError.

Categories : Python

Python's self argument
You're explicitly telling the Point object to display itself as (x,y) when you define the __str__ method. In order for the print to work it must convert itself to a string, and it does that by calling the __str__ method. Notice what happens when you remove the __str__ method: New Point object <__main__.Point instance at 0x1005da488> constructed In this case, python must still convert th

Categories : Python

Error installing package with pip
The $ refers to the beginning of a shell prompt, you shouldn't actually include it in your command :) So rather than (from the example question you posted) $ pip install requests you actually type pip install requests In any case, you can download matplotlib .exe files from here for use in Windows. Make sure you get the correct bitness (32bit vs 64bit) and the correct Python version.

Categories : Python

Getting lots of metadata from Spotify
Although I agree that you should be able to supply an offset that's greater than 100000 and that that's a technical issue that we may need to look into, I believe that having to page through more than 1000000 items is a clear indicator that the search query could be improved. What's most important here is what Jan-Philip Gehrcke has already mentioned - you're most likely violating Spotify's Terms

Categories : Python

Append columns to table, while preserving header
I figured it out. Copying the old header also copies the NAXIS1 keyword, which specifies the byte width of the first dimension. Adding extra columns increases this value. Make sure the NAXIS1 value reflects the width of the new table, not the old. EDIT: the above idea from Iguananaut works much better. But if you're doing something like copying only some of the header values, make sure you do no

Categories : Python

How to specify the method for fillna in pandas
If I understand correctly, you're looking for something like: >>> df = pd.DataFrame([[i, 20+i] for i in range(10)], columns=['a','b']) >>> df['b'][[3,4,5,8]] = np.nan >>> print df a b 0 0 20 1 1 21 2 2 22 3 3 NaN 4 4 NaN 5 5 NaN 6 6 26 7 7 27 8 8 NaN 9 9 29 >>> nan_indices = df.index[np.logical_not(df['b'] < np.inf)].values >>>

Categories : Python

Format list in email
Use str.join to join strings with newline: >>> ' '.join(['line1', 'line2', 'line3']) 'line1 line2 line3' >>> print(' '.join(['line1', 'line2', 'line3'])) line1 line2 line3 body = email.mime.Text.MIMEText(""" Report: %s """ % ' '.join(REPORT))

Categories : Python

django about permission with email as username login
It looks like AbstractUser subclasses the AbstractBaseUser and the PermissionsMixin which should allow a user to have groups. The examples in the link you posted only subclass AbstractBaseUser https://github.com/django/django/blob/master/django/contrib/auth/models.py#L374 I implemented a custom user (that uses email as username) for the first time a couple months ago (on django 1.6) and found m

Categories : Python

python - best way to write a list of images
Using list comprehension: self.img = [gtk.Image() for i in range(20)]

Categories : Python

Remove lines separating cells in seaborn heatmap when saved as pdf
This is an issue only when saving to PDF files, if you use something like a PNG then it will work fine. A Github Issue has been raised here with the developers. In the meantime, the developer mwaskom has found a fix where you can add rasterized=True to the seaborn.heatmap function which fixes the issue. Your code then becomes: import pandas as pd import numpy as np import seaborn as sns import m

Categories : Python

how to change the view
For abaqus the easiest thing to do watch the replay output generated by abaqus cae. Open the model manually in CAE and change the view to what you would like to see. Abaqus writes a python replay file of all the actions the user takes in the CAE window. Navigate to your working folder and find the file named abaqus.rpy. The last lines in that will be the python commands to replicate your actions i

Categories : Python

create a numpy array from the minimum values in the rows of an array
In [54]: dog=[[1,2],[4,3],[6,7]] In [55]: np.min(dog, axis=1) Out[55]: array([1, 3, 6]) or, if dog is a NumPy array, you could call its min method: In [57]: dog = np.array([[1,2],[4,3],[6,7]]) In [58]: dog.min(axis=1) Out[58]: array([1, 3, 6]) Since dog.shape is (3,2), (for 3 rows, 2 columns), the axis=1 refers to the second dimension in the shape -- the one with 2 elements. Putting axis=1

Categories : Python

Sorting a dictionary to an OrderedDict with a single key
The initialiser for dict/OrderedDict objects requires an interable of pairs key, val. As you clearly show in your testing, sorted(a) is an iterable but not of pairs, hence ValueError: need more than 1 value to unpack. If you want to create a dictionary from sorted(a), you should do it .fromkeys: >>> OrderedDict.fromkeys(sorted(a)) OrderedDict([('b', None)]) but I think you really w

Categories : Python

In Python's stat module, when I print stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO, why do I get 511 instead of 777?
0777 is an octal representation. In other word, 0777 = 7 * (8**2) + 7 * (8**1) + 7 * (8**0) >>> 0777 511 >>> 7 * (8**2) + 7 * (8**1) + 7 * (8**0) 511 >>> 0777 == 777 False If you want to get octal representation of a number, use oct, % operator or str.foramt with appropriate format specifier: >>> oct(511) '0777' >>> '%o' % 511 '777' >>>

Categories : Python

String replacement in SQL Query using Python
It's unclear wich sql library you're using but assuming it uses the Python DB API: Sql parameters are typically used for values, not columns names (while this is possible using stored procedures). It seems you're confused between string formatting in python and sql parametized queries. While %s can be used to format a string (see formatting strings) this is not the way to set sql parameters. S

Categories : Python

Create Python shell script with command line arguments
I'm responding to myself: #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Nov 19, 2014 @author: yllanos ''' # Standard libraries import sys import argparse # External libraries # Product modules import module1 as dbs import module2 as gen def main(argv): parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', action='store', dest='file', he

Categories : Python

jsoncpp : error while building the documentation
Ok, problem solved : $> cd jsoncpp/doc $> cat readme.txt The documentation is generated using doxygen (http://www.doxygen.org). $> sudo apt-get install doxygen ... OK $> python doxybuild.py --doxygen=$(which doxygen) --open --with-dot ... ok Just install doxygen and building the documentation will work.

Categories : Python

reading user input in shell script
The following will not cover all the possible use cases, but please try if this simple solution suffices for yours ... read -p "Enter your name : " choice < /dev/tty ... what happens, what was pointed to you... is that read reads from standard input, and you have globally redirected stdin to the file q0.txt

Categories : Python

How to load JSON data into nested classes?
You can identify objects by looking at their keys. You can then map them to the appropriate class. Using your example data: class AddressClass: # The parameters to init needs to be the same as the json keys def __init__(self, House_Number, Street_Number, State): self.house_number = House_Number self.street_number = Street_Number self.state = State class EmployeeC

Categories : Python

Simple form with CherryPy
You really need to learn the basics of the technology you deal with. And the basics of StackOverlow to ask good questions, so they are comprehensible and useful to others. You have relative form action, action='getnote', which tells a browser to appended it to the current pathname. This is why you get form submitted to /HomeP/getnote/. Use absolute action instead, action='/getnote'. Even though

Categories : Python

Open Python IDLE and Run Command
With a bit of trial and error I found the solution. In case anybody in future has same problem, it can be solved as below: import sys sys.argv=['','-n','-t','My New Shell','-c','execfile("VarLoader.py")'] import idlelib.PyShell idlelib.PyShell.main()

Categories : Python

Adding an alpha channel to a Monochrome Image using Open CV Python
You cannot create a 2-channel "luminance-alpha" image, however you can convert the 1-channel grayscale image to BGRA using only gray values by duplicating the grayscale channel and adding the alpha channel to that. Let l be the grayscale image: img_3gray = cv2.merge((l,l,l,a)) Nor can you apply an alpha channel to just one channel of an image, but you can take a single channel of the image (say

Categories : Python

Converting hex string to packet in Scapy
You can rebuild the packet using the class of the original packet, however there are other errors in your program. The official API documentation on the sniff function states that it returns a list: sniff(prn=None, lfilter=None, count=0, store=1, offline=None, L2socket=None, timeout=None) Sniffs packets from the network and return them in a packet list. Therefore, rather than e

Categories : Python

How to shift values in list of lists python?
You have hobbled yourself by naming your own variable list, preventing access to the built-in. If you give it a more sensible name: >>> lst = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] then you can easily transpose with zip, and use map to convert each resulting tuple into a list: >>> map(list, zip(*lst)) [[1, 1, 1], [2, 2, 2], [3, 3, 3]] Note that in Python 3.x map produces an iter

Categories : Python

How does a Django form know where to save its data when not using ModelForm?
You need to associate the form with your model at the view. Such as: form = CommentForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] url = form.cleaned_data['url'] comment = form.cleaned_data['comment'] my_comment = Comment(name=name,url=url,comment=comment) my_comment.save()

Categories : Python

A curious case of nginx uswgi python
The error probably occurs randomly because it's a runtime error in your code. That is, it doesn't get fired until a user visits your site with the right conditions to follow the code path that results in this error. It's unlikely to be an nginx caching issue. If it was caching it, then it would probably return the same result over and over rather then change on reload. However, you can test this

Categories : Python

Obtaining the first and second "column's" from a pair of lists
Use map function with zip and * stuple operator. l = [(38.621833, -10.825707), (38.572191, -10.84311), (38.580202, -10.860877), (38.610917, -10.85217), (38.631526, -10.839338)] x= map(list, zip(*l))[0] y = map(list, zip(*l))[1] print 'x = {}, y = {}' .format(x,y) x = [38.621833, 38.572191, 38.580202, 38.610917, 38.631526], y = [-10.825707, -10.84311, -10.860877, -10.85217, -10.83933

Categories : Python

Flask Redirect with parameter
According to the official docs, the parameters should be pass in the url_for, not the redirect. return redirect(url_for('register', message='email already exists'))

Categories : Python

Changing the rotation of tick labels in Seaborn heatmap
seaborn uses matplotlib internally, as such you can use matplotlib functions to modify your plots. I've modified the code below to use the plt.yticks function to set rotation=0 which fixes the issue. import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns data = pd.DataFrame(np.random.normal(size=40*40).reshape(40,40)) yticks = data.index keptticks = yticks

Categories : Python

How to find object by its id in Django Rest Framework
If you really want to use ListCreateAPIView. You need to make some changes: urls.py: url(r'^blogpost/(?P<post_id>w+)$', views.BlogPostList.as_view(),name='blogpost-list'), views.py class BlogPostList(generics.ListCreateAPIView): serializer_class = BlogPostSerializer permission_classes = (AllowAny,) filter_class = BlogPostListFilter paginate_by = 100 def get_queryset(self

Categories : Python

OGR Geometry changes Floating Points
The problem is that when using the float type you cannot exactly represent some numbers. e.g. In [47]: x = 0.4 In [48]: '{:.30f}'.format(x) Out[48]: '0.400000000000000022204460492503' and so when you store the number 12.5433026066 it actually is 12.543302606599999293734981620219. Your poly.ExportToWkt() method is exporting these numbers with a given number of decimal places, which is why the

Categories : Python

Error in creating status bar in PySide
You're trying to call statusBar() on your QApplication, which does not possess such method. You need to create a QMainWindows as your main widget, and call statusBar on it. Have a look at the PySide documentation of QMainWindow. You'll find an example of how to use the status bar.

Categories : Python

How can i mention current date in django rest framework filter field
DateRangeFilter in django_filters has already a similar functionality. It has predefined filters for today, this month etc. You can easily extend it to come up with a now filter.

Categories : Python

I have a bunch of strings, how do I make them into a list without having a list of individual words?
Use list. >>> s = ('hi my name is, huh', ' ', '', 'my name is, what', 'my name is harry potter') >>> list(s) ['hi my name is, huh', ' ', '', 'my name is, what', 'my name is harry potter']

Categories : Python

django EmailField point before @
In RFC 5321, section 4.2.1, the "local-part" of the address has the following grammar: Local-part = Dot-string / Quoted-string ; MAY be case-sensitive Dot-string = Atom *("." Atom) Atom = 1*atext The way I interpret this is that an Atom must have at least one character, and a Dot-string is one or more Atoms with dots in between them, and a Local-part is ei

Categories : Python

Python: Regex v. BeautifulSoup to remove from text
You can use a regular expression (yes) to match the contained text: soup.find_all('TYPE', text=re.compile('^s*(?:EX|XML)', re.I)) This will find all tags with tagname TYPE, whose directly contained text starts with EX or XML (case insensitively) but allowing for whitespace between the opening tag and the text. You can then extract those tags to remove them: for type_tag in soup.find_all('TYPE

Categories : Python

Python script to import mysql to postgresql
as reported in the answer you cite: from magic import Connect #Private mysql connect information Connect() is (I assume) a method feeding parameters to connect to a specific db. You thus have either to implement on your own this magic module, with references to your specific parameters, or to specify which connection you want to setup, namely MySQLdb.connect(...) or psycopg2.connect(...)

Categories : Python


Recently Add
Adding json to new Django database
document clustering in python
Only read the last character in a .txt file
Is it possible to redirect to different domain retaining the trailing endpoint, from a route?
Python NameError: not defined
Numpy array loop
Turning off Tick Marks in Bokeh
Python: Number and operator concatenation not working (Euler's Method)
Python: Twitter API tweets/search: Flatten nested dictionary to columns
Python 2.7 cmd autocomplete readline buffers seem stale
Memory usage/efficiency for pandas dataframe versus lists versus tuples, etc.
How can i use multiple lists as arguments in a function and receive them differently?
PyQt - setText method of QTableWidget gets AttributeError
Matplotlib - get value of autoscale
Backwards axes in numpy.delete
Twilio - How to determine the length of a conference call?
Counting string using for loop
Automating creation of class instances in python for an undetermined amount of instances
Printing 2D-array in a grid
Load PreComputed Vectors Gensim
IPython _repr_html_
Reversing a number using recursion
Is there a configuration under which a numpy operation will work on more than a single core/thread?
Is there a better way to write this if-statement?
Python: Effective reading from a file using csv module
Django/Python: CSV for-in loop overriding first row each time through
How to read the pickled igraph graph object from old version by new version igraph
Tornado WebSocket with Django ORM with shared session
trying to plot contours of bivariate normal, won't work with a correlation term
Python split users input
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.