spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » PYTHON » Page 4
Error "QObject::startTimer: QTimer can only be used with threads started with QThread" many times when closing application
Personally, I don't put any effort into chasing exit crashes anymore--just use pg.exit() and be done with it. (but if you do happen to find a bug in pyqtgraph, don't hesitate to open an issue on github)

Categories : Python

Simple map function error
I think what you're looking for is >>> list(map(lambda x: x, range(3))) [0, 1, 2] map returns an iterator. The message you are seeing is simply the object type for which you have just created an instance >>> map(lambda x: x, range(3)) <map object at 0x02E11F10>

Categories : Python

uWSGI env and PYTHON_EGG_CACHE configuration options
evn option exports an environment variables to the UWSGI web server process. The option can be specified manyt times to export multiple varibles. The values can be read from os.environ dict in Python. PYTHON_EGG_CACHE is not uWSGI specific and it is answered here: What is the Python egg cache (PYTHON_EGG_CACHE)? It is most likely related how Python eggs are deployed on your production server.

Categories : Python

Python: Appending to lists as keys within a dictionary
Two problems. First, everywhere you're using kingdom[1], you should just be using kingdom. Seems like you used to have a function that took a single list containing two sublists, and you didn't update the code to correspond to the new signature. Second, doing d[kingdom[j]] = b will cause all values in d to point to the exact same list. Appending to one of them will cause all the other ones to be

Categories : Python

Callbacks in Python Maya plugin
From the comments it sounds like there are two separate issues. Notificiations on object creation are 'free', in the sense that you can do this without the API by using a scriptJob. Here's a trivial example def new_object_callback(): print "created", cmds.ls(sl=True) cmds.scriptJob(e=('DagObjectCreated', new_object_callback)) The callback here is just a plain python script , but it could

Categories : Python

Python: how to locate a missing delimiter and append it to a text file
You simplify the code a lot by using re.sub function. ^(d+.*)(?<!//)$ Example usage: >>> file = open('input', 'r') >>> for line in file: ... print re.sub(r'^(d+.*)(?<!//)$', r'1//', line), Would produce an output as A string of information that does not require the delimiter 95 full !oe, !oeha // 96 new kaba// 100 name !uo5 // Regex ^ Anchors the regex at

Categories : Python

How to return .xlsx file?
You need to explicitly set the content-type header. The content-type for Excel files is application/vnd.ms-excel for .xls files or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for .xlsx files, so try this: response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' Full code: @route('/download') def download(): response.heade

Categories : Python

Python Pyserial Serial Buffer
Yes, you can use the Serial.outWaiting() method to check how much data is still waiting to be sent. I'm not sure exactly how the Serial.write() method behaves, if it just adds the data to the internal buffer before returning. It would have to be that way in order for the above to be needed, but on the other hand there's nonblocking() to make it non-blocking. It's a bit confusing.

Categories : Python

"error: command 'x86_64-linux-gnu-gcc' failed with exit status 1" in virtualenv
I installed python2.7-dev via Synaptic Package Manager in Linux Mint 17. I could then accomplish the following in virtualenv: pip install pillow pip install pycrypto And then I installed libxml2-dev and libxslt1-dev via Synaptic and could accomplish the following: pip install lxml I also did this so that the pymongo install didn't have any errors: pip uninstall pymongo pip install pymong

Categories : Python

Dynamic number of loops
This can be extended to arbitrarily long chains. The ranges should be apparent, you simply pass in a dictionary of the function mappings and the values you want to evaluate all the terms of the outer product over. import itertools def f(x,y): return x+y def g(x,y): return 2*x-y def outer_product_thing(F,M): keys = M.keys() ranges = [M[k] for k in keys] for rx in itertools.product(

Categories : Python

zeromq load balacing in "divide and conquer"
In this case it is better to use ROUTER and REQ sockets. This is possible in python with client = context.socket(zmq.ROUTER) and worker = context.socket(zmq.REQ) A fully worked out example by Jeremy Avnet can be found in the zguide. One can observe that even with the code of the question added the runtime will be close to optimal. Why this works is described also in the in the section The

Categories : Python

python separating element in a list
Through re.search function. >>> lst = ['<div class="closeColor">0</div>', '<div class="closeColor">0</div>', '<div class="openColor">6</div>'] >>> [re.search(r'(?<=>)[^<>]*(?=<)', i).group() for i in lst] ['0', '0', '6'] Regular Expression: (?<= look behind to see if there is: >

Categories : Python

pandas rearrange dataframe to have all values in ascending order per every column independently
The desired sort ignores the index values, so the operation appears to be more like a NumPy operation than a Pandas one: import pandas as pd d = {'one':[None, 2, 3, 4], 'two':[4, 1, 4, 2], 'three':[3, 4, 6, 8],} df = pd.DataFrame(d, index = list('ABCD')) # one three two # A NaN 3 4 # B 2 4 1 # C 3 6 4 # D 4 8 2 arr = df.values arr.sort(a

Categories : Python

Extended class not running the constructor
You aren't calling the constructor in your subclass. You need to explicitly call it, either with Submission.__init__() or by using super(). Note also that as you're using Python 2, your base class should inherit from object to ensure it's a new-style class. class Submission(object): sender = None def __init__(self): self.sender = 'test sender' class SmsSubmission(Submission):

Categories : Python

How to write an Ansible task using with_dict in a loop (with_items)
I find very interesting this way of organizing variables for .ini files. I wanted to use it myself, so I worked on a plugin that allows to generate all the keys of an .ini file in one pass with the inifile module. It works fine and I use to manage my OpenStack configuration files. I am not a specialist in development, but I think this plugin can be useful for everyone, so if someone wants to ta

Categories : Python

How to parse a CLI command output (table) in python?
# Did this in Python 2.7 import re # Assume your input is in this file INPUT_FILE = 'text.txt' # Regex to only pay attention to lines starting with Ib # and capture the port info regex = re.compile(r'^(Ibs*S+)') result = [] # Store results in a list with open(INPUT_FILE, 'r') as theFile: for line in theFile: match = regex.search(line) if not match: continue result.append(match.grou

Categories : Python

How is it possible to use 'auth.navbar' for custom navigations?
Check out the auth.navbar signature. What you want can be achieved with this: {{=auth.navbar(separators=('', '', ''))}} You can also call auth.navbar(mode='bare'), which will return a dictionary with the relevant URLs and labels. You can then pass that dictionary to a custom navbar function to lay out and style the navbar as you like. For more details, see the docstring.

Categories : Python

How to preprocess time series data in Python for forecasting
You can easily construct your shifted array in one line. Here I used the range of integers to help you see what is going on - just replace A with your data. import numpy as np A = np.arange(10) cut = 6 B = np.array([A[k-cut:k] for k in xrange(cut,A.size)]) print B Giving: [[0 1 2 3 4 5] [1 2 3 4 5 6] [2 3 4 5 6 7] [3 4 5 6 7 8]] For parsing the dates, try looking to pandas, it's an excel

Categories : Python

BeautifulSoup: TypeError: 'NoneType' object is not subscriptable
My guess is that label_tag isn't actually returning the part of the soup you are looking for. This minimal example works: import bs4 text = '''<a class="Label" href="_link_">_text_</a>''' soup = bs4.BeautifulSoup(text) link = soup.find("a",{"class":"Label"}) print (link["href"]) Output: _link_

Categories : Python

How to use Django's ORM to retrieve an aggregation using subquery?
It may be a little easier to think about this if you rename related_to to parent_user and profile to child_profiles: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) parent_user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='child_profiles') ... Then, you can do something like this: metric_sums = Met

Categories : Python

Django Rest Framework organizing ViewSets and Routers
For what it's worth, I've always created a separate api/ subdirectory within my Django apps to hold all Django REST Framework related files. This is just one way of doing things but it's helped keep separation of concerns within our applications. The hierarchy looked like this... Django Project/ Django App/ views.py models.py urls.py api/ serializers.py viewsets.py

Categories : Python

How to return height and width of a base 64 encoded graphic using tkinter
Use width, height method of the PhotoImage: ... photo = tk.PhotoImage(data=image_png) print(photo.width()) # => 32 print(photo.height()) # => 32 ...

Categories : Python

Changing encoding in csv file through python UTF-8 to UTF-16
If you want to convert a file from utf-8 encoding to a file with utf-16 encoding, this script works: #!/usr/bin/python2.7 import codecs import shutil with codecs.open("input_file.utf8.txt", encoding="utf-8") as input_file: with codecs.open( "output_file.utf16.txt", "w", encoding="utf-16") as output_file: shutil.copyfileobj(input_file, output_file)

Categories : Python

Convert one dimension list to two diminsions with specific delimiters
Use listcomprehension with with str.split() and str.strip() a = ['A;B;C;D E;F;G;H I;J;K;L '] In [152]: [x.split(';') for x in a[0].strip().split(' ')] Out[152]: [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']] or use map with lambda function In [160]: map(lambda x: x.split(';') ,a[0].strip().split(' ')) Out[160]: [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L

Categories : Python

Python Regex masking key-value pairs in strings
Use re.sub function. >>> s = "assdd ffdsfad 'result_secret_key': 'dfkfaj&^%2', 'auth_matrix': '213fsdf#', 'password': 'adsfa&&*!@#4' and 'app_auth': 'eff#@DS' dafsdsaf adfs adlsfjasdkjf " >>> re.sub(r"('S*?(?:secret|auth|key|password)S*?'s*:s*')[^']*(?=')", r'1******', s) "assdd ffdsfad 'result_secret_key': '******', 'auth_matrix': '******', 'password': '******' and

Categories : Python

Use of Inf on Matlab
It just assigns a minus infinity value to the left-hand side. It may appear weird to assign that value, particularly because a distance cannot be negative. But it looks like it's used for effectively removing those entries from the max computation in the last line. If Python doesn't have "infinity" (I don't know Python) and if dist is really a distance (hence nonnegative) , you could use any neg

Categories : Python

[Python]Put names in alphabetical order
Don't create it in alphabetical order; create it, then sort it. More specifically: put your randomly-generated names in a list, and use either the sort method to sort that list, or (as @gefei suggests) use the sorted function to get a sorted copy of the list.

Categories : Python

Numpy failing to properly square array
The trouble is that zs = np.array(range(80262,80268)) creates an array of int32 values. np.square(zs) returns an array of the same datatype as zs and the final squared value in the array overflows the four bytes of memory it's been allocated. You see that Ns = -np.square(zs) + 2*zs*R+ 3*R**2 has a datatype of int64 because NumPy has given this array more memory in order to accommodate the larger

Categories : Python

pandas column names to list
The list [u'q_igg', u'q_hcp', u'c_igg', u'c_hcp'] contains Unicode strings: the u indicates that they're Unicode strings and the ' are enclosed around each string. You can now use these names in any way you'd like in your code. See Unicode HOWTO for more details on Unicode strings in Python 2.x.

Categories : Python

Why is there a limit on delayed calls like asyncio.call_later to not exceed one day?
This is due to issue 20493: In asyncio, if the next event is in 2^40 seconds, epoll.poll() raises an OverflowError because epoll_wait() maximum value for the timeout is INT_MAX seconds. Guido van Rossum suggested that: For now, can we just add to the asyncio docs that timeouts shouldn't exceed one day? Then we can fix it later without breaking expectations. It's best to read the full i

Categories : Python

What's wrong with this following Tkinter program?
def __init__(self, master=None): frame = Frame(master) frame.pack() self.createWidgets() The frame you defined in __init__ is not visible in any other methods. If you want to be able to access it, you need to make it an attribute of self. def __init__(self, master=None): self.frame = Frame(master) self.frame.pack() self.createWidgets() Don't forget to include the self.

Categories : Python

Sort a Document by first character
Updated from operator import itemgetter filenames = ['1.txt', '2.txt', '3.txt'] with open('output.txt', 'w') as outfile: total_lines = [] for fname in filenames: with open(fname) as infile: total_lines += map(lambda s: s.strip(' '), infile.readlines()) for line in sorted(total_lines): outfile.write(line)

Categories : Python

How to use python variable in os.system?
You could use format to construct the string os.system('cowsay {}'.format(word)) Or simple string concatenation os.system('cowsay ' + word) But I prefer the former, especially if the string get more complicated.

Categories : Python

how to create a network of instances of a class in Python
What you need is to implement a directed graph. There are many ways to implement a graph I recommend you to read Python Patterns - Implementing Graphs. A simple idea: You could hold a list of every instance you want to pass input to (that's also a graph). class Node: def __init__(self): self.targets = [] def output(self): for target in self.targets: target.

Categories : Python

How to use exclude_properties and include_properties to exclude/include SQLAlchemy model attributes from corresponding Spyne model?
This doesn't directly answer your question, but please consider the following code: from spyne import * TableModel = TTableModel() class SomeClass(TableModel): __tablename__ = 'some_table' id = Integer(pk=True) s = Unicode i = Integer(exc_table=True) Here, pk stands for primary key (you can use the long form primary_key if you wish) and the i attribute will just be ignored by

Categories : Python

Error from amavisd-new-cronjob sa-sync
I recently investigated on this issue because I got the same error as a mail from cron. My server runs with Debian Wheezy. You can track the error by testing pyzor using the documented command line: $ su - amavis -c "echo test | spamassassin -D pyzor 2>&1 | less" Of course you can replace "echo test" with a real spam mail in order to get a real test result. But BTT: In my case, the prob

Categories : Python

How to use least squares with weight matrix in python?
I don't know how you have defined your weights, but you could try this if appropriate: import numpy as np A=np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,0,0]]) B = np.array([1,1,1,1,1]) W = np.array([1,2,3,4,5]) Aw = A * np.sqrt(W[:,np.newaxis]) Bw = B * np.sqrt(W) X = np.linalg.lstsq(Aw, Bw)

Categories : Python

TypeError: 'bool' object is not callable - python
What you get as a result of the first line is operators = (False, False, False, False, False) or something in those lines. Then you are trying to call a boolean that gets you the exception you have. add == str("add") will evaluate to False, since you're trying to compare a function to a string. I'm assuming you are trying to implement a simple math game, hence instead of using operator, whi

Categories : Python

get substring from the main string Python
Using urlparse.urlparse and cgi.parse_qs (Python 2.x): >>> import urlparse >>> import cgi >>> >>> s = 'http://domain.com/xxxxx/xxxxxxxx?tags=%7C105651%7C102496&Asidebar=1&dnr=y' >>> cgi.parse_qs(urlparse.urlparse(s).query) {'dnr': ['y'], 'Asidebar': ['1'], 'tags': ['|105651|102496']} >>> cgi.parse_qs(urlparse.urlparse(s).query)['tags']

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.