| PERLPACKTUT(1) | Perl Programmers Reference Guide | PERLPACKTUT(1) |
In Perl, you just can't access memory at random, but the structural and representational conversion provided by "pack" and "unpack" is an excellent alternative. The "pack" function converts values to a byte sequence containing representations according to a given specification, the so-called "template" argument. "unpack" is the reverse process, deriving some values from the contents of a string of bytes. (Be cautioned, however, that not all that has been packed together can be neatly unpacked - a very common experience as seasoned travellers are likely to confirm.)
Why, you may ask, would you need a chunk of memory containing some values in binary representation? One good reason is input and output accessing some file, a device, or a network connection, whereby this binary representation is either forced on you or will give you some benefit in processing. Another cause is passing data to some system call that is not available as a Perl function: "syscall" requires you to provide parameters stored in the way it happens in a C program. Even text processing (as shown in the next section) may be simplified with judicious usage of these two functions.
To see how (un)packing works, we'll start with a simple template code where the conversion is in low gear: between the contents of a byte sequence and a string of hexadecimal digits. Let's use "unpack", since this is likely to remind you of a dump program, or some desperate last message unfortunate programs are wont to throw at you before they expire into the wild blue yonder. Assuming that the variable $mem holds a sequence of bytes that we'd like to inspect without assuming anything about its meaning, we can write
my( $hex ) = unpack( 'H*', $mem ); print "$hex\n";
whereupon we might see something like this, with each pair of hex digits corresponding to a byte:
41204d414e204120504c414e20412043414e414c2050414e414d41
What was in this chunk of memory? Numbers, characters, or a mixture of both? Assuming that we're on a computer where ASCII (or some similar) encoding is used: hexadecimal values in the range 0x40 - 0x5A indicate an uppercase letter, and 0x20 encodes a space. So we might assume it is a piece of text, which some are able to read like a tabloid; but others will have to get hold of an ASCII table and relive that firstgrader feeling. Not caring too much about which way to read this, we note that "unpack" with the template code "H" converts the contents of a sequence of bytes into the customary hexadecimal notation. Since "a sequence of" is a pretty vague indication of quantity, "H" has been defined to convert just a single hexadecimal digit unless it is followed by a repeat count. An asterisk for the repeat count means to use whatever remains.
The inverse operation - packing byte contents from a string of hexadecimal digits - is just as easily written. For instance:
my $s = pack( 'H2' x 10, 30..39 ); print "$s\n";
Since we feed a list of ten 2-digit hexadecimal strings to "pack", the pack template should contain ten pack codes. If this is run on a computer with ASCII character coding, it will print<PHONE_NUMBER>.
Date |Description | Income|Expenditure 01/24/2001 Zed's Camel Emporium 1147.99 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 235.00
How do we do it? You might think first to use "split"; however, since "split" collapses blank fields, you'll never know whether a record was income or expenditure. Oops. Well, you could always use "substr":
while (<>) { my $date = substr($_, 0, 11); my $desc = substr($_, 12, 27); my $income = substr($_, 40, 7); my $expend = substr($_, 52, 7); ... }
It's not really a barrel of laughs, is it? In fact, it's worse than it may seem; the eagle-eyed may notice that the first field should only be 10 characters wide, and the error has propagated right through the other numbers - which we've had to count by hand. So it's error-prone as well as horribly unfriendly.
Or maybe we could use regular expressions:
while (<>) { my($date, $desc, $income, $expend) = m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|; ... }
Urgh. Well, it's a bit better, but - well, would you want to maintain that?
Hey, isn't Perl supposed to make this sort of thing easy? Well, it does, if you use the right tools. "pack" and "unpack" are designed to help you out when dealing with fixed-width data like the above. Let's have a look at a solution with "unpack":
while (<>) { my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_); ... }
That looks a bit nicer; but we've got to take apart that weird template. Where did I pull that out of?
OK, let's have a look at some of our data again; in fact, we'll include the headers, and a handy ruler so we can keep track of where we are.
1 2 3 4 5<PHONE_NUMBER>123456789012345678901234567890123456789012345678 Date |Description | Income|Expenditure 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 235.00
From this, we can see that the date column stretches from column 1 to column 10 - ten characters wide. The "pack"-ese for "character" is "A", and ten of them are "A10". So if we just wanted to extract the dates, we could say this:
my($date) = unpack("A10", $_);
OK, what's next? Between the date and the description is a blank column; we want to skip over that. The "x" template means "skip forward", so we want one of those. Next, we have another batch of characters, from 12 to 38. That's 27 more characters, hence "A27". (Don't make the fencepost error - there are 27 characters between 12 and 38, not 26. Count 'em!)
Now we skip another character and pick up the next 7 characters:
my($date,$description,$income) = unpack("A10xA27xA7", $_);
Now comes the clever bit. Lines in our ledger which are just income and not expenditure might end at column 46. Hence, we don't want to tell our "unpack" pattern that we need to find another 12 characters; we'll just say "if there's anything left, take it". As you might guess from regular expressions, that's what the "*" means: "use everything remaining".
Hence, putting it all together:
my ($date, $description, $income, $expend) = unpack("A10xA27xA7xA*", $_);
Now, that's our data parsed. I suppose what we might want to do now is total up our income and expenditure, and add another line to the end of our ledger - in the same format - saying how much we've brought in and how much we've spent:
while (<>) { my ($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_); $tot_income += $income; $tot_expend += $expend; } $tot_income = sprintf("%.2f", $tot_income); # Get them into $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format $date = POSIX::strftime("%m/%d/%Y", localtime); # OK, let's go: print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);
Oh, hmm. That didn't quite work. Let's see what happened:
01/24/2001 Zed's Camel Emporium 1147.99 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 1235.00 03/23/2001Totals 1235.001172.98
OK, it's a start, but what happened to the spaces? We put "x", didn't we? Shouldn't it skip forward? Let's look at what "pack" in perlfunc says:
x A null byte.
Urgh. No wonder. There's a big difference between "a null byte", character zero, and "a space", character 32. Perl's put something between the date and the description - but unfortunately, we can't see it!
What we actually need to do is expand the width of the fields. The "A" format pads any non-existent characters with spaces, so we can use the additional spaces to line up our fields, like this:
print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
(Note that you can put spaces in the template to make it more readable, but they don't translate to spaces in the output.) Here's what we got this time:
01/24/2001 Zed's Camel Emporium 1147.99 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 1235.00 03/23/2001 Totals 1235.00 1172.98
That's a bit better, but we still have that last column which needs to be moved further over. There's an easy way to fix this up: unfortunately, we can't get "pack" to right-justify our fields, but we can get "sprintf" to do it:
$tot_income = sprintf("%.2f", $tot_income); $tot_expend = sprintf("%12.2f", $tot_expend); $date = POSIX::strftime("%m/%d/%Y", localtime); print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
This time we get the right answer:
01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 1235.00 03/23/2001 Totals 1235.00 1172.98
So that's how we consume and produce fixed-width data. Let's recap what we've seen of "pack" and "unpack" so far:
Warning: when packing multiple pieces of data, "*" only means "consume all of the current piece of data". That's to say
pack("A*A*", $one, $two)
packs all of $one into the first "A*" and then all of $two into the second. This is a general principle: each format character corresponds to one piece of data to be "pack"ed.
So, for instance, to pack 20302 to a signed 16 bit integer in your computer's representation you write
my $ps = pack( 's', 20302 );
Again, the result is a string, now containing 2 bytes. If you print this string (which is, generally, not recommended) you might see "ON" or "NO" (depending on your system's byte ordering) - or something entirely different if your computer doesn't use ASCII character encoding. Unpacking $ps with the same template returns the original integer value:
my( $s ) = unpack( 's', $ps );
This is true for all numeric template codes. But don't expect miracles: if the packed value exceeds the allotted byte capacity, high order bits are silently discarded, and unpack certainly won't be able to pull them back out of some magic hat. And, when you pack using a signed template code such as "s", an excess value may result in the sign bit getting set, and unpacking this will smartly return a negative value.
16 bits won't get you too far with integers, but there is "l" and "L" for signed and unsigned 32-bit integers. And if this is not enough and your system supports 64 bit integers you can push the limits much closer to infinity with pack codes "q" and "Q". A notable exception is provided by pack codes "i" and "I" for signed and unsigned integers of the "local custom" variety: Such an integer will take up as many bytes as a local C compiler returns for "sizeof(int)", but it'll use at least 32 bits.
Each of the integer pack codes "sSlLqQ" results in a fixed number of bytes, no matter where you execute your program. This may be useful for some applications, but it does not provide for a portable way to pass data structures between Perl and C programs (bound to happen when you call XS extensions or the Perl function "syscall"), or when you read or write binary files. What you'll need in this case are template codes that depend on what your local C compiler compiles when you code "short" or "unsigned long", for instance. These codes and their corresponding byte lengths are shown in the table below. Since the C standard leaves much leeway with respect to the relative sizes of these data types, actual values may vary, and that's why the values are given as expressions in C and Perl. (If you'd like to use values from %Config in your program you have to import it with "use Config".)
signed unsigned byte length in C byte length in Perl s! S! sizeof(short) $Config{shortsize} i! I! sizeof(int) $Config{intsize} l! L! sizeof(long) $Config{longsize} q! Q! sizeof(long long) $Config{longlongsize}
The "i!" and "I!" codes aren't different from "i" and "I"; they are tolerated for completeness' sake.
+---------+ +----+----+ +---------+ TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI | +---------+ +----+----+ +---------+ | CS | | AL | AH | AX | DI | +---------+ +----+----+ +---------+ | BL | BH | BX | BP | +----+----+ +---------+ | CL | CH | CX | DS | +----+----+ +---------+ | DL | DH | DX | ES | +----+----+ +---------+
First, we note that this time-honored 16-bit CPU uses little-endian order, and that's why the low order byte is stored at the lower address. To unpack such a (unsigned) short we'll have to use code "v". A repeat count unpacks all 12 shorts:
my( $ip, $cs, $flags, $ax, $bx, $cd, $dx, $si, $di, $bp, $ds, $es ) = unpack( 'v12', $frame );
Alternatively, we could have used "C" to unpack the individually accessible byte registers FL, FH, AL, AH, etc.:
my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) = unpack( 'C10', substr( $frame, 4, 10 ) );
It would be nice if we could do this in one fell swoop: unpack a short, back up a little, and then unpack 2 bytes. Since Perl is nice, it proffers the template code "X" to back up one byte. Putting this all together, we may now write:
my( $ip, $cs, $flags,$fl,$fh, $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh, $si, $di, $bp, $ds, $es ) = unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame );
(The clumsy construction of the template can be avoided - just read on!)
We've taken some pains to construct the template so that it matches the contents of our frame buffer. Otherwise we'd either get undefined values, or "unpack" could not unpack all. If "pack" runs out of items, it will supply null strings (which are coerced into zeroes whenever the pack code says so).
my $buf = pack( 'N', length( $msg ) ) . $msg;
or even:
my $buf = pack( 'NA*', length( $msg ), $msg );
and pass $buf to your send routine. Some protocols demand that the count should include the length of the count itself: then just add 4 to the data length. (But make sure to read "Lengths and Widths" before you really code this!)
my @data = unpack 's*', pack 'S*', unpack 'n*', $buf;
This is ugly. As of Perl 5.9.2, there's a much nicer way to express your desire for a certain byte-order: the ">" and "<" modifiers. ">" is the big-endian modifier, while "<" is the little-endian modifier. Using them, we could rewrite the above code as:
my @data = unpack 's>*', $buf;
As you can see, the "big end" of the arrow touches the "s", which is a nice way to remember that ">" is the big-endian modifier. The same obviously works for "<", where the "little end" touches the code.
You will probably find these modifiers even more useful if you have to deal with big- or little-endian C structures. Be sure to read "Packing and Unpacking C Structures" for more on that.
"F" packs an "NV", which is the floating point type used by Perl internally.
There is no such thing as a network representation for reals, so if you want to send your real numbers across computer boundaries, you'd better stick to text representation, possibly using the hexadecimal float format (avoiding the decimal conversion loss), unless you're absolutely sure what's on the other end of the line. For the even more adventuresome, you can use the byte-order modifiers from the previous section also on floating point codes.
7 6 5 4 3 2 1 0 +-----------------+ | 1 0 0 0 1 1 0 0 | +-----------------+ MSB LSB
It's egg-eating all over again: Some think that as a bit string this should be written "10001100" i.e. beginning with the most significant bit, others insist on "00110001". Well, Perl isn't biased, so that's why we have two bit string codes:
$byte = pack( 'B8', '10001100' ); # start with MSB $byte = pack( 'b8', '00110001' ); # start with LSB
It is not possible to pack or unpack bit fields - just integral bytes. "pack" always starts at the next byte boundary and "rounds up" to the next multiple of 8 by adding zero bits as required. (If you do want bit fields, there is "vec" in perlfunc. Or you could implement bit field handling at the character string level, using split, substr, and concatenation on unpacked bit strings.)
To illustrate unpacking for bit strings, we'll decompose a simple status register (a "-" stands for a "reserved" bit):
+-----------------+-----------------+ | S Z - A - P - C | - - - - O D I T | +-----------------+-----------------+ MSB LSB MSB LSB
Converting these two bytes to a string can be done with the unpack template 'b16'. To obtain the individual bit values from the bit string we use "split" with the "empty" separator pattern which dissects into individual characters. Bit values from the "reserved" positions are simply assigned to "undef", a convenient notation for "I don't care where this goes".
($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign, $trace, $interrupt, $direction, $overflow) = split( //, unpack( 'b16', $status ) );
We could have used an unpack template 'b12' just as well, since the last 4 bits can be ignored anyway.
my $uubuf = pack( 'u', $bindat );
A repeat count after "u" sets the number of bytes to put into an uuencoded line, which is the maximum of 45 by default, but could be set to some (smaller) integer multiple of three. "unpack" simply ignores the repeat count.
my $buf = pack( 'iii', 100, 20, 3 ); print unpack( '%32i3', $buf ), "\n"; # prints 123
For string values, "%" returns the sum of the byte values saving you the trouble of a sum loop with "substr" and "ord":
print unpack( '%32A*', "\x01\x10" ), "\n"; # prints 17
Although the "%" code is documented as returning a "checksum": don't put your trust in such values! Even when applied to a small number of bytes, they won't guarantee a noticeable Hamming distance.
In connection with "b" or "B", "%" simply adds bits, and this can be put to good use to count set bits efficiently:
my $bitcount = unpack( '%32b*', $mask );
And an even parity bit can be determined like this:
my $evenparity = unpack( '%1b*', $mask );
The Unicode character sets associates characters with integers. Encoding these numbers in an equal number of bytes would more than double the requirements for storing texts written in Latin alphabets. The UTF-8 encoding avoids this by storing the most common (from a western point of view) characters in a single byte while encoding the rarer ones in three or more bytes.
Perl uses UTF-8, internally, for most Unicode strings.
So what has this got to do with "pack"? Well, if you want to compose a Unicode string (that is internally encoded as UTF-8), you can do so by using template code "U". As an example, let's produce the Euro currency symbol (code number 0x20AC):
$UTF8{Euro} = pack( 'U', 0x20AC ); # Equivalent to: $UTF8{Euro} = "\x{20ac}";
Inspecting $UTF8{Euro} shows that it contains 3 bytes: "\xe2\x82\xac". However, it contains only 1 character, number 0x20AC. The round trip can be completed with "unpack":
$Unicode{Euro} = unpack( 'U', $UTF8{Euro} );
Unpacking using the "U" template code also works on UTF-8 encoded byte strings.
Usually you'll want to pack or unpack UTF-8 strings:
# pack and unpack the Hebrew alphabet my $alefbet = pack( 'U*', 0x05d0..0x05ea ); my @hebrew = unpack( 'U*', $utf );
Please note: in the general case, you're better off using "Encode::decode('UTF-8', $utf)" to decode a UTF-8 encoded byte string to a Perl Unicode string, and "Encode::encode('UTF-8', $str)" to encode a Perl Unicode string to UTF-8 bytes. These functions provide means of handling invalid byte sequences and generally have a friendlier interface.
my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
A hex dump of $berbuf, with spaces inserted at the right places, shows 01 8100 8101 81807F. Since the last byte is always less than 128, "unpack" knows where to stop.
unpack( 'v2 (vXXCC)5 v5', $frame )
Let's explore this feature a little more. We'll begin with the equivalent of
join( '', map( substr( $_, 0, 1 ), @str ) )
which returns a string consisting of the first character from each string. Using pack, we can write
pack( '(A)'.@str, @str )
or, because a repeat count "*" means "repeat as often as required", simply
pack( '(A)*', @str )
(Note that the template "A*" would only have packed $str[0] in full length.)
To pack dates stored as triplets ( day, month, year ) in an array @dates into a sequence of byte, byte, short integer we can write
$pd = pack( '(CCS)*', map( @$_, @dates ) );
To swap pairs of characters in a string (with even length) one could use several techniques. First, let's use "x" and "X" to skip forward and back:
$s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) );
We can also use "@" to jump to an offset, with 0 being the position where we were when the last "(" was encountered:
$s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) );
Finally, there is also an entirely different approach by unpacking big endian shorts and packing them in the reverse byte order:
$s = pack( '(v)*', unpack( '(n)*', $s );
my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm );
Unpacking this message can be done with the same template:
( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg );
There's a subtle trap lurking in the offing: Adding another field after the Short Message (in variable $sm) is all right when packing, but this cannot be unpacked naively:
# pack a message my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio ); # unpack fails - $prio remains undefined! ( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg );
The pack code "A*" gobbles up all remaining bytes, and $prio remains undefined! Before we let disappointment dampen the morale: Perl's got the trump card to make this trick too, just a little further up the sleeve. Watch this:
# pack a message: ASCIIZ, ASCIIZ, length/string, byte my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio ); # unpack ( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg );
Combining two pack codes with a slash ("/") associates them with a single value from the argument list. In "pack", the length of the argument is taken and packed according to the first code while the argument itself is added after being converted with the template code after the slash. This saves us the trouble of inserting the "length" call, but it is in "unpack" where we really score: The value of the length byte marks the end of the string to be taken from the buffer. Since this combination doesn't make sense except when the second pack code isn't "a*", "A*" or "Z*", Perl won't let you.
The pack code preceding "/" may be anything that's fit to represent a number: All the numeric binary pack codes, and even text codes such as "A4" or "Z*":
# pack/unpack a string preceded by its length in ASCII my $buf = pack( 'A4/A*', "Humpty-Dumpty" ); # unpack $buf: '13 Humpty-Dumpty' my $txt = unpack( 'A4/A*', $buf );
"/" is not implemented in Perls before 5.6, so if your code is required to work on ancient Perls you'll need to "unpack( 'Z* Z* C')" to get the length, then use it to make a new unpack string. For example
# pack a message: ASCIIZ, ASCIIZ, length, string, byte # (5.005 compatible) my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio ); # unpack ( undef, undef, $len) = unpack( 'Z* Z* C', $msg ); ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg );
But that second "unpack" is rushing ahead. It isn't using a simple literal string for the template. So maybe we should introduce...
my $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C', map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 );
Let's examine the cogs of this byte mill, one by one. There's the "map" call, creating the items we intend to stuff into the $env buffer: to each key (in $_) it adds the "=" separator and the hash entry value. Each triplet is packed with the template code sequence "A*A*Z*" that is repeated according to the number of keys. (Yes, that's what the "keys" function returns in scalar context.) To get the very last null byte, we add a 0 at the end of the "pack" list, to be packed with "C". (Attentive readers may have noticed that we could have omitted the 0.)
For the reverse operation, we'll have to determine the number of items in the buffer before we can let "unpack" rip it apart:
my $n = $env =~ tr/\0// - 1; my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) );
The "tr" counts the null bytes. The "unpack" call returns a list of name-value pairs each of which is taken apart in the "map" block.
my $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env );
This simplifies the reverse operation as the number of repetitions can be unpacked with the "/" code:
my %env = unpack( 'S/(S/A* S/A*)', $env );
Note that this is one of the rare cases where you cannot use the same template for "pack" and "unpack" because "pack" can't determine a repeat count for a "()"-group.
The first step of processing such a line is the conversion, to binary, of the hexadecimal data, to obtain the four fields, while checking the checksum. No surprise here: we'll start with a simple "pack" call to convert everything to binary:
my $binrec = pack( 'H*', substr( $hexrec, 1 ) );
The resulting byte sequence is most convenient for checking the checksum. Don't slow your program down with a for loop adding the "ord" values of this string's bytes - the "unpack" code "%" is the thing to use for computing the 8-bit sum of all bytes, which must be equal to zero:
die unless unpack( "%8C*", $binrec ) == 0;
Finally, let's get those four fields. By now, you shouldn't have any problems with the first three fields - but how can we use the byte count of the data in the first field as a length for the data field? Here the codes "x" and "X" come to the rescue, as they permit jumping back and forth in the string to unpack.
my( $addr, $type, $data ) = unpack( "x n C X4 C x3 /a", $bin );
Code "x" skips a byte, since we don't need the count yet. Code "n" takes care of the 16-bit big-endian integer address, and "C" unpacks the record type. Being at offset 4, where the data begins, we need the count. "X4" brings us back to square one, which is the byte at offset 0. Now we pick up the count, and zoom forth to offset 4, where we are now fully furnished to extract the exact number of data bytes, leaving the trailing checksum byte alone.
If you have to deal with a lot of C structures, and don't want to hack all your template strings manually, you'll probably want to have a look at the CPAN module "Convert::Binary::C". Not only can it parse your C source directly, but it also has built-in support for all the odds and ends described further on in this section.
To see how this affects "pack" and "unpack", we'll compare these two C structures:
typedef struct { char c1; short s; char c2; long l; } gappy_t; typedef struct { long l; short s; char c1; char c2; } dense_t;
Typically, a C compiler allocates 12 bytes to a "gappy_t" variable, but requires only 8 bytes for a "dense_t". After investigating this further, we can draw memory maps, showing where the extra 4 bytes are hidden:
0 +4 +8 +12 +--+--+--+--+--+--+--+--+--+--+--+--+ |c1|xx| s |c2|xx|xx|xx| l | xx = fill byte +--+--+--+--+--+--+--+--+--+--+--+--+ gappy_t 0 +4 +8 +--+--+--+--+--+--+--+--+ | l | h |c1|c2| +--+--+--+--+--+--+--+--+ dense_t
And that's where the first quirk strikes: "pack" and "unpack" templates have to be stuffed with "x" codes to get those extra fill bytes.
The natural question: "Why can't Perl compensate for the gaps?" warrants an answer. One good reason is that C compilers might provide (non-ANSI) extensions permitting all sorts of fancy control over the way structures are aligned, even at the level of an individual structure field. And, if this were not enough, there is an insidious thing called "union" where the amount of fill bytes cannot be derived from the alignment of the next item alone.
OK, so let's bite the bullet. Here's one way to get the alignment right by inserting template codes "x", which don't take a corresponding item from the list:
my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l );
Note the "!" after "l": We want to make sure that we pack a long integer as it is compiled by our C compiler. And even now, it will only work for the platforms where the compiler aligns things as above. And somebody somewhere has a platform where it doesn't. [Probably a Cray, where "short"s, "int"s and "long"s are all 8 bytes. :-)]
Counting bytes and watching alignments in lengthy structures is bound to be a drag. Isn't there a way we can create the template with a simple program? Here's a C program that does the trick:
#include <stdio.h> #include <stddef.h> typedef struct { char fc1; short fs; char fc2; long fl; } gappy_t; #define Pt(struct,field,tchar) \ printf( "@%d%s ", offsetof(struct,field), # tchar ); int main() { Pt( gappy_t, fc1, c ); Pt( gappy_t, fs, s! ); Pt( gappy_t, fc2, c ); Pt( gappy_t, fl, l! ); printf( "\n" ); }
The output line can be used as a template in a "pack" or "unpack" call:
my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l );
Gee, yet another template code - as if we hadn't plenty. But "@" saves our day by enabling us to specify the offset from the beginning of the pack buffer to the next item: This is just the value the "offsetof" macro (defined in "<stddef.h>") returns when given a "struct" type and one of its field names ("member-designator" in C standardese).
Neither using offsets nor adding "x"'s to bridge the gaps is satisfactory. (Just imagine what happens if the structure changes.) What we really need is a way of saying "skip as many bytes as required to the next multiple of N". In fluent Templatese, you say this with "x!N" where N is replaced by the appropriate value. Here's the next version of our struct packaging:
my $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l );
That's certainly better, but we still have to know how long all the integers are, and portability is far away. Rather than 2, for instance, we want to say "however long a short is". But this can be done by enclosing the appropriate pack code in brackets: "[s]". So, here's the very best we can do:
my $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l );
my $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l );
If the target machine is little-endian, we could write:
my $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l );
This forces the short and the long members to be little-endian, and is just fine if you don't have too many struct members. But we could also use the byte-order modifier on a group and write the following:
my $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l );
This is not as short as before, but it makes it more obvious that we intend to have little-endian byte-order for a whole group, not only for individual template codes. It can also be more readable and easier to maintain.
typedef struct { short count; char glyph; } cell_t; typedef cell_t buffer_t[BUFLEN];
Where's the catch? Padding is neither required before the first field "count", nor between this and the next field "glyph", so why can't we simply pack like this:
# something goes wrong here: pack( 's!a' x @buffer, map{ ( $_->{count}, $_->{glyph} ) } @buffer );
This packs "3*@buffer" bytes, but it turns out that the size of "buffer_t" is four times "BUFLEN"! The moral of the story is that the required alignment of a structure or array is propagated to the next higher level where we have to consider padding at the end of each component as well. Thus the correct template is:
pack( 's!ax' x @buffer, map{ ( $_->{count}, $_->{glyph} ) } @buffer );
typedef struct { char foo[2]; } foo_t;
vary in size. The alignment constraint of the structure can be greater than any of its elements. [And if you think that this doesn't affect anything common, dismember the next cellphone that you see. Many have ARM cores, and the ARM structure rules make "sizeof (foo_t)" == 4]
Template code "P" promises to pack a "pointer to a fixed length string". Isn't this what we want? Let's try:
# allocate some storage and pack a pointer to it my $memory = "\x00" x $size; my $memptr = pack( 'P', $memory );
But wait: doesn't "pack" just return a sequence of bytes? How can we pass this string of bytes to some C code expecting a pointer which is, after all, nothing but a number? The answer is simple: We have to obtain the numeric address from the bytes returned by "pack".
my $ptr = unpack( 'L!', $memptr );
Obviously this assumes that it is possible to typecast a pointer to an unsigned long and vice versa, which frequently works but should not be taken as a universal law. - Now that we have this pointer the next question is: How can we put it to good use? We need a call to some C function where a pointer is expected. The read(2) system call comes to mind:
ssize_t read(int fd, void *buf, size_t count);
After reading perlfunc explaining how to use "syscall" we can write this Perl function copying a file to standard output:
require 'syscall.ph'; # run h2ph to generate this file sub cat($){ my $path = shift(); my $size = -s $path; my $memory = "\x00" x $size; # allocate some memory my $ptr = unpack( 'L', pack( 'P', $memory ) ); open( F, $path ) || die( "$path: cannot open ($!)\n" ); my $fd = fileno(F); my $res = syscall( &SYS_read, fileno(F), $ptr, $size ); print $memory; close( F ); }
This is neither a specimen of simplicity nor a paragon of portability but it illustrates the point: We are able to sneak behind the scenes and access Perl's otherwise well-guarded memory! (Important note: Perl's "syscall" does not require you to construct pointers in this roundabout way. You simply pass a string variable, and Perl forwards the address.)
How does "unpack" with "P" work? Imagine some pointer in the buffer about to be unpacked: If it isn't the null pointer (which will smartly produce the "undef" value) we have a start address - but then what? Perl has no way of knowing how long this "fixed length string" is, so it's up to you to specify the actual size as an explicit length after "P".
my $mem = "abcdefghijklmn"; print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde"
As a consequence, "pack" ignores any number or "*" after "P".
Now that we have seen "P" at work, we might as well give "p" a whirl. Why do we need a second template code for packing pointers at all? The answer lies behind the simple fact that an "unpack" with "p" promises a null-terminated string starting at the address taken from the buffer, and that implies a length for the data item to be returned:
my $buf = pack( 'p', "abc\x00efhijklmn" ); print unpack( 'p', $buf ); # prints "abc"
Albeit this is apt to be confusing: As a consequence of the length being implied by the string's length, a number after pack code "p" is a repeat count, not a length as after "P".
Using "pack(..., $x)" with "P" or "p" to get the address where $x is actually stored must be used with circumspection. Perl's internal machinery considers the relation between a variable and that address as its very own private matter and doesn't really care that we have obtained a copy. Therefore:
It's safe, however, to P- or p-pack a string literal, because Perl simply allocates an anonymous variable.
# Convert IP address for socket functions pack( "C4", split /\./, "<IP_ADDRESS>" ); # Count the bits in a chunk of memory (e.g. a select vector) unpack( '%32b*', $mask ); # Determine the endianness of your system $is_little_endian = unpack( 'c', pack( 's', 1 ) ); $is_big_endian = unpack( 'xc', pack( 's', 1 ) ); # Determine the number of bits in a native integer $bits = unpack( '%32I!', ~0 ); # Prepare argument for the nanosleep system call my $timespec = pack( 'L!L!', $secs, $nanosecs );
For a simple memory dump we unpack some bytes into just as many pairs of hex digits, and use "map" to handle the traditional spacing - 16 bytes to a line:
my $i; print map( ++$i % 16 ? "$_ " : "$_\n", unpack( 'H2' x length( $mem ), $mem ) ), length( $mem ) % 16 ? "\n" : '';
# Pulling digits out of nowhere... print unpack( 'C', pack( 'x' ) ), unpack( '%B*', pack( 'A' ) ), unpack( 'H', pack( 'A' ) ), unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n"; # One for the road ;-) my $advice = pack( 'all u can in a van' );
| 2019-10-21 | perl v5.30.3 |


A place for general developer talk – for everyone! | Documentation https://developers.komodoplatform.com | MoreDev Docs - https://docs.komodoplatform.com | Mastering CryptoConditions - https://github.com/KomodoPlatform/Mastering_CryptoConditions
100 messages
Before 05-Dec-19 12:00 AM
dukeleto15-Nov-18 08:34 AM
@D.rabbani kill or pkill works if other things don't
A short description of the C++ build process. Contribute to green7ea/cpp-compilation development by creating an account on GitHub.
D.rabbani15-Nov-18 08:51 AM
why does activating best chain takes too long ?
sometimes
i am stuck on my local host before it used to work fine
but now its stuck on activating best
./komodo-cli getinfo
error 28 :
activating best chain ?
stuck for about 2 hours
i am preparing a documentation for my own self but i dont know why it is not starting?
jl777c15-Nov-18 08:59 AM
tail the debug.log
what is happening
dukeleto15-Nov-18 09:03 AM
@D.rabbani shouldn't take that long, usually that lasts for a few seconds or maybe minutes. Perhaps something triggered a full rescan
debug.log is always your friend
D.rabbani15-Nov-18 09:03 AM
Oh no so i t means i need to wait
for a whole day for it to be activated
D.rabbani15-Nov-18 09:12 AM
i cannot find any debug log
unfrutnateoly
dukeleto15-Nov-18 09:18 AM
oh gosh
@D.rabbani ~/.komodo/debug.log
D.rabbani15-Nov-18 09:19 AM
thanks
dukeleto15-Nov-18 09:19 AM
@D.rabbani it will be in a subdir of that, for an asset chain, like ~/.komodo/MYCHAIN/debug.log
KMD has the top-level debug.log
D.rabbani15-Nov-18 09:20 AM
yes i wanted to see the komodo on e:D
thanks
i got i t
dukeleto15-Nov-18 09:20 AM
yup
its ~/Library/Application Support/Komodo/debug.log on OS X, somewhere else on other crazy OS's
D.rabbani15-Nov-18 09:22 AM
yup but debug log doesnt show any error
i dont know what to do now
its normal
as always
dukeleto15-Nov-18 09:26 AM
@D.rabbani do you have a HD or partition full? is does the debug.log have new stuff as you tail -f it ?
sometimes you need to look further up the debug.log, maybe hundreds of lines
the thing you want is not always at the very end
D.rabbani15-Nov-18 10:40 AM
okai its running the log so ill let you know thanks alot for that ]
and sorry for my questiosn
i am on the learning pahse
D.rabbani15-Nov-18 11:42 AM
another question please if someone can reply
D.rabbani15-Nov-18 11:51 AM
is it possible that we can only give the command without the supply and reward and en ? for syncing with other nodes or is it necessary to do that ? i mean to say shall i give like that
./komodo-cli -ac_name =EXAMPLECOIN -addnode=<IP_ADDRESS> -addnode=<IP_ADDRESS> ?? will that work
jl777c15-Nov-18 11:52 AM
komodo-cli is local
komodod needs all the parameters, otherwise it is a different chain
D.rabbani15-Nov-18 11:56 AM
but we are giving the parameter in the -ac_name is not enough for the komodod ?
do we need to give the full supply including the rewards and the end to our clients actually just want that hidden from the clients the suply and the rewards ?
jl777c15-Nov-18 11:58 AM
how is a node supposed to know the chain parameters if it never sees it?
maybe some repository of chain parameters can be setup, but for now each node needs to be given the exact parameters
1
you can just make a script file that encapsulates all the parameters and have users just run the script file
1
D.rabbani15-Nov-18 11:59 AM
true that @jl777c we can give that to the users thanks alot for the help
Bar_F1sh_Rel15-Nov-18 01:32 PM
Kmdlabs startscripts encapsulate the chain params in a json file - pulled from git on activation. That works nicely.
1
D.rabbani15-Nov-18 02:51 PM
can we change the -ac_end ?? afterwards ? just asking >
jl777c15-Nov-18 02:56 PM
if you change any chain parameters, you change the chain
immutable and all that
IndieBlock15-Nov-18 07:14 PM
Anyone following the BCH drama?
jorian15-Nov-18 07:18 PM
#talk-trading
smdmitry16-Nov-18 11:59 AM
Hi! Please point me to where can I find patched node for insight explorer?
jl777c16-Nov-18 12:00 PM
add -addressindex=1 -spentindex=1 -timestampindex=1 to any komodod. that enables the insight required rpc calls
Python HTTP Requests for Humans™ . Contribute to requests/requests development by creating an account on GitHub.
CMaurice16-Nov-18 04:25 PM
cheers for the pointer
dukeleto16-Nov-18 04:25 PM
"bitcoin for humans" was definitely in reference to that
@CMaurice do you know if your code validated addresses in any way, where if we try to use KMD address like Rfoo.., will it allow that?
it seems to allow setting an RPC port, which is good
CMaurice16-Nov-18 04:42 PM
No idea, @dukeleto , I just came across the repo earlier and dumped the epub docs for later perusal.
Alright16-Nov-18 11:12 PM
I could use some help debugging this chain if anyone has some time right now.
./komodod -ac_name=PTX -ac_supply=12000000 -ac_end=12000000 -ac_staked=50 -ac_reward=1500000000 -ac_pubkey=0359e2ee32833398c26378a2bb0962f98a7d77f3f6e6e4d27316bcb85542f23c61 -addnode=<IP_ADDRESS>
Seems it's bugged out. I can connect to peers, but it will never start syncing blocks. Any ideas?
Has anyone ever experienced something similar?
TonyL17-Nov-18 05:21 AM
@Alright is there any node with non 0 blocks amount?
I get 18-11-17 05:18:54 connect() to <IP_ADDRESS>:26435 failed after select(): Connection refused (111) in debug.log
Maybe node/s which got blocks have some network restrictions on connections
This will continually lower the difficulty during hashing based on the timestamp the miner assigns when he's changing the nonce. Hopefully it will solve the problem of delays after on-off minin...
Nabob18-Nov-18 12:29 PM
@Deleted User I have MQ Experience of other properierity software not in Rabbit, Whats the query ?(edited)
@radix42 and then Act III, where the Count of Monte DPoWconfs says "one confirmation ... one confirmation ... one confirmation ... SEVEN confirmations and it's notarized! https://t.co/lKtw8FTz0X
1
Rohit19-Nov-18 10:24 AM
hi
anyone can help me how to generate komodo wallete address using nodejs


Guidance
Information about how 16 to 19 funding is allocated to colleges, providers, schools and academies.
The Education Funding Agency ( EFA ) funds schools, academies, colleges and commercial and charitable providers. We calculate funding using the 16 to 19 national funding formula . The formula is driven by student recruitment and includes factors which reflect student retention, higher cost subjects, disadvantaged students and area costs. The 16 to 19: how it works page includes further information about each element within the 16 to 19 national funding formula.
Funding calculated using the national funding formula is also supplemented by additional funding for high needs students, bursaries and other financial support awarded to individual students.
The allocations timeline for issuing 2017 to 2018 academic year allocations is set out below:
| Month | Activity | Latest news |
|---|---|---|
| December 2016 | ILR R04 deadline (6 December) – first EFA return for 2016 to 2017 | R04 data return window closed on 6 December 2016 |
| December 2016 | Publication of dedicated schools grant (DSG), schools block and high needs block allocations for 2017 to 2018 (prior to academy recoupment) | We published dedicated schools grant (DSG), schools block and high needs block allocations in December 2016 |
| January 2017 | Allocation Calculation Toolkit for 2017 to 2018 containing funding factors sent to FE institutions | We uploaded FE ACT files to EFA Document Exchange and published supporting information in January |
| January 2017 | Final high needs place numbers confirmed for 2017 to 2018 | We published high needs place numbers in January |
| Early February 2017 | Allocation Calculation Toolkit for 2017 to 2018 containing funding factors and student numbers sent to schools and academies | We uploaded school and academy ACT files to EFA Document Exchange and published supporting information in February |
| February 2017 | ILR R06 deadline (6 February) | R06 data return window closed on 6 February 2017 |
| February 2017 | Allocations, including high needs place numbers, notified to most institutions | We have now uploaded post-16 funding allocation statements to EFA Information Exchange for most schools and academies with sixth-forms, and further education colleges. We are still finalising statements for a small number of institutions. We aim to upload these remaining allocation statements to Information Exchange during March. We have published supporting documents to help you understand your statement |
| March 2017 | Allocations notified to all special post-16 institutions, non-maintained special schools and charitable and commercial providers and other institutions where lagged numbers are based on R06 | |
| April 2017 | Deadline for institutions to return any business cases in relation to exceptional circumstances affecting their allocation (excluding high needs) | |
| April/May/June 2017 | All business cases reviewed | |
| June to August 2017 | Funding agreements/contracts issued to institutions either directly or through the lead contact. Agreements/contracts signed and returned by funded organisation. Institutions informed of outcomes of business cases in June | |
| August/September 2017 | First payment made to LAs (in respect of schools with sixth forms) and directly to academies, colleges and other institutions |
We have published a funding letter setting out the key decisions and information relating to allocations for 2017 to 2018.
As in previous years, we will base your funding allocation for 2017 to 2018 on your 2016 to 2017 lagged student numbers. Your allocation statement will include a breakdown of the calculation and explanatory notes will be available to help you understand your allocation.
We have streamlined the process this year in consultation with key provider associations and this will reduce the number of separate documents we will send to institutions during January and February 2017. We will issue statements to EFA Information Exchange: ‘Revenue Funding’ folder, under ‘AY 2017-18’. We expect most institutions to be informed of your allocation by the end of February 2017. We expect all institutions to be informed of your allocation by the end of March 2017.
We publish a full list of the allocations made to all individual FE institutions, schools and academies each year around October.
The deadline for business cases is April 2017, and we will confirm the precise dates shortly.
We have produced a video explaining the funding allocations for academic year 2017 to 2018.
The provisional data sources we expect to use to calculate 2017 to 2018 funding allocations are detailed in the tables below:
| Institution type | Method of determining number of students attracting funding |
|---|---|
| Schools, academies, free schools, studio schools, university technical colleges | Lagged numbers based on 2016 to 2017 student numbers in autumn 2016 census. Some academies are funded on estimated numbers where their funding agreement states this |
| FE colleges, some other FE or higher education institutions | The starting point is the number of valid students with a census date of 1 November 2016 based on R04 for 2016 to 2017. This is multiplied by the ratio of 1 November to all-year student numbers based on the R04 return for 2015 to 2016 and the final R14 return for that year. We will also compare this figure with the student numbers calculated from R06, both the year-to-date (as at 1 February) figure and the number recruited by 1 November. Where there is a significant increase or decrease in student numbers we may revise the allocation accordingly. This could result in a delay to issuing allocations for institutions involved |
| Commercial and charitable providers | The approach is similar to that for 2016 to 2017 allocations, that is, depending on the profile of recruitment for the individual provider we either use a 12 month rolling figure for February 2016 to January 2017 based on R14 (2015 to 2016) and R06 (2016 to 2017) data; or the same approach as set out above for FE colleges. The use of R06 data means that CCPs receive allocations slightly later than colleges, schools and academies |
| Higher education institutions, local authorities, some other FE institutions | Where use of in-year data was not appropriate, a full year figure will be used based on, R14 (2015 to 2016) or HESA data for 2015 to 2016 |
| Maintained special schools | The high needs place funding allocation will be made at local authority level, rather than at individual school level. Local authorities then determine the place funding to individual maintained special schools |
| Special academies | Published 2016 to 2017 academic year high needs place numbers revised by place changes requested by local authorities in the autumn of 2016 |
| Special free schools | EFA contacts special free schools direct for information to determine their place funding allocations for the 2017 to 2018 academic year |
| Special post-16 institutions | Continue to be funded on the basis of elements 1 and 2 in 2017 to 2018. The place funding will be allocated based on ILR data. We will confirm shortly which data set will be used for 2017 to 2018 allocation purposes |
| Non maintained special schools | Continue to be funded based on school census data. We will confirm shortly which data set will be used for 2017 to 2018 allocation purposes |
| New institutions | Year 1 – starting point 1/3 of capacity, any variation from this would require a business case by February 2017, Year 2 – double the actual recruitment in year 1 (2016 to 2017 Autumn Census/R04), Year 3 – institution is funded on lagged numbers |
| Closing institutions | We will reduce the lagged numbers to reflect the expected decline in student numbers. No 16 to 19 funding will be allocated to any institution that is completely ceasing 16 to 19 provision, and there will also be a reduction in funding before that, if the change in delivery is material (for example, a rundown of provision over 2 years) |
| Institution type | Size of programme/Retention/Programme cost weighting | Disadvantage - Block 1 factor | Disadvantage - Block 2 instances | Large programmes | Condition of Funding |
|---|---|---|---|---|---|
| Institutions making ILR return | R14 2015 to 2016 | R14 2015 to 2016 | R14 2015 to 2016 (1) | 2014 to 2015 Young People’s matched admin data set (YPMAD) | R14 2015 to 2016 |
| Institutions making census return | Autumn census 2016 (end-year 2015 to 2016 data) | Autumn census 2016 (end-year 2015 to 2016 data) | Autumn census 2016 (end-year 2015 to 2016 data) | 2014 to 2015 Young People’s matched admin data set (YPMAD) | Autumn census 2016 (end-year 2015 to 2016 data) |
| Institutions making HESA return | HESA 2015 to 2016 | HESA 2015 to 2016 | HESA 2015 to 2016 | Based on exceptional business cases where appropriate | HESA 2015 to 2016 |
| Institutions with no historical data | National average for institution type | LA average for institution type | National average for institution type | No impact | No impact |
(1) YPMAD 2014 to 2015 data will be used in the mitigation calculation
This information is not applicable for maintained special schools, non maintained special schools, special academies, special free schools, these institutions are funded at £10,000 per place for Element 1 and 2.
Published: 10 March 2014
Updated: 28 February 2017
From: Education Funding Agency
Part of: Funding education for 16- to 19-year-olds
Related guides: 16 to 19 education: funding guidance


7 Week 7: Scatterplots
7.1 Goals
- You’ll learn how to visualise the relationship between two continuous variables in a scatterplot.
- You’ll gain some experience with summarising and manipulating large datasets.
7.2 Summarising datasets
Vanhove (2014) investigated how people’s ability to
recognise written and spoken cognates in a related but
unknown language develops throughout the lifespan and
how it is related to linguistic and cognitive factors.
The dataset Vanhove2014_Translations.csv
contains the
raw data of this study. For each of the 163 participants,
this dataset contains 100 entries (one for each cognate),
for a total of 16,300 rows.
Each translation was rated as correct or incorrect.
Additionally, the dataset contains some information
about the participants (e.g., their performance on other
tasks) as well as about the stimuli (e.g., a measure
expressing its formal similarity to its French, German or English cognate).
# Read in data
<- read_csv(here("data", "Vanhove2014_Translations.csv")) d
## Rows: 16300 Columns: 15
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): Stimulus, Mode, Translation, Sex, Status
## dbl (10): Subject, Trial, Correct, Age, NrLang, DS.Total, WST.Right, Raven.R...
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
The variables:
Stimulus
: The word to be translated.Subject
: The participant’s ID.Mode
: Whether the word was presented in its spoken (Auditory
) or in its written form (Visual
).Trial
: The position of the word in the task.Translation
: The participant’s translation attempt for the stimulus.Correct
: Whether the translation was correct (1) or incorrect (0).Sex
Age
NrLang
: The number of languages the participant spoken.DS.Total
: The participant’s score on a working memory task.WST.Right
: The participant’s score on a German vocabulary test.Raven.Right
: The participant’s score on an intelligence test.English.Total
: The participant’s score on an English-language test.Status
: Whether the stimulus has a German, English, or French cognates (target
) or not (profile
).MinLev
: The degree of formal discrepancy between the stimulus and its most similar German, English or French cognate. (lower = more similar)
Missing values were labelled NA
(not available).
 If we’re interested in the relationship between the participants’ age, sex, and linguistic and cognitive test results on the one hand and their translation performance on the other hand, it seems useful to first compute the number of correct translations for spoken and written words per participant. There are a couple of ways you could do this in R; I find the method outlined below the most transparent one.
Let’s start with a simple example. We’ll first compute the total number of correct responses in the entire dataset. The comments show you how you can read the R code out loud.
# 1st attempt: Total number of correct answers
# Take object 'd' (our dataset), then
|>
d # summarise it as follows:
# - compute the sum of 'Correct' and call this sum 'number_correct'
summarise(number_correct = sum(Correct))
## # A tibble: 1 × 1
## number_correct
## <dbl>
## 1 5743
The result is shown in the console. We can also
save it as a separate object so that we can
work with it later. Here I save it as an object
called overall_accuracy
:
<- d |>
overall_accuracy summarise(number_correct = sum(Correct))
(To type the symbol combination |> (known as the pipe; read out loud as ‘and then’), you can also use the shortcut ctrl + shift + m.)
The total number of correct answers in the entire dataset isn’t too useful to us: we need the number of correct answers per participant.
# 2nd attempt: Number of correct answers per participant
# Create new object 'per_part' as follows:
# take 'd', and then...
<- d |>
per_part # group it by Subject, and then...
group_by(Subject) |>
# compute the sum of Correct within each group
summarise(number_correct = sum(Correct))
# Show result
per_part
## # A tibble: 163 × 2
## Subject number_correct
## <dbl> <dbl>
## 1 64 49
## 2 78 39
## 3 134 36
## 4 230 38
## 5 288 21
## 6 326 45
## 7 447 47
## 8 527 24
## 9 545 33
## 10 550 46
## # … with 153 more rows
Now we have the total number of correct translations per participant, but this figure contains both the responses to written and to spoken words. It’d be more useful to split this figure up by modality:
# 3rd attempt: Number of correct translations per participant,
# split up by modality.
<- d |>
per_part2 # group by Subject and Mode
group_by(Subject, Mode) |>
summarise(number_correct = sum(Correct))
## `summarise()` has grouped output by 'Subject'. You can override using the
## `.groups` argument.
per_part2
## # A tibble: 326 × 3
## # Groups: Subject [163]
## Subject Mode number_correct
## <dbl> <chr> <dbl>
## 1 64 Auditory 24
## 2 64 Visual 25
## 3 78 Auditory 19
## 4 78 Visual 20
## 5 134 Auditory 24
## 6 134 Visual 12
## 7 230 Auditory 12
## 8 230 Visual 26
## 9 288 Auditory 12
## 10 288 Visual 9
## # … with 316 more rows
The message (summarise()
has grouped output by ‘Subject’.) isn’t harmful, but you can get rid of it as follows:
<- d |>
per_part2 group_by(Subject, Mode) |>
summarise(number_correct = sum(Correct),
.groups = "drop")
Our goal is to visualise the relationship between variables such as IQ, age, and L1 vocabulary skills on the one hand and the participants’ translation performance on the other hand. To do this, we need to add these variable to the summary. Again, there are several ways to do this; here’s one.
# 4th attempt: Like above, but adding Age, etc.
# Create a new object with participant-related information.
# Take 'd', and then...
<- d |>
part_info # Select the following columns
select(Subject, Age, Sex, WST.Right,
Raven.Right, English.Total, NrLang, DS.Total)
Like d
, part_info
consists of 16,300 rows.
But each row is repeated 100 times.
Using distinct()
, the duplicates are deleted:
<- part_info |>
part_info distinct()
Now we can add the information from part_info
to per_part2
:
# Create new object 'per_part3'.
# Take object 'per_part2', and then...
<- per_part2 |>
per_part3 # join it with 'part_info' using 'Subject' as the "zipper"
full_join(part_info, by = "Subject")
# Show result
per_part3
## # A tibble: 326 × 10
## Subject Mode number_correct Age Sex WST.Right Raven.Right English.Total
## <dbl> <chr> <dbl> <dbl> <chr> <dbl> <dbl> <dbl>
## 1 64 Audit… 24 27 fema… 34 28 42
## 2 64 Visual 25 27 fema… 34 28 42
## 3 78 Audit… 19 47 fema… 33 26 27
## 4 78 Visual 20 47 fema… 33 26 27
## 5 134 Audit… 24 33 male 32 24 24
## 6 134 Visual 12 33 male 32 24 24
## 7 230 Audit… 12 84 male 37 20 31
## 8 230 Visual 26 84 male 37 20 31
## 9 288 Audit… 12 28 male 35 24 39
## 10 288 Visual 9 28 male 35 24 39
## # … with 316 more rows, and 2 more variables: NrLang <dbl>, DS.Total <dbl>
One final problem remains: The number of correct answers
includes responses to both cognates and to non-cognates.
We’re only interested in the responses to cognates, however.
Using filter()
, we only retain the responses that are of interest:
# 5th attempt: Like above, but only consider target stimuli.
<- d |>
per_part # only consider target stimuli
filter(Status == "target") |>
# group by Subject and Mode
group_by(Subject, Mode) |>
# Compute sum of Correct
summarise(number_correct = sum(Correct),
.groups = "drop") |>
# Add the information from part_info using Subject as the "zipper"
full_join(part_info, by = "Subject")
per_part
## # A tibble: 326 × 10
## Subject Mode number_correct Age Sex WST.Right Raven.Right English.Total
## <dbl> <chr> <dbl> <dbl> <chr> <dbl> <dbl> <dbl>
## 1 64 Audit… 23 27 fema… 34 28 42
## 2 64 Visual 25 27 fema… 34 28 42
## 3 78 Audit… 19 47 fema… 33 26 27
## 4 78 Visual 20 47 fema… 33 26 27
## 5 134 Audit… 24 33 male 32 24 24
## 6 134 Visual 12 33 male 32 24 24
## 7 230 Audit… 12 84 male 37 20 31
## 8 230 Visual 26 84 male 37 20 31
## 9 288 Audit… 12 28 male 35 24 39
## 10 288 Visual 9 28 male 35 24 39
## # … with 316 more rows, and 2 more variables: NrLang <dbl>, DS.Total <dbl>
7.3 Scatterplots
To investigate the relationhip between, say, WST.Right
and number_correct
,
we can plot these data in a scatterplot. While we’re at it, we can split up
this graph into two panels: one for written words, and one for spoken words.
ggplot(dat = per_part,
aes(x = WST.Right,
y = number_correct)) +
# Incidentally, you can specify the shape and colour of the points yourself.
geom_point(shape = 21, colour = "darkblue", fill = "green") +
# Type in "colours()" to see which colour names are recognised by R.
# Type in ?pch to see which 'shape' values are accepted.
xlab("L1 vocabulary test") +
ylab("Number of correct translations\n(out of 45)") +
facet_grid(cols = vars(Mode)) +
labs(title = "A title of your choice",
subtitle = "(and perhaps even a subtitle)",
caption = "(and a caption)")
## Warning: Removed 2 rows containing missing values (geom_point).
(The warning concerns two missing values in the WST
variable.)
As we’ll discuss in class, scatterplots are the indispensable first (and sometimes final) step when analysing the relationship between two continuous variables.
As for the decision which variable to put along which axis. By and large, put the variable that is most likely to be the cause of the relationship along the x axis and the variable that is most likely to be the effect along the y axis. In this case, it seems more likely that L1 skills affect one’s ability to recognise cognates in a foreign language than vice versa. Hence, put the variable representing L1 skills along the x axis.
7.4 Exercise
Draw a scatterplot that shows the relationship between the participants’ score on the English-language test and the number of correct translations. How many participants’ data are shown?
Hand in both the graph and the compiled HTML report. Mention the number of participants whose data are shown in the R code.


- SAVE_PATH_FILE_CLIENTS - Static variable in class model.Restaurant
-
The constant SAVE_PATH_FILE_CLIENTS.
- SAVE_PATH_FILE_EMPLOYEES - Static variable in class model.Restaurant
-
The constant SAVE_PATH_FILE_EMPLOYEES.
- SAVE_PATH_FILE_INGREDIENTS - Static variable in class model.Restaurant
-
The constant SAVE_PATH_FILE_INGREDIENTS.
- SAVE_PATH_FILE_ORDERS - Static variable in class model.Restaurant
-
The constant SAVE_PATH_FILE_ORDERS.
- SAVE_PATH_FILE_PRODUCTS - Static variable in class model.Restaurant
-
The constant SAVE_PATH_FILE_PRODUCTS.
- SAVE_PATH_FILE_TYPES - Static variable in class model.Restaurant
-
The constant SAVE_PATH_FILE_TYPES.
- SAVE_PATH_FILE_USERS - Static variable in class model.Restaurant
-
The constant SAVE_PATH_FILE_USERS.
- saveDataClients() - Method in class model.Restaurant
-
Save data clients.
- saveDataEmployees() - Method in class model.Restaurant
-
Save data employees.
- saveDataOrder() - Method in class model.Restaurant
-
Save data order.
- saveDataProduct() - Method in class model.Restaurant
-
Save data product.
- saveDataUpdated(MouseEvent) - Method in class ui.MasterGUI
-
- saveDataUsers() - Method in class model.Restaurant
-
Save data users.
- saveIngredients() - Method in class model.Restaurant
-
Save ingredients.
- saveTypes() - Method in class model.Restaurant
-
Save types.
- searchClient(ActionEvent) - Method in class ui.MasterGUI
-
- setAddress(String) - Method in class model.Client
-
- setAmountOfOrders(ArrayList<Order>) - Method in class model.Employee
-
- setAmountOfRequest(int) - Method in class model.Product
-
- setAuxPrice(String) - Method in class model.Product
-
- setAvailable(boolean) - Method in class model.Ingredient
-
- setAvailable(boolean) - Method in class model.Order
-
- setAvailable(boolean) - Method in class model.Product
-
- setAvailableT(boolean) - Method in class model.TypeProduct
-
- setClientRequest(Client) - Method in class model.Order
-
- setClientSearchedIndex(int) - Method in class model.Restaurant
-
Sets client searched index.
- setCode(String) - Method in class model.Order
-
- setCreatorU(User) - Method in class model.Ingredient
-
- setCreatorU(User) - Method in class model.Order
-
- setCreatorU(User) - Method in class model.Product
-
- setCreatorUser(User) - Method in class model.TypeProduct
-
- setCurrentUser(User) - Method in class model.Person
-
- setCurrentUser(User) - Method in class model.Restaurant
-
Sets current user.
- setDate(Date) - Method in class model.Order
-
- setEmployee(Employee) - Method in class model.Order
-
- setFeedback(String) - Method in class model.Order
-
- setHabilitate(boolean) - Method in class model.Person
-
- setIdentification(String) - Method in class model.Person
-
- setIngredients(ArrayList<Ingredient>) - Method in class model.Product
-
- setIsAvailable(String) - Method in class model.Ingredient
-
- setIsAvailableP(String) - Method in class model.Product
-
- setIsAvalibleT(String) - Method in class model.TypeProduct
-
- setLastName(String) - Method in class model.Person
-
- setLastU(User) - Method in class model.Ingredient
-
- setLastU(User) - Method in class model.Order
-
- setLastUser(User) - Method in class model.Person
-
- setLastUser(User) - Method in class model.Product
-
- setLastUser(User) - Method in class model.Restaurant
-
Sets last user.
- setLastUser(User) - Method in class model.TypeProduct
-
- setName(String) - Method in class model.Person
-
- setName(String) - Method in class model.TypeProduct
-
- setNameI(String) - Method in class model.Ingredient
-
- setNameP(String) - Method in class model.Product
-
- setOrderAddress(String) - Method in class model.Order
-
- setPassword(String) - Method in class model.User
-
- setPrice(int) - Method in class model.Order
-
- setPrice(int) - Method in class model.Product
-
- setPrice(String) - Method in class model.Product
-
- setProductsList(ArrayList<Product>) - Method in class model.Order
-
- setSize(String) - Method in class model.Product
-
- setStatus(Status) - Method in class model.Order
-
- setTabClients(ActionEvent) - Method in class ui.MasterGUI
-
- setTabEmployee(ActionEvent) - Method in class ui.MasterGUI
-
- setTabIngredients(ActionEvent) - Method in class ui.MasterGUI
-
- setTabOrders(ActionEvent) - Method in class ui.MasterGUI
-
- setTabProduct(ActionEvent) - Method in class ui.MasterGUI
-
- setTabType(ActionEvent) - Method in class ui.MasterGUI
-
- setTabUsers(ActionEvent) - Method in class ui.MasterGUI
-
- setTelephone(String) - Method in class model.Client
-
- setType(TypeProduct) - Method in class model.Product
-
- setType(String) - Method in class model.Product
-
- setUserName(String) - Method in class model.User
-
- showIngredientsOfProducts(ActionEvent) - Method in class ui.MasterGUI
-
- signUp(ActionEvent) - Method in class ui.MasterGUI
-
Sign up.
- sortEmployees() - Method in class model.Restaurant
-
Sort employees.
- sortIngredients() - Method in class ui.MasterGUI
-
- sortProduct(ActionEvent) - Method in class ui.MasterGUI
-
- start(Stage) - Method in class ui.Main
-
- Status - Enum in model
-


Better. Human. Simple. Confident. Cohesive. Thoughtful.
We have thoughtfully designed and strategically built Canopy to streamline and remove the tedious day-to-day busy work that plagues tax professionals. Tax professionals are human and they deserve simple, elegant and useful tools that allow them to be confident in the work they are doing.
Our mission is not only to help practitioners be more efficient, it’s also to build innovative tools that allow them to be the experts they are and elevate their own game.
We design Canopy to be intentionally better than our competitors by staying centered around our practioner’s goals and needs.
We accomplish this through constant discovery of our practitioner’s needs and iterating as goals will change year after year. To provide the best tools we need to design the best tools.
Canopy is designed and built by humans for humans and should always reflect that.
The application should always communicate with our practitioners in a friendly, respectful, accomodating, and professional manner. Canopy should never feel robotic and technical.
Our goal is to provide an efficient, delightful application that helps our practioners be better at their jobs, it’s not only about getting things done.
Making deliberate effort to constantly audit inefficiencies and make simple interface improvements as we go will delight our prationers and keep them engaged long term.
We design and build an application for a highly educated and confident user base. Canopy should not make them feel any different.
Like the tools of a skilled carpenter, our application should be simple, efficient, and always assume that our practioners know how to use it correctly. “Are you sure?” should never be in Canopy’s vocabulary.
Canopy is should feel like one cohesive application that is thoughtfully crafted to function as one integrated, wholistic experience.
While our application is built by many teams, those teams should always honor and remember that our practioners don’t experience just one feature at a time.
The work practitioners do can be very complex. As the creators and builders of application, we actively look for ways to bear the burden of their complexity to ensure innovative, simple tools.
Canopy should always be designed to alleviate complexity, it should never add complexity to the practioner’s journey. Our goal is to simplify their experience.


Contracts
View and sign your contracts with the SFA.
Previous contracts, payments and remittance data can be found on the Hub.
Contract action list
Related
View all versions of your contract(s).
View and sign your contracts with the SFA.
Previous contracts, payments and remittance data can be found on the Hub.
View all versions of your contract(s).


Okay, we know that after trying our salmon treats, you definitely have to bring home something to commemorate this life changing experience. Take a look at our merch!
Everything is $3.50
Images courtesy of Apple, Visa, and Paypal


{{ message }}
Requirements to obtain a voter ID:
Requirements to obtain a birth certificate:
Birth certificate by mail:
Birth certificate online:
Birth certificate in person:
Cost:


Toggle navigation
[SAND] That's No Tornado
Events
Social
New to Dry Top?
About the Guild
Guild Leadership
Guild Recruitment
Site Info
Site Feedback
Contribute Updates
[SAND] Birthday Donations


Let's play ping-pong!
Enter a number, and ping-pong will return a range of numbers from 1 to your number, with the following exceptions:
- Numbers divisible by 3 are replaced with "ping"
- Numbers divisible by 5 are replaced with "pong"
- Numbers divisible by 15 are replaced with "pingpong"


{% extends 'layouts/narrow.html' %} {% block title %}install :: {{ parent() }}{% endblock %} {% block content %}
Congratulations, B3 has been installed! You can now
log in
with username
{{ user.username }}
and password
{{ password }}
.
Note: This data won't be shown again, so note it down now!


-
coder, Reader, Traveller
-
@wileam
-
Life blog.
-
Powered by Wordpress.
-
Tech blog.
-
Powered by Hexo.
coder, Reader, Traveller
@wileam
Life blog.
Powered by Wordpress.
Tech blog.
Powered by Hexo.


Message browsing facility (MBF)
| MBF presents a list of message headers that correspond to a selected area of interest and a set of advisors. This list is sorted according to an aggregated rating gained from a set of advisors. Confidence is a calculated value that shows how much a user should trust an aggregated rating. | |
By clicking on a message header a user will be presented a message body. On this page user will also see a tree of replies and two buttons: Rate message and Rate advisor. Clicking on any of these buttons will take a user to a Rate facility. |
|


7 TIPS TO MAKE YOUR NOTES MORE UNIQUE THAN OTHERS
AHEM-AHEM...ATTENTION
You must have always heard that learning is productive. But let us tell you, notes are equally profitable as well. To make your understanding effective, you need to have effective notes as well. So, why not make your notes more unique and well-organized than others so that whenever you open them again, you get impressed by yourself all over again. Let us have a quick glance at the ways through which you can make your notes look more pretty and unique.
1. AVOID FILLERS
Do not write unnecessary things. You do want to write extra and extra.  Keep the content short and crisp. By short, we do not mean that you stop writing even the main points. So, make sure that you write all those points which will help you to understand the content in the shortest way possible.
2. RECORD YOUR CONVERSATION
The reasonable way to complete your notes is to record the conversation that occurred during the classroom learning process. After that, refine it after the classroom session. Cut the unnecessary part and make only those points well-organized which are super-important and pass the criteria of need-to-know basis.
3. NOTE SHEET
There are some points which need some additional emphasis. For instance, while reading modern history, you need to emphasize the movements along with their year. So, such points require extra attention. You can give a shout out in such points by highlighting them either through highlighter or writing those points with a varied ink.
4. EXTRA ATTENTION, EXTRA SHOUTOUT
There are some points which need some additional emphasis. For instance, while reading modern history, you need to emphasize the movements along with their year. So, such points require extra attention. You can give a shout out in such points by highlighting them either through highlighter or writing those points with a varied ink.
5. OODLE-DOODLE
An elegant heading makes the topics nicer. Sometimes doodling with the topics makes things more interesting. Do not forget to bold the headings as the bold part gets imprinted into the mind very quickly. Some doodles in the topic retain the interest in the chapter as well.
6. STICKY IS SERIOUS
Sometimes, you forget to highlight the points or get to know some extra information about the topic sometime later. In that case, sticky notes save you the way. Easy to remove and stick to extra serious points, the sticky notes are crucial to point savers for learners like you.
7. TABLE IN THE FRONT
A table of content makes the notes look more professional. How many of the students actually make this? Well, not much. This is what makes it look different. A proper table of content helps you to know where to reach directly. It creates the surface gist of the chapter and helps the notes to look like a personal book, written in your own words, and at your convenience.
Found the points interesting?
Why not give it a try?
And if you are worried about what to write in the notes, then do not be. We are here to help you.
Connect here to take off to the notes page directly: (https://notespickup.com/notes.php)
Leave a Suggestion


Симуляция формирования галактики
by GenrichMatushka3Formation of a single massive galaxy through time in the TNG50 cosmic simulation
The formation of a single massive galaxy through time, from early cosmic epochs until the present day, in the TNG50 cosmic simulation. The main panel shows the …www.youtube.com


GE exists to bring real progress and possibility to every corner of the planet.
Total revenue for GE in 2018 was US$ 121 billion (2018).
617-443-3000


Welcome to the Dashboard.
Hit "Deploy to Displays" to deploy this app to a display group and see it in action.
Once this app is displayed, it will never disappear off the screen.
tick() has fired 0 times.


{# Context Variables #} {# section: ContentSection #} {# block: ContentBlock #} {% with section=block.section %} {% if section %} {% include 'dt_content/snippets/breadcrumbs/section.html' %}


Inspiration is subjective, as different people will find different things to be inspiring. However, Christians can unite around one inspirational source—God himself.
God is the basis for all of our inspiration because He is the basis for everything good and everything worth imitating.
Here, are quotes from a variety of influential Christians that inspire us and point us back to Christ. Enjoy these many different thoughts on the Christian life.
{% for i in inst %}
- {{i.text}}
{% endfor %}
{% include "home/pagination.html" with page=inst %}


[§236D-10] Administration; rules. The department shall adopt such rules under chapter 91 as may be necessary to carry into effect this chapter, including rules relating to the return for taxes due under this chapter. [L 1983, c 217, pt of §1]


Thicc mario hub is a meme server which is active more than ever!
Many eincredible things like haha weed and alot more
A friendly server. Really cool features and many things to do.


{% capture included %}{% include _main/about.md %}{% endcapture %}{{included | markdownify}}
{% include _main/news.html %}
{% capture included %}{% include _main/research/research.md %}{% endcapture %}{{included | markdownify}}
{% capture included %}{% include _main/industry.md %}{% endcapture %}{{included | markdownify}}
{% capture included %}{% include _main/contact.md %}{% endcapture %}{{included | markdownify}}


Distribution
jMock 2
Stable: 2.6.0 (Java 6)
Binary JARs
(includes the source to let IDEs provide context-sensitive help)
Javadocs
jMock 1: Java 1.3 and above.
Stable: 1.2.0
Binary JARs
(includes the source to let IDEs provide context-sensitive help)
Javadocs
To use the jMock/CGLIB extension you also need
CGLIB 2.1
.


Class: ActionDispatch::SystemTesting::Server
Do not use. This class is for internal use only.
| Relationships & Source Files | |
| Inherits: | Object |
| Defined in: | actionpack/lib/action_dispatch/system_testing/server.rb |
Class Attribute Summary
Instance Method Summary
- #run
- #set_port private
- #set_server private
- #setup private
Class Attribute Details
.silence_puma (rw)
[ GitHub ]# File 'actionpack/lib/action_dispatch/system_testing/server.rb', line 7
attr_accessor :silence_puma
Instance Method Details
#run
[ GitHub ]# File 'actionpack/lib/action_dispatch/system_testing/server.rb', line 12
def run setup end
#set_port (private)
[ GitHub ]# File 'actionpack/lib/action_dispatch/system_testing/server.rb', line 26
def set_port Capybara.always_include_port = true end
#set_server (private)
[ GitHub ]# File 'actionpack/lib/action_dispatch/system_testing/server.rb', line 22
def set_server Capybara.server = :puma, { Silent: self.class.silence_puma } if Capybara.server == Capybara.servers[:default] end
#setup (private)
[ GitHub ]# File 'actionpack/lib/action_dispatch/system_testing/server.rb', line 17
def setup set_server set_port end


The Green Mile (6/10)
Writer-director Frank Darabont has obviously got a thing about inspirational period prison dramas based on Stephen King stories. With The Shawshank Redemption, he made a film which, although not a great commercial success on its original release, has since had a strange cultural impact, making it onto many moviegoers' lists of all-time favourites. With The Green Mile, Darabont has taken a superficially similar King story and tried to tap into the same popular appetite for uplifting tales of decent human beings rising above brutality and injustice, but I think The Green Mile will disappoint many admirers of Shawshank.
Tom Hanks stars as a death row prison guard who takes delivery of an unusual new inmate to await execution - a gentle and slow-witted black giant (played by Michael Clarke Duncan) convicted of the murder of two young white girls. The prison regime, with its mundane distractions filling time between the horrifying electrocutions, is nicely developed and impeccably crafted. Then the relationship between the guard and his new charge takes a mystical turn, at which point the film basically falls apart, and none of the top-drawer production design, acting and photography on display can save it.
Apart from Kubrick's The Shining, which King hated, I've always thought that the films based on King's non-spooky stories, such as Shawshank and Stand By Me, have worked better than those inspired by his supernatural tales. But with The Green Mile, we get an ill-judged mixture of the magical and the earthly. First, we're asked to accept that rather than sitting in a multiplex surrounded by popcorn-munching filmgoers, we are in a prison in 1930s Louisiana. Fine. I'll go along with that. That's what I'm here for.  Give me a break. In fantasy films, the impossible thing we're meant to believe in for a couple of hours must be introduced, or at least alluded to, from the start so we have a chance to get used to the idea and give ourselves over to it. Introducing unexpected miraculous elements into an established earthly story is to trample on well-established conventions. Imagine an episode of NYPD Blue in which Andy Sipowitz is abducted by aliens. Doesn't work, does it? Even if the mystical thrust of the story had been established from the start, our credulity would still have been severely tested by the sheer niceness of the prison staff - apart from one enjoyably sadistic and slimy guard (played by Doug Hutchison) they are probably the most thoughtful and decent bunch every to fry people for living.
Although beautifully made, The Green Mile is let down by its bolted-on mystical elements and its crude religious allegory. It also suffers from the sort of sentimentality that Steven Spielberg is criticised for, often unfairly. After a bum-numbing three hours plus, I felt I'd served my time and was glad to be released.
--
Gary Jones
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


subtitle: 'Types of shapes' --- ## Types of shapes In the previous tutorial (4-shapes) we have shown the basics of shape creation, styling and modifications. Here, we simply showcase the different provided with jsGraph with their specificities. Let us consider the following graph as a basic: ```javascript var g = new Graph('example-1'); // Creates a new graph g.resize(400, 300); // Resizes the graph var s = g .newSerie('employment_nb') .setData([ 1900, 1555, 1910, 1783, 1920, 1872, 1930, 1943, 1941, 1992, 1948, 2378, 1949, 2339, 1950, 2309, 1951, 2437, 1953, 2455, 1954, 2482, 1955, 2533, 1956, 2606, 1957, 2666, 1958, 2644, 1959, 2644, 1960, 2717, 1961, 2644, 1962, 2954, 1963, 2999, 1964, 3046, 1965, 3025, 1966, 3014, 1967, 3030, 1968, 3048, 1969, 3098, 1970, 3143, 1971, 3199, 1972, 3243, 1973, 3277, 1974, 3273, 1975, 3108, 1976, 3019, 1977, 3032, 1978, 3062, 1979, 3095, 1980, 3166, 1981, 3240, 1982, 3256, 1983, 3257, 1984, 3288, 1985, 3354, 1986, 3430, 1987, 3515, 1988, 3607, 1989, 3704, 1990, 3821, 1991, 4136, 1992, 4069, 1993, 4025, 1994, 3999, 1995, 3996, 1996, 3994, 1997, 3991, 1998, 4044, 1999, 4075, 2000, 4116, 2001, 4183, 2002, 4213, 2003, 4198, 2004, 4210, 2005, 4241, 2006, 4328, 2007, 4440, 2008, 4548, 2009, 4588, 2010, 4593, 2011, 4705, 2012, 4776, 2013, 4837, 2014, 4918 ]) .autoAxis() .setLineColor('purple') .setLineWidth(2); g.setTitle('Number of employed people in Switzerland (yearly average)'); g.getXAxis() .setLabel('Year') .gridsOff(); g.getYAxis() .setLabel('Number of people (in thousands)') .secondaryGridOff(); g.draw(); ```
## Lines The basic line with the type `line` and only two positions (the start and the end of the line). ``` var line = graph.newShape( 'line', { selectable: true, handles: true, resizable: true, movable: true, position: [ { x: 1950, y: 3000 }, { x: 1960, y: "50px" } ], labels: [ { text: "Shape label", color: "braun", size: 2, angle: 10, baseline: "hanging", anchor: "end", position: { x: 1950, y: 3200 } } ] }); line.draw(); ``` ## Rectangles Rectangles with the type `rect` and only two positions (two opposite corners). ## Arrows Arrows with the type `arrow` and only two positions (the start and the end position). ## Label The label shape (type `label`) displays a label without particular shape. It can be used as simply as: ```javascript graph .newShape('label', { labels: [ { text: 'Shape label', color: 'ForestGreen', size: 12, angle: 20, baseline: 'hanging', anchor: 'end', position: { x: 1950, y: 3200 } } ] }) .draw(); ``` ````