w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » PYTHON » Page 34
Python OpenCV Colorspace Differences Between LAB and Grayscale
gray = 0.299R + 0.587G + 0.114B But the conversion from RGB to the L channel of LAB differs. (which is a non-linear function) The exact conversion can be found here. And the non-linearity of LAB conversion explains the last part of your question.

Categories : Python

Why whitespace is not the delimiter for input()?
In Python, input default type is string and in a string object's value, whitespaces are allowed (e.g s = "Bob Fred"). split(delim) is for splitting string object by a specified delimiter (again, default delimiter is whitespace here if you leave the delim argument empty). I think this is a default choice (design decision) as you will soon realise that converting string to integer, float, etc. typ

Categories : Python

Python- Changing element within a list of lists
your error is due the fact that colList is the pointer to a list and not a list itself. If you want to have "independent" list in each element of myboard you have to replace myboard.append(colList) with myboard.append(colList.copy()) In this way each element of myboard will be a copy of the list.

Categories : Python

Binary search tree insertion Python
So, the way insertion in a binary tree usually works is that you start at the root node, and then decide which side, i.e. which subtree, you want to insert your element. Once you have made that decision, you are recursively inserting the element into that subtree, treating its root node as the new root node. However, what you are doing in your function is that instead of going down towards the tr

Categories : Python

Pass a system argument into the following function
file does not equal 'image.jpg' because sys.argv is a list of arguments and doing [1:] simply creates a new list: >>> argv = ['script_name.py', 'image.jpg'] >>> file = argv[1:] >>> file ['image.jpg'] >>> type(file) <class 'list'> >>> Instead of using slice notation to extract the filename, you should be indexing the sys.argv list: >>>

Categories : Python

UnicodeEncodeError: 'latin-1' codec can't encode character u'u015f' in position 21: ordinal not in range(256)
"S with cedilla" is not in latin-1. You're probably looking for ISO_8859-3, ISO_8859-9, or maybe even windows-1254.

Categories : Python

How to plot 3D data as 2D grid colormap in Python?
You can use griddata from matplotlib.mlab to grid your data properly. import numpy as np from matplotlib.mlab import griddata x = np.array([0,0,1,1]) y = np.array([0,1,0,1]) z = np.array([0,10,20,30]) xi = np.arange(x.min(),x.max()+1) yi = np.arange(y.min(),y.max()+1) ar = griddata(x,y,z,xi,yi) # ar is now # array([[ 0., 20.], # [ 10., 30.]]) The choice of the mapped xi and yi point

Categories : Python

what can i do to fix this and print out all the names in the tuple that start with the same first letter
You're using name[0] as the index when accessing boys. You want to be using name2: if begin == boys[name2][0]: startn += boys[name2] Alternatively you can just iterate over the boys array itself: for boy_name in boys: boy_name[0] == begin: startn += boy_name (I'm not entirely sure what you're doing with startn as you haven't included that bit of your code.)

Categories : Python

Append csv by row from two lists in Python?
Looks like you just want the useful and flexible zip built-in. >>> away = ["away1", "away2", "away3"] >>> home = ["home1", "home2", "home3"] >>> list(zip(away, home)) [('away1', 'home1'), ('away2', 'home2'), ('away3', 'home3')]

Categories : Python

List is modified even when using deepcopy
Probably you have this struct: a = [[1, 2, 3, 5], [0, 5, 9, 10]] b = [[a]] No you change the list of a, if you set the list element with a copy or not, is irrelevant. a[0] = [1] # b[0][-1][0][:1] So now a is a = [[1], [0, 5, 9, 10]] and b is what you printed.

Categories : Python

check date range with only month and year in Python
You can first compute the two dates at the beginning and the end of your month: from calendar import monthrange from datetime import date, datetime begin = date(year, month, 1) end = date(year, month, monthrange(year, month)[1]) Then you can simply check that either begin or end fall within your range: (min_post_date <= begin <= max_post_date) or (min_post_date <= end <= max_post_

Categories : Python

numpy too many indices for array error
This looks like a structured array, most likely created by reading data from a csv (with np.genfromtxt). If so it probably is 1 dimensional with a complex dtype. Assuming the first field is called 'Date', then you can get an array of all the dates with myData['Date'] The data for the 1st row will be myData[0] The 1st date will either be myData[0]['Date'] or myData['Date'][0]. As I guess

Categories : Python

TypeError: object of type 'builtin_function_or_method' has no len(), in 2 parts of the code
The problem is with this line: guess = guess.lower You forgot to call the str.lower method so guess is being assigned to the method object itself. To fix the problem, call the method by placing () after its name: guess = guess.lower() # ^^ Below is a demonstration: >>> guess = 'ABCDE' >>> guess = guess.lower >>> guess <built-in method lower

Categories : Python

Overlapping bars in horizontal Bar graph
You set the width of the bars to 0.4, but you have three bars in each group. That means the width of each group is 1.2. But you set the ticks only 1 unit apart, so your bars don't fit into the spaces. Since you are using pandas, you don't really need to do all that. Just do df.plot(kind='barh') and you will get a horizontal bar chart of the dataframe data. You can tweak the display colors, et

Categories : Python

Plotting ROC curves for viola-jones results
Hope this helps, it plots ROC curve using face data, non face data function thresh = ComputeROC( Cparams, Fdata, NFdata ) %function ComputeROC compute the ROC curve face_fnames = dir(Fdata.dirname); full_face = 3:length(face_fnames); test_face = setdiff(full_face, Fdata.fnums); num_tf = size(test_face,2); nface_fnames = dir(NFdata.dirname); full_nface = 3:length(nface_fn

Categories : Python

Python + Pyside + QThreads emit signal and segmentation fault
You do not need the MySig class, and the signal should not be defined to emit a QObject because that does not match the type of object you are emitting. I cannot test your example code, but try this: class MyThread(QtCore.QThread): sig = QtCore.Signal(object) def __init__(self, parent=None): QtCore.QThread.__init__(self, parent) self.exiting = 10 ... def run(sel

Categories : Python

Django: "'p' is an invalid keyword argument for this function" in ManyToManyField
You cannot set a many-to-many association in create by passing it to the keyword argument p. You need to set the association separately, not in the create. You can also look into how to optimize the queries so the create and the setting-many-to-many don't turn into too many queries. See this StackOverflow question.

Categories : Python

Python: Returning a list doesn't work
You're defining classes in your intro method, and, even though it's returning it, your action1 method doesn't see any variable named classes anywhere. Relevant answer on Python scope and relevant documentation.

Categories : Python

Sharing python MySQL connection object between python classes
You can make a db class which has a self.dbconn = MySQLdb.connect(...) as a member and make it answer the queries for Age, Name etc. So then you use the same dbconn object for all your queries. You can also reuse cursor objects for different queries. To be really perfect, you can also specify a del method on the db class to close the connection on destruction. (Check also this discussion)

Categories : Python

How to over-write a label
Do not create mpnew labels. Create the label once, then use the configure method to change the text. global l l = Label(...) l.pack(...) ... l.configure(text="some string") As a suggestion: when learning tkinter, ignore place. It is much less useful than pack and grid. note: you must create the label and then call pack/place/grid on separate lines because pack/place/grid always returns None.

Categories : Python

string.template with arrays as placeholders
I suggest using the new .format() string formatting syntax: output = """<div class="form-group" id="{info_id}_container">""".format(info_id=info['id']) or even: info = {'id': 'my_id'} output = """<div class="form-group" id="{id}_container">""".format(**info)

Categories : Python

UnicodeEncodeError: 'ascii' codec can't encode character u'xea' in position 39: ordinal not in range(128)
The error happens here: print post+" "+post_dict[post]+" #python" The problem seems to be that you're concatenating ASCII strings and Unicode strings in this line. That's causing a problem here. Try concatenating only Unicode strings: print post + u" " + post_dict[post] + u" #python" If you're still having problems, look at the output of type(post) and type(post_dict[post]) which should both

Categories : Python

Timezone.now() vs datetime.datetime.now()
Just always use timezone.now(). Django now has timezone support which requires timezone 'aware' datetime objects. datetime.now() will return a timezone naive object, whereas timezone.now() will return a timezone aware object.

Categories : Python

Is there a way for me to download all the tweets made by all twitter users in a particular region?
Yes! You can. Use Tweepy import tweepy consumer_key = '' consumer_secret = '' access_token_key = '' access_token_secret = '' auth1 = tweepy.OAuthHandler(consumer_key, consumer_secret) auth1.set_access_token(access_token_key, access_token_secret) class StreamListener(tweepy.StreamListener): def on_status(self, tweet): print 'Ran on_status' def on_error(self, status_code):

Categories : Python

python, calling method on main thread from timer callback
I'm now sure what you trying to achive but i played with your code and did this: import threading import datetime def do_some_work(): print datetime.datetime.now() def start_working_interval(): def timer_tick(): do_some_work() timer = threading.Timer(10.0, timer_tick) timer.start() timer_tick() start_working_interval() So basically what i did was to se

Categories : Python

Pass pandas dataframe into class
You don't need a @staticmethod for this. You can pass the pandas DataFrame whenever you're creating instances of the class: class MyClass: def __init__(self, my_dataframe): self.my_dataframe = my_dataframe a = MyClass(my_dataframe) b = MyClass(my_dataframe) At this point, both a and b have access to the DataFrame that you've passed and you don't have to read the DataFrame each tim

Categories : Python

re.sub replace spaces with comma
To remove the leading and trailing spaces you can use .strip(), and then to replace consecutive whitespace characters using the regular expression s+: >>> import re >>> s = " 2.4 -2.0 4.3" >>> re.sub("s+", ",", s.strip()) '2.4,-2.0,4.3'

Categories : Python

Keep User authenticated using Django Rest and Phonegap?
Yes, send a post request to a RESTful backend with username and password combo Django authenticates the username and password and logs the user in which sets a sessionid associated with the user which I believe you are referring to as a token. This is done via the login() method. https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.login Normally Django would set a sess

Categories : Python

PyOpenGL: gluLookAt behaviour?
You are missing glMatrixMode(GL_PROJECTION) before the glOrtho. So after the init call you have an identity (no-op) projection matrix and a modelview matrix that happens to include the orthographic projection before the lookat. I would assume that the first frame you draw looks OK. After that you set up the MODELVIEW matrix correctly, but the projection is wrong. The usual pattern for OpenGL ren

Categories : Python

HTTP Error 422: Unprocessable Entity - when calling API from Python (but curl works)
Why are you url-encoding the data? That's not what the curl version is doing. Dump it to JSON instead: data = json.dumps(json_values) req = urllib.request.Request(create_droplets_url, data)

Categories : Python

SAS, Python, Excel Create Constantly Updating Function
In SAS you can create a view so that it updates as your table updates. Regardless of what solution you use, its important to clarify how your table is being updated. data have; do id=1 to 10; numobs=ceil(rand('uniform')*5); do i=1 to numobs; value=rand('bernoulli', 0.3); output; end; end; drop i numobs; run; proc sql; create view want as select id, value, su

Categories : Python

Output and Import list of lists to Pandas DataFrame
One way to do this is to separate your columns with a custom separator such as '|' Say: somelist = ['a','b','b','c'] somefloat = -0.64524 sometuple = (235,633,4245,524) output = str(somelist) + "|" + str(somefloat) + "|" + str(sometuple) (if you wanna have many more columns, then use string.join() or something like that) Then, just as before: outfile = open('log.txt','a') out = output + ' '

Categories : Python

Can't get CKEditor plugins to work in django
The Code Snippet plugin has various dependencies each of which has sub-dependencies, i.e.: Widget (has Line Utilities as a sub-dependency amongst others) Dialog (also has sub dependencies) I had to as a minimum add Code Snippet, Widget and Line Utils in the ckeditor/plugins path to get it to work, as well as use the following setting to get the button to show up in the toolbar. CKEDITOR_CONFI

Categories : Python

Levenshtein module in python doesn't work
You're not forgetting to use the module namespace are you? Calls should look something like this: import Levenshtein lev_dist = Levenshtein.distance(args) Alternatively, you can make distance() accessible without the module. bit by doing: from Levenshtein import distance lev_dist = distance(args)

Categories : Python

python pandas overwriting the timestamps
Use the .transform method of the GroupBy object: import pandas import numpy dtindex = pandas.DatetimeIndex( start='2012-01-01', end='2012-01-15', freq='10s' ) df = pandas.DataFrame( data=numpy.random.normal(size=(len(dtindex), 2)), index=dtindex, columns=['A', 'B'] ) groups_5min = df.groupby(pandas.TimeGrouper('5Min')) first_5_of_everything = groups_5min.transform(lam

Categories : Python

Atom not found in symbol index when installing PyLucene on Mac OS X 10.9
You either need to build Python from source with the same compiler, as described here, or alternatively build it in NO_SHARED mode. The latter is the default for the pylucene homebrew formula.

Categories : Python

Get the ranges for repeated values in a Python list
If the repeated calls to plot are the problem, then you will get a speedup if you group all the points by color and render them all together. A way to do this (quick and dirty, so that you can check if this makes your rendering faster at all) is here: from collections import defaultdict points = defaultdict(list) # will have a list of points per color for i in range(len(X)): color = self.pos

Categories : Python

How to change the output of this Python program
Join the characters to together with the str.join() method; pick a joining string and call the method on that, passing in your list: password = ''.join(password) This joins the characters with the empty string (''): >>> password = ['x', 'p', 'E', 'X', 'V', '#', ',', '@', 'q', 'N', 'F', 'U', 'b', 'W', '.'] >>> ''.join(password) 'xpEXV#,@qNFUbW.' For other uses you could pick

Categories : Python

redirect to last page not working on python social auth
You can include this in head of your template of the redirected page - <script type="text/javascript"> if (window.location.hash == '#_=_') { window.location.hash = ''; } </script>` It will do the trick!

Categories : Python




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