text stringlengths 256 65.5k |
|---|
I have three collection.deques and what I need to do is to iterate over each of them and perform the same action:
for obj in deque1:
some_action(obj)
for obj in deque2:
some_action(obj)
for obj in deque3:
some_action(obj)
I'm looking for some function XXX which would ideally allow me to write:
for ... |
Published 12 Aug 2011
I recently came across an amazing technique for manipulating Python iterators in a recipe by Raymond Hettinger.
The technique consists in defining an iterator as a function of itself, thus making a cyclical definition. The recipe hinges on using itertools.tee to split the to-be iterator, which is ... |
When trying to get Django up and running to host this site and blog, I ran into quite a few potholes. Hopefully this will help someone else out that wants to get it working as well. I should probably update this page a bit, which had some helpful hints but seemed woefully outdated.
Getting it up and running
The first s... |
Magma can compute the kernel and the image of a homomorphism between abelian groups. For instance,
A<[x]> := AbelianGroup([0]);
B<[y]> := AbelianGroup([2,4]);
C<[z]> := AbelianGroup([2]);
g := hom< B -> C | [z[1],2*z[1]]>;
K := Kernel(g);
K;
f := hom< A -> K | [4*y[1]-2*y[2]]>;
I := Image(f);
I;
K/I;
... |
Leo 7
Re : A quoi ressemble votre environnement - printemps/été 2012
J'adore ton unity Mario_26
Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli.
Merci d'avance
A+
hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures !
Hors ligne
Major Gr... |
tomtom
Re : [HOW TO] adesklets : installation sous Ubuntu Breezy
raaah ! j'ai un probleme d'interpreteur python !
J'ai installé toutes les librairies via synaptic et adesklets aussi.
J'ai DL YAB (Yet Another Bar) et j'ai ca :
[i]tomtom@barad-luin:/mnt/config/programmes/adesklets/yab-0.0.2$ [/i][b]ls -l[/b]
total 56
-rw... |
I'm working with satellite images. I have a program (Python) to contrast satellite images by temperature of the cloud's top, the program is below:
from pylab import *
#import pylab imread,imshow
sat=imread('1101092045G13I04.tif')
imshow(sat)
map=imread('map.tif')
map=mean(map,2,)/3
#contour(map,cmap=cm.gray)
imshow((sa... |
I am trying to compare two separate feature classes to identify differences between them (sort of a diff function). My basic workflow:
I extract the geometries using a SearchCursor
Save the geometries of the two feature classes as GeoJSON using a modified __geo_interface__(got it from valveLondonreturn {'type': 'Polygo... |
As has Bálint Aradi already mentioned in the comments, the node is not interoperable with C in it's current form. For that you need to change fortran pointers into C pointers, but that makes it extremely painful to use inside fortran itself. The most elegant solution I could come up with was putting the C interoperabl... |
toma222
[HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy
Il existe désormais un article sur le wiki concernant Adesklets donc je vous conseille de vous y fier, ce tutoriel n'étant plus mis à jour.
Je poste ce sujet en complément du sujet sur l'installation de adesklets sous Breezy.
Je ne reviendrais pas sur... |
In Snow Leopard the Play / Pause media button (on the F8 key) opens up iTunes. How can I disable that? Preferably keeping the old Leopard behaviour, so I can use it to control other media applications (e.g. Spotify).
a better temporary fix is to start quicktime and just have it running(not playing a movie) in the backg... |
I am getting a WorkerLostError from my worker when Calling a celery task decorated function with the delay method (do_stuff.delay()) in my web application.
Setup: Django 1.5, Celery 3.1.9, Billiard 3.3.0.16, Heroku, CloudAMQP and Psycopg2 2.5.1.
Heroku logs
app[worker.1]: [2014-03-04 10:29:00,850: INFO/MainProcess] Rec... |
I'm using Google App Engine for creating a page with a form to create an entity called "tutorial". Then when hit next, the user has another form in order to create a chapter for the tutorial previously created. My problem is bringing the reference of the "tutorial" to the "chapter"
handler for the new tutorial page:
cl... |
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
J'ai l'impression que tu as un problème de droits d'écritures.
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Où as-tu placer le script?
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes d... |
I guess using Jython, you can do anything with Python that you can do in Java.
Conversely, Python has the PyPy compiler, which is pretty cool - a virtual machine with multiple backeds (Java Runtime, LLVM, .net, and Python IIRC), multiple garbage collectors, multiple implementations (Stackless), etc. I know Java has a b... |
#2001 Le 26/04/2013, à 19:31
abelthorne
Re : Valve : Steam sous Linux, l'aventure est officiellement confirmée...
Info en passant : dans le dernier bundle IndieRoyale, il y a Dungeon Hearts pour Steam Linux.
Dernière modification par abelthorne (Le 26/04/2013, à 19:31)
Hors ligne
#2002 Le 26/04/2013, à 21:53
N0rihiori
... |
I have a form that triggers an ajax request to a view after the user tabs out of the 'address' field. It retrieves the zip code and then populates pickups with the same zip. The problem is that if there are any form errors is that the drop down with the results I generate from my get_pickups view is lost. How can I kee... |
If you need to micro-optimize like this, the only way to know what's fastest is to test.
The short version is: append is faster than extend, and Joran Beasley's suggestion itertools.chain.from_iterable is slightly faster than eitherâbut only if you replace the map with a list comprehension.
So:
import itertools
impor... |
I have an application I am developing in wxPython. Part of the application creates a large number of TextCtrls in a grid in order to enter four-letter codes for each day of the week for an arbitrarily large list of people.
I've managed to make it work, but I'm having to do something kludgy. Specifically, I haven't foun... |
kryss
Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy
ah la galere...
etu tu crois que tu peux savoir pourquoi les desklets de gdesklet marchent pas?
c est quoi un capteur rss grab?
Hors ligne
toma222
Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy
Non désolé, j'ai laissé tomber gdes... |
Ruby
kriston — 2010-04-28T23:30:50-04:00 — #1
I'm up to page 283 of Simply Rails 2 in the "protective measures" chapter. As the note states, I'm getting errors because now that I'm attempting to reference a user_id, and none exist in previous entries, it is failing...
I thought that I could change all of the story entr... |
Hada de la Luna
[résolu] 12.04 LTS : régler la luminosité de façon "définitive"
Bonjour,
pour une personne qui a des problèmes avec la luminosité excessive de l'écran, j'aimerais savoir comment régler cela de façon "fixe" qui ne soit pas remise en question à chaque démarrage.
En effet, en utilisant : Paramètres système... |
Share your command line features and tricks for Unix/Linux. Try to keep it shell/distro agnostic if possible. Interested in seeing aliases, one-liners, keyboard shortcuts, small shell scripts, etc.
This expands somewhat on the
Word designators can be added on to a
Modifiers can also be appended to a
press it again and ... |
Panormaica di web2py
Avvio
web2py è distribuito in pacchetti binari per Windows e Mac OS X. E' scaricabile anche una versione in codice sorgente che può essere eseguita su Windows, Mac, Linux ed altri sistemi Unix. Le versioni binarie per Windows e per Mac OS X già includono il necessario interprete Python. La versione... |
I am struggling to understand the proper syntax for executing a subquery in SQLAlchemy when the value needs to be returned (i.e. not used in the WHERE).
I am using the declarative approach.
There are two models being used:
class ProjectInvoices(Base):
InvoiceID = Column(Integer(unsigned=True), default=0, primary_ke... |
switched to
db file scattered reads
. Argh! This is not what I wanted.
direct path reads
For reference, when a server process asks the operating system for multiple blocks at once (for example, using the system call
) and places them into the buffer cache, Oracle records the time using the wait event facility and gives... |
I have a list as follows:
A= [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)]
From the list A, I would like to generate the output list like this:
Average = [('1', 5), ('2', 6), ('3', 2)]
Any tips would be really grateful! =)
from collections import defaultdict
a = [('1', 3), ('2', 7), ('3', 5), ('1', 7), (... |
Web Client Fuzzer.py
Fuzzing – such a wonderful concept
. I wish it worked more often usual. Anyway, here is my attempt to put down a fuzzer for testing various web client specific issues. The fuzzer is written in python and I am not aware of any other tool that fuzzes the way I do, although I must admit, haven’t resea... |
Portability unknown
Stability experimental
Maintainer aenor.realm@gmail.com
Safe Haskell Safe-Infered
There's no need to invoke full getOpt power in everyday use. So, here it is a most common use case implemented to be as painless as possible while retaining some functionality. It's divided into three layers, each buil... |
Preamble
I spent some time and designed and implemented a tiny framework to deal with this problem, over the last two days. Here is what I've got. The main ideas will involve implementing a simple key-value store in Mathematica based on a file system, heavy use and automatic generation of UpValues, some OOP - inspired ... |
I want to calculate an indexed weight sum across a large (1,000,000 x 3,000) boolean numpy array. The large boolean array changes infrequently, but the weights come at query time, and I need answers very fast, without copying the whole large array, or expanding the small weight array to the size of the large array.
The... |
Kanor
Re : Idée projet Logiciel RDM Eurocodes Structures Bois, Acier, Béton...
D'aprés ce que je comprend Salome utilise code_aster
Sinon pdf qui me semble intéressant
http://calcul.math.cnrs.fr/Documents/Journees/dec2006/aster.pdf
ça date un peu 2006
Hors ligne
ossatureLibre
Re : Idée projet Logiciel RDM Eurocodes Str... |
I got a brain smashing problem with Fedora 16 and my serial port.
I use the serial to monitor an STB on which I'm developping. The STB runs on Linux and when booted, I launch the program I'm working on through the serial interface.
Now, my program outputs lots of traces when I'm debugging, and I get loads of buffer ove... |
luc765
Re : Synthèse vocale SVOX Pico
Merci à frafra et tuxmuraille, pour votre travail.
J'utilisais espeak avec mbrola, la qualité de SVOX est nettement meilleure
J'ai installé gSpeech sur Lucid via la compilation pour SVOX. Tout est parfait.
Dans l'utilisation est-il possible de modifier la vitesse de lecture par un ... |
Share your command line features and tricks for Unix/Linux. Try to keep it shell/distro agnostic if possible. Interested in seeing aliases, one-liners, keyboard shortcuts, small shell scripts, etc.
This expands somewhat on the
Word designators can be added on to a
Modifiers can also be appended to a
press it again and ... |
Possible Duplicate:
uncompressing tar.Z file with python?
I am trying to read a zlib compressed in order to directly access the data in the contained HDF file (using pyhdf). However, I always receive an error message. Here is the file.
import zlib
file = open('3B42.20070101.00.7A.HDF.Z','rb')
data = zlib.decompress(fil... |
Sissio
Boot kernel 3.5.0-17
Bonjour,
Ce matin j'ai eu la mise à jour du kernel en version 3.5.0-17 sur voyager 12.04 Lts.
Lors du reboot l'animation de démarrage se charge correctement et avant d'arriver sur le bureau cela reste figé et je perd totalement la main car même le clavier ne répond plus.
La seule solution qu... |
Basically, the title.
I am trying to trace down where a spurious print happens in a large codebase, and I would like to break, or somehow get a stack trace whenever a print "happens." Any ideas?
For this particular case you can redirect
Full example:
import sys
import inspect
class PrintSnooper:
def __init__(self, ... |
I need to create an empty html file using python. I'm new to OS module and i can't find any examples of doing it.
How can I create an empty html file using python?
Thank you!
You donât need the
with open('index.html', 'w'):
pass
You might want to write nothing to it explicitly as other developers may be confused... |
Vediamo:
# cat /var/log/Xorg.0.log|grep driver
Ecco:
$ cat /var/log/Xorg.0.log|grep driver
[ 29.990] X.Org XInput driver : 13.0
[ 29.993] (==) Matched intel as autoconfigured driver 0
[ 29.993] (==) Matched vesa as autoconfigured driver 1
[ 29.993] (==) Matched fbdev as autoconfigured driver 2
[ 29.993... |
class Geolocation(db.Model):
__tablename__ = "geolocation"
id = db.Column(db.Integer, primary_key=True)
latitude = db.Column(db.Float)
longitude = db.Column(db.Float)
elevation = db.Column(db.Float) # Meters
# Relationships
pin = db.relationship('Pin', uselist=False, backref="geoloca... |
I am trying to develop a GNOME applet (put into panel) using python (pyGTK). I've started by following the tutorial suggested in other SO question.
My plan is to let the applet do something in the background in a repetitive fashion (causing its display to be updated). So I thought I am gonna need threads to do it. I've... |
So I've read all the RMDB vs BigTable debates
I tried to model a simple game class using BigTable concepts.
Goals : Provide very fast reads and considerably easy writes
Scenario: I have 500,000 user entities in my User model. My user sees a user statistics at the top of his/her game page (think of a status bar like in ... |
I have following code in my django application.
class Status(object):
def __init__(self, id, desc):
self.id = id
self.desc = desc
def __unicode__(self):
return self.desc
STATUS = Status(0, _(u"Some text"))
When I try to display some status (or even coerce it to unicode), I get:
TypeErro... |
When you've been using a programming language for a long time, you like to think that syntax-wise, it has no more secrets left for you.
Today I was proven wrong and found out about Python's extended slice assignment, which is present since Python 2.3.5.
def eras(n): siv=range(n+1) siv[1]=0 sqn=int(round(n**0.5)) for i ... |
Remove Database Access Information from settings.py
One thing I've done in my Django site's settings.py is load database access info from a file in /etc. This way the access setup (database host, port, username, password) can be different for each machine, and sensitive info like the password isn't in my project's repo... |
Everything began one fine day when I visited our storage room to see if there was anything interesting for me to look at. Soon I came across an old shabby dark-gray Toshiba notebook thrown there amidst different computer rubbish long ago, from the time when Intel's Pentium I was the top of performance. I couldn't pass ... |
Kind of a strange request.
Let's say I have the following list:
[1,2,3]
And I want something, say, the number 9, to pass through every index, to get the following list of lists:
[[9,1,2,3], [1,9,2,3], [1,2,9,3], [1,2,3,9]]
Any idea how to do this easily? Also, is there a name for this sort of thing?
Edit: I realize I c... |
I have a raster that I'd like to do some point interpolations with. Here is where I'm at:
from osgeo import gdal
from numpy import array
# Read raster
source = gdal.Open('my_raster.tif')
nx, ny = source.RasterXSize, source.RasterYSize
gt = source.GetGeoTransform()
band_array = source.GetRasterBand(1).ReadAsArray()
# Cl... |
If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do block-by-block processing using efficient and tr... |
models.py
class Job(db.Model):
title = db.StringProperty(verbose_name='Project Title:')
description = db.StringProperty(multiline=True, verbose_name='Description:')
created_at = db.DateTimeProperty(auto_now_add=True)
updated_at = db.DateTimeProperty(auto_now=True)
budget = db.IntegerProperty()
max_project_duration = db... |
The Django Framework's Killer Feature for Java Developers
Code Speaks for Itself
Here is how the model definition for the invoicing application would look like (usually in a file called models.py):
from django.db import models
class Product(models.Model):
name = models.CharField("Name",max_length=30)
price = mo... |
#2301 Le 28/10/2012, à 16:38
ynad
Re : TVDownloader: télécharger les médias du net !
Re
@11gjm
la liste des correctifs, dans la dernière il y a 4h les deux nouveaux fichiers main.py (v 0.9.3) et PluzzDL.py
qui permettent le changement url
@+
Hors ligne
#2302 Le 28/10/2012, à 16:56
11gjm
Re : TVDownloader: télécharger l... |
I'm a beginner in Python, and I'm doing this project where I have a text file with 7 columns of numbers. I need to write a program that extracts the data for columns 1, 6, and 7, and prints them out in columns with just those data in columns alone. This is what I have done so far, but something seems to be wrong. Can s... |
Thanks to Ubuntu sites I no longer thought it was just me even though I reported this around almost a year ago. Just right-clicking for desktop not only kills the conceptual menu but hikes the cpu wild & hot, forget even activating the fixed desktop slideshow feature which locks the cpu to run high and hot even if you ... |
I want to post a file to a server via python, for this I need to name this file as "xmlfile" so that server recognizes the input.
import urllib2
url = "http://somedomain"
to_send = open('test.xml').read()
data = {}
data['xmlfile'] = to_send
f = urllib2.urlopen(url, data)
This doesn't work, in addition, how can I retri... |
Overview
Startup
web2py comes in binary packages for Windows and Mac OS X. They include the Python interpreter so you do not need to have it pre-installed. There is also a source code version that runs on Windows, Mac, Linux, and other Unix systems. The Windows and OS X binary versions include the necessary Python inte... |
malbo
[Tuto] identifier si on est dans un système UEFI ou Bios
ATTENTION : CETTE MÉTHODE D’IDENTIFICATION EST OBSOLÈTE : IL FAUT UTILISER LA PROCÉDURE DE LA DOC : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
Le problème se pose pour des PC achetés en 2011 (et +) pour ceux qui souhaitent faire cohabiter Windows ... |
I have this problem, and I'm not really sure where the issue is on client or on server or both. I'll appreciate any help diagnosing and resolving this.
I have remote linux box running debian, that I regularity download files and folders from to a Windows 8 box. Most of the time it just works. I'm using a download manag... |
Python in the Cloud
A basic introduction to using the Python boto library to interact with AWS services and resources.
This article explores using the boto library to work with resources in the Amazon Web Services (AWS) cloud. For those wondering, the boto name refers to a species of freshwater dolphin found in the Ama... |
jbfabin
mise à jour / téléchargement des paquets impossibles
Bonjour, quand je veux mettre à jour mon système, j'obtiens le message :"le téléchargement des informations du dépot a échoué".
si quelqu'un peut m'aider, je lui serai reconnaissant.
PS : au terminal, j'obtiens ces messages :
W: Impossible de récupérer http:/... |
I'm getting myself into issues with python class attributes vs data attributes in my sqlalchemy model. This is a small example to demonstrate what's happening:
# -*- coding: utf-8 -*-
import cherrypy
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ... |
How can I import a file that is in a parent directory within a python package (that is not on the path) into a file in a child dir?
I'm not totally clear on the vocabulary of python packaging so by way of example:
dir1/ __init__.py runner.py in_dir1.py dir2/ __init__.py in_dir2.py
dir1/in_dir1.py:
def example():
pr... |
Suppose I have a df which has columns of 'ID', 'col_1', 'col_2'. And I define a function :
f = lambda x, y : my_function_expression.
Now I want to apply the f to df's two columns 'col_1', 'col_2' to element-wise calculate a new column 'col_3' , somewhat like :
df['col_3'] = df[['col_1','col_2']].apply(f)
# Pandas giv... |
I'm trying to set up a worker daemon for processing messages from rabbitmq. I'm using pika and its SelectConnection. The code works fine if I don't run it as a daemon. I can use
py worker.py
and
py worker.py &
successfully. However, when I add
import daemon
with daemon.DaemonContext():
connection.ioloop.start()
to... |
Another key point is that the mouse messages all report the position in "Screen Coordinates" (i.e., relative to the top-left corner of the screen) rather than in "Client Coordinates" (i.e., relative to the top-left corner of our window). You use a member function PyCWnd.ScreenToClient() to transform these coordinates.
... |
I have been playing with BeautifulSoup, which is great. My end goal is to try and just get the text from a page. I am just trying to get the text from the body, with a special case to get the title and/or alt attributes from <a> or <img> tags.
So far I have this EDITED & UPDATED CURRENT CODE:
soup = BeautifulSoup(page)... |
I have been given a hint to try out the inline formset as a solution to a problem. Just experimenting with it in a sandbox project. I am trying to replicate the exact same example as in the Django documentation and it fails. :(
Models:
TITLE_CHOICES = (
('MR', 'Mr.'),
('MRS', 'Mrs.'),
('MS', 'Ms.'),
)
clas... |
Mint 15 doesn't see internet after installing it in dualboot with windows 8 (in Windows internet works well). My network card is Qualcomm Atheros QCA8172 Fast Ethernet (rev 10).
What I did:
Install drivers from http://www.linuxfoundation.org/collaborate/workgroups/networking/alx
Update kernel to 3.11.6
But it didn't fi... |
Clang 3.1 is scheduled to be released any hour now. And, I'm proud to say that I've contributed to it! Specifically, I've contributed improvements to the Python bindings, which are an interface to libclang, the C interface to Clang.
Since 3.1 is being released today, I wanted to share some of the new features in this r... |
I find Apache Digester a big help for rules-based parsing of XML.
Update: If it's filtering and output that you're concerned with, review this set of articles on Developerworks which is concerned with the same issues. Of particular relevance are parts 2, 3 and 4. The summary: Use SAX, XMLFilter and XMLWriter.
While I s... |
Unicode in RTF documents
How to encode unicode codepoints in RTF documents using PyRTF.
Some time ago I had to output some nicely formatted reports from a web application, to be usable offline by Windows users. Naturally, I used the aging but still reliable PyRTF module to generate RTF documents with headers, tables, a... |
#2476 Le 05/04/2014, à 12:33
jibel
Re : Live Voyager
C'est bien pour ça qu'il est temps pour moi de prendre une retraite bien mérité ...aarrggghhhhh
j'en arrive a avoir les yeux qui se croisent
Plus grande est la face, plus grand est le dos!
Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dess... |
I have two classes like this:
class ClassNrOne(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Title',size=(1024,600))
self.panel = wx.Panel(self,size=(1024,600))
self.mybutton = wx.Button(self.panel,label="OK",pos=(215,160),size=(80,40))
self.Bind(wx.EVT_B... |
How to use forms
Other languages: français | ...
Problem
How to use forms.
Solution
The web.form module provides support for creating, validating, and rendering forms.This module contains a Form class and classes for various inputs like Textbox, Password etc.
Each input can take a list of validators as arguments which ... |
Ayu
Grub ne se lance pas
Bonsoir,
J'ai installé windows 7 et Xubuntu 11.10 sur un nouveau pc avec cette configuration:CM: Asus P8H67 B3Processeur: i5 2500kDD: 1TO 7200 RPMRAM: 2x4GOCG: Gigabyte GeForce GTX 560
Mais je boot toujours sur windows et Grub ne se lance pas
j'ai essayé de réinstaller grub depuis une session l... |
There is a way using ModelAdmin objects to specify your own form. By specifying your own form, you have complete control over the form's composition and validation.
Say that the model which has an FK to User is Foo.
Your myapp/models.py might look like this:
from django.db import models
from django.contrib.auth.models ... |
Being a beginner with python, I am very frustrated because after hours of research I can not find a solution for reading+plotting time serieses in python which could be done in matlab, R or gnuplot in 1 minute.
Data file:
# id date value1 quality anothervalue value2
1 2011-05-19_16:30:19 974.3 3_... |
user@amd64:~$ sudo add-apt-repository ppa:jd-team/jdownloader
[sudo] password for 1:
Traceback (most recent call last):
File "/usr/bin/add-apt-repository", line 125, in <module>
ppa_info = get_ppa_info_from_lp(user, ppa_name)
File "/usr/lib/python2.7/dist-packages/softwareproperties/ppa.py", line 80, in get_pp... |
In Ruby, I can define a method foo=(bar):
irb(main):001:0> def foo=(bar)
irb(main):002:1> p "foo=#{bar}"
irb(main):003:1> end
=> nil
Now I'd like to check if it has been defined,
irb(main):004:0> defined?(foo=)
SyntaxError: compile error
(irb):4: syntax error, unexpected ')'
from (irb):4
from :0
What is the prope... |
Enhancing the DocumentTemplate
Although MFC and PythonWin support multiple document templates, there's a slight complication that isn't immediately obvious. When MFC is asked to open a document file, it asks each registered DocumentTemplate in turn if it can handle this document type. The default implementation for Doc... |
Tagged union
It has been suggested that Variant type be merged into this article. (Discuss) Proposed since August 2014.
This article does not cite any references or sources. (August 2009)
In computer science, a tagged union, also called a variant, variant record, discriminated union, disjoint union, or sum type, is a d... |
Jazyk Python
O Pythonu
Python je vyšší programovací jazyk všeobecného určení. Filozofie jeho stavby je zaměřena na programátorskou produktivitu a čitelnost kódu. Má minimalistickou základní syntaxi s jen několika základními příkazy a snadnou sémantikou, ale současně má rozsáhlou a výkonnou standardní knihovnu (standard... |
You might also want to look at the gmpy module. It is an interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:
>>> import gmpy
>>> gmpy.invert(1234567, 1000000007)
mpz(989145189)
Updated answer
As noted by @hyh , the gmpy.invert() returns 0 i... |
python is a powerfull tool for almost everything (tested in linux)
#!/bin/python
from sys import argv
from os import system
from subprocess import Popen, PIPE
ffm = 'ffmpeg -i' # input file
aud = ' -acodec mp3' #add your quality preferences
dur = ' 2>&1 | grep "Duration" | cut -d " " -f 4'
def cutter(inp,t=0):
out... |
Equipment
A computer with an internet connection
Python
pySerial
Arduino ( I'm using Duemilanove )
Red LED
Pushbutton (optional)
Wires
On the computer
A python script will run continuously on the computer, and fetch the Gmail RSS feed every few minutes. pySerial will be used to notify the Arduino of new mails.
Here are... |
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?
Let's say I have an object o. How do I check whether it's a str?
To check if the type of
type(o) is str
To check if
isinstance(o, str)
The following also works, and can be useful ... |
So you want to have multiple files which contain part of the entries in the main file and each contains the table header?
If that is what you want, one could write a simple script that takes the first file and the number of files that you want (or the number of lines in each file) and creates those files.
If it does no... |
Why it does not work
Your code cannot work because while is executed until os.path.basename(sourcePath) is not evaluated to True, then if statement is called, which (because it looks like: if not os.path.basename(sourcePath)) is obviously evaluated as True and thus the message (your "error") is shown:
Annotated source ... |
What is the shortest hash (in filename-usable form, like a hexdigest) available in python? My application wants to save cache files for some objects. The objects must have unique repr() so they are used to 'seed' the filename. I want to produce a possibly unique filename for each object (not that many). They should not... |
i've just installed python (Python 2.7.6) with pyside (Version 1.2.1) on Mac OS Lion 10.7.5 via Macports.
When I wanted to test this very simple code, python crashes unexpectedly:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import sys
from PySide import QtCore, QtGui
app = QtGui.QApplication(sys.argv)
app.exec_()
wh... |
I am working against an application that seems keen on returning, what I believe to be, double UTF-8 encoded strings.
I send the string u'XüYÃ' encoded using UTF-8, thus becoming X\u00fcY\u00df (equal to X\xc3\xbcY\xc3\x9f).
The server should simply echo what I sent it, yet returns the following: X\xc3\x83\xc2\xbcY\x... |
If you review the sidebar "wxPython Window Layout," you'll see a number of choices available, but we have chosen to use the brute-force mechanism for the Edit Transaction dialog:
# Create some controls
wxStaticText(self, -1, "Date:", wxDLG_PNT(self, 5,5))
self.date = wxTextCtrl(self, ID_DATE, "",
... |
I just wrote this up on my biz site.
I hope it helps somebody out!
I just wrote this up on my biz site.
I hope it helps somebody out!
Been writing python for a long time. When I wrote this code, I could not figure out why I was getting a syntax error.
d1 = dict(
user_id=99,
display_name='Matt Wilson',)
d2 = dic... |
Class StockholmWriter
source code
object --+
|
Interfaces.AlignmentWriter --+
|
Interfaces.SequentialAlignmentWriter --+
|
St... |
I have seen this macro defined before but never really knew its purpose. Can anyone shed light on this?
This is a compiler intrinsic used for optimization, typically seen in embedded programming. The only time I have seen it used is in the "default" for a switch statement to assert that the variable has a limited range... |
I have been working on an iPhone App for a couple of weeks now and one of the earlier features I added was a UIWebView that loaded context sensitive Wikipedia page topics. This was pretty trivial to implement and has been working fine for some time.
Today, I found that functionality had unexpectedly stopped working. I ... |
I read today that Django 1.3 alpha is shipping, and the most touted new feature is the introduction of class-based views.
I've read the relevant documentation, but I find difficult to see the big advantage⢠that I could get by using them, so I'm asking here for some help in understanding them.
Let's take an advanced ... |
Getting Started with WSGI
by Jason R. Briggs
11/09/2006
What is WSGI, and why should you care? WSGI, or the Web Server Gateway Interface, is a Python Enhancement Proposal (#333) authored by Philip Eby in an attempt to address the lack of standardization among Python web frameworks. Think of it as the servlet spec for t... |
I'm using the algorithm 'COBYLA' in scipy's optimize.minimize function (v.0.11 build for cygwin). I observed that the parameter bounds seems not to be used in this case. For instance, the simple example:
from scipy.optimize import minimize
def f(x):
return -sum(x)
minimize(f, x0=1, method='COBYLA', bounds=(-2,2))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.