Signals And Slots Pyqt Array

 

A Deeper Look at Signals and Slots ScottCollins2005.12.19 what are signals and slots?

To establish a signal and slot connection between two widgets in a dialog, you first need to switch to Qt Designer's Edit Signals/Slots mode. To do that, you can press the F4 key, select the EditEdit Signals/Slots option in the main menu, or click on the Edit Signals/Slots button on the toolbar. Sending Python values with signals and slots On the #pyqt channel on Freenode, Khertan asked about sending Python values via Qt's signals and slots mechanism. The following example uses the PyQtPyObject value declaration with an old-style signal-slot connection, and again when the signal is emitted, to communicate a Python dictionary.

Every GUI library provides the details of events that take place, such as mouse clicks and key presses. For example, if we have a button with the text Click Me, and the user clicks it, all kinds of information becomes available. The GUI library can tell us the coordinates of the mouse click relative to the button, relative to the button's parent widget, and relative to the screen; it can tell us the state of the Shift, Ctrl, Alt, and NumLock keys at the time of the click; and the precise time of the click and of the release; and so on. Similar information can be provided if the user 'clicked' the button without using the mouse. The user may have pressed the Tab key enough times to move the focus to the button and then pressed Spacebar, or maybe they pressed Alt+C. Although the outcome is the same in all these cases, each different means of clicking the button produces different events and different information.

The Qt library was the first to recognize that in almost every case, programmers don't need or even want all the low-level details: They don't care how the button was pressed, they just want to know that it was pressed so that they can respond appropriately. For this reason Qt, and therefore PyQt, provides two communication mechanisms: a low-level event-handling mechanism which is similar to those provided by all the other GUI libraries, and a high-level mechanism which Trolltech (makers of Qt) have called 'signals and slots'. We will look at the low-level mechanism in Chapter 10, and again in Chapter 11, but in this section we will focus on the high-level mechanism.

Every QObject—including all of PyQt's widgets since they derive from QWidget, a QObject subclass—supports the signals and slots mechanism. In particular, they are capable of announcing state changes, such as when a checkbox becomes checked or unchecked, and other important occurrences, for example when a button is clicked (by whatever means). All of PyQt's widgets have a set of predefined signals.

Whenever a signal is emitted, by default PyQt simply throws it away! To take notice of a signal we must connect it to a slot. In C++/Qt, slots are methods that must be declared with a special syntax; but in PyQt, they can be any callable we like (e.g., any function or method), and no special syntax is required when defining them.

Most widgets also have predefined slots, so in some cases we can connect a predefined signal to a predefined slot and not have to do anything else to get the behavior we want. PyQt is more versatile than C++/Qt in this regard, because we can connect not just to slots, but also to any callable, and from PyQt 4.2, it is possible to dynamically add 'predefined' signals and slots to QObjects. Let's see how signals and slots works in practice with the Signals and Slots program shown in Figure 4.6.

Figure 4.6 The Signals and Slots program

Both the QDial and QSpinBox widgets have valueChanged() signals that, when emitted, carry the new value. And they both have setValue() slots that take an integer value. We can therefore connect these two widgets to each other so that whichever one the user changes, will cause the other to be changed correspondingly:

class Form(QDialog):

def_init_(self, parent=None):

super(Form, self)._init_(parent)

dial.setNotchesVisible(True) spinbox = QSpinBox()

layout = QHBoxLayout() layout.addWidget(dial) layout.addWidget(spinbox) self.setLayout(layout)

self.connect(dial, SIGNAL('valueChanged(int)'), spinbox.setValue) self.connect(spinbox, SIGNAL('valueChanged(int)'), dial.setValue)

self.setWindowTitle('Signals and Slots')

Since the two widgets are connected in this way, if the user moves the dial—say to value 20—the dial will emit a valueChanged(20) signal which will, in turn, cause a call to the spinbox's setValue() slot with 20 as the argument. But then, since its value has now been changed, the spinbox will emit a valueChanged(20) signal which will in turn cause a call to the dial's setValue() slot with 20 as the argument. So it looks like we will get an infinite loop. But what happens is that the valueChanged() signal is not emitted if the value is not actually changed. This is because the standard approach to writing value-changing slots is to begin by comparing the new value with the existing one. If the values are the same, we do nothing and return; otherwise, we apply the change and emit a signal to announce the change of state. The connections are depicted in Figure 4.7.

SIGNAL('valueChanged(int)')

setValue(int)

QDial

QSpinBox setValue(int) ; ! SIGNAL('valueChanged(int)')

Figure 4.7 The signals and slots connections

Now let's look at the general syntax for connections. We assume that the PyQt modules have been imported using the from ... import * syntax, and that s and w are QObjects, normally widgets, with s usually being self.

s.connect(w, SIGNAL('signalSignature'), functionName) s.connect(w, SIGNAL('signalSignature'), instance.methodName) s,connect(w, SIGNAL('signalSignature'), instance, SLOT('slotSignature'))

The signalSignature is the name of the signal and a (possibly empty) comma-separated list of parameter type names in parentheses. If the signal is a Qt signal, the type names must be the C++ type names, such as int and QString. C++ type names can be rather complex, with each type name possibly including one or more of const, *, and &. When we write them as signal (or slot) signatures we can drop any consts and &s, but must keep any *s. For example, almost every Qt signal that passes a QString uses a parameter type of const QString&, but in PyQt, just using QString alone is sufficient. On the other hand, the QListWidget has a signal with the signature itemActivated(QListWidgetItem*), and we must use this exactly as written.

PyQt signals are defined when they are actually emitted and can have any number of any type of parameters, as we will see shortly.

The slotSignature has the same form as a signalSignature except that the name is of a Qt slot. A slot may not have more arguments than the signal that is connected to it, but may have less; the additional parameters are then discarded. Corresponding signal and slot arguments must have the same types, so for example, we could not connect a QDial's valueChanged(int) signal to a QLineEdit's setText(QString) slot.

In our dial and spinbox example we used the instance.methodName syntax as we did with the example applications shown earlier in the chapter. But when the slot is actually a Qt slot rather than a Python method, it is more efficient to use the SLOT() syntax:

self.connect(dial, SIGNAL('valueChanged(int)'), spinbox, SLOT('setValue(int)')) self.connect(spinbox, SIGNAL('valueChanged(int)'), dial, SLOT('setValue(int)'))

We have already seen that it is possible to connect multiple signals to the same slot. It is also possible to connect a single signal to multiple slots. Although rare, we can also connect a signal to another signal: In such cases, when the first signal is emitted, it will cause the signal it is connected to, to be emitted.

Connections are made using QObject.connect(); they can be broken using QOb-ject.disconnect(). In practice, we rarely need to break connections ourselves since, for example, PyQt will automatically disconnect any connections involving an object that has been deleted.

So far we have seen how to connect to signals, and how to write slots—which are ordinary functions or methods. And we know that signals are emitted to signify state changes or other important occurrences. But what if we want to create a component that emits its own signals? This is easily achieved using QObject.emit(). For example, here is a complete QSpinBox subclass that emits its own custom atzero signal, and that also passes a number:

class ZeroSpinBox(QSpinBox): zeros = 0

def_init_(self, parent=None):

super(ZeroSpinBox, self)._init_(parent)

self.connect(self, SIGNAL('valueChanged(int)'), self.checkzero)

def checkzero(self):

self.emit(SIGNAL('atzero'), self.zeros)

We connect to the spinbox's own valueChanged() signal and have it call our checkzero() slot. If the value happens to be 0, the checkzero() slot emits the atzero signal, along with a count of how many times it has been zero; passing additional data like this is optional. The lack of parentheses for the signal is important: It tells PyQt that this is a 'short-circuit' signal.

A signal with no arguments (and therefore no parentheses) is a short-circuit Python signal. When such a signal is emitted, any data can be passed as additional arguments to the emit() method, and they are passed as Python objects. This avoids the overhead of converting the arguments to and from C++ data types, and also means that arbitrary Python objects can be passed, even ones which cannot be converted to and from C++ data types. A signal with at least one argument is either a Qt signal or a non-short-circuit Python signal. In these cases, PyQt will check to see whether the signal is a Qt signal, and if it is not will assume that it is a Python signal. In either case, the arguments are converted to C++ data types.

Here is how we connect to the signal in the form's __init__() method: zerospinbox = ZeroSpinBox()

self.connect(zerospinbox, SIGNAL('atzero'), self.announce)

Again, we must not use parentheses because it is a short-circuit signal. And for completeness, here is the slot it connects to in the form:

def announce(self, zeros):

print 'ZeroSpinBox has been at zero %d times' % zeros

If we use the SIGNAL() function with an identifier but no parentheses, we are specifying a short-circuit signal as described earlier. We can use this syntax both to emit short-circuit signals, and to connect to them. Both uses are shown in the example.

If we use the SIGNAL() function with a signalSignature (a possibly empty parenthesized list of comma-separated PyQt types), we are specifying either a Python or a Qt signal. (A Python signal is one that is emitted in Python code; a Qt signal is one emitted from an underlying C++ object.) We can use this syntax both to emit Python and Qt signals, and to connect to them. These signals can be connected to any callable, that is, to any function or method, including Qt slots; they can also be connected using the SLOT() syntax, with a slotSignature. PyQt checks to see whether the signal is a Qt signal, and if it is not it assumes it is a Python signal. If we use parentheses, even for Python signals, the arguments must be convertible to C++ data types.

We will now look at another example, a tiny custom non-GUI class that has a signal and a slot and which shows that the mechanism is not limited to GUI classes—any QObject subclass can use signals and slots.

class TaxRate(QObject):

def rate(self):

return self._rate def setRate(self, rate):

self._rate = rate self.emit(SIGNAL('rateChanged'), self.__rate)

Both the rate() and the setRate() methods can be connected to, since any Python callable can be used as a slot. If the rate is changed, we update the private _rate value and emit a custom rateChanged signal, giving the new rate as a parameter. We have also used the faster short-circuit syntax. If we wanted to use the standard syntax, the only difference would be that the signal would be written as SIGNAL('rateChanged(float)'). If we connect the rateChanged signal to the setRate() slot, because of the if statement, no infinite loop will occur. Let us look at the class in use. First we will declare a function to be called when the rate changes:

def rateChanged(value):

print 'TaxRate changed to %.2f%%' % value

And now we will try it out:

vat.connect(vat, SIGNAL('rateChanged'), rateChanged) vat.setRate(17.5) # No change will occur (new rate is the same) vat.setRate(8.5) # A change will occur (new rate is different)

This will cause just one line to be output to the console: 'TaxRate changed to 8.50%'.

In earlier examples where we connected multiple signals to the same slot, we did not care who emitted the signal. But sometimes we want to connect two or more signals to the same slot, and have the slot behave differently depending on who called it. In this section's last example we will address this issue.

Connections

1 1

1

One

Two

Three

IT Four fl

Five

~J You clicked button 'Four' I

« «

Figure 4.8 The Connections program

Figure 4.8 The Connections program

The Connections program shown in Figure 4.8, has five buttons and a label. When one of the buttons is clicked the signals and slots mechanism is used to update the label's text. Here is how the first button is created in the form's _init_() method:

buttonl = QPushButton('One')

All the other buttons are created in the same way, differing only in their variable name and the text that is passed to them.

We will start with the simplest connection, which is used by button1. Here is the_init_() method's connect() call:

self.connect(button1, SIGNAL('clicked()'), self.one)

We have used a dedicated method for this button:

def one(self):

self.label.setText('You clicked button 'One')

Connecting a button's clicked() signal to a single method that responds appropriately is probably the most common connection scenario.

Partial function application

Back on page 65 we created a wrapper function which used Python 2.5's functools.partial() function or our own simple partial() function:

import sys if sys.version_info[:2] < (2, 5): def partial(func, arg): def callme():

return func(arg) return callme else:

from functools import partial

Using partial() we can now wrap a slot and a button name together. So we might be tempted to do this:

self.connect(button2, SIGNAL('clicked()'), partial(self.anyButton, 'Two')) # WRONG for PyQt 4.0-4.2

PyQtl 4.3

But what if most of the processing was the same, with just some parameterization depending on which particular button was pressed? In such cases, it is usually best to connect each button to the same slot. There are two approaches to doing this. One is to use partial function application to wrap a slot with a parameter so that when the slot is invoked it is parameterized with the button that called it. The other is to ask PyQt to tell us which button called the slot. We will show both approaches, starting with partial function application.

Unfortunately, this won t work for PyQt versions prior to 4.3. The wrapper function is created in the connect() call, but as soon as the connect() call completes, the wrapper goes out of scope and is garbage-collected. From PyQt 4.3, wrappers made with functools.partial() are treated specially when they are used for connections like this. This means that the function connected to will not be garbage-collected, so the code shown earlier will work correctly.

Lambda functions

For PyQt 4.0, 4.1, and 4.2, we can still use partial(): We just need to keep a reference to the wrapper—we will not use the reference except for the connect() call, but the fact that it is an attribute of the form instance will ensure that the wrapper function will not go out of scope while the form exists, and will therefore work. So the connection is actually made like this:

self.button2callback = partial(self.anyButton, 'Two') self.connect(button2, SIGNAL('clicked()'), self.button2callback)

When button2 is clicked, the anyButton() method will be called with a string parameter containing the text 'Two'. Here is what this method looks like:

def anyButton(self, who):

self.label.setText('You clicked button

We could have used this slot for all the buttons using the partial() function that we have just shown. And in fact, we could avoid using partial() at all and get the same results:

self.button3callback = lambda who='Three': self.anyButton(who) self.connect(button3, SIGNAL('clicked()'), self.button3callback)

Here we've created a lambda function that is parameterized by the button's name. It works the same as the partial() technique, and calls the same anyBut-ton() method, only with lambda being used to create the wrapper.

Both button2callback() and button3callback() call anyButton(); the only difference between them is that the first passes 'Two' as its parameter and the second passes 'Three'.

If we are using PyQt 4.1.1 or later, and we use lambda callbacks, we don't have to keep a reference to them ourselves. This is because PyQt treats lambda specially when used to create wrappers in a connection. (This is the same special treatment that is expected to be extended to functools.partial() in PyQt 4.3.) For this reason we can use lambda directly in connect() calls. For example:

self.connect(button3, SIGNAL('clicked()'), lambda who='Three': self.anyButton(who))

The wrapping technique works perfectly well, but there is an alternative approach that is slightly more involved, but which may be useful in some cases, particularly when we don't want to wrap our calls. This other technique is used to respond to button4 and to button5. Here are their connections:

self.connect(button4, SIGNAL('clicked()'), self.clicked) self.connect(button5, SIGNAL('clicked()'), self.clicked)

Notice that we do not wrap the clicked() method that they are both connected to, so at first sight it looks like there is no way to tell which button called the clicked() method.* However, the implementation makes clear that we can distinguish if we want to:

def clicked(self):

button = self.sender()

if button is None or not isinstance(button, QPushButton): return self.label.setText('You clicked button '%s' % button.text())

Inside a slot we can always call sender() to discover which QObject the invoking signal came from. (This could be None if the slot was called using a normal method call.) Although we know that we have connected only buttons to this slot, we still take care to check. We have used isinstance(), but we could have used hasattr(button, 'text') instead. If we had connected all the buttons to this slot, it would have worked correctly for them all.

Some programmers don't like using sender() because they feel that it isn't good object-oriented style, so they tend to use partial function application when needs like this arise.

There is actually one other technique that can be used to get the effect of QSig-wrapping a function and a parameter. It makes use of the QSignalMapper class, and an example of its use is shown in Chapter 9.

It is possible in some situations for a slot to be called as the result of a signal, and the processing performed in the slot, directly or indirectly, causes the signal that originally called the slot to be called again, leading to an infinite cycle. Such cycles are rare in practice. Two factors help reduce the possibility of cycles. First, some signals are emitted only if a real change takes place. For example, if the value of a QSpinBox is changed by the user, or programmatically by a setValue() call, it emits its valueChanged() signal only if the new value is different from the current value. Second, some signals are emitted only as the result of user actions. For example, QLineEdit emits its textEdited() signal only when the text is changed by the user, and not when it is changed in code by a setText() call.

If a signal-slot cycle does seem to have occurred, naturally, the first thing to check is that the code's logic is correct: Are we actually doing the processing we thought we were? If the logic is right, and we still have a cycle, we might be able to break the cycle by changing the signals that we connect to—for example, replacing signals that are emitted as a result of programmatic changes, with those that are emitted only as a result of user interaction. If the problem persists, we could stop signals being emitted at certain places in our code using QObject.blockSignals(), which is inherited by all QWidget classes and is nal-Mapper

* It is conventional PyQt programming style to give a slot the same name as the signal that connects to it.

passed a Boolean—True to stop the object emitting signals and False to resume signalling.

This completes our formal coverage of the signals and slots mechanism. We will see many more examples of signals and slots in practice in almost all the examples shown in the rest of the book. Most other GUI libraries have copied the mechanism in some form or other. This is because the signals and slots mechanism is very useful and powerful, and leaves programmers free to focus on the logic of their applications rather than having to concern themselves with the details of how the user invoked a particular operation.

Was this article helpful?

In PyQt4 I have a main window which when the settings button is clicked opens the settings dialog

The above works and my SettingsDialog is displayed but I cant get the setPageIndex to work

The bookSettingsBtn is a QToolButton

And the settingsStackedWidget is a QStackedWidget

At this point I am pretty confused on signals and slots and nothing I have read clears this up - if anyone can point out what I am doing wrong above and also potentially direct me to a good (beginners) guide / tutorial on signals and slots it would be greatly appreciated

I would also like to know how to make setPageIndex work as follows:

I'm not sure why you're doing the following, but that's the issue:

SettingsDialog itself is a proper QDialog. You don't need to instantiate another QDialog.

Right now, you're creating an empty QDialog and then populate it with the same ui as SettingsDialog (i.e. setupUi(dialog)), then you show this dialog. But... The signal connection is for SettingsDialog, and the dialog you're showing doesn't have that.

Basically, you don't need that extra QDialog at all. The following should be enough:

How does the class_weight parameter in scikit-learn work?

python,scikit-learn

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level)...

Identify that a string could be a datetime object

python,regex,algorithm,python-2.7,datetime

What about fuzzyparsers: Sample inputs: jan 12, 2003 jan 5 2004-3-5 +34 -- 34 days in the future (relative to todays date) -4 -- 4 days in the past (relative to todays date) Example usage: >>> from fuzzyparsers import parse_date >>> parse_date('jun 17 2010') # my youngest son's birthday datetime.date(2010,...

REGEX python find previous string

python,regex,string

Updated: This will check for the existence of a sentence followed by special characters. It returns false if there are no special characters, and your original sentence is in capture group 1. Updated Regex101 Example r'(.*[w])([^w]+)' Alternatively (without a second capture group): Regex101 Example - no second capture group r'(.*[w])(?:[^w]+)'...

Can't get value from xpath python

python,html,xpath,web-scraping,html-parsing

The values in the table are generated with the help of javascript being executed in the browser. One option to approach it is to automate a browser via selenium, e.g. a headless PhantomJS: >>> from selenium import webdriver >>> >>> driver = webdriver.PhantomJS() >>> driver.get('http://www.tabele-kalorii.pl/kalorie,Actimel-cytryna-miod-Danone.html') >>> >>> table = driver.find_element_by_xpath(u'//table[tbody/tr/td/h3...

Python: histogram/ binning data from 2 arrays.

python,histogram,large-files

if you only need to do this for a handful of points, you could do something like this. If intensites and radius are numpy arrays of your data: bin_width = 0.1 # Depending on how narrow you want your bins def get_avg(rad): average_intensity = intensities[(radius>=rad-bin_width/2.) & (radius<rad+bin_width/2.)].mean() return average_intensities #...

Displaying a 32-bit image with NaN values (ImageJ)

python,image-processing,imagej

The display range of your image might not be set correctly. Try outputImp.resetDisplayRange() or outputImp.setDisplayRange(Stats.min, Stats.max) See the ImagePlus javadoc for more info....

Inconsistency between gaussian_kde and density integral sum

python,numpy,kernel-density

As stated in my comment, this is an issue with kernel density support. The Gaussian kernel has infinite support. Even fit on data with a specific range the range of the Gaussian kernel will be from negative to positive infinity. That being said the large majority of the density will...

SyntaxError: invalid syntax?

python,syntax

Check the code before the print line for errors. This can be caused by an error in a previous line; for example: def x(): y = [ print 'hello' x() This produces the following error: File 'E:Pythontest.py', line 14 print 'hello' ^ SyntaxError: invalid syntax When clearly the error is...

Matplotlib: Plot the result of an SQL query

python,sql,matplotlib,plot

Take this for a starter code : import numpy as np import matplotlib.pyplot as plt from sqlalchemy import create_engine import _mssql fig = plt.figure() ax = fig.add_subplot(111) engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test') connection = engine.connect() result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id') ## the data data =...

group indices of list in list of lists

python,list

Use collections.OrderedDict: from collections import OrderedDict od = OrderedDict() lst = [2, 0, 1, 1, 3, 2, 1, 2] for i, x in enumerate(lst): od.setdefault(x, []).append(i) ... >>> od.values() [[0, 5, 7], [1], [2, 3, 6], [4]] ...

Calling function and passing arguments multiple times

python,function,loops

a,b,c = 1,2,3 while i<n: a,b,c = myfunction(a,b,c) i +=1 ...

How do variables inside python modules work?

python,module,python-module

The convention is to declare constants in modules as variables written in upper-case (Python style guide: https://www.python.org/dev/peps/pep-0008/#global-variable-names). But there's no way to prevent someone else to re-declare such a variable -- thus ignoring conventions -- when importing a module. There are two ways of working around this when importing modules...

How to use template within Django template?

python,html,django,templates,django-1.4

You can use the include tag in order to supply the included template with a consistent variable name: For example: parent.html <div> <div> {% include 'templates/child.html' with list_item=mylist.0 t=50 only %} </div> </div> child.html {{ list_item.text truncatewords:t }} UPDATE: As spectras recommended, you can use the...

Strange Behavior: Floating Point Error after Appending to List

python,python-2.7,behavior

Short answer: your correct doesn't work. Long answer: The binary floating-point formats in ubiquitous use in modern computers and programming languages cannot represent most numbers like 0.1, just like no terminating decimal representation can represent 1/3. Instead, when you write 0.1 in your source code, Python automatically translates this to...

represent an index inside a list as x,y in python

python,list,numpy,multidimensional-array

According to documentation of numpy.reshape , it returns a new array object with the new shape specified by the parameters (given that, with the new shape, the amount of elements in the array remain unchanged) , without changing the shape of the original object, so when you are calling the...

Python Popen - wait vs communicate vs CalledProcessError

python,python-2.7,error-handling,popen

about the deadlock: It is safe to use stdout=PIPE and wait() together iff you read from the pipe. .communicate() does the reading and calls wait() for you about the memory: if the output can be unlimited then you should not use .communicate() that accumulates all output in memory. what...

Replace nodejs for python?

python,node.js,webserver

You might want to have a look at Tornado. It is well-documented and features built-in support for WebSockets. If you want to steer clear of the Tornado-framework, there are several Python implementations of Socket.io. Good luck!...

Python: can't access newly defined environment variables

python,bash,environment-variables

After updating your .bashrc, perform source ~/.bashrc to apply the changes. Also, merge the two BONSAI-related calls into one: export BONSAI=/home/me/Utils/bonsai_v3.2 UPDATE: It was actually an attempt to update the environment for some Eclipse-based IDE. This is a different usecase altogether. It should be described in the Eclipse help. Also,...

How to change the IP address of Amazon EC2 instance using boto library

python,amazon-web-services,boto

Make sure you have set properly with ~/.boto and connect to aws, have the boto module ready in python. If not, go through this first: Getting Started with Boto For example, you need assign a new EIP 54.12.23.34 to the instance i-12345678 Make sure, EIP has been allocated(existed) and you...

Sum of two variables in RobotFramework

python,automated-tests,robotframework

By default variables are string in Robot. So your first two statements are assigning strings like 'xx,yy' to your vars. Then 'evaluate' just execute your statement as Python would do. So, adding your two strings with commas will produce a list: $ python >>> 1,2+3,4 (1, 5, 4) So you...

Inserting a variable in MongoDB specifying _id field

python,mongodb,pymongo

Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but...

Twilio Client Python not Working in IOS Browser

javascript,python,ios,flask,twilio

Twilio developer evangelist here. Twilio Client uses WebRTC and falls back to Flash in order to make web browsers into phones. Unfortunately Safari on iOS supports neither WebRTC nor Flash so Twilio Client cannot work within any browser on iOS. It is possible to build an iOS application to use...

In sklearn, does a fitted pipeline reapply every transform?

python,scikit-learn,pipeline,feature-selection

The pipeline calls transform on the preprocessing and feature selection steps if you call pl.predict. That means that the features selected in training will be selected from the test data (the only thing that makes sense here). It is unclear what you mean by 'apply' here. Nothing new will be...

Find the tf-idf score of specific words in documents using sklearn

python,scikit-learn,tf-idf

Yes. See .vocabulary_ on your fitted/transformed TF-IDF vectorizer. In [1]: from sklearn.datasets import fetch_20newsgroups In [2]: data = fetch_20newsgroups(categories=['rec.autos']) In [3]: from sklearn.feature_extraction.text import TfidfVectorizer In [4]: cv = TfidfVectorizer() In [5]: X = cv.fit_transform(data.data) In [6]: cv.vocabulary_ It is a dictionary of the form: {word : column index in...

Signals and slots pyqt array java

The event loop is already running

python,python-3.x,pyqt,pyqt4

I think the problem is with your start.py file. You have a function refreshgui which re imports start.py import will run every part of the code in the file. It is customary to wrap the main functionality in an 'if __name__ '__main__': to prevent code from being run on...

trying to understand LSH through the sample python code

python,similarity,locality-sensitive-hash

a. It's a left shift: https://docs.python.org/2/reference/expressions.html#shifting-operations It shifts the bits one to the left. b. Note that ^ is not the 'to the power of' but 'bitwise XOR' in Python. c. As the comment states: it defines 'number of bits per signature' as 2**10 → 1024 d. The lines calculate...

Create an exe with Python 3.4 using cx_Freeze

python,python-3.4,cx-freeze

Since you want to convert python script to exe have a look at py2exe

Sort when values are None or empty strings python

python,list,sorting,null

If you want the None and ' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be...

Peewee: reducing where conditionals break after a certain length

Signals And Slots Pyqt Array Cheat

python,peewee

Try ...where(SomeTable.BIN.in_(big_list)) PeeWee has restrictions as to what can be used in their where clause in order to work with the library. http://docs.peewee-orm.com/en/latest/peewee/querying.html#query-operators...

How do I read this list and parse it?

Signals And Slots Pyqt Array Java

python,list

Your list contains one dictionary you can access the data inside like this : >>> yourlist[0]['popularity'] 2354 [0] for the first item in the list (the dictionary). ['popularity'] to get the value associated to the key 'popularity' in the dictionary....

MySQLdb Python - Still getting error when using CREATE TABLE IF NOT EXISTS

python,mysql

MySQL is actually throwing a warning rather that an error. You can suppress mysql warnings like this : import MySQLdb as mdb from warnings import filterwarnings filterwarnings('ignore', category = mdb.Warning) Now the mysql warnings will be gone. But mysql errors will be shown as usual Read more about warnings at...

Python - Opening and changing large text files

python,replace,out-of-memory,large-files

You need to read one bite per iteration, analyze it and then write to another file or to sys.stdout. Try this code: mesh = open('file.mesh', 'r') mesh_out = open('file-1.mesh', 'w') c = mesh.read(1) if c: mesh_out.write('{') else: exit(0) while True: c = mesh.read(1) if c ': break if c...

How to check for multiple attributes in a list

python,python-2.7

You can create a set holding the different IDs and then compare the size of that set to the total number of quests. The difference tells you how many IDs are duplicated. Same for names. Something like this (untested): def test_quests(quests): num_total = len(quests) different_ids = len(set((q.ID for q in...

Python np.delete issue

python,numpy

Don't call np.delete in a loop. It would be quicker to use boolean indexing: In [6]: A[X.astype(bool).any(axis=0)] Out[6]: array([[3, 4, 5]]) X.astype(bool) turns 0 into False and any non-zero value into True: In [9]: X.astype(bool).any(axis=0) Out[9]: array([False, True, False], dtype=bool) the call to .any(axis=0) returns True if any value in...

Parse text from a .txt file using csv module

python,python-2.7,parsing,csv

How about using Regular Expression def get_info(string_to_search): res_dict = {} import re find_type = re.compile('Type:[s]*[w]*') res = find_type.search(string_to_search) res_dict['Type'] = res.group(0).split(':')[1].strip() find_Status = re.compile('Status:[s]*[w]*') res = find_Status.search(string_to_search) res_dict['Status'] = res.group(0).split(':')[1].strip() find_date = re.compile('Date:[s]*[/0-9]*') res = find_date.search(string_to_search) res_dict['Date'] = res.group(0).split(':')[1].strip() res_dict['description'] =...

SQLAlchemy. 2 different relationships for 1 column

python,sqlalchemy

I'm afraid you can't do it like this. I suggest you have just one relationship users and validate the insert queries.

How to remove structure with python from this case?

python,python-2.7

It's complicated to use regex, a stupid way I suggested: def remove_table(s): left_index = s.find('<table>') if -1 left_index: return s right_index = s.find('</table>', left_index) return s[:left_index] + remove_table(s[right_index + 8:]) There may be some blank lines inside the result....

ctypes error AttributeError symbol not found, OS X 10.7.5

python,c++,ctypes

Your first problem is C++ name mangling. If you run nm on your .so file you will get something like this: nm test.so 0000000000000f40 T __Z3funv U _printf U dyld_stub_binder If you mark it as C style when compiled with C++: #ifdef __cplusplus extern 'C' char fun() #else char fun(void)...

sys.argv in a windows environment

python,windows,python-3.x

You are calling the script wrong Bring up a cmd (command line prompt) and type: cd C:/Users/user/PycharmProjects/helloWorld/ module_using_sys.py we are arguments And you will get the correct output....

Count function counting only last line of my list

python,python-2.7

I don't know what you are exactly trying to achieve but if you are trying to count R and K in the string there are more elegant ways to achieve it. But for your reference I had modified your code. N = int(raw_input()) s = [] for i in range(N):...

How to put an image on another image in python, using ImageTk?

python,user-interface,tkinter

Just use photoshop or G.I.M.P.. I assure you, doing it that way will be much simpler and less redundant than essentially getting Tkinter to photo edit for you (not to mention what you're talking about is just bad practice when it comes to coding) Anyways, I guess if you really...

C++ & Qt: Random string from an array area

Signals And Slots Pyqt Array Tutorial

c++,arrays,string,qt,random

You should use the random header. #include <random> std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for...

how to enable a entry by clicking a button in Tkinter?

python,tkinter

You need to use the configure method of each widget: def rakhi(): entry1.configure(state='normal') entry2.configure(state='normal') ...

Signals And Slots Pyqt Array C++

odoo v8 - Field(s) `arch` failed against a constraint: Invalid view definition

python,xml,view,odoo,add-on

You have made silly mistake in defining _columns. _colums is not valid dictionary name for fields structure. Replace this by _columns and restart service and update module. ...

Pandas - Dropping multiple empty columns

python,pandas

You can just subscript the columns: df = df[df.columns[:11]] This will return just the first 11 columns or you can do: df.drop(df.columns[11:], axis=1) To drop all the columns after the 11th one....

Pandas Dataframe Complex Calculation

python,python-2.7,pandas,dataframes

I believe the following does what you want: In [24]: df['New_Col'] = df['ActualCitations']/pd.rolling_sum(df['totalPubs'].shift(), window=2) df Out[24]: Year totalPubs ActualCitations New_Col 0 1994 71 191.002034 NaN 1 1995 77 2763.911781 NaN 2 1996 69 2022.374474 13.664692 3 1997 78 3393.094951 23.240376 So the above uses rolling_sum and shift to generate the...

Python recursive function not recursing

python,recursion

Afraid I don't know much about python, but I can probably help you with the algorithm. The encoding process repeats the following: multiply the current total by 17 add a value (a = 1, b = 2, ..., z = 26) for the next letter to the total So at...

Django: html without CSS and the right text

python,html,css,django,url

Are you using the {% load staticfiles %} in your templates?

Spring-integration scripting with Python

python,spring-integration,jython

This is a bug in Spring Integration; I have opened a JIRA Issue. if (variables != null) { result = scriptEngine.eval(script, new SimpleBindings(variables)); } else { result = scriptEngine.eval(script); } When the first branch of the if test is taken, the result variable is added to the SimpleBindings object, and...

Using counter on array for one value while keeping index of other values

python,collections

To count how often one value occurs and at the same time you want to select those values, you'd simply select those values and count how many you selected: fruits = [f for f in foods if f[0] 'fruit'] fruit_count = len(fruits) If you need to do this for...