spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » PYTHON » Page 2
python - how to compute correlation-matrix with nans in data-matrix
You can convert all nan values to zeros using np.nan_to_num() and then proceed further. Demo: >>> data array([[ 5.1, 3.5, 1.4, 0.2], [ 4.9, 3. , nan, 0.2], [ 4.7, 3.2, 1.3, nan], [ nan, 3.1, 1.5, 0.2]]) >>> np.cov(data.T) array([[ nan, nan, nan, nan], [ nan, 0.04666667, nan, nan],

Categories : Python

Django and Apache2 error - You don't have permission to access / on this server
This bit doesn't look right: activate_env=os.path.expanduser("~/opt/teenvestor/bin/activate_this.py") Where is your virtualenv? In /opt or ~/opt? They are two different places. Everywhere else, you're referring to /opt.

Categories : Python

How to print output using only a POST Method?
Hey make sure your trailing stashes in your html are correct. you may refer to : Flask - POST Error 405 Method Not Allowed and flask documentation : http://flask.pocoo.org/docs/0.10/quickstart/ this <form action="/" method="post"> and this is same same but different <form action="" method="post"> Accessing it without a trailing slash will cause Flask to redirect to the canoni

Categories : Python

Get the last substring in string?
You can use awk to print the n:th column: awk '{print $14}' file You can filter out all lines that does not have at least 14 columns with the following syntax: awk 'NF==14 {print $14}' file

Categories : Python

ImportError: No module named injectpkg.database
Can you advise what you did to install injectpkg? Did this come with a .msi installer file or just the raw files to download? If you just downloaded the files then navigating to the directory where they are stored and running: python setup.py install should install this for you. If there is no setup.py file then you could try adding the path with the files in to your PYTHONPATH environment v

Categories : Python

Recursion on a python list, using cython?
You are appending to a list in your recursion: s.append(point), which is inefficient no matter whether you are working with C arrays (because you would have to allocate a new array of size old array + 1, copy old array over and add one element) or python lists. Then you are searching a list here: if i not in s: which means that for every point i, the whole list is going to be traversed to check i

Categories : Python

Python: How to remove whitespace from number in a string
You could use re.sub function like below, re.sub(r'(?<=d)s(?=d)', r'', string) DEMO OR To replace inbetween one or more space characters. re.sub(r'(?<=d)s+(?=d)', r'', string) Example: >>> import re >>> s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nost

Categories : Python

create np array index from 3 seperate columns of a pd dataframe
Instead of index = np.array((temp['X'], temp['Y'], temp['Z'])) you could use integer array indexing to perform the assignment: data = np.zeros((256, 256, 256), dtype=np.int) data[temp['X'], temp['Y'], temp['Z']] = temp['intensity']

Categories : Python

How to apply different rules for different start_urls in python scrapy?
You want to override the start_requests method and use custom methods with link extractors: def start_requests(self): yield Request('http://a.com', self.parse_a) yield Request('http://b.com', self.parse_b) yield Request('http://c.com', self.parse_data) def parse_a(self, response): links = LinkExtractor( # ... extract links from http://a.com ).extract_links(response)

Categories : Python

Read files in reverse till specific line (character) in Python
import re p = re.compile(r'#@#@#@#@#@#@#@(?!.*?#@#@#@#@#@#@#@)(.*)$', re.DOTALL) test_str = "#@#@#@#@#@#@#@ Time:12:00 PM, CPU:12.0,RAM:12334321,Network:1231231233,.... #@#@#@#@#@#@#@ Time:12:01 PM, CPU:14.0,RAM:12354621,Network:1239864833,.... #@#@#@#@#@#@#@ Time:12:02 PM, CPU:9.0,RAM:12398781,Network:1231598697,.... #@#@#@#@#@#@#@ Time:12:02 PM, CPU:9.0,RAM:12398781,Network:1231598697,.... asas

Categories : Python

module object has no attribute open in shelve
You imported a different module shelve, one that masks the standard library version. Do: import shelve print(shelve.__file__) and move that file aside, rename it, or delete it.

Categories : Python

Need help exporting data to JSON file
Create dictionaries to begin with, in one list, then save that one list to a JSON file so you have one valid JSON object: soupamd = BeautifulSoup(amd.content) products = [] for item in soupamd.select("div.listRow"): prodname = item.find("span", class_="name") adinfo = item.find("span", class_="additional") formfactor, grafisch, socket = item.find_all("span", class_="info")[:3] p

Categories : Python

Regular expression optimization
A bit more optimized. >>> import re >>> s = "-tpf0q16|856B 11/20/2014 00:00:00.015 0 0 0 0 0 689 14 689 703 702 701 700" >>> re.findall(r'(?m)^([^|]+)|[wd]+?s+?(d{2}/d{2}/d{4}s+d{2}:d{2}:d{2}.d{3})[sd]+?(d+)s+d+s+(d+?)$', s) [('-tpf0q16', '11/20/2014 00:00:

Categories : Python

How to compute different metric value in python cross validation
I am not sure if there is any wrapper function is provided by sklearn but something like this can save you some time. scores = ['accuracy', 'f1', 'precision', 'recall'] metrics = {score: cross_validation.cross_val_score(dt,x_data_tfidf.toarray(), target_arr, cv=cv,scoring=score) for score in scores}

Categories : Python

How to check if regex matches only number?
If I understand the question correctly, you want to check - given some regular expression r - if r might match anything which is not a number. In that sense, the empty regex $^ (matching nothing) would pass the test, since it matches nothing (and hence no non-number). 1[0-9][0-9a-z], however, matches 10s, which is not a number, hence the test fails. That is not possible with Python's regex facili

Categories : Python

why use django haystack slice queryset too slow?
Probably because: SearchQuerySet().models(Ringtone).filter(content=query_word)[:3] Does everything that SearchQuerySet().models(Ringtone).filter(content=query_word) does, but also, updates the query set with a limit clause and returns a new queryset. This could account for all or some of the time difference. To get meaningful results you'd need to average the time taken over many calls, and

Categories : Python

Make stretchable split screen in Tkinter
You're making this way too complicated. Just following the first example here, I made what you want: from Tkinter import * root = Tk() m = PanedWindow(root) m.pack(fill=BOTH, expand=1) text1 = Text(m, height=15, width =15) m.add(text1) text2=Text(m, height=15, width=15) m.add(text2) root.mainloop()

Categories : Python

Split a list into sub lists of decreasing size
Use a simple list comprehension, which iterates over the length of original list. Also, I have used variable name lst, since list is a python type. Here you go: >>> lst = [0,1,2,3] >>> [lst[i:] for i in range(len(lst))] [[0, 1, 2, 3], [1, 2, 3], [2, 3], [3]]

Categories : Python

"_csv.Error: line contains NULL byte" in CSV reader from STDIN
i solved it by handling CSV exception import sys , csv def main(argv): reader = csv.reader(sys.stdin, delimiter=',') lineCount = 0 errorCount = 0 while True: # keep iterating indefinitely until exception is raised for end of the reader (an iterator) try: lineCount += 1 line = next(reader) print "%d - %s" % (lineCount

Categories : Python

What is the best way to create a parent/master entry in a DJANGO CRUD database app and then add associating data fields to the parent/master?
No. You don't need multiple barcode models. The fact that you have a ForeignKey from barcode to hardware already allows you to have multiple barcodes for each hardware: a ForeignKey defines a many-to-one relationship. Also, it doesn't make any sense to name the foreignkey after the model it is in: it needs to be named for the model it is pointing to, ie hardware. Finally, don't prefix your field n

Categories : Python

Default libraries in freshly created Python virtual environment
Those are the libraries that are already installed globally on your system. Best practice is to use the --no-site-packages option when creating the virtualenv in order to avoid this exact issue.

Categories : Python

Call python function using HTML
There are many ways to do this: 1 - You can register a new Jinja2 filter 2 - You can pass your function as a Jinja2 parameter (This one is easier) For method 2: @app.route('/crawl') def crawl(): return render_template('crawl.html', myfunction=search) On the template call the parameter has a function {% extends "layout.html" %} {% block content %} <div class="jumbo"> <h2>Welc

Categories : Python

move values of 3D array knowing new coordinates with mask
Your map matrices are wrong, to get the result you want they need to be like these (since, when you put values into b, you are checking if m[k, j, i] != -1 and you want the last columns to be 0, not the first ones) mx = np.array([[[ 1., 2., 3., 4., -1.], [ 1., 2., 3., 4., -1.], [ 1., 2., 3., 4., -1.], [ 1., 2., 3., 4., -1.], [ 1., 2., 3., 4., -1.]],

Categories : Python

Retrieving all active variables from all stackframes during an exception
The traceback consists of a chain of object, linked together through the tb_next attribute. Each traceback object also links to the frame through tb_frame, and each frame has a f_locals attribute. Given a traceback object, you can print all locals along the chain with: current = traceback while current is not None: print current.tb_frame.f_locals current = current.tb_next See the Stand

Categories : Python

How to connect external mysql server in docker container
It looks like you granted access to your user accessing only through the localhost. Try the following on your MySQL server: GRANT ALL PRIVILEGES ON * . * TO 'xxx'@'192.168.1.13'; Please note that the IP address after the @ above refers to the address the MySQL client is connecting from (your Django container), not the address of the MySQL server.

Categories : Python

How can I find where a vector value passes a threshold and the n+1 value meets a condition?
Well, I solved it myself! (see Finding local maxima/minima with Numpy in a 1D numpy array ) locs = (np.diff(np.sign(np.diff(v_1))) < 0).nonzero()[0] +1

Categories : Python

How to make an object of a class extending Enum
Per the docstring in the source code (note that this method is defined on the metaclass, EnumMeta): [__call__] is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='red green blue')). The required positional argument value is either one of the values of an existing enumerator, or th

Categories : Python

Exception in classes when using Django
You shouldn't be trying to return an HttpResponse in your requests class. Instead of catching the exception and replacing it with an unwanted HttpResponse, let it propagate and catch it in the view: try: user_details = auth_client['auth/users/%s/details' % (request.POST.get('username'))].get().json()['result'] except requests.Timeout: return HttpResponse('whatever') Edit OK, so here's a

Categories : Python

Find and replace empty rows in list width Python
It is easy to keep record of the previous value in a loop than of the coming values. So my idea is to reverse the list. Replace each empty value by its previous one. Finally reverse the list back and you will get the result. >>> lst=('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '') >>> lst=list(lst[::-1]) >>> pr=0 >>> for j in

Categories : Python

Celery task that returns group in chain
Convert your group task to chord to achieve that. Here is a simple example. @app.task def dummy_task(): return 'I am a dummy task' @app.task def add(x, y): return x + y @app.task def task_with_group_task(): task1 = add.si(1, 2) group_task = group(add.si(i, i) for i in range(5)) task2 = chord(group_task, dummy_task.si()) task3 = add.si(9, 9) pipeline = chain(task1, t

Categories : Python

how to do 3d matrix to 3d multiplication in python without loops?
AFAIK, numpy can braodcast biscuitMask along the color dimension to fit the shape of the frame. This broadcasting is done automatically. Thus, maskedFrame = rgbFrame * biscuitMask maskedHsvFrame = hsvFrame * biscuitMask Should work without any loops or modifications. PS, If you are familiar with matlab, broadcasting is very much like applying bsxfun only numpy does it automatically for you.

Categories : Python

len(n) x len(m) array in NumPy
>>> arr = np.empty((len(m), len(n)), dtype=str) >>> arr.fill('') >>> arr[0] = list(n) >>> arr[:,0] = list(m) >>> arr array([['A', 'A', 'A', 'D', 'D', 'D', 'E', 'E', 'E'], ['A', '', '', '', '', '', '', '', ''], ['D', '', '', '', '', '', '', '', ''], ['D', '', '', '', '', '', '', '', ''], ['D', '', '', '', '', '', '', '', ''],

Categories : Python

python xpath IndexError: list index out of range
Use Try Except import requests from lxml import html def do_get(xpath): # OR URL What ever you need url='http://www.example.com' cont=requests.get(url) tree=html.fromstring(cont) out=tree.xpath(xpath)[0] try: do_get('....') except: do_get('....') Or if you wanna do it forever until you get the right one: def do_get(xpath): url='http://www.example.com' cont=req

Categories : Python

How to deal with keys not found in Python Dictionaries
collections.defaultdict import collections D = collections.defaultdict(int) D['foo'] = 42 print D['foo'], D['bar']

Categories : Python

Is there a python code to concatenate values into 1 cell in excel
This will take the input, and 'uniquify' on the 2nd column. #!/usr/bin/env python import csv dict={} with open('gene_test.csv','rB') as f: reader = csv.reader(f) for line in reader: try: dict[line[1]].append(line[0]) except: dict[line[1]]=[line[0]] with open('out_gene_test.csv','wb') as f: writer = csv.writer(f, delimiter='|') for key in

Categories : Python

Weird behavior from pythons multiprocessing
Fabric has its own facilities for parallel execution of tasks - you should use those, rather than just trying to execute Fabric tasks in multiprocessing pools. The problem is that the env object is mutated when executing the tasks, so the different workers are stepping on each other (unless you put locking in).

Categories : Python

Get all disconnected pairs of nodes in a network
Re the first question (listing pairs of disconnected nodes): yes, you have to do this manually, but it is fairly easy: from itertools import product all_nodes = set(range(g.vcount()) disconnected_pairs = [list(product(cluster, all_nodes.difference(cluster))) for cluster in g.clusters()] But beware, this could be a fairly large list if your graph is large and consists of

Categories : Python

Save File Using Common Dialog in Python3
Use could use the class FileChooserDialog from the module gtk: import gtk gtk.FileChooserDialog().run()

Categories : Python

Null/No SIFT descriptor and keypoints generated in python
The function sift.detectAndCompute will first try to detect a SIFT keypoint then compute a descriptor at the found location. This is not what you want: you want to have a descriptor for each patch. You can hand craft the keypoint locations first (by adjusting their pt property to the center of your patches and adjusting their size property to your patch size). Then, call only the descriptor extr

Categories : Python


Recently Add
Unable to Delete and redraw or Draw over plot axes based on PYQT widget state change
Generate, fill and plot a hexagonal lattice in Python
Getting a decorator with args to work with method: self does not exist
Is this function correct?
kivy adding variables to the root widget
Pandas: Generate a histogram/pivot against timeseries data
bash wrap a piped command with a python script
Selecting a combo box using selenium webdriver xpath
How to check how many calls left in AlchemyAPI? python
sklearn.ensemble.AdaBoostClassifier cannot accecpt SVM as base_estimator?
Sklearn Linear Regression - "IndexError: tuple index out of range"
How can I keep an object selected in the outliner after physically deselecting it in the 3d view?
Limiting results with Jinja (Python)
Python Flask - Which file is used to log?
ros python publisher/subscriber
Get spline fit residual from scipy.interpolate.splprep()
A linker error of Boost.Python in Visual Studio 2008
access parent methods in python
Python retreive DayOfWeek as integer
Async insertAll requests using python-api-client
django modelForm filter isn't effective?
Many numpy array manipulations in one array
How can I unit-test a method without instantiating the class?
base.html can't access {% if user.is_authenticated %}
How to cope with diacritics while trying to match with regex in Python
Data is missing after using @validate with Schema
Find out where a process writes to
kivy - getting a spinner to remember its selection
Regular expression is not working
Django - Get a QuerySet of Months and the amount of expense
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.