txt
stringlengths
93
37.3k
## dist_zef-FCO-SeqSplitter.md [![Build Status](https://travis-ci.org/FCO/SeqSplitter.svg?branch=master)](https://travis-ci.org/FCO/SeqSplitter) # NAME SeqSplitter - Creates `.pull-while`, `.pull-until`, `.pull`, `.skip-while`, `.skip-until` and `.skip` on `Seq` and `Any`. # SYNOPSIS ``` use SeqSplitter; say ^10 .pull-while(* < 2) .skip-while(* < 5) .pull-until(7) .skip-until(8) .pull .skip(3) ; ``` Will print: ``` (0 1 5 6 8) ``` # DESCRIPTION SeqSplitter is a "better solution" for `.toggle` it was being discussed here <https://github.com/rakudo/rakudo/issues/2089> # AUTHOR Fernando Correa de Oliveira [fernandocorrea@gmail.com](mailto:fernandocorrea@gmail.com) # COPYRIGHT AND LICENSE Copyright 2018 Fernando Correa de Oliveira This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-stuart-little-RakuRename.md # RakuRename A file-rename tool inspired by Perl's [File::Rename](https://metacpan.org/dist/File-Rename/view/rename.PL). ## Installation If you have [zef](https://github.com/ugexe/zef), there are a number of options: * just run `zef install RakuRename`; * or clone this repo and issue `zef install <path-to-cloned-repo>`; * as yet another variation, after cloning it, `cd` into the repo and `zef install .` (note the dot at the end). Additionally, since all there is here, really, is the executable `bin/rrnm`, you can just download that and use it. ## Usage The distribution only provides the `rrnm` binary. In general: * Run `rrnm --help` to see information on the possible command-line switches / options. * The first positional argument should be a substitution or transliteration operator, as documented under `Raku`'s [substitution-operators](https://docs.raku.org/language/operators#Substitution_operators) doc section. * The positional arguments following that should be the files you want to move / copy / whatever (see the examples below). * The regex syntax is whatever `Raku` [will recognize](https://docs.raku.org/language/regexes). ## Examples Some usage examples follow, all of which are to be run in a terminal where you have access to `zef`-installed binaries. ``` rrnm 's/^a/b/' <DIRECTORY>/a* ``` will rename every file / directory of the form `<DIRECTORY>/a<BLAH>` to `<DIRECTORY>/b<BLAH>`. On the other hand, ``` rrnm -c='cp' 's/^a/b/' <DIRECTORY>/a* ``` will take every file of the form `<DIRECTORY>/a<BLAH>` and *copy* it to `<DIRECTORY>/b<BLAH>`. It will complain about not being able to copy directories among those (because the [cp command](https://linux.die.net/man/1/cp) behaves this way), but you can fix that with ``` rrnm -c='cp -r' 's/^a/b/' <DIRECTORY>/a* ``` You can even do the following in a `git` repo, to effect a regex-based [git-mv](https://git-scm.com/docs/git-mv): ``` rrnm -c='git mv' 's/^(\d)/0$0/' [0-9]* ``` or equivalently, using [lookahead assertions](https://docs.raku.org/language/regexes#Lookahead_assertions), ``` rrnm -c='git mv' 's/^<?before \d>/0/' [0-9]* ``` That will perform a `git mv` on every file whose name starts with a digit, prepending a `0` (if you wanted to do this for some reason). The `--dry` option just *shows* you the command that would be run. So in a git repo that contains files `1.txt` and `2.txt` (and nothing else starting with a digit), ``` rrnm -c='git mv' 's/^(\d)/0$0/' [0-9]* --dry ``` would simply show you ``` git mv 1.txt ./01.txt git mv 2.txt ./02.txt ``` in the terminal. I use this all the time: first run what you *think* will work with `--dry`, then recall the last command and remove the `--dry` option.
## keys.md keys Combined from primary sources listed below. # [In List](#___top "go to top of document")[§](#(List)_routine_keys "direct link") See primary documentation [in context](/type/List#routine_keys) for **routine keys**. ```raku sub keys($list --> Seq:D) method keys(List:D: --> Seq:D) ``` Returns a sequence of indexes into the list (e.g., `0...(@list.elems-1)`). ```raku say (1,2,3,4).keys; # OUTPUT: «(0 1 2 3)␤» ``` # [In role Baggy](#___top "go to top of document")[§](#(role_Baggy)_method_keys "direct link") See primary documentation [in context](/type/Baggy#method_keys) for **method keys**. ```raku method keys(Baggy:D: --> Seq:D) ``` Returns a [`Seq`](/type/Seq) of all keys in the `Baggy` object without taking their individual weights into account as opposed to [kxxv](#method_kxxv). ```raku my $breakfast = bag <eggs spam spam spam>; say $breakfast.keys.sort; # OUTPUT: «(eggs spam)␤» my $n = ("a" => 5, "b" => 2).BagHash; say $n.keys.sort; # OUTPUT: «(a b)␤» ``` # [In Capture](#___top "go to top of document")[§](#(Capture)_method_keys "direct link") See primary documentation [in context](/type/Capture#method_keys) for **method keys**. ```raku multi method keys(Capture:D: --> Seq:D) ``` Returns a [`Seq`](/type/Seq) containing all positional keys followed by all named keys. For positional arguments the keys are the respective arguments ordinal position starting from zero. ```raku my $capture = \(2, 3, 5, apples => (red => 2)); say $capture.keys; # OUTPUT: «(0 1 2 apples)␤» ``` # [In Map](#___top "go to top of document")[§](#(Map)_method_keys "direct link") See primary documentation [in context](/type/Map#method_keys) for **method keys**. ```raku method keys(Map:D: --> Seq:D) ``` Returns a [`Seq`](/type/Seq) of all keys in the Map. ```raku my $m = Map.new('a' => (2, 3), 'b' => 17); say $m.keys; # OUTPUT: «(a b)␤» ``` # [In Pair](#___top "go to top of document")[§](#(Pair)_method_keys "direct link") See primary documentation [in context](/type/Pair#method_keys) for **method keys**. ```raku multi method keys(Pair:D: --> List:D) ``` Returns a [`List`](/type/List) containing the [key](/type/Pair#method_key) of the invocant. ```raku say (Raku => "d").keys; # OUTPUT: «(Raku)␤» ``` # [In Any](#___top "go to top of document")[§](#(Any)_method_keys "direct link") See primary documentation [in context](/type/Any#method_keys) for **method keys**. ```raku multi method keys(Any:U: --> List) multi method keys(Any:D: --> List) ``` For defined `Any` returns its [keys](/routine/keys) after calling `list` on it, otherwise calls `list` and returns it. ```raku my $setty = Set(<Þor Oðin Freija>); say $setty.keys; # OUTPUT: «(Þor Oðin Freija)␤» ``` See also [`List.keys`](/type/List#routine_keys). Trying the same on a class will return an empty list, since most of them don't really have keys. # [In role Setty](#___top "go to top of document")[§](#(role_Setty)_method_keys "direct link") See primary documentation [in context](/type/Setty#method_keys) for **method keys**. ```raku multi method keys(Setty:D: --> Seq:D) ``` Returns a [`Seq`](/type/Seq) of all elements of the set. ```raku my $s = Set.new(1, 2, 3); say $s.keys; # OUTPUT: «(3 1 2)␤» ```
## dist_zef-thundergnat-List-Allmax.md [![Actions Status](https://github.com/thundergnat/List-Allmax/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/List-Allmax/actions) # NAME List::Allmax - Find all of the maximum or minimum elements of a list. # SYNOPSIS ``` use List::Allmax; say (^20).roll(50).&all-max; # values say (^20).roll(50).&all-min: :k; # keys say [1,2,3,4,5,5,4,3,2,1,2,2,5,4,4].classify({$_}).sort.List.&all-max( :by(+*.value) ); # [2 => [2,2,2,2], 4 => [4,4,4,4]] ``` # DESCRIPTION Raku provides `max` and `min` routines to find the maximum or minimum elements of a list. If there is more than one value that evaluates to the maximum, (minimum) only the first is reported, no matter how many there may be. This module provides a remedy for that. Provides the routines `all-max()` and `all-min()` that return *all* of the elements that evaluate to maximum or minimum value. Similar to the built-ins, you may request either a list of values or a list of indicies (keys) where those values are located. If you want to compare based on something other than the values of the individual elements, supply a named `:by()` Callable block to be used as an evaluator. Defaults to `{$_}` (self). Note: Only operates on Positional objects. If want to use it on a Hash or some other Associative type, coerce to a Listy type object first. # AUTHOR Stephen Schulze (aka thundergnat [thundergnat@comcast.net](mailto:thundergnat@comcast.net)) # COPYRIGHT AND LICENSE Copyright 2023 thundergnat This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-nige123-SHAI.md # shai (shell ai) LLM-powered utility for requesting and executing shell commands. Make a request using natural language and **shai** prompts an LLM for a shell command to fulfil your request. It's OK to feel shy about executing the suggested command. The command will not execute without your confirmation. Please be careful when confirming. ## Usage ``` shell> shai ask for what you want -- in natural language shell> shai what processes are using the most memory shell> shai how much disk space is left shell> shai what programs have ports open shell> shai remove .tmp files larger than 100 meg shell> shai config -- change LLM settings shell> shai help -- show this help ``` ## Install **shai** is a Raku command-line utility. 1. Install Raku <https://raku.org/downloads/> 2. Install shai ``` shell> zef install SHAI ``` 3. Set up your LLM with LLM::DWIM ``` shell> rakudoc LLM::DWIM ```
## permutations.md permutations Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_permutations "direct link") See primary documentation [in context](/type/Any#method_permutations) for **method permutations**. ```raku method permutations(|c) ``` Coerces the invocant to a `list` by applying its [`.list`](/routine/list) method and uses [`List.permutations`](/type/List#routine_permutations) on it. ```raku say <a b c>.permutations; # OUTPUT: «((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))␤» say set(1,2).permutations; # OUTPUT: «((2 => True 1 => True) (1 => True 2 => True))␤» ``` Permutations of data structures with a single or no element will return a list containing an empty list or a list with a single element. ```raku say 1.permutations; # OUTPUT: «((1))␤» ``` # [In List](#___top "go to top of document")[§](#(List)_routine_permutations "direct link") See primary documentation [in context](/type/List#routine_permutations) for **routine permutations**. ```raku multi permutations(Int() $from --> Seq:D) multi permutations(Iterable $from --> Seq:D) multi method permutations(List:D: --> Seq:D) ``` Returns all possible permutations of a list as a [`Seq`](/type/Seq) of lists: ```raku .say for <a b c>.permutations; # OUTPUT: # (a b c) # (a c b) # (b a c) # (b c a) # (c a b) # (c b a) ``` `permutations` treats all elements as unique, thus `(1, 1, 2).permutations` returns a list of 6 elements, even though there are only three distinct permutations, due to first two elements being the same. The subroutine form behaves the same as the method form, computing permutations from its first argument `$from`. If `$from` is not an [`Iterable`](/type/Iterable), coerces `$from` to an [`Int`](/type/Int) and picks from a [`Range`](/type/Range) constructed with `0..^$from`: ```raku .say for permutations 3; # OUTPUT: # (0 1 2) # (0 2 1) # (1 0 2) # (1 2 0) # (2 0 1) # (2 1 0) ```
## dist_cpan-MELEZHIK-Sparrowdo-Archive.md # SYNOPSIS Extract archived files with the help of various archivers programs. Archive formats supported: ``` +-----------+---------------------------+ | extension | internal archive program | +-----------+---------------------------+ | *.zip | unzip | | *.tar | tar | | *.tar.gz | tar | | *.gem | gem | +-----------+---------------------------+ ``` # Build Status [![Build Status](https://travis-ci.org/melezhik/sparrowdo-archive.svg?branch=master)](https://travis-ci.org/melezhik/sparrowdo-archive) # INSTALL ``` $ zef install Sparrowdo::Archive ``` # USAGE Through cli ``` s6 --module-run Archive@source=test.tar.gz,target=/tmp/foo2,verbose=1 ``` Through Sparrow6 DSL ``` module-run 'Archive', %( source => '/tmp/foo/test.tar.gz', target => '/tmp/foo2', verbose => 1, ); ``` # Parameters ## source A local file path to archived file. Obligatory. No default. ## target A local file path where to store extracted archive data. No default value. Obligatory. ## user A user which run a archive program and thus to which user extracted files will belong to. Optional. No default value. ## no-install-deps Don't install dependencies ( tar/gzip package, etc ). Optional. ## verbose Try to run archive extractor program in verbose mode. Default value is `0` ( no verbose ). Optional. # Author [Alexey Melezhik](melezhik@gmail.com)
## dist_cpan-ALLSOPP-Operator-dB.md # Operator::dB Operator to support decibel (dB) arithmetic. ``` use Operator::dB; put 100 + 3dB; # 199.52623149688796 put 100 - 3dB; # 50.11872336272723 put 10dB + 20dB; # 20.413927dB ``` ## Description The interface tries to be intuitive while avoiding ambiguity. For example, the following makes sense (adding 3dB is approximately equivalent to doubling). ``` 10 + 3dB # 19.952623149688794 ``` But the following doesn't make sense. It could represent either `13dB` or `10.8dB` (i.e. `3dB + 10dB`). ``` 3dB + 10 # DOESN'T WORK! ``` All supported operations are discussed in the following subsections. ### Addition and subtraction on numbers Adding or subtracting decibel values to and from numbers (of `Numeric` type) scales the number by the corresponding decibel gain: ``` put 100 + 3dB; # 199.52623149688796 put 100 - 3dB; # 50.11872336272723 ``` ### Addition and subtraction on decibels Decibels can be added to, or subtracted from, each other. This type of operation returns an `Operator::dB::Decibel` wrapper object: ``` my $foo = 3dB + 2dB - 1dB; # Operator::dB::Decibel.new(x => 10, y => 0.365...) ``` You can get the decibel value itself with `.dB`: ``` $foo.dB; # 3.6571819272302735 ``` Or by stringification: ``` "The gain is: $foo"; # The gain is: 3.657182dB ``` Or by defining your own format with `.fmt`: ``` $foo.fmt("%.1f dB(A)"); # 3.7 dB(A) ``` ## Caveats This package exports overloads to built-in operators, which is potentially reckless. But the operator signatures all contain at least one `Operator::dB::Decibel` object (which is not built-in), so it *should* be fine! The `Num` method is not implemented on the wrapper class, so many built-in numerical operations don't work, e.g. `1dB * 1`. This is a necessary limitation because decibel arithmetic is only semantically valid for addition and subtraction AFAIK. ## See also * [Operators in Raku](https://docs.raku.org/language/operators) * [Creating operators in Raku](https://docs.raku.org/language/optut)
## dist_cpan-HANENKAMP-Amazon-DynamoDB.md # NAME Amazon::DynamoDB - Low-level access to the DynamoDB API # SYNOPSIS ``` use Amazon::DynamoDB; my $ddb = Amazon::DynamoDB.new await $ddb.CreateTable( AttributeDefinitions => [ { AttributeName => 'ForumName', AttributeType => 'S', }, { AttributeName => 'Subject', AttributeType => 'S', }, { AttributeName => 'LastPostDateTime', AttributeType => 'S', }, ], TableName => 'Thread', KeySchema => [ { AttributeName => 'ForumName', KeyType => 'HASH', }, { AttributeName => 'Subject', KeyType => 'RANGE', }, ], LocalSecondaryIndexes => [ { IndexName => 'LastPostIndex', KeySchema => [ { AttributeName => 'ForumName', KeyType => 'HASH', }, { AttributeName => 'LastPostDateTime', KeyType => 'RANGE', } ], Projection => { ProjectionType => 'KEYS_ONLY' }, }, ], ProvisionedThroughput => { ReadCapacityUnits => 5, WriteCapacityUnits => 5, }, ); $ddb.PutItem( TableName => "Thread", Item => { LastPostDateTime => { S => "201303190422" }, Tags => { SS => ["Update","Multiple Items","HelpMe"] }, ForumName => { S => "Amazon DynamoDB" }, Message => { S => "I want to update multiple items in a single call. What's the best way to do that?" }, Subject => { S => "How do I update multiple items?" }, LastPostedBy => { S => "fred@example.com" } }, ConditionExpression => "ForumName <> :f and Subject <> :s", ExpressionAttributeValues => { ':f' => {S => "Amazon DynamoDB"}, ':s' => {S => "How do I update multiple items?"} } ); my $res = await $ddb.GetItem( TableName => "Thread", Key => { ForumName => { S => "Amazon DynamoDB" }, Subject => { S => "How do I update multiple items?" } }, ProjectionExpression => "LastPostDateTime, Message, Tags", ConsistentRead => True, ReturnConsumedCapacity => "TOTAL" ); say "Message: $res<Item><Message><S>"; ``` # DESCRIPTION This module provides an asynchronous, low-level API that interacts directly with DynamoDB. This is a low-level implementation that sticks as close as possible to the API described by AWS, keeping the names of actions and parameter names as-is (i.e., not using nice kabob-case most Perl 6 modules use, but the PascalCase that most AWS APIs present natively). This has the benefit of allowing you to use the AWS documentation directly. The API is currently very primitive and may change to provide better type-checking in the future. # DIAGNOSTICS The following exceptions may be thrown by this module: ## X::Amazon::DynamoDB::APIException This encapsulates the errors returned from the API itself. The name of the error can be checked at the `type` method and the message in `message`. It has the following accessors: * request-id The request id returned with the error. * raw-type The \_\_type returned with the error (a combination of the API version and error type). * type The error type pulled from the raw-type. * message The detailed message sent with the error. This is the exception you will most likely want to capture. For this reason, a special helper named `of-type` is provided to aid in easy matching. For example, if you want to perform a `CreateTable` operation, but ignore any "ResourceInUseException" indicating that the table already exists, it is recommended that you do something like this: ``` my $ddb = Amazon::DynamoDB.new; $ddb.CreateTable( ... ); CATCH { when X::Amazon::DynamoDB::APIException.of-type('ResourceInUseException') { # ignore } } ``` ## X::Amazon::DynamoDB::CommunicationError This is a generic error, generally caused by HTTP connection problems, but might be caused by especially fatal errors in the API. The message is simply "Communication Error", but provides two attributes for more information: * request This is the `HTTP::Request` that was attempted. * response This is the `HTTP::Response` that was received (which might be a fake response generated by the user agent if no response was received. ## X::Amazon::DynamoDB::CRCError Every response from DynamoDB includes a CRC32 checksum. This module verifies that checksum on every request. If the checksum given by Amazon does not match the checksum calculated, this error will be thrown. It provides these attributes: * got-crc32 This is the integer CRC32 we calculated. * expected-crc32 This is the integer CRC32 Amazon sent. # ASYNC API The API for this is asynchronous. Mostly, this means that the API methods return a <Promise> that will be kept with a <Hash> containing the results. If you want a purely syncrhonous API, you just need to place an `await` before every call to the library. Under the hood, the implementation is currently implemented to use Cro::HTTP::Client if present. If not present, then [HTTP::UserAgent](http::UserAgent) is used instead, though all actions will run on separate threads from the calling thread. # METHODS ## method new ``` multi method new( AWS::Session :$session, AWS::Credentials :$credentials, Str :$scheme = 'https', Str :$domain = 'amazonaws.com', Str :$hostname, Int :$port, HTTP::UserAgent :$ua, ) returns Amazon::DynamoDB ``` All arguments to new are optional. The `$session` and `$credentials` will be constructed lazily if not given to `new` using default settings. By default, the `$port` and `$hostname` are unset. This means that no port will be specified (just the default port for the scheme will be used) and the `hostname` used till be constructed from the `$domain` and region defined in the session. See AWS::Session and AWS::Credentials for details on how to customize your settings. However, if you are familiar with how botocore/aws-cli and other tools configure themselves, this will be familiar. ## method session ``` method session() returns AWS::Session is rw ``` Getter/setter for the session used to configure AWS settings. ## method credentials ``` method credentials() returns AWS::Credentials is rw ``` Getter/setter for the credentails used to contact AWS. ## method scheme ``` method scheme() returns Str ``` Getter for the scheme. Defaults to "https". ## method domain ``` method domain() returns Str ``` Getter for the domain. Defaults to "amazonaws.com". ## method hostname ``` method hostname() returns Str ``` This returns the hostname that will be contacted with DynamoDB calls. It is either set by the `hostname` setting when calling `new` or constructed from the `domain` and configured region. ## method port ``` method port() returns Int ``` This returns the port number to use when contacting DynamoDB. This returns `Nil` if the default port is used (i.e., 80 when `scheme` is "http" or 443 when "https"). # API METHODS These are the methods implemented as part of the AWS API. Please see the AWS API documentation for more detail as to what each argument does and the structure of the return value. ## method BatchGetItem ``` method BatchGetItem( :%RequestItems!, Str :$ReturnConsumedCapacity, ) returns Promise ``` The BatchGetItem operation returns the attributes of one or more items from one or more tables. You identify requested items by primary key. See the [AWS BatchGetItem API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html). ## method BatchWriteItem ``` method BatchWriteItem( :%RequestItems! Str :$ReturnConsumedCapacity, Str :$ReturnItemCollectionMetrics, ) returns Promise ``` The BatchWriteItem operation puts or deletes multiple items in one or more tables. A single call to BatchWriteItem can write up to 16 MB of data, which can comprise as many as 25 put or delete requests. Individual items to be written can be as large as 400 KB. See the [AWS BatchWriteItem API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html). ## method DeleteItem ``` method DeleteItem( :%Key!, Str :$TableName!, Str :$ConditionalOperator, Str :$ConditionExpression, Str :$Expected, :%ExpressionAttributeNames, :%ExpressionAttributeValues, Str :$ReturnConsumedCapacity, Str :$ReturnItemCollectionMetrics, Str :$ReturnValues, ) returns Promise ``` Deletes a single item in a table by primary key. You can perform a conditional delete operation that deletes the item if it exists, or if it has an expected attribute value. See the [AWS DeleteItem API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html). ## method GetItem ``` method GetItem( :%Key!, Str :$TableName!, :@AttributesToGet, Bool :$ConsistentRead, :%ExpressionAttributeNames, Str :$ProjectionExpression, Str :$ReturnConsumedCapacity, ) returns Promise ``` The GetItem operation returns a set of attributes for the item with the given primary key. If there is no matching item, GetItem does not return any data and there will be no Item element in the response. See the [AWS GetItem API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html). ## method PutItem ``` method PutItem( :%Item!, Str :$TableName!, Str :$ConditionalOperator, Str :$ConditionExpression, :%Expected, :%ExressionAttributeNames, :%ExpressionAttributeValues, Str :$ReturnConsumedCapacity, Str :$ReturnItemCollectionMetrics, Str :$ReturnValues, ) returns Promise ``` Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values. You can return the item's attribute values in the same operation, using the ReturnValues parameter. See the [AWS PutItem API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html). ## method Query ``` method Query( Str :$TableName!, :@AttributesToGet, Str :$ConditionalOperator, Bool :$ConsistentRead, :%ExclusiveStartKey, :%ExpressionAttributeNames, :%ExpressionAttributeValues, Str :$FilterExpression, Str :$IndexName, Str :$KeyConditionExpression, :%KeyConditions, Int :$Limit, Str :$ProjectionExpression, :%QueryFilter, Str :$ReturnConsumedCapacity, Bool :$ScanIndexForward, Str :$Select, ) returns Promise ``` The Query operation finds items based on primary key values. You can query any table or secondary index that has a composite primary key (a partition key and a sort key). See the [AWS Query API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html). ## method Scan ``` method Scan( Str :$TableName!, :@AttributesToGet, Str :$ConditionalOperator, Bool :$ConsistentRead, :%ExclusiveStartKey, :%ExpressionAttributeNames, :%ExpressionAttributeValues, Str :$FilterExpression, Str :$IndexName, Int :$Limit, Str :$ProjectionExpression, :%QueryFilter, Str :$ReturnConsumedCapacity, :%ScanFilter, Int :$Segment, Str :$Select, Int :$TotalSegments, ) returns Promise ``` The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation. See the [AWS Scan API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html). ## method UpdateItem ``` method UpdateItem( :%Key!, Str :$TableName!, :%AttributeUpdates, Str :$ConditionalOperator, Str :$ConditionExpression, :%Expected, :%ExpressionAttributeNames, :%ExpressionAttributeValues, Str :$ReturnConsumedCapacity, Str :$ReturnItemCollectionMetrics, Str :$ReturnValues, Str :$UpdateExpression, ) returns Promise ``` Edits an existing item's attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update on an existing item (insert a new attribute name-value pair if it doesn't exist, or replace an existing name-value pair if it has certain expected attribute values). See the [AWS UpdateItem API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html). ## method CreateTable ``` method CreateTable( :@AttributeDefinitions!, Str :$TableName!, :@KeySchema!, :%ProvisionedThroughput!, :@GlobalSecondaryIndexes, :@LocalSecondaryIndexes, :%SSESpecification, :%StreamSpecification, ) returns Promise ``` The CreateTable operation adds a new table to your account. In an AWS account, table names must be unique within each region. That is, you can have two tables with same name if you create the tables in different regions. See the [AWS CreateTable API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_CreateTable.html). ## method DeleteTable ``` method DeleteTable( Str :$TableName, ) returns Promise ``` The DeleteTable operation deletes a table and all of its items. After a DeleteTable request, the specified table is in the DELETING state until DynamoDB completes the deletion. If the table is in the ACTIVE state, you can delete it. If a table is in CREATING or UPDATING states, then DynamoDB returns a ResourceInUseException. If the specified table does not exist, DynamoDB returns a ResourceNotFoundException. If table is already in the DELETING state, no error is returned. See the [AWS DeleteTable API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteTable.html). ## method DescribeTable ``` method DescribeTable( Str :$TableName!, ) returns Promise ``` Returns information about the table, including the current status of the table, when it was created, the primary key schema, and any indexes on the table. See the [AWS DescribeTable API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeTable.html). ## method DescribeTimeToLive ``` method DescribeTimeToLive( Str :$TableName!, ) returns Promise ``` Gives a description of the Time to Live (TTL) status on the specified table. See the [AWS DescribeTimeToLive API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeTimeToLive.html). ## method ListTables ``` method ListTables( Str :$ExclusiveStartTableName, Int :$Limit, ) returns Promise ``` Returns an array of table names associated with the current account and endpoint. The output from ListTables is paginated, with each page returning a maximum of 100 table names. See the [AWS ListTables API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ListTables.html). ## method UpdateTable ``` method UpdateTable( Str :$TableName!, :@AttributeDefinitions, :@GlobalSecondaryIndexUpdates, :%ProvisionedThroughput, :%StreamSpecification, ) returns Promise ``` Modifies the provisioned throughput settings, global secondary indexes, or DynamoDB Streams settings for a given table. See the [AWS UpdateTable API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateTable.html). ## method UpdateTimeToLive ``` method UpdateTimeToLive( Str :$TableName!, :%TableToLiveSpecification!, ) returns Promise ``` The UpdateTimeToLive method will enable or disable TTL for the specified table. A successful UpdateTimeToLive call returns the current TimeToLiveSpecification; it may take up to one hour for the change to fully process. Any additional UpdateTimeToLive calls for the same table during this one hour duration result in a ValidationException. See the [AWS UpdateTimeToLive API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateTimeToLive.html). ## method CreateGlobalTable ``` method CreateGlobalTable( Str :$GlobalTableName!, :@ReplicationGroup!, ) returns Promise ``` Creates a global table from an existing table. A global table creates a replication relationship between two or more DynamoDB tables with the same table name in the provided regions. See the [AWS CreateGlobalTable API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_CreateGlobalTable.html). ## method DescribeGlobalTable ``` method DescribeGlobalTable( Str :$GlobalTableName!, ) returns Promise ``` Returns information about the specified global table. See the [AWS DescribeGlobalTable API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeGlobalTable.html). ## method ListGlobalTables ``` method ListGlobalTables( Str :$ExclusiveStartGlobalTableName, Int :$Limit, Str :$RegionName, ) returns Promise ``` Lists all global tables that have a replica in the specified region. See the [AWS ListGlobalTables API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ListGlobalTables.html). ## method UpdateGlobalTable ``` method UpdateGlobalTable( Str :$GlobalTableName!, :@ReplicaUpdates!, ) returns Promise ``` Adds or removes replicas in the specified global table. The global table must already exist to be able to use this operation. Any replica to be added must be empty, must have the same name as the global table, must have the same key schema, and must have DynamoDB Streams enabled and must have same provisioned and maximum write capacity units. See the [AWS UpdateGlobalTable API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateGlobalTable.html). ## method ListTagsOfResource ``` method ListTagsOfResource( Str :$ResourceArn!, Str :$NextToken, ) returns Promise ``` List all tags on an Amazon DynamoDB resource. You can call ListTagsOfResource up to 10 times per second, per account. See the [AWS ListTagsOfResource API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ListTagsOfResource.html). ## method TagResource ``` method TagResource( Str :$ResourceArn!, :@Tags!, ) returns Promise ``` Associate a set of tags with an Amazon DynamoDB resource. You can then activate these user-defined tags so that they appear on the Billing and Cost Management console for cost allocation tracking. You can call TagResource up to 5 times per second, per account. See the [AWS TagResource API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TagResource.html). ## method UntagResource ``` method UntagResource( Str :$ResourceArn!, :@TagKeys!, ) returns Promise ``` Removes the association of tags from an Amazon DynamoDB resource. You can call UntagResource up to 5 times per second, per account. See the [AWS UntagResource API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UntagResource.html). ## method CreateBackup ``` method CreateBackup( Str :$BackupName!, Str :$TableName!, ) returns Promise ``` Creates a backup for an existing table. See the [AWS CreateBackup API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_CreateBackup.html). ## method DeleteBackup ``` method DeleteBackup( Str :$BackupArn!, ) returns Promise ``` Deletes an existing backup of a table. See the [AWS DeleteBackup API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteBackup.html). ## method DescribeBackup ``` method DescribeBackup( Str :$BackupArn!, ) returns Promise ``` Describes an existing backup of a table. See the [AWS DescribeBackup API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeBackup.html). ## method DescribeContinuousBackups ``` method DescribeContinuousBackups( Str :$TableName!, ) returns Promise ``` Checks the status of continuous backups and point in time recovery on the specified table. Continuous backups are ENABLED on all tables at table creation. If point in time recovery is enabled, PointInTimeRecoveryStatus will be set to ENABLED. See the [AWS DescribeContinuousBackups API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeContinuousBackups.html). ## method ListBackups ``` method ListBackups( Str :$ExclusiveStartBackupArn, Int :$Limit, Str :$TableName, Int :$TimeRangeLowerBound, Int :$TimeRangeUpperBound, ) returns Promise ``` List backups associated with an AWS account. To list backups for a given table, specify TableName. ListBackups returns a paginated list of results with at most 1MB worth of items in a page. You can also specify a limit for the maximum number of entries to be returned in a page. See the [AWS ListBackups API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ListBackups.html). ## method RestoreTableFromBackup ``` method RestoreTableFromBackup( Str :$BackupArn!, Str :$TargetTableName!, ) returns Promise ``` Creates a new table from an existing backup. Any number of users can execute up to 4 concurrent restores (any type of restore) in a given account. See the [AWS RestoreTableFromBackup API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_RestoreTableFromBackup.html). ## method DescribeLimits ``` method DescribeLimits() returns Promise ``` Returns the current provisioned-capacity limits for your AWS account in a region, both for the region as a whole and for any one DynamoDB table that you create there. See the [AWS DescribeLimits API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeLimits.html).
## dist_zef-lizmat-P5getgrnam.md [![Actions Status](https://github.com/lizmat/P5getgrnam/workflows/test/badge.svg)](https://github.com/lizmat/P5getgrnam/actions) # NAME Raku port of Perl's getgrnam() and associated built-ins # SYNOPSIS ``` use P5getgrnam; my @result = getgrnam(~$*USER); ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `getgrnam` and associated built-ins as closely as possible in the Raku Programming Language. It exports: ``` endgrent getgrent getgrgid getgrnam setgrent ``` # ORIGINAL PERL 5 DOCUMENTATION ``` getgrnam NAME getgrgid GID getgrent setgrent endgrent These routines are the same as their counterparts in the system C library. In list context, the return values from the various get routines are as follows: # 0 1 2 3 4 ( $name, $passwd, $gid, $members ) = getgr* In scalar context, you get the name, unless the function was a lookup by name, in which case you get the other thing, whatever it is. (If the entry doesn't exist you get the undefined value.) For example: $gid = getgrnam($name); $name = getgrgid($num); The $members value returned by getgr*() is a space-separated list of the login names of the members of the group. ``` # PORTING CAVEATS This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! Source can be located at: <https://github.com/lizmat/P5getgrnam> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen Re-imagined from Perl as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## collation.md class Collation Encapsulates instructions about how strings should be sorted ```raku class Collation { } ``` `Collation` is the class that allows proper sorting, taking into account all Unicode characteristics. It's the class the object [`$*COLLATION`](/language/variables#index-entry-%24*COLLATION) is instantiated to, and thus includes *collation levels*, that is, what kind of features should be looked up when comparing two strings and in which order. # [Methods](#class_Collation "go to top of document")[§](#Methods "direct link") ## [method set](#class_Collation "go to top of document")[§](#method_set "direct link") ```raku method set ( Int :$primary = 1, Int :$secondary = 1, Int :$tertiary = 1, Int :$quaternary = 1) ``` Sets if the different levels should be used in ascending or descending order, or if they are going to be ignored (when set to 0). ```raku my $*COLLATION = Collation.new; say 'a' coll 'z'; # OUTPUT: «Less␤» $*COLLATION.set(:primary(-1)); say 'a' coll 'z'; # OUTPUT: «More␤» ``` ## [method primary](#class_Collation "go to top of document")[§](#method_primary "direct link") ```raku method primary ``` Returns the state of the primary collation level. ## [method secondary](#class_Collation "go to top of document")[§](#method_secondary "direct link") ```raku method secondary ``` Returns the state of the secondary collation level. ## [method tertiary](#class_Collation "go to top of document")[§](#method_tertiary "direct link") ```raku method tertiary ``` Returns the state of the tertiary collation level. ## [method quaternary](#class_Collation "go to top of document")[§](#method_quaternary "direct link") ```raku method quaternary ``` Returns the state of the quaternary collation level. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Collation` raku-type-graph Collation Collation Any Any Collation->Any Mu Mu Any->Mu [Expand chart above](/assets/typegraphs/Collation.svg)
## dist_cpan-JNTHN-Concurrent-Stack.md # Concurrent::Stack A lock-free stack data structure, safe for concurrent use. ## Synopsis ``` use Concurrent::Stack; my $stack = Concurrent::Stack.new; for 'a'..'z' { $stack.push($_); } say $stack.elems; # 26 say $stack.peek; # z say $stack.pop; # z say $stack.pop; # y say $stack.peek; # x $stack.push('k'); say $stack.peek; # k say $stack.elems; # 25 say $stack.Seq; # A Seq iterating a snapshot of the stack say $stack.list; # A lazy List with a snapshot of the stack $stack.pop for ^25; say $stack.elems; # 0 my $x = $stack.peek; # Failure with X::Concurrent::Stack::Empty my $y = $stack.pop; # Failure with X::Concurrent::Stack::Empty ``` ## Overview Lock-free data structures may be safely used from multiple threads, yet do not use locks in their implementation. They achieve this through the use of atomic operations provided by the hardware. Nothing can make contention between threads cheap - synchronization at the CPU level is still synchronization - but lock free data structures tend to scale better. This lock-free stack data structure uses a linked list of immutable nodes, the only mutable state being a head pointer to the node representing the stack top and an element counter mintained through atomic increment/decrement operations. The element count updates are not performed as part of the stack update, and so may lag the actual state of the stack. However, since checking the number of elements to decide whether to `peek` or `pop` is doomed in a concurrent setting anyway (since another thread may `pop` the last value in the meantime), this is not problematic. The `elems` method primarily exists so that the number of elements can be queried once the stack reaches some known stable point (for example, when a bunch of working threads that `push` to it are all known to have completed their work). ### Methods #### push(Any $value) Pushes a value onto the stack. Returns the value that was pushed. #### pop() If the stack is not empty, removes the top value and returns it. Otherwise, returns a `Failure` containing an exception of type `X::Concurrent::Stack::Empty`. #### peek() If the stack is not empty, returns the top value. Otherwise, returns a `Failure` containing an exception of type `X::Concurrent::Stack::Empty`. #### elems() Returns the number of elements on the stack. This value can only be relied upon when it is known that no threads are pushing/popping from the stack at the point this method is called. Never use the result of `elems` to decide whether to `peek` or `pop`, since another thread may `pop` in the meantime. Instead, check if `peek` or `pop` return a `Failure`. #### Bool() Returns `False` if the stack is empty and `True` if the stack is non-empty. The result can only be relied upon when it is known that no threads are pushing/popping from the stack at the point this method is called. Never use the result of `Bool` to decide whether to `peek` or `pop`, since another thread may `pop` in the meantime. Instead, check if `peek` or `pop` return a `Failure`. #### Seq() Returns a `Seq` that will iterate to a snapshot of the stack content, starting from the stack top. The snapshot is made at the time this method is called. #### list() Returns a `List` that will lazily evaluate to a snapshot of the stack content, starting from the stack top. The snapshot is made at the time this method is called.
## dist_zef-jonathanstowe-RPi-Device-SMBus.md # RPi::Device::SMBus i²c on Raspberry Pi for Raku ![Build Status](https://github.com/jonathanstowe/RPi-Device-SMBus/workflows/CI/badge.svg) ## Synopsis ``` use RPi::Device::SMBus; # Obviously you will need to actually read the data sheet of your device. my RPi::Device::SMBus $smbus = RPi::Device::SMBus.new(device => '/dev/i2c-1', address => 0x54); $smbus.write-byte(0x10); .... ``` ## Description This is an SMBus/i²c interface that has been written and tested for the Raspberry Pi, however it uses a fairly generic POSIX interface so if your platform exposes the i²c interface as a character special device it may work. In order to use this you will need to install and configure the i2c-dev kernel module and tools. On a default Debian image you should be able to just do: ``` sudo apt-get install libi2c-dev i2c-tools ``` And then edit the `/etc/modules` to add the modules by adding: ``` i2c-dev i2c-bcm2708 ``` Or for a Raspberry Pi 3 ``` i2c-dev i2c-bcm2835 ``` And then rebooting. If you have a more recent raspbian you may alternatively be able to use `raspi-config` where you can turn on `i2c` under "Interfacing Options". Typicaly the i2c device will be `/dev/i2c-1` on a Raspberry Pi rev B. or v2 or `/dev/i2c-0` on older versions. You can determine the bus address of your device by doing: ``` sudo i2cdetect -y 1 # replace the 1 with a 0 for older versions ``` (Obviously the device should be connected, consult the manual for your device about this.) Which should give you the hexadecimal address of your device. Some devices may not respond, so you may want to either check the data sheet of your device or read the `i2cdetect` manual page to get other options. It should be noted that because there is no easy way of testing this without using physical devices then it may not work perfectly in all cases, but I'd be delighted to receive patches for any issues found. ## Installation Assuming you have a working Rakudo installation you should be able to install this with *zef* : ``` # From the source directory zef install . # Remote installation zef install RPi::Device::SMBus ``` The tests are likely to completely fail on anything but a Raspberry Pi with the i²c configured as above. ## Support Suggestions/patches are welcomed via [github](https://github.com/jonathanstowe/RPi-Device-SMBus/issues) ## Licence This is free software. Please see the <LICENCE> file in the distribution © Jonathan Stowe 2015 - 2021
## dist_zef-raku-community-modules-Data-MessagePack.md [![Actions Status](https://github.com/raku-community-modules/Data-MessagePack/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Data-MessagePack/actions) [![Actions Status](https://github.com/raku-community-modules/Data-MessagePack/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Data-MessagePack/actions) [![Actions Status](https://github.com/raku-community-modules/Data-MessagePack/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Data-MessagePack/actions) # NAME Data::MessagePack - Raku implementation of MessagePack # SYNOPSIS ``` use Data::MessagePack; my $data-structure = { key => 'value', k2 => [ 1, 2, 3 ] }; my $packed = Data::MessagePack::pack( $data-structure ); my $unpacked = Data::MessagePack::unpack( $packed ); Or for streaming: use Data::MessagePack::StreamingUnpacker; my $supplier = Some Supplier; #Could be from IO::Socket::Async for instance my $unpacker = Data::MessagePack::StreamingUnpacker.new( source => $supplier.Supply ); $unpacker.tap( -> $value { say "Got new value"; say $value.raku; }, done => { say "Source supply is done"; } ); ``` # DESCRIPTION The present module proposes an implementation of the MessagePack specification as described on <http://msgpack.org/>. The implementation is now in Pure Raku which could come as a performance penalty opposed to some other packer implemented in C. # FUNCTIONS ## function pack That function takes a data structure as parameter, and returns a `Blob` with the packed version of the data structure. ## function unpack That function takes a `MessagePack` packed message as parameter, and returns the deserialized data structure. # Author Pierre Vigier # Contributors Timo Paulssen Source can be located at: <https://github.com/raku-community-modules/MessagePack> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2016 - 2018 Pierre Vigier Copyright 2023, 2025 The Raku Community
## dist_zef-martimm-Gnome-Graphene.md ![](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-perl6.png) # Gnome Graphene - A thin layer of types for graphic libraries ![Artistic License 2.0](https://martimm.github.io/label/License-label.svg) # Description Graphene contains optimizations for speeding up vector operations; those optimizations are optional, and used only if both Graphene was compiled with support for them and if the system you're running on has them ## Documentation * [🔗 Website, entry point for all documents and blogs](https://martimm.github.io/) * [🔗 License document](https://www.perlfoundation.org/artistic_license_2_0) * [🔗 Release notes of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/blob/main/CHANGES.md) * [🔗 Issues of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/issues) # Installation Do not install this package on its own. Instead install `Gnome::Gtk4` newest api. `zef install Gnome::Gtk4:api<2>` # Author Name: **Marcel Timmerman** Github account name: **MARTIMM** # Issues There are always some problems! If you find one please help by filing an issue at [my github project](https://github.com/MARTIMM/gnome-source-skim-tool/issues). # Attribution * The inventors of Raku, formerly known as Perl 6, of course and the writers of the documentation which helped me out every time again and again. * The builders of all the Gnome libraries and the documentation. * Other helpful modules for their insight and use.
## dist_cpan-JFORGET-Date-Calendar-Gregorian.md # NAME Date::Calendar::Gregorian - Extending the core class 'Date' with strftime and conversions with other calendars # SYNOPSIS Printing the date 2020-04-05 in French *without* Date::Calendar::Gregorian ``` use Date::Names; use Date::Calendar::Strftime; my Date $date .= new('2020-04-05'); my Date::Names $locale .= new(lang => 'fr'); my $day = $locale.dow($date.day-of-week); my $month = $locale.mon($date.month); $date does Date::Calendar::Strftime; say $date.strftime("$day %d $month %Y"); # --> dimanche 05 avril 2020 ``` Printing the date 2020-04-05 in French *with* Date::Calendar::Gregorian ``` use Date::Calendar::Gregorian; my Date::Calendar::Gregorian $date .= new('2020-04-05', locale => 'fr'); say $date.strftime("%A %d %B %Y"); # --> dimanche 05 avril 2020 ``` # INSTALLATION ``` zef install Date::Calendar::Gregorian ``` or ``` git clone https://github.com/jforget/raku-Date-Calendar-Gregorian.git cd raku-Date-Calendar-Gregorian zef install . ``` # DESCRIPTION Date::Calendar::Gregorian is a child class to the core class 'Date', to extend it with the string-generation method `strftime` and with the conversion methods `new-from-date` and `to-date`. # AUTHOR Jean Forget [JFORGET@cpan.org](mailto:JFORGET@cpan.org) # COPYRIGHT AND LICENSE Copyright © 2020 Jean Forget This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-melezhik-Tomtit.md # Tomtit Tomtit - Raku Task Runner # Build Status ![SparkyCI](https://sparky.sparrowhub.io/badge/gh-melezhik-Tomtit?foo=bar) # Install ``` zef install Tomtit ``` # Quick start Tomtit is a task runner based on Sparrow6 engine, so just drop a few tasks under *some* folder and run them as Raku scenarios: ``` mkdir -p tasks/hello ``` `tasks/hello/task.bash`: ``` echo "hello world" ``` `.tomty/hello.raku`: ``` task-run "tasks/hello"; ``` You can do *more* then that, [read more](https://github.com/melezhik/Sparrow6/blob/master/documentation/development.md) about Sparrow6 tasks on Sparrow6 documentation. # Cli api ``` tom $action|$options $thing ``` Initialize tomtit: ``` tom --init ``` Run scenario: ``` tom $scenario ``` Default action (list of scenarios): ``` tom ``` List available scenarios: ``` tom --list ``` Get help: ``` tom --help ``` Show the last executed scenario: ``` tom --last ``` Clean Tomtit cache: ``` tom --clean ``` Example: ``` tom --list [scenarios list] test build install tom test ``` # Create scenarios Tomtit scenarios are just Raku wrappers for underlying Sparrow6 tasks. Create a `.tom` directory, to hold all the scenarios: ``` mkdir .tom/ nano .tom/build.raku nano .tom/test.raku nano .tom/install.raku ``` And the drop some tasks at *some* folder: `tasks/build/task.bash`: ``` set -e make make test sudo make install ``` `.tom/build.raku`: ``` task-run "tasks/build"; ``` You might want to ignore Tomtit cache which commit files to SCM: ``` git add .tom/ echo .tom/.cache >> .gitignore ``` # Using prebuilt Sparrow6 DSL functions [Sparrow6 DSL](https://github.com/melezhik/Sparrow6/blob/master/documentation/dsl.md) provides one with ready to use function for some standard automation tasks: `.tom/example.raku`: ``` # you can use Sparrow6 DSL functions # to do many system tasks, like: # creation of files and directories file 'passwords.txt', %( owner => "root", mode => "700", content => "super secret" ); directory '.cache', %( owner => "server" ); # or restarting of services service-restart "web-app"; # or you can run a specific sparrow plugin # by using task-run function: task-run 'my task', 'plugin', %( foo => 'bar' ); # for example, to set git repository, # use git-base plugin: task-run "set git", "git-base", %( email => 'melezhik@gmail.com', name => 'Alexey Melezhik', config_scope => 'local', set_credential_cache => 'on' ); ``` # Profiles Profiles are predefined sets of Tomtit scenarios. To start using scenarios from profile you say: ``` tom --profile $profile ``` Once the command is executed the profile scenarios get installed to the base Tomtit directory. To list available profiles say this: ``` tom --profile ``` To list profiles scenarios say this: ``` tom --list --profile $profile ``` You can install selected scenario from profile by using special notation: ``` tom --profile $profile@$scenario ``` For example to install `commit` scenario from `git` profile: ``` tom --profile git@commit ``` # Portable profiles Tomtit exposes API to create portable profiles as regular Raku modules. You should create Raku module in `Tomtit::Profile` namespace with the *our* function `profile-data`, returning `Hash` with scenarios data. For example: ``` unit module Tomtit::Profile::Pets:ver<0.0.1>; our sub profile-data () { my %a is Map = ( cat => (slurp %?RESOURCES<cat.raku>.Str), dog => (slurp %?RESOURCES<dog.raku>.Str), fish => (slurp %?RESOURCES<fish.raku>.Str) ); } ``` The above module defines [Tomtit::Profile::Pets](https://github.com/melezhik/tomtit-profile-pets) profile with 3 scenarios `cat, dog, fish` installed as module resources: ``` resources/ cat.raku dog.raku fish.raku ``` Now we can install it as regular Raku module and use through tom: ``` zef install Tomtit::Profile::Pets ``` Once module is installed we can install related profile. Note that we should replace `::` by `-` (\*) symbols when referring to profile name. ``` tom --list --profile Tomtit-Profile-Pets load portable profile Tomtit::Profile::Pets as Raku module ... [profile scenarios] Tomtit::Profile::Pets@cat installed: False Tomtit::Profile::Pets@dog installed: False Tomtit::Profile::Pets@fish installed: False tom --profile Tomtit-Profile-Pets install Tomtit::Profile::Pets@cat ... install Tomtit::Profile::Pets@dog ... install Tomtit::Profile::Pets@fish ... ``` (\*) Tomtit require such a mapping so that Bash completion could work correctly. # Removing scenarios To remove installed scenario say this: ``` tom --remove $scenario ``` # Edit scenario source code Use `--edit` to create scenario from the scratch or to edit existed scenario source code: ``` tom --edit $scenario ``` # Getting scenario source code Use `--cat` command to print out scenario source code: ``` tom --cat $scenario ``` Use `--lines` flag to print out with line numbers. # Environments * Tomtit environments are configuration files, written on Raku and technically speaking are plain Raku Hashes * Environment configuration files should be placed at `.tom/conf` directory: .tom/env/config.raku: ``` { name => "Tomtit", who-are-you => "smart bird" } ``` Run Tomtit. It will pick the `.tom/env/config.raku` and read configuration from it, variables will be accessible as `config` Hash, inside Tomtit scenarios: ``` my $name = config<name>; my $who-are-you = config<who-are-you>; ``` To define *named* configuration ( environment ), simply create `.tom/env/config{$env}.raku` file and refer to it through `--env=$env` parameter: ``` nano .tom/env/config.prod.raku tom --env=prod ... other parameters here # will run with production configuration ``` You can run editor for environment configuration by using --edit option: ``` tom --env-edit test # edit test enviroment configuration tom --env-edit default # edit default configuration ``` You can activate environment by using `--env-set` parameter: ``` tom --env-set prod # set prod environment as default tom --env-set # to list active (current) environment tom --env-set default # to set current environment to default ``` To view environment configuration use `--env-cat` command: ``` tom --env-cat $env ``` You print out the list of all environments by using `--env-list` parameters: ``` tom --env-list ``` # Tomtit cli configuration You can set Tomtit configuration in `~/tom.yaml` file: ``` # list of portable Tomtit profiles, # will be available through Bash completion profiles: - Tomtit-Foo - Tomtit-Bar - Tomtit-Bar-Baz # you can also setup some Tomtit cli options here options: quiet: true ``` # Options ``` --verbose # run scenario in verbose mode --quiet,-q # run scenario in less verbose mode --color # color output --no_index_update # don't update Sparrow repository index --dump_task # dump task code before execution, see SP6_DUMP_TASK_CODE Sparrow documentation ``` Example of `~/tom.yaml` file: ``` options: no_index_update: true quiet: true ``` # Bash completion You can install Bash completion for tom cli. ``` tom --completion source ~/.tom_completion.sh ``` # Development ``` git clone https://github.com/melezhik/Tomtit.git zef install --/test . zef install Tomty tomty --all # run tests ``` # See also * [ake](https://github.com/Raku/ake) - a Raku make-a-like inspired by rake # Author Alexey Melezhik # Thanks to God Who gives me inspiration in my work
## dist_cpan-JNTHN-cro.md # Cro Build Status This is part of the Cro libraries for implementing services and distributed systems in Raku. See the [Cro website](https://cro.services/) for further information and documentation.
## dist_zef-bduggan-Slang-Mosdef.md ## Slang::Mosdef All the cool kids are using def to declare methods. Now you can, too. [![Linux](https://github.com/bduggan/mosdef/actions/workflows/linux.yml/badge.svg)](https://github.com/bduggan/mosdef/actions/workflows/linux.yml) ``` use Slang::Mosdef; class Foo { def bar { say 'I am cool too'; } method baz { say 'This is not as much fun'; } } ``` You can also use lambda for subs! ``` my $yo = lambda { say 'oy' }; $yo(); ``` Or λ! ``` my $twice = λ ($x) { $x * 2 }; say $twice(0); # still 0 ``` Compute 5 factorial using a Y combinator: ``` say λ ( &f ) { λ ( \n ) { return f(&f)(n); } }( λ ( &g ) { λ ( \n ) { return n==1 ?? 1 !! n * g(&g)(n-1); } })(5) ```
## real.md Real Combined from primary sources listed below. # [In DateTime](#___top "go to top of document")[§](#(DateTime)_method_Real "direct link") See primary documentation [in context](/type/DateTime#method_Real) for **method Real**. ```raku multi method Real(DateTime:D: --> Instant:D) ``` Converts the invocant to [`Instant`](/type/Instant). The same value can be obtained with the [`Instant`](/type/Instant) method. Available as of release 2023.02 of the Rakudo compiler. # [In Complex](#___top "go to top of document")[§](#(Complex)_method_Real "direct link") See primary documentation [in context](/type/Complex#method_Real) for **method Real**. ```raku multi method Real(Complex:D: --> Num:D) multi method Real(Complex:U: --> Num:D) ``` Coerces the invocant to [`Num`](/type/Num). If the imaginary part isn't [approximately](/routine/=~=) zero, coercion [fails](/routine/fail) with [`X::Numeric::Real`](/type/X/Numeric/Real). The `:D` variant returns the result of that coercion. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0e0`. # [In RatStr](#___top "go to top of document")[§](#(RatStr)_method_Real "direct link") See primary documentation [in context](/type/RatStr#method_Real) for **method Real**. ```raku multi method Real(Real:D: --> Rat:D) multi method Real(Real:U: --> Rat:D) ``` The `:D` variant returns the numeric portion of the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0.0`. # [In Date](#___top "go to top of document")[§](#(Date)_method_Real "direct link") See primary documentation [in context](/type/Date#method_Real) for **method Real**. ```raku multi method Real(Date:D: --> Int:D) ``` Converts the invocant to [`Int`](/type/Int). The same value can be obtained with the `daycount` method. Available as of release 2023.02 of the Rakudo compiler. # [In NumStr](#___top "go to top of document")[§](#(NumStr)_method_Real "direct link") See primary documentation [in context](/type/NumStr#method_Real) for **method Real**. ```raku multi method Real(NumStr:D: --> Num:D) multi method Real(NumStr:U: --> Num:D) ``` The `:D` variant returns the numeric portion of the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0e0`. # [In Cool](#___top "go to top of document")[§](#(Cool)_method_Real "direct link") See primary documentation [in context](/type/Cool#method_Real) for **method Real**. ```raku multi method Real() ``` Coerces the invocant to a [`Numeric`](/type/Numeric) and calls its [`.Real`](/routine/Real) method. [Fails](/routine/fail) if the coercion to a [`Numeric`](/type/Numeric) cannot be done. ```raku say 1+0i.Real; # OUTPUT: «1␤» say 2e1.Real; # OUTPUT: «20␤» say 1.3.Real; # OUTPUT: «1.3␤» say (-4/3).Real; # OUTPUT: «-1.333333␤» say "foo".Real.^name; # OUTPUT: «Failure␤» ``` # [In ComplexStr](#___top "go to top of document")[§](#(ComplexStr)_method_Real "direct link") See primary documentation [in context](/type/ComplexStr#method_Real) for **method Real**. ```raku multi method Real(ComplexStr:D: --> Num:D) multi method Real(ComplexStr:U: --> Num:D) ``` Coerces the numeric portion of the invocant to [`Num`](/type/Num). If the imaginary part isn't [approximately](/language/operators#infix_≅) zero, coercion [fails](/routine/fail) with [`X::Numeric::Real`](/type/X/Numeric/Real). The `:D` variant returns the result of that coercion. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0e0`. # [In role Enumeration](#___top "go to top of document")[§](#(role_Enumeration)_method_Real "direct link") See primary documentation [in context](/type/Enumeration#method_Real) for **method Real**. ```raku multi method Real(::?CLASS:D:) ``` Takes a value of an enum and returns it after coercion to [`Real`](/type/Real): ```raku enum Numbers ( cool => '42', almost-pi => '3.14', sqrt-n-one => 'i' ); say cool.Real; # OUTPUT: «42␤» say almost-pi.Real; # OUTPUT: «3.14␤» try say sqrt-n-one.Real; say $!.message if $!; # OUTPUT: «Cannot convert 0+1i to Real: imaginary part not zero␤» ``` Note that if the value cannot be coerced to [`Real`](/type/Real), an exception will be thrown. # [In IntStr](#___top "go to top of document")[§](#(IntStr)_method_Real "direct link") See primary documentation [in context](/type/IntStr#method_Real) for **method Real**. ```raku multi method Real(IntStr:D: --> Int:D) multi method Real(IntStr:U: --> Int:D) ``` The `:D` variant returns the numeric portion of the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0`. # [In role Real](#___top "go to top of document")[§](#(role_Real)_method_Real "direct link") See primary documentation [in context](/type/Real#method_Real) for **method Real**. ```raku multi method Real(Real:D: --> Real:D) multi method Real(Real:U: --> Real:D) ``` The `:D` variant simply returns the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns `self.new`.
## dist_zef-raku-community-modules-Netstring.md [![Actions Status](https://github.com/raku-community-modules/Netstring/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Netstring/actions) # NAME Netstring - A library for working with netstrings # SYNOPSIS ``` use Netstring; say to-netstring("hello world!"); # 12:hello world!, my $b = Buf.new(0x68,0x65,0x6c,0x6c,0x6f,0x20,0x77,0x6f,0x72,0x6c,0x64,0x21); say to-netstring($b); # 12:hello world!, to-netstring-buf("hello world!"); # returns Buf:0x<31 32 3a 68 65 6c 6c 6f 20 77 6f 72 6c 64 21 2c> to-netstring-buf($b); # returns Buf:0x<31 32 3a 68 65 6c 6c 6f 20 77 6f 72 6c 64 21 2c> ``` # DESCRIPTION Work with netstrings. This currently supports generating netstrings, and parsing a netstring from an [IO::Socket](https://docs.raku.org/type/IO::Socket). # READING FROM A SOCKET ``` use Netstring; my $daemon = IO::Socket::INET.new( :localhost<localhost>, :localport(42), :listen ); while my $client = $daemon.accept() { # The client sends "12:hello world!," as a stream of bytes. my $rawcontent = read-netstring($client); my $strcontent = $rawcontent.decode; say "The client said: $strcontent"; # prints "The client said: hello world!" $client.write($strcontent.flip); # sends "!dlrow olleh" back to the client. $client.close(); } ``` # AUTHOR Timothy Totten # COPYRIGHT AND LICENSE Copyright 2012 - 2016 Timothy Totten Copyright 2017 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## grep.md grep Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_grep "direct link") See primary documentation [in context](/type/Any#method_grep) for **method grep**. ```raku method grep(Mu $matcher, :$k, :$kv, :$p, :$v --> Seq) ``` Coerces the invocant to a `list` by applying its [`.list`](/routine/list) method and uses [`List.grep`](/type/List#routine_grep) on it. For undefined invocants, based on `$matcher` the return value can be either `((Any))` or the empty List. ```raku my $a; say $a.grep({ True }); # OUTPUT: «((Any))␤» say $a.grep({ $_ }); # OUTPUT: «()␤» ``` # [In HyperSeq](#___top "go to top of document")[§](#(HyperSeq)_method_grep "direct link") See primary documentation [in context](/type/HyperSeq#method_grep) for **method grep**. ```raku method grep(HyperSeq:D: $matcher, *%options) ``` Applies `grep` to the `HyperSeq` similarly to how it would do it on a [`Seq`](/type/Seq). ```raku my @hyped = (^10000).map(*²).hyper; @hyped.grep( * %% 3 ).say; # OUTPUT: «(0 9 36 81 144 ...)␤» ``` When you use `hyper` on a [`Seq`](/type/Seq), this is the method that is actually called. # [In List](#___top "go to top of document")[§](#(List)_routine_grep "direct link") See primary documentation [in context](/type/List#routine_grep) for **routine grep**. ```raku sub grep(Mu $matcher, *@elems, :$k, :$kv, :$p, :$v --> Seq:D) method grep(List:D: Mu $matcher, :$k, :$kv, :$p, :$v --> Seq:D) ``` Returns a sequence of elements against which `$matcher` smartmatches. The elements are returned in the order in which they appear in the original list. Examples: ```raku say ('hello', 1, 22/7, 42, 'world').grep: Int; # OUTPUT: «(1 42)␤» say grep { .Str.chars > 3 }, 'hello', 1, 22/7, 42, 'world'; # OUTPUT: «(hello 3.142857 world)␤» ``` Note that if you want to grep for elements that do not match, you can use a `none`-[`Junction`](/type/Junction): ```raku say <a b 6 d 8 0>.grep(none Int); # OUTPUT: «(a b d)␤» say <a b c d e f>.grep(none /<[aeiou]>/); # OUTPUT: «(b c d f)␤» ``` Another option to grep for elements that do not match a regex is to use a block: ```raku say <a b c d e f>.grep({! /<[aeiou]>/}) # OUTPUT: «(b c d f)␤» ``` The reason the example above works is because a regex in Boolean context applies itself to `$_`. In this case, `!` boolifies the `/<[aeiou]>/` regex and negates the result. Smartmatching against a [`Callable`](/type/Callable) (in this case a [`Block`](/type/Block)) returns the value returned from that callable, so the boolified result of a regex is then used to decide whether the current value should be kept in the result of a grep. The optional named parameters `:k`, `:kv`, `:p`, `:v` provide the same functionality as on slices: * k Only return the index values of the matching elements in order. * kv Return both the index and matched elements in order. * p Return the index and the matched element as a [`Pair`](/type/Pair), in order. * v Only return the matched elements (same as not specifying any named parameter at all). Examples: ```raku say ('hello', 1, 22/7, 42, 'world').grep: Int, :k; # OUTPUT: «(1 3)␤» say grep { .Str.chars > 3 }, :kv, 'hello', 1, 22/7, 42, 'world'; # OUTPUT: «(0 hello 2 3.142857 4 world)␤» say grep { .Str.chars > 3 }, :p, 'hello', 1, 22/7, 42, 'world'; # OUTPUT: «(0 => hello 2 => 3.142857 4 => world)␤» ``` # [In Supply](#___top "go to top of document")[§](#(Supply)_method_grep "direct link") See primary documentation [in context](/type/Supply#method_grep) for **method grep**. ```raku method grep(Supply:D: Mu $test --> Supply:D) ``` Creates a new supply that only emits those values from the original supply that smartmatch against `$test`. ```raku my $supplier = Supplier.new; my $all = $supplier.Supply; my $ints = $all.grep(Int); $ints.tap(&say); $supplier.emit($_) for 1, 'a string', 3.14159; # prints only 1 ``` # [In RaceSeq](#___top "go to top of document")[§](#(RaceSeq)_method_grep "direct link") See primary documentation [in context](/type/RaceSeq#method_grep) for **method grep**. ```raku method grep(RaceSeq:D: $matcher, *%options) ``` Applies `grep` to the `RaceSeq` similarly to how it would do it on a [`Seq`](/type/Seq). ```raku my @raced = (^10000).map(*²).race; @raced.grep( * %% 3 ).say; # OUTPUT: «(0 9 36 81 144 ...)␤» ``` When you use `race` on a [`Seq`](/type/Seq), this is the method that is actually called.
## packages.md Packages Organizing and referencing namespaced program elements Packages are nested namespaces of named program elements. [Modules](/language/module-packages), classes, grammars, and others are types of packages. Like files in a directory, you can generally refer to named elements with their short-name if they are local, or with the longer name that includes the namespace to disambiguate as long as their scope allows that. # [Names](#Packages "go to top of document")[§](#Names "direct link") A package *name* is anything that is a legal part of a variable name (not counting the sigil). This includes: ```raku class Foo { sub zape () { say "zipi" } class Bar { method baz () { return 'Þor is mighty' } our &zape = { "zipi" }; our $quux = 42; } } my $foo; # simple identifiers say Foo::Bar.baz; # calling a method; OUTPUT: «Þor is mighty␤» say Foo::Bar::zape; # compound identifiers separated by ::; OUTPUT: «zipi␤» my $bar = 'Bar'; say $Foo::($bar)::quux; # compound identifiers with interpolations; OUTPUT: «42␤» $42; # numeric names $!; # certain punctuation variables ``` `::` is used to separate nested package names. Packages do not really have an identity; they can be simply part of a module or class name, for instance. They are more similar to namespaces than to modules. A module of the same name will *capture* the identity of a package if it exists. ```raku package Foo:ver<0> {}; module Foo:ver<1> {}; say Foo.^ver; # OUTPUT: «1␤» ``` The syntax allows the declared package to use a version as well as an *authority* `auth`, but as a matter of fact, it's dismissed; only modules, classes and other higher order type objects have an identity that might include `auth` and `ver`. ```raku package Foo:ver<0>:auth<bar> {}; say Foo.^auth; # OUTPUT: «(exit code 1) No such method 'auth' for invocant of type # 'Perl6::Metamodel::PackageHOW' ... ``` ## [Package-qualified names](#Packages "go to top of document")[§](#Package-qualified_names "direct link") Ordinary package-qualified names look like this: `$Foo::Bar::quux`, which would be the `$quux` variable in package `Foo::Bar`; `Foo::Bar::zape` would represent the `&zape` variable in the same package. Sometimes it's clearer to keep the sigil with the variable name, so an alternate way to write this is: ```raku Foo::Bar::<$quux> ``` This does not work with the `Foo«&zape»` variable, since `sub`s, by default, have lexical scope. The name is resolved at compile time because the variable name is a constant. We can access the rest of the variables in `Bar` (as shown in the example above) since classes, by default, have package scope. If the name part before `::` is null, it means the package is unspecified and must be searched for. Generally this means that an initial `::` following the main sigil is a no-op on names that are known at compile time, though `::()` can also be used to introduce an interpolation. Also, in the absence of another sigil, `::` can serve as its own sigil indicating intentional use of a not-yet-declared package name. # [Pseudo-packages](#Packages "go to top of document")[§](#Pseudo-packages "direct link") The following pseudo-package names are reserved at the front of a name: | | | | --- | --- | | MY | Symbols in the current lexical scope (aka $?SCOPE) | | OUR | Symbols in the current package (aka $?PACKAGE) | | CORE | Outermost lexical scope, definition of standard Raku | | GLOBAL | Interpreter-wide package symbols, really UNIT::GLOBAL | | PROCESS | Process-related globals (superglobals). The last place dynamic variable lookup will look. | | COMPILING | Lexical symbols in the scope being compiled | The following relative names are also reserved but may be used anywhere in a name: | | | | --- | --- | | CALLER | Dynamic symbols in the immediate caller's lexical scope | | CALLERS | Dynamic symbols in any caller's lexical scope | | DYNAMIC | Dynamic symbols in my or any caller's lexical scope | | OUTER | Symbols in the next outer lexical scope | | OUTERS | Symbols in any outer lexical scope | | LEXICAL | Dynamic symbols in my or any outer's lexical scope | | UNIT | Symbols in the outermost lexical scope of compilation unit | | SETTING | Lexical symbols in the unit's DSL (usually CORE) | | PARENT | Symbols in this package's parent package (or lexical scope) | | CLIENT | The nearest CALLER that comes from a different package | The file's scope is known as `UNIT`, but there are one or more lexical scopes outside of that corresponding to the linguistic setting (often known as the prelude in other cultures). Hence, the `SETTING` scope is equivalent to `UNIT::OUTERS`. For a standard Raku program `SETTING` is the same as `CORE`, but various startup options (such as `-n` or `-p`) can put you into a domain specific language, in which case `CORE` remains the scope of the standard language, while `SETTING` represents the scope defining the DSL that functions as the setting of the current file. When used as a search term in the middle of a name, `SETTING` includes all its outer scopes up to `CORE`. To get *only* the setting's outermost scope, use `UNIT::OUTER` instead. # [Looking up names](#Packages "go to top of document")[§](#Looking_up_names "direct link") ## [Interpolating into names](#Packages "go to top of document")[§](#Interpolating_into_names "direct link") You may [interpolate](https://en.wikipedia.org/wiki/String_interpolation) a string into a package or variable name using `::($expr)` where you'd ordinarily put a package or variable name. The string is allowed to contain additional instances of `::`, which will be interpreted as package nesting. You may only interpolate entire names, since the construct starts with `::`, and either ends immediately or is continued with another `::` outside the parentheses. Most symbolic references are done with this notation: ```raku my $foo = "Foo"; my $bar = "Bar"; my $foobar = "Foo::Bar"; $::($bar) # lexically-scoped $Bar $::("MY::$bar") # lexically-scoped $Bar $::("OUR::$bar") # package-scoped $Bar $::("GLOBAL::$bar") # global $Bar $::("PROCESS::$bar") # process $Bar $::("PARENT::$bar") # current package's parent's $Bar $::($foobar) # $Foo::Bar @::($foobar)::baz # @Foo::Bar::baz @::($foo)::Bar::baz # @Foo::Bar::baz @::($foobar)baz # ILLEGAL at compile time (no operator baz) @::($foo)::($bar)::baz # @Foo::Bar::baz ``` An initial `::` doesn't imply global; here as part of the interpolation syntax it doesn't even imply package. After the interpolation of the `::()` component, the indirect name is looked up exactly as if it had been there in the original source code, with priority given first to leading pseudo-package names, then to names in the lexical scope (searching scopes outwards, ending at `CORE`). The current package is searched last. Use the `MY` pseudopackage to limit the lookup to the current lexical scope, and `OUR` to limit the scopes to the current package scope. In the same vein, class and method names can be interpolated too: ```raku role with-method { method a-method { return 'in-a-method of ' ~ $?CLASS.^name }; } class a-class does with-method { method another-method { return 'in-another-method' }; } class b-class does with-method {}; my $what-class = 'a-class'; say ::($what-class).a-method; # OUTPUT: «in-a-method of a-class␤» $what-class = 'b-class'; say ::($what-class).a-method; # OUTPUT: «in-a-method of b-class␤» my $what-method = 'a-method'; say a-class."$what-method"(); # OUTPUT: «in-a-method of a-class␤» $what-method = 'another-method'; say a-class."$what-method"(); # OUTPUT: «in-another-method␤» ``` ## [Direct lookup](#Packages "go to top of document")[§](#Direct_lookup "direct link") To do direct lookup in a package's symbol table without scanning, treat the package name as a hash: ```raku Foo::Bar::{'&baz'} # same as &Foo::Bar::baz PROCESS::<$IN> # same as $*IN Foo::<::Bar><::Baz> # same as Foo::Bar::Baz ``` Unlike `::()` symbolic references, this does not parse the argument for `::`, nor does it initiate a namespace scan from that initial point. In addition, for constant subscripts, it is guaranteed to resolve the symbol at compile time. You cannot use this kind of direct lookup inside regular expressions, unless you issue a `MONKEY-SEE-NO-EVAL` pragma. The main intention of this measure is to avoid user input being executed externally. The null pseudo-package is the same search list as an ordinary name search. That is, the following are all identical in meaning: ```raku $foo ::{'$foo'} ::<$foo> ``` Each of them scans the lexical scopes outward, and then the current package scope (though the package scope is then disallowed when `use strict` is in effect). ## [Package lookup](#Packages "go to top of document")[§](#Package_lookup "direct link") Subscript the package object itself as a hash object, the key of which is the variable name, including any sigil. The package object can be derived from a type name by use of the `::` postfix: ```raku MyType::<$foo> ``` ## [Class member lookup](#Packages "go to top of document")[§](#Class_member_lookup "direct link") Methods—including auto-generated methods, such as public attributes' accessors—are stored in the class metaobject and can be looked up through by the [lookup](/routine/lookup) method. ```raku Str.^lookup('chars') ``` # [Globals](#Packages "go to top of document")[§](#Globals "direct link") Interpreter globals live in the `GLOBAL` package. The user's program starts in the `GLOBAL` package, so "our" declarations in the mainline code go into that package by default. Process-wide variables live in the `PROCESS` package. Most predefined globals such as `$*UID` and `$*PID` are actually process globals. # [Programmatic use of modules](#Packages "go to top of document")[§](#Programmatic_use_of_modules "direct link") It is sometimes useful to be able to programmatically define and use modules. Here is a practical example. Assume we have a series of modules with the module files in a directory tree like this: 「text」 without highlighting ``` ``` lib/ TomtomMaps/ Example/ # a directory of example file modules programmatically # created from the Tomtom Maps SDK A01.rakumod #... C09.rakumod #... ``` ``` Module `TomtomMaps::Example::C09` looks like this: ```raku unit module TomtomMaps::Example::C09; # ensure you use the 'our' declarator our sub print-example($fh, # filehandle open for writing :$api-maps-key ) { # do not need to export the sub $fh.print: qq:to/HERE/; # ... the example html file HERE } ``` We can access and use the subroutines like this: ```raku use lib 'lib'; my $module-dir = 'TomtomMaps::Example'; my $example = 'C09'; my $m = "{$module-dir}::{$example}"; # you must use the runtime 'require', not the compile-time 'use' require ::($m); my $fh = open "./example-{$example}.html", :w; my $api-maps-key = 'ghghfxnnhrgfsWE.mmn'; # execute the subroutine &::($m)::print-example($fh, :$api-maps-key); # the map's html file is written $fh.close; ```
## dist_github-zostay-CompUnit-DynamicLib.md # NAME CompUnit::DynamicLoader - load modules from temporarily included locations # SYNOPSIS ``` use CompUnit::DynamicLib; my @includes = <plugin/lib module/lib other/lib>; require-from(@includes, "MyPlugin::Module"); use-lib-do @includes, { require ModuleX; require ModuleY <&something>; } ``` # DESCRIPTION **Experimental:** I do not really know if what this module does is a good idea or the best way to do it, but I am trying it out. Please use with caution and let me know if you have any problems. When searching for compilation units (more commonly referred to as just "modules" or "packages" or "classes") in Perl 6, the VM hunts through all the CompUnit::Repository objects chained in `$*REPO` (this is a more flexible solution to the `@INC` setting using in Perl 5). Normally, to add a new repository to the list, you would just run: ``` use lib "my-other-lib"; # load your modules here ``` However, perhaps you don't wnat to normally load from a location in your program. You might want to load from a location just long enough to get files out of it and then never see it again. This is a common scenario if your application allows for the use of custom plugin code. This library makes it possible to add a directory to the list of repositories, load the modules you want, and then remove them so that no more code will be loaded from there: ``` use-lib-do "my-other-lib", { # load your modules here } ``` # EXPORTED ROUTINES ## sub use-lib-do ``` multi sub use-lib-do(@include, &block) multi sub use-lib-do($include, &block) ``` Given a set of repository specs to `@include` (or `$include`) and a `&block` to run, add those repositories (usually directory names) to `$*REPO`, run the `&block`, and then strip the temporary repositories back out again. ## sub require-from ``` multi sub require-from(@include, $module-name) multi sub require-from($include, $module-name) ``` In cases where you only need to load a single module, this can be used as a shortcut for: ``` use-lib-do @include, { require ::($module-name) }; ``` # AUTHOR & COPYRIGHT Copyright 2016 Sterling Hanenkamp. This software is made available under the same terms as Perl 6 itself.
## dist_github-moznion-HTML-Escape.md [![Build Status](https://travis-ci.org/moznion/p6-HTML-Escape.svg?branch=master)](https://travis-ci.org/moznion/p6-HTML-Escape) # NAME HTML::Escape - Utility of HTML escaping # SYNOPSIS ``` use HTML::Escape; escape-html("<^o^>"); # => '&lt;^o^&gt;' ``` # DESCRIPTION HTML::Escape provides a function which escapes HTML's special characters. It performs a similar function to PHP's htmlspecialchars. This module is perl6 port of [HTML::Escape of perl5](https://metacpan.org/pod/HTML::Escape). # Functions ## `escape-html(Str $raw-str) returns Str` Escapes HTML's special characters in given string. # TODO * Support unescaping function? # SEE ALSO [HTML::Escape of perl5](https://metacpan.org/pod/HTML::Escape) # COPYRIGHT AND LICENSE ``` Copyright 2017- moznion <moznion@gmail.com> This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. ``` And original perl5's HTML::Escape is ``` This software is copyright (c) 2012 by Tokuhiro Matsuno E<lt>tokuhirom AAJKLFJEF@ GMAIL COME<gt>. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. ```
## dist_zef-antononcube-DSL-Entity-Geographics.md # DSL::Entity::Geographics [![MacOS](https://github.com/antononcube/Raku-DSL-Entity-Geographics/actions/workflows/macos.yml/badge.svg)](https://github.com/antononcube/Raku-DSL-Entity-Geographics/actions/workflows/macos.yml) [![Linux](https://github.com/antononcube/Raku-DSL-Entity-Geographics/actions/workflows/linux.yml/badge.svg)](https://github.com/antononcube/Raku-DSL-Entity-Geographics/actions/workflows/linux.yml) [![Win64](https://github.com/antononcube/Raku-DSL-Entity-Geographics/actions/workflows/windows.yml/badge.svg)](https://github.com/antononcube/Raku-DSL-Entity-Geographics/actions/workflows/windows.yml) [![](https://raku.land/zef:antononcube/DSL::Entity::Geographics/badges/version)](https://raku.land/zef:antononcube/DSL::Entity::Geographics) [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) Raku grammar classes for geographic entities (names.) This package is closely related, but independent of [Data::Geographics](https://raku.land/zef:antononcube/Data::Geographics), [AAp5]. ## Installation From [Zef ecosystem](https://raku.land): ``` zef install DSL::Entity::Geographics ``` From GitHub: ``` zef install https://github.com/antononcube/Raku-DSL-Entity-Geographics.git ``` ## Examples ### Basic entity name retrieval Here we show how the entity ID is retrieved using an adjective: ``` use DSL::Entity::Geographics; ToGeographicEntityCode('Brazilian'); ``` ``` # "Brazil" ``` ### Identifiers The known cities are have identifier in the form: `<country>.<province>.<city>`. The names in the identifiers have underscore characters ("\_") instead of spaces. For example: ``` United_States.Nevada.Las_Vegas ``` **Remark:** Both packages "DSL::Entity::Geographics" and "Data::Geographics" have the same identifiers. ### City specs There is a dedicated function for parsing city names together with a state- or country name: ``` entity-city-and-state-name('Chicago, IL') ``` ``` # United_States.Illinois.Chicago ``` If the adverb `:exhaustive` (or just `:ex`) is used then all matches for city name in country (like USA) are returned: ``` .say for entity-city-and-state-name('Atlanta United States'):ex ``` ``` # United_States.Missouri.Atlanta # United_States.Kansas.Atlanta # United_States.Indiana.Atlanta # United_States.Michigan.Atlanta # United_States.Texas.Atlanta # United_States.Illinois.Atlanta # United_States.Louisiana.Atlanta # United_States.Georgia.Atlanta # United_States.Wisconsin.Atlanta # United_States.Nebraska.Atlanta ``` A city name without a specified country or state is considered a generic city name if found in the gazeteer database: ``` say entity-city-and-state-name('Miama'); ``` ``` #ERROR: Possible misspelling of 'miami' as 'miama'. # CITYNAME.Miami ``` **Remark:** Misspellings are recognized and allowed: ### Grammar parsing One of the main motivations for this package is to be able to use known country names and related adjectives as grammar tokens. For example, in packages like ["DSL::English::FoodPreparationWorkflows"](https://github.com/antononcube/Raku-DSL-English-FoodPreparationWorkflows), [AAp4]. Here are few grammar parsing examples: ``` use DSL::Entity::Geographics::Grammar; my $pCOMMAND = DSL::Entity::Geographics::Grammar.new; $pCOMMAND.set-resources(DSL::Entity::Geographics::resource-access-object()); say $pCOMMAND.parse('Argentina', rule => 'geographic-entity-command'); ``` ``` #ERROR: Possible misspelling of 'argentine' as 'argentina'. # 「Argentina」 # entity-country-adjective => 「Argentina」 # 0 => 「Argentina」 # word-value => 「Argentina」 ``` ``` say $pCOMMAND.parse('United States of America', rule => 'geographic-entity-command'); ``` ``` # 「United States of America」 # entity-country-name => 「United States of America」 # 0 => 「United States of America」 # word-value => 「United」 # word-value => 「States」 # word-value => 「of」 # word-value => 「America」 ``` Again, misspellings are recognized and allowed: ``` say $pCOMMAND.parse('Indianapolia, Indiana', rule => 'entity-city-and-state-name'); ``` ``` #ERROR: Possible misspelling of 'indianapolis' as 'indianapolia'. # 「Indianapolia, Indiana」 # entity-city-name => 「Indianapolia」 # 0 => 「Indianapolia」 # word-value => 「Indianapolia」 # entity-state-name => 「Indiana」 # 0 => 「Indiana」 # word-value => 「Indiana」 ``` ## References [AAp1] Anton Antonov, [DSL::Shared Raku package](https://github.com/antononcube/Raku-DSL-Shared), (2020), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [DSL::Entity::Jobs Raku package](https://github.com/antononcube/Raku-DSL-Entity-Jobs), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [DSL::Entity::Foods Raku package](https://github.com/antononcube/Raku-DSL-Entity-Foods), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp4] Anton Antonov, [DSL::English::FoodPreparationWorkflows Raku package](https://github.com/antononcube/Raku-DSL-English-FoodPreparationWorkflows), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp5] Anton Antonov, [Data::Geographics Raku package](https://github.com/antononcube/Raku-Data-Geographics), (2024), [GitHub/antononcube](https://github.com/antononcube).
## unshift.md unshift Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_unshift "direct link") See primary documentation [in context](/type/Any#method_unshift) for **method unshift**. ```raku multi method unshift(Any:U: --> Array) multi method unshift(Any:U: @values --> Array) ``` Initializes `Any` variable as empty [`Array`](/type/Array) and calls [`Array.unshift`](/type/Array#routine_unshift) on it. ```raku my $a; say $a.unshift; # OUTPUT: «[]␤» say $a; # OUTPUT: «[]␤» my $b; say $b.unshift([1,2,3]); # OUTPUT: «[[1 2 3]]␤» ``` # [In Array](#___top "go to top of document")[§](#(Array)_routine_unshift "direct link") See primary documentation [in context](/type/Array#routine_unshift) for **routine unshift**. ```raku multi unshift(Array:D, **@values --> Array:D) multi method unshift(Array:D: **@values --> Array:D) ``` Adds the `@values` to the start of the array, and returns the modified array. Fails if `@values` is a lazy list. Example: ```raku my @foo = <a b c>; @foo.unshift: 1, 3 ... 11; say @foo; # OUTPUT: «[(1 3 5 7 9 11) a b c]␤» ``` The notes in [the documentation for method push](/type/Array#method_push) apply, regarding how many elements are added to the array. The [routine prepend](/type/Array#routine_prepend) is the equivalent for adding multiple elements from one list or array. # [In role Buf](#___top "go to top of document")[§](#(role_Buf)_method_unshift "direct link") See primary documentation [in context](/type/Buf#method_unshift) for **method unshift**. ```raku method unshift() ``` Inserts elements at the beginning of the buffer. ```raku my $bú = Buf.new( 1, 1, 2, 3, 5 ); $bú.unshift( 0 ); say $bú.raku; # OUTPUT: «Buf.new(0,1,1,2,3,5)␤» ``` # [In IterationBuffer](#___top "go to top of document")[§](#(IterationBuffer)_method_unshift "direct link") See primary documentation [in context](/type/IterationBuffer#method_unshift) for **method unshift**. ```raku method unshift(IterationBuffer:D: Mu \value) ``` Adds the given value at the beginning of the `IterationBuffer` and returns the given value. Available as of the 2021.12 release of the Rakudo compiler. # [In Nil](#___top "go to top of document")[§](#(Nil)_method_unshift "direct link") See primary documentation [in context](/type/Nil#method_unshift) for **method unshift**. ```raku method unshift(*@) ``` Warns the user that they tried to unshift onto a `Nil` or derived type object.
## dist_cpan-HANENKAMP-HTTP-Request-FormData.md # NAME HTTP::Request::FormData - handler to expedite the handling of multipart/form-data requests # SYNOPSIS ``` use HTTP::UserAgent; use HTTP::Request::Common; my $ua = HTTP::UserAgent.new; my $fd = HTTP::Request::FormData.new; $fd.add-part('username', 'alice'); $fd.add-part('avatar', 'alice.png'.IO, content-type => 'image/png'); my $req = POST( 'http://example.com/', Content-Type => $fd.content-type, content => $fd.content, ); my $res = $ua.request($req); ``` # DESCRIPTION This provides a structured object for use with [HTTP::Request](http::Request) that serializes into a nice neat content buffer. I wrote this as an expedient work-around to some encoding issues I have with the way [HTTP::Request](http::Request) works. This may be a better way to solve that problem than the API ported form LWP in Perl 5, but I am not making a judgement in that regard. I was merely attempting to expedite a solution and sharing it with the hope that it might be useful to someone else as well. That said, this module aims at correctly rendering multipart/form-data content according to the specification laid out in RFC 7578. # METHODS ## method new ``` multi method new() returns HTTP::Request::FormData:D ``` Constructs a new, empty form data object. ## method add-part ``` multi method add-part(Str:D $name, IO::Path $file, Str :$content-type, Str :$filename) multi method add-part(Str:D $name, IO::Handle $file, Str :$content-type, Str :$filename) multi method add-part(Str:D $name, $value, Str :$content-type, Str :$filename) ``` These methods append a new part to the end of the object. Three methods of adding parts are provided. Passing an IO::Path will result in the given file being slurped automatically. The part will be read as binary data unless you specify a `$content-type` that starts with "text/". Similarly, an IO::Handle may be passed and the contents will be slurped from here as well. This allows you control over whether to set the binary flag or not yourself. Finally, you can pass an explicit value, which can be pretty much any string, blob, or other cool value you like. In each case, you can specify the `$filename` to use for that part. Note that the `$filename` will be inferred from the given path if an IO::Path is passed. ## method parts ``` method parts() returns Seq:D ``` Returns a <Seq> of the parts. Each part is returned as a HTTP::Request::FormData::Part object, which provides the following accessors: * * `name` This is the name of the part. * * `filename` This is the filename of the part (if it is a file). * * `content-type` This is the content type to use (if any). * * `value` This is the value that was set when the part was added. * * `content` This is the content that will be rendered with the part (derived from the `value` with headers at the top). ## method boundary ``` method boundary() returns Str:D ``` This is an accessor that allows you to see what the boundary will be used to separate the parts when rendered. This boundary meets the requirements of RFC 7578, which stipulates that the boundary must not be found in the content contained within any of the parts. This means that if you add a new part, the boundary may have to change. For this reason, the `add-part` method will throw an exception if you attempt to add a part after calling this method to select a boundary. ## method content-type ``` method content-type() returns Str:D ``` This is a handy helper for generating a MIME type with the boundary parameter like this: ``` use HTTP::Request::Common; my $fd = HTTP::Request::FormData.new; $fd.add-part('name', 'alice'); my $req = POST( 'http://example.com/', Content-Type => $fd.content-type, content => $fd.content, ); ``` It is essentially equivalent to: ``` qq<multipart/formdata; boundary=$fd.boundary()> ``` As this calls `boundary()`, calls to `add-part` will throw an exception after the first call to this method is made. ## method content ``` method content() returns Blob:D ``` This will return the serialized data associated with this form data object. Each part will have it's headers and content rendered in order and separated by the boundary as specified in RFC 7578.
## rmdir.md rmdir Combined from primary sources listed below. # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_routine_rmdir "direct link") See primary documentation [in context](/type/IO/Path#routine_rmdir) for **routine rmdir**. ```raku sub rmdir(*@dirs --> List:D) method rmdir(IO::Path:D: --> True) ``` Remove the invocant, or in sub form, all of the provided directories in the given list, which can contain any [`Cool`](/type/Cool) object. Only works on empty directories. Method form returns `True` on success and returns a [`Failure`](/type/Failure) of type [`X::IO::Rmdir`](/type/X/IO/Rmdir) if the directory cannot be removed (e.g. the directory is not empty, or the path is not a directory). Subroutine form returns a list of directories that were successfully deleted. To delete non-empty directory, see [rmtree in `File::Directory::Tree` module](https://github.com/labster/p6-file-directory-tree).
## dist_zef-raku-community-modules-Test-Class.md [![Actions Status](https://github.com/raku-community-modules/Test-Class/workflows/test/badge.svg)](https://github.com/raku-community-modules/Test-Class/actions) # NAME Test::Class - Raku version of Perl's Test::Class # SYNOPSIS ``` use Dest::Class; ``` # DESCRIPTION Some people at work are enamored of Perl's Test::Class, so I thought I'd have a look at it. This module is an attempt to recreate much of the same functionality for Raku. There are no docs yet. See the programs in examples/ for how to use it. Random things that come to mind though: * * this Test::Class is a role that you can compose into your own classes * * Instead of running Test::Class.run-tests, you execute YourClass.run-tests or Test::Class.run-tests(YourClass) * * where in Perl you'd say "sub foo : Test", here you'd say "method foo is test" * * instead of ": Test(no\_plan)", you say "is test(\*)" or "is tests" * * this Test::Class will also export the Test routines so that you don't have to (i.e., in Perl you'd need to say "use Test::Class; use Test::More;" if you wanted to use the is(), ok(), etc. routines. For this version of Test::Class, you just say "use Test::Class;" and you've automatically got those routines in your lexical scope) # AUTHOR Jonathan Scott Duff # COPYRIGHT AND LICENSE Copyright 2015 - 2017 Jonathan Scott Duff Copyright 2018 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-jnthn-Spreadsheet-XLSX.md # Spreadsheet::XLSX A Raku module for working with Excel spreadsheets (XLSX format), both reading existing files, creating new files, or modifying existing files and saving the changes. Of note, it: * Knows how to lazily load sheet content, so if you don't look at a sheet then time won't be spent deserializing it (down to a cell level, even) * In the modification scenario, tries to leave as much intact as it can, meaning that it's possible to poke data into a sheet more complex than could be produced by the module from scratch * Only depends on the Raku LibXML and Libarchive modules (and their respective native dependencies) This module is currently in development, and supports the subset of XLSX format features that were immediately needed for the use-case it was built for. That isn't so much, for now, but it will handle the most common needs: * Enumerating worksheets * Reading text and numbers from cells on a worksheet * Creating new workbooks with worksheets with text and number cells * Setting basic styles and number formats on cells in newly created worksheets * Reading a workbook, making modifications, and saving it again * Reading and writing column properties (such as column width) ## Synopsis ### Reading existing workbooks ``` use Spreadsheet::XLSX; # Read a workbook from an existing file (can pass IO::Path or a # Blob in the case it was uploaded). my $workbook = Spreadsheet::XLSX.load('accounts.xlsx'); # Get worksheets. say "Workbook has {$workbook.worksheets.elems} sheets"; # Get the name of a worksheet. say $workbook.worksheets.name; # Get cell values (indexing is zero-based, done as a multi-dimensional array # indexing operation [row ; column]. my $cells = $workbook.worksheets[0].cells; say .value with $cells[0;0]; # A1 say .value with $cells[0;1]; # B1 say .value with $cells[1;0]; # A2 say .value with $cells[1;1]; # B2 ``` ### Creating new workbooks ``` use Spreadsheet::XLSX; # Create a new workbook and add some worksheets to it. my $workbook = Spreadsheet::XLSX.new; my $sheet-a = $workbook.create-worksheet('Ingredients'); my $sheet-b = $workbook.create-worksheet('Matching Drinks'); # Put some data into a worksheet and style it. This is how the model # actually works (useful if you want to add styles later). $sheet-a.cells[0;0] = Spreadsheet::XLSX::Cell::Text.new(value => 'Ingredient'); $sheet-a.cells[0;0].style.bold = True; $sheet-a.cells[0;1] = Spreadsheet::XLSX::Cell::Text.new(value => 'Quantity'); $sheet-a.cells[0;1].style.bold = True; $sheet-a.cells[1;0] = Spreadsheet::XLSX::Cell::Text.new(value => 'Eggs'); $sheet-a.cells[1;1] = Spreadsheet::XLSX::Cell::Number.new(value => 6); $sheet-a.cells[1;1].style.number-format = '#,###'; # However, there is a convenience form too. $sheet-a.set(0, 0, 'Ingredient', :bold); $sheet-a.set(0, 1, 'Quantity', :bold); $sheet-a.set(1, 0, 'Eggs'); $sheet-a.set(1, 1, 6, :number-format('#,###')); # Save it to a file (string or IO::Path name). $workbook.save("foo.xlsx"); # Or get it as a blob, e.g. for a HTTP response. my $blob = $workbook.to-blob(); ``` ## Credits Thanks goes to [Agrammon](https://agrammon.ch/) for making the development of this module possible. If you need further development on the module and are willing to fund it (or other Raku ecosystem work), you can get in contact with [Edument](https://www.edument.se/en) or [Oetiker+Partner](https://www.oetiker.ch/en/).
## dist_zef-lizmat-DirHandle.md [![Actions Status](https://github.com/lizmat/DirHandle/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/DirHandle/actions) [![Actions Status](https://github.com/lizmat/DirHandle/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/DirHandle/actions) [![Actions Status](https://github.com/lizmat/DirHandle/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/DirHandle/actions) # NAME Raku port of Perl's DirHandle module # SYNOPSIS ``` use DirHandle; with Dirhandle.new(".") -> $d { while $d.read -> $entry { something($entry) } $d->rewind; while $d.read(Mu) { something_else($_) } $d.close; } ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `DirHandle` module as closely as possible in the Raku Programming Language. The DirHandle object provides an alternative interface to the `opendir`, `closedir`, `readdir`, `telldir`, `seekdir` and `rewinddir` functions. The only objective benefit to using DirHandle is that it avoids namespace pollution. # PORTING CAVEATS ## Handling void context Since Raku does not have a concept like void context, one needs to specify `Mu` as the only positional parameter with `read` to mimic the behaviour of `DirHandle.read` of Perl in void context. Please note that due to optimizations in Raku from version `6.d` onwards, it is no longer possible to (always) assign to `$_` in the caller's scope. So this either locks your code into `6.c`, or you will need to change your code to do explicit assignment with the `read` method. ## Extra methods The Perl version of `DirHandle` for some mysterious reason does not contain methods for performing a `telldir` or a `seekdir`. The Raku version **does** contain equivalent methods `tell` and `seek`. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! Source can be located at: <https://github.com/lizmat/DirHandle> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023, 2024 Elizabeth Mattijsen Re-imagined from Perl as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## copy.md copy Combined from primary sources listed below. # [In Parameter](#___top "go to top of document")[§](#(Parameter)_method_copy "direct link") See primary documentation [in context](/type/Parameter#method_copy) for **method copy**. ```raku method copy(Parameter:D: --> Bool:D) ``` Returns `True` for [`is copy`](/language/signatures#Parameter_traits_and_modifiers) parameters. ```raku my Signature $sig = :(Str $x, Bool :$is-named is copy); say $sig.params[0].copy; # OUTPUT: «False␤» say $sig.params[1].copy; # OUTPUT: «True␤» ``` # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_routine_copy "direct link") See primary documentation [in context](/type/IO/Path#routine_copy) for **routine copy**. ```raku method copy(IO::Path:D: IO() $to, :$createonly --> Bool:D) sub copy(IO() $from, IO() $to, :$createonly --> Bool:D) ``` Copies a file. Returns `True` on success; [fails](/routine/fail) with [`X::IO::Copy`](/type/X/IO/Copy) if `:$createonly` is `True` and the `$to` path already exists or if the operation failed for some other reason, such as when `$to` and `$from` are the same file.
## dist_cpan-KAIEPI-Kind.md [![Build Status](https://travis-ci.com/Kaiepi/p6-Kind.svg?branch=master)](https://travis-ci.com/Kaiepi/p6-Kind) # NAME Kind - Typechecking based on kinds # SYNOPSIS ``` use Kind; my constant Class = Kind[Metamodel::ClassHOW]; proto sub is-class(Mu --> Bool:D) {*} multi sub is-class(Mu $ where Class --> True) { } multi sub is-class(Mu --> False) { } say Str.&is-class; # OUTPUT: True say Blob.&is-class; # OUTPUT: False ``` # DESCRIPTION Kind is an uninstantiable parametric type that can be used to typecheck values based off their kind. If parameterized, it may be used in a `where` clause or on the right-hand side of a smartmatch to typecheck a value's HOW against its type parameter. Kind is documented. You can view the documentation for it and its methods at any time using `WHY`. For examples of how to use Kind with any of Rakudo's kinds, see `t/01-kind.t`. # METAMETHODS ## method parameterize ``` method ^parameterize(Kind:U $this is raw, Mu \K --> Kind:U) { } ``` Mixes in `kind` and `ACCEPTS` methods. See below. Some useful values with which to parameterize Kind are: * a metaclass or metarole ``` # Smartmatches any class. Kind[Metamodel::ClassHOW] ``` * a junction of metaclasses or metaroles ``` # Smartmatches any type that supports naming, versioning, and documenting. Kind[Metamodel::Naming & Metamodel::Versioning & Metamodel::Documenting] ``` * a block ``` # Smartmatches any parametric type. Kind[{ use nqp; nqp::hllbool(nqp::can($_, 'parameterize')) }] ``` * a metaobject ``` # This class' metamethods ensure they can only be called with itself or its # subclasses. class Configurable { my Map:D %CONFIGURATIONS{ObjAt:D}; method ^configure(Configurable:_ $this where Kind[self], %configuration --> Map:D) { %CONFIGURATIONS{$this.WHAT.WHICH} := %configuration.Map } method ^configuration(Configurable:_ $this where Kind[self] --> Map:D) { %CONFIGURATIONS{$this.WHAT.WHICH} // Map.new } } ``` # METHODS ## method ACCEPTS ``` method ACCEPTS(Kind:U: Mu $checker is raw) { } ``` Returns `True` if the HOW of `$checker` typechecks against `Kind`'s type parameter, otherwise returns `False`. If `Kind`'s type parameter has an `ACCEPTS` method, this will smartmatch the HOW of `$checker` against it; otherwise, `Metamodel::Primitives.is_type` will be called with `$checker`'s HOW and it. Most of the time, the former will be the case; the latter behaviour exists because it's not guaranteed `K` will actually have `Mu`'s methods (this is case with Rakudo's metaroles). ## method kind ``` method kind(Kind:U: --> Mu) { } ``` Returns `Kind`'s type parameter. # AUTHOR Ben Davies (Kaiepi) # COPYRIGHT AND LICENSE Copyright 2020 Ben Davies This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-ALOREN-pack6.md An tools can easily create CPAN tarball for you! # Usage: ``` pack6 [module@*] [OPTIONs] ``` ## Example ``` pack6 . -md -ex .idea -ex raku-pack6.iml ``` This command will create a tarball for pack6. ## Options * `-d` ``` Print debug message ``` * `-ex=<array>` ``` Exclude file from module source, in default are .precomp and .git. ``` * `-h` ``` Print the help message. ``` * `-md` ``` Require module CPAN::Convert wrap the &*pack6-hook, convert all the asciidoc to markdown. ``` * `-out=<string>` ``` Set the pack output directory, in default is current directory. ``` * `-pp=<array>` ``` User can create a module like CPAN::Convert hook the &*pack6-hook. Pack6 will call &*pack6-hook on output directory, in default do nothing. ``` * `-v` ``` Print the version information. ``` * `-ver=<string>` ``` Using ver instead of version info in META6.json. ``` # Installation * install with zef ``` zef install pack6 ``` # Lincese The MIT License (MIT).
## dist_cpan-FRITH-Math-Libgsl-Statistics.md [![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-Statistics/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-Statistics/actions) # NAME Math::Libgsl::Statistics - An interface to libgsl, the Gnu Scientific Library - Statistics # SYNOPSIS ``` use Math::Libgsl::Statistics; my @data = ^10; say "mean = { mean(@data) }, variance = { variance(@data) }"; ``` # DESCRIPTION Math::Libgsl::Statistics is an interface to the Statistics functions of libgsl, the Gnu Scientific Library. The functions in this module come in 10 data types: * Math::Libgsl::Statistics (default: num64) * Math::Libgsl::Statistics::Num32 * Math::Libgsl::Statistics::Int8 * Math::Libgsl::Statistics::Int16 * Math::Libgsl::Statistics::Int32 * Math::Libgsl::Statistics::Int64 * Math::Libgsl::Statistics::UInt8 * Math::Libgsl::Statistics::UInt16 * Math::Libgsl::Statistics::UInt32 * Math::Libgsl::Statistics::UInt64 All the following functions are available for the classes correspondig to each datatype, except where noted. ### mean(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the arithmetic mean of @data. ### variance(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the estimated variance of @data. This function computes the mean, if you already computed the mean, use the next function. ### variance-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride) This function returns the sample variance of @data relative to the given value of $mean. ### sd(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the estimated standard deviation of @data. ### sd-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the sample standard deviation of @data relative to the given value of $mean. ### tss(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) These functions return the total sum of squares (TSS) of @data. ### tss-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) These functions return the total sum of squares (TSS) of @data relative to the given value of $mean. ### variance-with-fixed-mean(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes an unbiased estimate of the variance of @data when the population mean $mean of the underlying distribution is known a priori. ### sd-with-fixed-mean(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function calculates the standard deviation of @data for a fixed population mean $mean. ### absdev(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the absolute deviation from the mean of @data. ### absdev-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the absolute deviation of the dataset @data relative to the given value of $mean. ### skew(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the skewness of @data. ### skew-m-sd(@data!, Num() $mean!, Num() $sd!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the skewness of the dataset @data using the given values of the mean $mean and standard deviation $sd, ### kurtosis(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the kurtosis of @data. ### kurtosis-m-sd(@data!, Num() $mean!, Num() $sd!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the kurtosis of the dataset @data using the given values of the mean $mean and standard deviation $sd, ### autocorrelation(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the lag-1 autocorrelation of the dataset @data. ### autocorrelation-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the lag-1 autocorrelation of the dataset @data using the given value of the mean $mean. ### covariance(@data1!, @data2! where \*.elems == @data1.elems, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num) This function computes the covariance of the datasets @data1 and @data2. ### covariance-m(@data1!, @data2! where \*.elems == @data1.elems, Num() $mean1!, Num() $mean2!, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num) This function computes the covariance of the datasets @data1 and @data2 using the given values of the means, $mean1 and $mean2. ### correlation(@data1!, @data2! where \*.elems == @data1.elems, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num) This function efficiently computes the Pearson correlation coefficient between the datasets @data1 and @data2. ### spearman(@data1!, @data2! where \*.elems == @data1.elems, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num) This function computes the Spearman rank correlation coefficient between the datasets @data1 and @data2. ### wmean(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the weighted mean of the dataset @data using the set of weights @w. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wvariance(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the estimated variance of the dataset @data using the set of weights @w. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wvariance-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the estimated variance of the weighted dataset @data using the given weighted mean $wmean. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wsd(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the standard deviation of the weighted dataset @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wsd-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the standard deviation of the weighted dataset @data using the given weighted mean $wmean. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wvariance-with-fixed-mean(@w!, @data!, Num() $mean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes an unbiased estimate of the variance of the weighted dataset @data when the population mean $mean of the underlying distribution is known a priori. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wsd-with-fixed-mean(@w!, @data!, Num() $mean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes an unbiased estimate of the standard deviation of the weighted dataset @data when the population mean $mean of the underlying distribution is known a priori. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wtss(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) These functions return the weighted total sum of squares (TSS) of @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wtss-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) These functions return the weighted total sum of squares (TSS) of @data when the population mean $mean of the underlying distribution is known a priori. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wabsdev(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the weighted absolute deviation from the weighted mean of @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wabsdev-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the absolute deviation of the weighted dataset @data about the given weighted mean $wmean. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wskew(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the weighted skewness of the dataset @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wskew-m-sd(@w!, @data!, Num() $wmean!, Num() $wsd!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the weighted skewness of the dataset @data using the given values of the weighted mean and weighted standard deviation, $wmean and $wsd. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wkurtosis(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the weighted kurtosis of the dataset @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### wkurtosis-m-sd(@w!, @data!, Num() $wmean!, Num() $wsd!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function computes the weighted kurtosis of the dataset @data using the given values of the weighted mean and weighted standard deviation, $wmean and $wsd. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32. ### smax(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the maximum value in @data. ### smin(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the minimum value in @data. ### sminmax(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> List) This function returns both the minimum and maximum values in @data in a single pass. ### smax-index(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Int) This function returns the index of the maximum value in @data. ### smin-index(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Int) This function returns the index of the minimum value in @data. ### sminmax-index(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> List) This function returns the indexes of the minimum and maximum values in @data in a single pass. ### median-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) This function returns the median value of @sorted-data. ### median(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function returns the median value of @data. ### quantile-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Num() $percentile!, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) This function returns a quantile value of @sorted-data. The quantile is determined by the $percentile, a fraction between 0 and 1. For example, to compute the value of the 75th percentile $percentile should have the value 0.75. ### select(@data!, Int() $k, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) This function finds the k-th smallest element of the input array @data. ### trmean-from-sorted-data(Num() $alpha, @sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) This function returns the trimmed mean of @sorted-data. ### gastwirth-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) This function returns the Gastwirth location estimator of @sorted-data. ### mad0(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) ### mad(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num) These functions return the median absolute deviation of @data. The mad0 function calculates the MAD statistic without the bias correction scale factor. ### Sn0-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) ### Sn-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) These functions return the Sₙ statistic of @sorted-data. The Sn0 function calculates the Sₙ statistic without the bias correction scale factors. ### Qn0-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) ### Qn-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num) These functions return the Qₙ statistic of @sorted-data. The Qn0 function calculates the Qₙ statistic without the bias correction scale factors. # C Library Documentation For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format. # Prerequisites This module requires the libgsl library to be installed. Please follow the instructions below based on your platform: ## Debian Linux and Ubuntu 20.04 ``` sudo apt install libgsl23 libgsl-dev libgslcblas0 ``` That command will install libgslcblas0 as well, since it's used by the GSL. ## Ubuntu 18.04 libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries: * <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb> * <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb> * <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb> # Installation To install it using zef (a module management tool): ``` $ zef install Math::Libgsl::Statistics ``` # AUTHOR Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com) # COPYRIGHT AND LICENSE Copyright 2020 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-ugexe-Text-Table-Simple.md ## Text::Table::Simple Create basic tables from a two dimensional array ## Synopsis ``` use Text::Table::Simple; my @columns = <id name email>; my @rows = ( [1,"John Doe",'johndoe@cpan.org'], [2,'Jane Doe','mrsjanedoe@hushmail.com'], ); my @table = lol2table(@columns,@rows); .say for @table; # O----O----------O-------------------------O # | id | name | email | # O====O==========O=========================O # | 1 | John Doe | johndoe@cpan.org | # | 2 | Jane Doe | mrsjanedoe@hushmail.com | # ------------------------------------------- ``` ## Exports #### lol2table(@body, \*%options --> Str @rows) #### lol2table(@header, @body, @footer?, \*%options --> Str @rows) Create a an array of strings that can be printed line by line to create a table view of the data. ``` > my @cols = <XXX XXXX>; > my @rows = ([1,2],[3,4]); > say lol2table(@cols, @rows).join("\n"); O-----O------O | XXX | XXXX | O=====O======O | 1 | 2 | | 3 | 4 | -------------- ``` ##### Options ``` # default values %options = %( rows => { column_separator => '|', corner_marker => '-', bottom_border => '-', }, headers => { top_border => '-', column_separator => '|', corner_marker => 'O', bottom_border => '=', }, footers => { column_separator => 'I', corner_marker => '%', bottom_border => '*', }, ); ``` You can replace any of the default options by passing in a replacement. C<corner\_marker> is used when more specific corner markers are not set. ``` > my %options = rows => { column_separator => '│', bottom_left_corner_marker => '└', bottom_right_corner_marker => '┘', bottom_corner_marker => '┴', bottom_border => '─', }, headers => { top_border => '═', column_separator => '│', top_corner_marker => '╤', top_left_corner_marker => '╒', top_right_corner_marker => '╕', bottom_left_corner_marker => '╞', bottom_right_corner_marker => '╡', bottom_corner_marker => '╪', bottom_border => '═', }; > my @columns = <id name email>; > my @rows = ( [1,"John Doe",'johndoe@cpan.org'], [2,'Jane Doe','mrsjanedoe@hushmail.com'], ); > .put for lol2table(@columns, @rows, |%options); ╒════╤══════════╤═════════════════════════╕ │ id │ name │ email │ ╞════╪══════════╪═════════════════════════╡ │ 1 │ John Doe │ johndoe@cpan.org │ │ 2 │ Jane Doe │ mrsjanedoe@hushmail.com │ └────┴──────────┴─────────────────────────┘ ``` ## Examples Showing your Benchmark output: ``` use Text::Table::Simple; use Text::Levenshtein::Damerau; use Benchmark; my $str1 = "lsd"; my $str2 = "lds"; my %results = timethese(1000, { 'dld' => sub { Text::Levenshtein::Damerau::{"&dld($str1,$str2)"} }, 'ld ' => sub { Text::Levenshtein::Damerau::{"&ld($str1,$str2)"} }, }); my @headers = ['func','start','end','diff','avg']; my @rows = %results.map: {.key, .value.Slip} my @table = lol2table(@headers,@rows); .say for @table; ``` Also see the [examples](https://github.com/ugexe/Raku-Text--Table--Simple/tree/main/examples) directory.
## dist_zef-ulisesb-ERK.md # ERK ERK (Embedded RaKu) is a templating engine for evaluating Raku code embedded in arbitrary text files. Heavily inspired by [ESH](https://github.com/jirutka/esh) (Embedded SHell), which is itself like [ERB](https://github.com/ruby/erb) (Embedded RuBy). See `lib/ERK.rakumod` and `bin/erk` for more information.
## spec.md class IO::Spec Platform specific operations on file and directory paths ```raku class IO::Spec { } ``` Objects of this class are not used directly but as a sub-class specific to the platform Raku is running on via the `$*SPEC` variable which will contain an object of the appropriate type. The sub-classes are documented separately, with the platform-specific differences documented in [`IO::Spec::Cygwin`](/type/IO/Spec/Cygwin), [`IO::Spec::QNX`](/type/IO/Spec/QNX), [`IO::Spec::Unix`](/type/IO/Spec/Unix) and [`IO::Spec::Win32`](/type/IO/Spec/Win32). # [About sub-classes IO::Spec::\*](#class_IO::Spec "go to top of document")[§](#About_sub-classes_IO::Spec::* "direct link") The `IO::Spec::*` classes provide low-level path operations. Unless you're creating your own high-level path manipulation routines, you don't need to use `IO::Spec::*`. Use [`IO::Path`](/type/IO/Path) instead. Beware that no special validation is done by these classes (e.g. check whether path contains a null character). It is the job of higher-level classes, like [`IO::Path`](/type/IO/Path), to do that. # [Methods](#class_IO::Spec "go to top of document")[§](#Methods "direct link")
## dist_zef-jonathanstowe-LibraryCheck.md # LibraryCheck Determine whether a shared library is available to be loaded by Raku ![Build Status](https://github.com/jonathanstowe/LibraryCheck/workflows/CI/badge.svg) ## Synopsis ``` use LibraryCheck; if !library-exists('sndfile', v1) { die "Cannot load libsndfile"; } ``` ## Description This module provides a mechanism that will determine whether a named shared library is available and can be used by NativeCall. It exports a single function `library-exists` that returns a boolean to indicate whether the named shared library can be loaded and used. The library name should be supplied without any (OS-dependent) "lib" prefix and no extension (for example, `'crypt'` for `libcrypt.so`). This can be used in a builder to determine whether a module has a chance of working (and possibly aborting the build), or in tests to cause the tests that may rely on a missing library to be skipped. The second positional argument is a <Version> object that indicates the version of the library that is required, it defaults to `v1`, if you don't care which version exists then it possible to pass a new Version object without any version parts (i.e., `Version.new()`). Many systems require that the version is specified, so if portability is a concern, an actual version number should be given. If the `:exception` adverb is passed to `library-exists` then an exception (`X::NoLibrary`) will be thrown if the library isn't available rather than returning `False`. So the case above can be more simply written as: ``` library-check('sndfile', v1, :exception); ``` The implementation is somewhat of a hack currently and definitely shouldn't be taken as an example of nice Raku code. ## Installation Assuming you have a working Rakudo installation you should be able to install this with *zef*: ``` # From the source directory zef install . # Remote installation zef install LibraryCheck ``` Other install mechanisms may be become available in the future. ## Support Suggestions/patches are welcomed via github at <https://github.com/jonathanstowe/LibraryCheck/issues> I'd be particularly interested in having it work properly on all the platforms that rakudo will work on. ## Licence Please see the <LICENCE> file in the distribution. © Jonathan Stowe 2015 - 2021
## dist_zef-raku-community-modules-Testo.md # NAME [Test in a Raku container](https://github.com/raku-community-modules/Testo/actions/workflows/test.yaml) Testo - Raku Testing Done Right # SYNOPSIS ``` use Testo; plan 10; # `is` uses smart match semantics: is 'foobar', *.contains('foo'); # test passes is (1, 2, (3, 4)), [1, 2, [3, 4]]; # test passes is (1, 2, (3, 4)), '1 2 3 4'; # test fails; unlike Test's `is` is 'foobar', /foo/; # no more Test's `like`; just use a regex is 'foobar', Str; # no more Test's `isa-ok`; just use a type object is 'foobar', Stringy; # no more Test's `does-ok`; just use a type object ok $number < 0; nok $io-path.e, 'path does not exist'; # uses `eqv` semantics and works right with Seqs is-eqv (1, 2).Seq, (1, 2); # test fails; unlike Test's `is-deeply` # execute a program with some args and STDIN input and smartmatch its # STDERR, STDOUT, and exit status: is-run $*EXECUTABLE, :in<hi!>, :args['-e', 'say $*IN.uc'], :out(/'HI!'/), 'can say hi'; # run a bunch of tests as a group; like Test's `subtest` group 'a bunch of test' => 3 => { is 1, 1; is 4, 4; is 'foobar', /foo/; } ``` # FEATURES * Tests routines designed for testing Raku code * Configurable output: TAP, JSON, or even a custom type! * Easy to extend with your own custom test routines! # BETA-WARE Note this module is still in fleshing-out stage. JSON output type, more test functions, and docs for the classes under the hood and customization are yet to be made, but will be made soon! # DESCRIPTION Testo is the New and Improved version of `Test` that you can use *instead* of `Test` to test all of your code and generate output in [TAP](https://testanything.org/tap-specification.html), JSON, or any other custom format! # EXPORTED ROUTINES ## `plan` Defined as: ``` sub plan (Int $number-of-tests); ``` Specifies the number of tests you plan to run. ``` plan 5; ``` ## `is` Defined as: ``` sub is (Mu $expected, Mu $got, Str $desc?); ``` Testo's workhorse you'll use for most testing. Performs the test using [smartmatch](https://docs.raku.org/routine/~~.html) semantics; i.e. it's equivalent to doing `($expected ~~ $got).Bool`, with the test passing if the result is `True`. An optional description of the test can be specified ``` is 'foobar', *.contains('foo'); # test passes is (1, 2, (3, 4)), [1, 2, [3, 4]]; # test passes is (1, 2, (3, 4)), '1 2 3 4'; # test fails; unlike Test's `is` is 'foobar', /foo/; # no more Test's `like`; just use a regex is 'foobar', none /foo/; # no more Test's `unlike`; just use a none Junction is 'foobar', Str; # no more Test's `isa-ok`; just use a type object is 'foobar', Stringy; # no more Test's `does-ok`; just use a type object is 1, 2, 'some description'; # you can provide optional description too ``` Note that Testo does not provide several of [Test's tests](https://docs.raku.org/language/testing), such as `isnt`, `like`, `unlike`, `isa-ok` or `does-ok`, as those are replaced by `is` with Regex/type objects/`none` Junctions as arguments. ## `is-eqv` Defined as: ``` sub is-eqv (Mu $expected, Mu $got, Str $desc?); ``` Uses [`eqv`](https://docs.raku.org/routine/eqv) semantics to perform the test. An optional description of the test can be specified. ``` is-eqv (1, 2).Seq, (1, 2); # fails; types do not match is-eqv 1.0, 1; # fails; types do not match is-eqv 1, 1; # succeeds; types and values match ``` ## `ok` and `nok` ``` ok $number < 0; nok $io-path.e, 'path does not exist'; ``` ## `is-run` ``` is-run $*EXECUTABLE, :in<hi!>, :args['-e', 'say $*IN.uc'], :out(/'HI!'/), 'can say hi'; is-run $*EXECUTABLE, :args['-e', '$*ERR.print: 42'], :err<42>, 'can err 42'; is-run $*EXECUTABLE, :args['-e', 'die 42'], :err(*), :42status, 'can exit with exit code 42'; ``` **NOTE:** due to [a Rakudo bug RT#130781](https://github.com/Raku/old-issue-tracker/issues/6072) exit code is currently always reported as `0` Runs an executable (via [&run](https://docs.raku.org/routine/run)), optionally supplying extra args given as `:args[...]` or feeding STDIN with a `Str` or `Blob` data given via C<:in>. Runs three `is` tests on STDOUT, STDERR, and exit code expected values for which are provided via `:out`, `:err` and `:status` arguments respectively. If omitted, `:out` and `:err` default to empty string (`''`) and `:status` defaults to `0`. Use the [Whatever star](https://docs.raku.org/type/Whatever) (`*`) as the value for any of the three arguments (see `:err` in last example above). ## `group` ``` plan 1; # run a bunch of tests as a group; like Test's `subtest` group 'a bunch of tests' => 4 => { is 1, 1; is 4, 4; is 'foobar', /foo/; group 'nested bunch of tests; with manual `plan`' => { plan 2; is 1, 1; is 4, 4; } } ``` Similar to `Test`'s `subtest`. Groups a number of tests into a... group with its own plan. The entire group counts as 1 test towards the planned/ran number of tests. Takes a `Pair` as the argument that is either `Str:D $desc => &group-code` or `Str:D $desc => UInt:D $plan where .so => &group-code` (see code example above), the latter form lets you specify the plan for the group, while the former would require you to manually use `&plan` inside of the `&group-code`. Groups can be nested for any (reasonable) number of levels. --- #### REPOSITORY Fork this module on GitHub: <https://github.com/raku-community-modules/Testo> #### BUGS To report bugs or request features, please use <https://github.com/raku-community-modules/Testo/issues> #### AUTHOR Zoffix Znet #### LICENSE You can use and distribute this module under the terms of the The Artistic License 2.0. See the `LICENSE` file included in this distribution for complete details. Some portions of this software may be based on or re-use code of `Test` module shipped with [Rakudo 2107.04.03](http://rakudo.org/downloads/rakudo/), © 2017 by The Raku Foundation, under The Artistic License 2.0. The `META6.json` file of this distribution may be distributed and modified without restrictions or attribution.
## positionalbindfailover.md role PositionalBindFailover Failover for binding to a Positional ```raku role PositionalBindFailover { ... } ``` This role provides an interface by which an object can be coerced into a [`Positional`](/type/Positional) when binding to [`Positional`](/type/Positional) parameters. For example, [`Seq`](/type/Seq) type is not [`Positional`](/type/Positional), but you can still write the following, because it [does](/routine/does) `PositionalBindFailover` role: ```raku sub fifths(@a) { # @a is constraint to Positional @a[4]; } my $seq := gather { # a Seq, which is not Positional take $_ for 1..*; } say fifths($seq); # OUTPUT: «5␤» ``` The invocation of `fifths` in the example above would ordinarily give a type error, because `$seq` is of type [`Seq`](/type/Seq), which doesn't do the [`Positional`](/type/Positional) interface that the `@`-sigil implies. But the signature binder recognizes that [`Seq`](/type/Seq) does the `PositionalBindFailover` role, and calls its `cache` method to coerce it to a [`List`](/type/List), which does the [`Positional`](/type/Positional) role. The same happens with custom classes that do the role; they simply need to provide an `iterator` method that produces an [`Iterator`](/type/Iterator): ```raku class Foo does PositionalBindFailover { method iterator { class :: does Iterator { method pull-one { return 42 unless $++; IterationEnd } }.new } } sub first-five (@a) { @a[^5].say } first-five Foo.new; # OUTPUT: # OUTPUT: «(42 Nil Nil Nil Nil)␤» ``` # [Methods](#role_PositionalBindFailover "go to top of document")[§](#Methods "direct link") ## [method cache](#role_PositionalBindFailover "go to top of document")[§](#method_cache "direct link") ```raku method cache(PositionalBindFailover:D: --> List:D) ``` Returns a [`List`](/type/List) based on the `iterator` method, and caches it. Subsequent calls to `cache` always return the same [`List`](/type/List) object. ## [method list](#role_PositionalBindFailover "go to top of document")[§](#method_list "direct link") ```raku multi method list(::?CLASS:D:) ``` Returns a [`List`](/type/List) based on the `iterator` method without caching it. ## [method iterator](#role_PositionalBindFailover "go to top of document")[§](#method_iterator "direct link") ```raku method iterator(PositionalBindFailover:D:) { ... } ``` This method stub ensure that a class implementing role `PositionalBindFailover` provides an `iterator` method. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `PositionalBindFailover` raku-type-graph PositionalBindFailover PositionalBindFailover Sequence Sequence Sequence->PositionalBindFailover Mu Mu Any Any Any->Mu Iterable Iterable RaceSeq RaceSeq RaceSeq->Sequence RaceSeq->Any RaceSeq->Iterable Cool Cool Cool->Any Seq Seq Seq->Sequence Seq->Iterable Seq->Cool HyperSeq HyperSeq HyperSeq->Sequence HyperSeq->Any HyperSeq->Iterable [Expand chart above](/assets/typegraphs/PositionalBindFailover.svg)
## dist_cpan-MOZNION-Object-Container.md [![Build Status](https://travis-ci.org/moznion/p6-Object-Container.svg?branch=master)](https://travis-ci.org/moznion/p6-Object-Container) # NAME Object::Container - A simple container for object for perl6 # SYNOPSIS ## Instance method ``` use Object::Container; my $container = Object::Container.new; $container.register('obj1', $obj1); $container.register('obj2', $obj2); $container.get('obj1'); # <= equals $obj1 $container.get('obj2'); # <= equals $obj2 $container.get('not-existed'); # <= equals Nil ``` ## Class method (singleton) ``` use Object::Container; Object::Container.register('obj1', $obj1); Object::Container.register('obj2', $obj2); Object::Container.get('obj1'); # <= equals $obj1 Object::Container.get('obj2'); # <= equals $obj2 Object::Container.get('not-existed'); # <= equals Nil ``` # DESCRIPTION Object::Container is a simple container for object. A simple DI mechanism can be implemented easily by using this module. This module provides following features; * Register object to container * Find object from container * Remove registered object from container * Clear container # METHODS ## `register(Str:D $name, Any:D $object)` Registers the instantiated object with name in the container. ## `register(Str:D $name, Callable:D $initializer)` Registers the `Callable` as initializer to instantiate the object with the name in the container. This method instantiates the object with calling `Callable`. This is a **lazy** way to instantiate; it means it defers instantiation (i.e. calling `Callable`) until `get(...)` is invoked. ``` my $container = Object::Container.new; my $initializer = sub { # Reach here when `$container.get()` is called (only at once) return $something; }; $container.register('obj-name', $initializer); ``` ## `get(Str:D $name) returns Any` Finds the registered object from the container by the name and return it. If the object is missing, it returns `Nil`. ## `remove(Str:D $name) returns Bool` Removes the registered object from the container by the name. It returns whether the registered object was existed in the container or not. ## `clear()` Clears the container. In other words, it rewinds the container to its initial state. # Singleton pattern If you use this module with class method (e.g. `Object::Container.register(...)`), this module handles the container as singleton object. # AUTHOR moznion [moznion@gmail.com](mailto:moznion@gmail.com) # COPYRIGHT AND LICENSE Copyright 2017- moznion This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## stash.md class Stash Table for "our"-scoped symbols ```raku class Stash is Hash { } ``` A `Stash` is a hash that is used for symbol tables at the package scoping level in Raku. To get a Stash, you can call the `.WHO` pseudo-method on a package (because it answers the question *who lives here?*), or if you write the package name as a literal, append two colons: ```raku class Boring { class Nested { }; our sub package_sub { } my sub lexical { }; method a_method() { } } say Boring::.^name; # OUTPUT: «Stash␤» say Boring.WHO === Boring::; # OUTPUT: «True␤» ``` Since it inherits from [`Hash`](/type/Hash), you can use all the usual hash functionality: ```raku say Boring::.keys.sort; # OUTPUT: «(&package_sub Nested)␤» say Boring::<Nested>; # OUTPUT: «(Nested)␤» ``` As the example above shows only "our"-scoped things appear in the `Stash` (nested classes are "our" by default, but can be excluded with "my".) Lexicals and methods are not included in a Stash, since they do not live in the package table. Lexicals live in a separate lexical pad, which is only visible from inside the scope. Methods (in the case that the package is also a class) have a separate method table, and are accessible through introspection on the class itself, via `.can` and `.^methods`. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Stash` raku-type-graph Stash Stash Hash Hash Stash->Hash Mu Mu Any Any Any->Mu Cool Cool Cool->Any Iterable Iterable Associative Associative Map Map Map->Cool Map->Iterable Map->Associative Hash->Map [Expand chart above](/assets/typegraphs/Stash.svg)
## dist_zef-2colours-Ddt.md # NAME Ddt - Distribution Development Tool # SYNOPSIS ``` $ ddt --license-name=LGPL new Foo::Bar # create Foo-Bar distribution $ cd Foo-Bar $ ddt build # build the distribution and re-generate # README.md & META6.json $ ddt -C test # Run tests when files change ``` # DESCRIPTION **Ddt** is an authoring and distribution development tool for Raku. It provides scaffolding for generating new distributions, packages, modules, grammers, classes and roles. # WARNING This project is a technology preview. It may change at any point. The only API which can be considered stable up to the `v1.0` is the command line interface. # USAGE ``` ddt [--license-name=«NAME»] new <module> -- Create new module ddt build -- Build the distribution and update README.md ddt [-C|--continues] test [<tests> …] -- Run distribution tests ddt release -- Make release ddt hack <identity> [<dir>] -- Checkout a Distribution and start hacking on it ddt generate class <name> -- Generate a class ddt generate role <name> -- Generate a role ddt generate package <name> -- Generate a package ddt generate grammar <name> -- Generate a grammar ddt generate module <name> -- Generate a module ddt generate test <name> [<description>] -- Generate stub test file ddt [-v] deps distri -- Show all the modules used ddt [-u|--update] deps -- Update META6.json dependencies ddt watch [<cmd>…] -- Watch lib/, bin/ & t/ for changes respecting .gitignore and execute given cmd ``` # INSTALLATION ``` # with zef > zef install Ddt ``` # Differences to Mi6 * Support for different licenses via `License::Software` * META6 is generated using `META6` * Meta test * Use prove for tests * Run tests on changes * Extended .gitignore * Support for different licenses * Support for Distributions with a hyphen in the name # FAQ * How can I manage depends, build-depends, test-depends? Use `ddt -u deps` * Where is the spec of META6.json? The documentation site describes the current practices pretty well at <https://docs.raku.org/language/modules#Distributing_modules>. The original design document of META6.json is available at <http://design.perl6.org/S22.html>. # SEE ALSO * <https://github.com/skaji/mi6> * <https://github.com/tokuhirom/Minilla> * <https://github.com/rjbs/Dist-Zilla> # AUTHOR * Bahtiar `kalkin-` Gadimov [bahtiar@gadimov.de](mailto:bahtiar@gadimov.de) * Shoichi Kaji [skaji@cpan.org](mailto:skaji@cpan.org) # COPYRIGHT AND LICENSE * Copyright © 2015 Shoichi Kaji * Copyright © 2016-2017 Bahtiar `kalkin-` Gadimov This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-antononcube-DSL-Bulgarian.md # Raku DSL::Bulgarian ## In brief This Raku package facilitates the specification computational workflows using natural language commands in Bulgarian. Using the Domain Specific Languages (DSLs) executable code is generated for different programming languages: Julia, Python, R, Raku, Wolfram Language. Translation to other natural languages is also done: English, Korean, Russian, Spanish. --- ## Data query (wrangling) workflows Translate Bulgarian data wrangling specifications to different natural and programming languages: ``` use DSL::English::DataQueryWorkflows; my $command = ' зареди данните iris; вземи елементите от 1 до 120; филтрирай чрез Sepal.Width е по-голямо от 2.4 и Petal.Length е по-малко от 5.5; групирай с колоната Species; покажи размерите '; for <English Python::pandas Raku::Reshapers Spanish Russian> -> $t { say '=' x 60, "\n", $t, "\n", '-' x 60; say ToDataQueryWorkflowCode($command, $t, language => 'Bulgarian', format => 'code'); } ``` ``` # ============================================================ # English # ------------------------------------------------------------ # load the data table: "iris" # take elements from 1 to 120 # filter with the predicate: ((Sepal.Width greater than 2.4) и (Petal.Length less than 5.5)) # group by the columns: Species # show the count(s) # ============================================================ # Python::pandas # ------------------------------------------------------------ # obj = example_dataset('iris') # obj = obj.iloc[1-1:120] # obj = obj[((obj["Sepal.Width"]> 2.4) & (obj["Petal.Length"]< 5.5))] # obj = obj.groupby(["Species"]) # print(obj.size()) # ============================================================ # Raku::Reshapers # ------------------------------------------------------------ # my $obj = example-dataset('iris') ; # $obj = $obj[ (1 - 1) ... (120 - 1 ) ] ; # $obj = $obj.grep({ $_{"Sepal.Width"} > 2.4 and $_{"Petal.Length"} < 5.5 }).Array ; # $obj = group-by($obj, "Species") ; # say "counts: ", $obj>>.elems # ============================================================ # Spanish # ------------------------------------------------------------ # cargar la tabla: "iris" # tomar los elementos de 1 a 120 # filtrar con la condicion: ((Sepal.Width más grande 2.4) y (Petal.Length menos 5.5)) # agrupar con columnas: "Species" # mostrar recuentos # ============================================================ # Russian # ------------------------------------------------------------ # загрузить таблицу: "iris" # взять элементы с 1 по 120 # фильтровать с предикатом: ((Sepal.Width больше 2.4) и (Petal.Length меньше 5.5)) # групировать с колонками: Species # показать число ``` --- ## Classification workflows ``` use DSL::English::ClassificationWorkflows; my $command = ' използвай dfTitanic; раздели данните с цепещо съотношение 0.82; направи gradient boosted trees класификатор; покажи TruePositiveRate и FalsePositiveRate; '; for <English Russian WL::ClCon> -> $t { say '=' x 60, "\n", $t, "\n", '-' x 60; say ToClassificationWorkflowCode($command, $t, language => 'Bulgarian', format => 'code'); } ``` ``` # ============================================================ # English # ------------------------------------------------------------ # use the data: dfTitanic # split into training and testing data with the proportion 0.82 # train classifier with method: gradient boosted trees # ============================================================ # Russian # ------------------------------------------------------------ # использовать данные: dfTitanic # разделить данные на пропорцию 0.82 # обучить классификатор методом: gradient boosted trees # ============================================================ # WL::ClCon # ------------------------------------------------------------ # ClConUnit[ dfTitanic ] \[DoubleLongRightArrow] # ClConSplitData[ 0.82 ] \[DoubleLongRightArrow] # ClConMakeClassifier[ "GradientBoostedTrees" ] \[DoubleLongRightArrow] # ClConClassifierMeasurements[ {"Recall", "FalsePositiveRate"} ] \[DoubleLongRightArrow] ClConEchoValue[] ``` --- ## Latent Semantic Analysis ``` use DSL::English::LatentSemanticAnalysisWorkflows; my $command = ' създай със textHamlet; направи документ-термин матрица със автоматични стоп думи; приложи LSI функциите IDF, TermFrequency, и Cosine; извади 12 теми чрез NNMF и максимален брой стъпки 12; покажи таблица на темите с 12 термина; покажи текущата лентова стойност '; for <English Python::LSAMon R::LSAMon Russian> -> $t { say '=' x 60, "\n", $t, "\n", '-' x 60; say ToLatentSemanticAnalysisWorkflowCode($command, $t, language => 'Bulgarian', format => 'code'); } ``` ``` #ERROR: Possible misspelling of 'термини' as 'термина'. #ERROR: Possible misspelling of 'термини' as 'термина'. #ERROR: Possible misspelling of 'термини' as 'термина'. #ERROR: Possible misspelling of 'термини' as 'термина'. # ============================================================ # English # ------------------------------------------------------------ # create LSA object with the data: textHamlet # make the document-term matrix with the parameters: use the stop words: NULL # apply the latent semantic analysis (LSI) functions: global weight function : "IDF", local weight function : "None", normalizer function : "Cosine" # extract 12 topics using the parameters: method : Non-Negative Matrix Factorization (NNMF), max number of steps : 12 # show topics table using the parameters: numberOfTerms = 12 # show the pipeline value # ============================================================ # Python::LSAMon # ------------------------------------------------------------ # LatentSemanticAnalyzer(textHamlet).make_document_term_matrix( stop_words = None).apply_term_weight_functions(global_weight_func = "IDF", local_weight_func = "None", normalizer_func = "Cosine").extract_topics(number_of_topics = 12, method = "NNMF", max_steps = 12).echo_topics_table(numberOfTerms = 12).echo_value() # ============================================================ # R::LSAMon # ------------------------------------------------------------ # LSAMonUnit(textHamlet) %>% # LSAMonMakeDocumentTermMatrix( stopWords = NULL) %>% # LSAMonApplyTermWeightFunctions(globalWeightFunction = "IDF", localWeightFunction = "None", normalizerFunction = "Cosine") %>% # LSAMonExtractTopics( numberOfTopics = 12, method = "NNMF", maxSteps = 12) %>% # LSAMonEchoTopicsTable(numberOfTerms = 12) %>% # LSAMonEchoValue() # ============================================================ # Russian # ------------------------------------------------------------ # создать латентный семантический анализатор с данных: textHamlet # сделать матрицу документов-терминов с параметрами: стоп-слова: null # применять функции латентного семантического индексирования (LSI): глобальная весовая функция: "IDF", локальная весовая функция: "None", нормализующая функция: "Cosine" # извлечь 12 тем с параметрами: метод: Разложение Неотрицательных Матричных Факторов (NNMF), максимальное число шагов: 12 # показать таблицу темы по параметрам: numberOfTerms = 12 # показать текущее значение конвейера ``` --- ## Quantile Regression Workflows ``` use DSL::English::QuantileRegressionWorkflows; my $command = ' създай с dfTemperatureData; премахни липсващите стойности; покажи данново обобщение; премащабирай двете оси; изчисли квантилна регресия с 20 възела и вероятности от 0.1 до 0.9 със стъпка 0.1; покажи диаграма с дати; покажи чертеж на абсолютните грешки; покажи текущата лентова стойност '; for <English R::QRMon Russian WL::QRMon> -> $t { say '=' x 60, "\n", $t, "\n", '-' x 60; say ToQuantileRegressionWorkflowCode($command, $t, language => 'Bulgarian', format => 'code'); } ``` ``` #ERROR: Possible misspelling of 'възли' as 'възела'. #ERROR: Possible misspelling of 'възли' as 'възела'. #ERROR: Possible misspelling of 'възли' as 'възела'. #ERROR: Possible misspelling of 'възли' as 'възела'. # ============================================================ # English # ------------------------------------------------------------ # create quantile regression object with the data: dfTemperatureData # delete missing values # show data summary # rescale: over both regressor and value axes # compute quantile regression with parameters: degrees of freedom (knots): 20, automatic probabilities # show plot with parameters: use date axis # show plot of relative errors # show the pipeline value # ============================================================ # R::QRMon # ------------------------------------------------------------ # QRMonUnit( data = dfTemperatureData) %>% # QRMonDeleteMissing() %>% # QRMonEchoDataSummary() %>% # QRMonRescale(regressorAxisQ = TRUE, valueAxisQ = TRUE) %>% # QRMonQuantileRegression(df = 20, probabilities = seq(0.1, 0.9, 0.1)) %>% # QRMonPlot( datePlotQ = TRUE) %>% # QRMonErrorsPlot( relativeErrorsQ = TRUE) %>% # QRMonEchoValue() # ============================================================ # Russian # ------------------------------------------------------------ # создать объект квантильной регрессии с данными: dfTemperatureData # удалить пропущенные значения # показать сводку данных # перемасштабировать: по осям регрессии и значений # рассчитать квантильную регрессию с параметрами: степени свободы (узлы): 20, автоматическими вероятностями # показать диаграмму с параметрами: использованием оси дат # показать диаграму на относительных ошибок # показать текущее значение конвейера # ============================================================ # WL::QRMon # ------------------------------------------------------------ # QRMonUnit[dfTemperatureData] \[DoubleLongRightArrow] # QRMonDeleteMissing[] \[DoubleLongRightArrow] # QRMonEchoDataSummary[] \[DoubleLongRightArrow] # QRMonRescale["Axes"->{True, True}] \[DoubleLongRightArrow] # QRMonQuantileRegression["Knots" -> 20, "Probabilities" -> Range[0.1, 0.9, 0.1]] \[DoubleLongRightArrow] # QRMonDateListPlot[] \[DoubleLongRightArrow] # QRMonErrorPlots[ "RelativeErrors" -> True] \[DoubleLongRightArrow] # QRMonEchoValue[] ``` --- ## Recommender workflows ``` use DSL::English::RecommenderWorkflows; my $command = ' създай чрез dfTitanic; препоръчай със профила "male" и "died"; покажи текущата лентова стойност '; for <English Python::SMRMon R::SMRMon Russian> -> $t { say '=' x 60, "\n", $t, "\n", '-' x 60; say ToRecommenderWorkflowCode($command, $t, language => 'Bulgarian', format => 'code'); } ``` ``` # ============================================================ # English # ------------------------------------------------------------ # create with data table: dfTitanic # recommend with the profile: ["male", "died"] # show the pipeline value # ============================================================ # Python::SMRMon # ------------------------------------------------------------ # obj = SparseMatrixRecommender().create_from_wide_form(data = dfTitanic).recommend_by_profile( profile = ["male", "died"]).echo_value() # ============================================================ # R::SMRMon # ------------------------------------------------------------ # SMRMonCreate(data = dfTitanic) %>% # SMRMonRecommendByProfile( profile = c("male", "died")) %>% # SMRMonEchoValue() # ============================================================ # Russian # ------------------------------------------------------------ # создать с таблицу: dfTitanic # рекомендуй с профилю: ["male", "died"] # показать текущее значение конвейера ``` --- ## Implementation notes The rules in the file ["DataQueryPhrases.rakumod"](./lib/DSL/Bulgarian/DataQueryWorkflows/Grammar/DataQueryPhrases.rakumod) are derived from file ["DataQueryPhrases-template"](./lib/DSL/Bulgarian/DataQueryWorkflows/Grammar/DataQueryPhrases-template) using the package ["Grammar::TokenProcessing"](https://github.com/antononcube/Raku-Grammar-TokenProcessing) , [AAp3]. In order to have Bulgarian commands parsed and interpreted into code the steps taken were split into four phases: 1. Utilities preparation 2. Bulgarian words and phrases addition and preparation 3. Preliminary functionality experiments 4. Packages code refactoring ### Utilities preparation Since the beginning of the work on translation of the computational DSLs into programming code it was clear that some the required code transformations have to be automated. While doing the preparation work -- and in general, while the DSL-translation work matured -- it became clear that there are several directives to follow: 1. Make and use Command Line Interface (CLI) scripts that do code transformation or generation. 2. Adhere to of the [Eric Raymond's 17 Unix Rules](https://en.wikipedia.org/wiki/Unix_philosophy), [Wk1]: * *Make data complicated when required, not the program* * *Write abstract programs that generate code instead of writing code by hand* In order to facilitate the "from Bulgarian" project the package "Grammar::TokenProcessing", [AAp3], was "finalized." The initial versions of that package were used from the very beginning of the DSLs grammar development in order to facilitate handling of misspellings. ### (Current) recipe This sub-section lists the steps for endowing a certain already developed workflows DSL package with Bulgarian translations. Denote the DSL workflows we focus on as DOMAIN (workflows.) For example, DOMAIN can stand for `DataQueryWorkflows`, or `RecommenderWorkflows`. *Remark:* In the recipe steps below DOMAIN would be `DataQueryWorkflows` It is assumed that: * DOMAIN in English are already developed. * Since both English and Bulgarian are analytical, non-agglutinative languages "just" replacing English words with Bulgarian words in DOMAIN would produce good enough parsers of Bulgarian. Here are the steps: 1. Add global Bulgarian words (*optional*) 1. Add Bulgarian words and phrases in the [DSL::Shared](https://github.com/antononcube/Raku-DSL-Shared) file ["Roles/Bulgarian/CommonSpeechParts-template"](https://github.com/antononcube/Raku-DSL-Shared/blob/master/lib/DSL/Shared/Roles/Bulgarian/CommonSpeechParts-template). 2. Generate the file [Roles/Bulgarian/CommonSpeechParts.rakumod](https://github.com/antononcube/Raku-DSL-Shared/blob/master/lib/DSL/Shared/Roles/Bulgarian/CommonSpeechParts.rakumod) using the CLI script [`AddFuzzyMatching`](https://github.com/antononcube/Raku-Grammar-TokenProcessing/blob/main/bin/AddFuzzyMatching) 3. Consider translating, changing, or refactoring global files, like, [Roles/English/TimeIntervalSpec.rakumod](https://github.com/antononcube/Raku-DSL-Shared/blob/master/lib/DSL/Shared/Roles/English/TimeIntervalSpec.rakumod) 2. Translate DOMAIN English words and phrases into Bulgarian 1. Take the file [DOMAIN/Grammar/DOMAIN-template](https://github.com/antononcube/Raku-DSL-English-DataQueryWorkflows/blob/master/lib/DSL/English/DataQueryWorkflows/Grammar/DataQueryPhrases-template) and translate its words into Bulgarian 3. Add the corresponding files into [DSL::Bulgarian](https://github.com/antononcube/Raku-DSL-Bulgarian), [AAp1]. 1. Use the `DOMAIN/Grammarish.rakumod` role. * The English DOMAIN package should have such rule. If do not do the corresponding code refactoring. 2. Test with implemented DOMAIN languages. 3. See the example grammar and role in [DataQueryWorkflows in DSL::Bulgarian](https://github.com/antononcube/Raku-DSL-Bulgarian/tree/main/lib/DSL/Bulgarian/DataQueryWorkflows). --- ## References ### Articles [AA1] Anton Antonov, ["Introduction to data wrangling with Raku"](https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku), (2021), [RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com). [Wk1] Wikipedia entry, [UNIX-philosophy rules](https://en.wikipedia.org/wiki/Unix_philosophy). ### Packages [AAp1] Anton Antonov, [DSL::Bulgarian, Raku package](https://github.com/antononcube/Raku-DSL-Bulgarian), (2022), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [DSL::Shared, Raku package](https://github.com/antononcube/Raku-DSL-Shared), (2018-2022), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [Grammar::TokenProcessing, Raku project](https://github.com/antononcube/Raku-Grammar-TokenProcessing) (2022), [GitHub/antononcube](https://github.com/antononcube). [AAp4] Anton Antonov, [DSL::English::ClassificationWorkflows, Raku package](https://github.com/antononcube/Raku-DSL-General-ClassificationWorkflows), (2018-2022), [GitHub/antononcube](https://github.com/antononcube). [AAp5] Anton Antonov, [DSL::English::DataQueryWorkflows, Raku package](https://github.com/antononcube/Raku-DSL-English-DataQueryWorkflows), (2020-2022), [GitHub/antononcube](https://github.com/antononcube). [AAp6] Anton Antonov, [DSL::English::LatentSemanticAnalysisWorkflows, Raku package](https://github.com/antononcube/Raku-DSL-General-LatentSemanticAnalysisWorkflows), (2018-2022), [GitHub/antononcube](https://github.com/antononcube). [AAp7] Anton Antonov, [DSL::English::QuantileRegressionWorkflows, Raku package](https://github.com/antononcube/Raku-DSL-General-QuantileRegressionWorkflows), (2018-2022), [GitHub/antononcube](https://github.com/antononcube). [AAp8] Anton Antonov, [DSL::English::QuantileRegressionWorkflows, Raku package](https://github.com/antononcube/Raku-DSL-General-RecommenderWorkflows), (2018-2022), [GitHub/antononcube](https://github.com/antononcube).
## dist_github-thundergnat-Base-Any.md # NAME Base::Any - Convert numbers to or from pretty much any base [![Build Status](https://travis-ci.org/thundergnat/Base-Any.svg?branch=master)](https://travis-ci.org/thundergnat/Base-Any) # SYNOPSIS ``` use Base::Any; # Regular positive and negative bases say 123456789.&to-base(1391); # À୧Ꮣ say 'À୧Ꮣ'.&from-base(1391); # 123456789 say 6576148.249614.&to-base( 62, :precision(-3) ); # Raku.FTW say 99999.&to-base(-10); # 1900019 say '1900019'.&from-base(-10); # 99999 say (2**256).&to-base(1000); # õѶÛŰDŽņȳΖՀ8ЍӱһƐԿϷϝΐdɕΥ7ӷĄϜԎ # Imaginary bases say (5+5i).&to-base(-3i); # 1085.6 say (227.65625+10.859375i).&to-base(37i, :precision(-6)); # 1ŧ.Ԯɣ২Άí೭ÂႬ௫ǚȣᎴ say 'Rakudo'.&from-base(6i).round(1e-8); # 11904+205710i # Hash encoded say (2**256).&to-base-hash(10000); #`{ whole => [11 5792 892 3731 6195 4235 7098 5008 6879 785 3269 9846 6564 564 394 5758 4007 9131 2963 9936], fraction => [0], base => 10000 } # Array encoded say (-2**256).&to-base-array(10000); # ( [-11 -5792 -892 -3731 -6195 -4235 -7098 -5008 -6879 -785 -3269 -9846 -6564 -564 -394 -5758 -4007 -9131 -2963 -9936], [0], 10000 ) # Set a custom digit set set-digits('ABCDEFGHIJ'); # or set-digits('A'..'J'); # Reset to default digit set reset-digits(); ``` # DESCRIPTION Rakudo has built-in operators .base and .parse-base to do base conversions, but they only handle bases 2 through 36. Base::Any provides convenient tools to transform numbers to and from nearly any positional, non-streaming base. (A streaming base is one where characters are packed so that one glyph does not necessarily correspond to one character. E.G. MIME Base32, Base64, Base85, etc.) Nor does it handle some specialized bases with customized glyph sets and attached checksums: e.g. Bitcoin Base58check. (It could be used in calculating Base58 with the correct mapped glyph set, but doesn't do it by default.) For general base conversion, handles positive bases 2 through 4516, negative bases -4516 through -2, imaginary bases -67i through -2i and 2i through 67i. The rather arbitrary threshold of 4516 was chosen because that is how many unique and discernible digit and letter glyphs are in the basic and first Unicode planes. (Under Unicode 12.1) (There's 4517 actually, but one of them needs to represent zero... and conveniently enough, it's 0) Punctuation, symbols, white-space and combining characters as digit glyphs are problematic when trying to round-trip an encoded number. Font coverage tends to get spotty in the higher Unicode planes as well. If 4516 bases is not enough, also provides array encoded numbers to nearly any imaginable magnitude integer base. You may also choose to map the arrays to your own selection of glyphs to enumerate a custom base definition. The default glyph set is enumerated in the file `Base::Any::Digits`. #### BASIC USAGE: ``` sub to-base(Real $number, Integer $radix, :$precision = -15) ``` * Where $radix is ±2 through ±4516. Works with any Real type value, though Rats and Nums will have limited precision in the least significant digits. You may set a precision parameter if desired. Defaults to -15 (1e-15). Converting a Rat or Num to a base and back likely will not return the exact same number. Some rounding will likely be necessary if that is critical. Negative base numbers are encoded to always produce a positive result. Technically, there is no such thing as a negative Negative based number. -- ``` sub from-base(Str $number, Integer $radix) ``` * Where $radix is ±2 through ±4516. Takes a String of the encoded number. Returns the number encoded in base 10. ##### CASE INSENSITIVITY As long as the default digit set is loaded Base::Any mimics the built-in operators, in that bases with an absolute magnitude 36 (-36) and below ignore case when converting `from-base()`. ``` 'raku'.&from-base(36) == 'RAKU'.&from-base(36); # 76999005259948 ``` and ``` 'raku'.&from-base(-36) == 'RAKU'.&from-base(-36); # 75428091766540 ``` A consequence to be aware of: `.&from-base().&to-base()` in radicies ±11 through ±36 may not round-trip to the same string. If a custom digit set is loaded, Base::Any makes no assumptions about case equivalence. ##### UNDERSCORE SEPARATORS Raku allows underscores in numeric values as a visual aid to keep track of orders of magnitude. Since the numbers fed to the `to-base()` routine are standard Raku numerics, Base::Any will automatically allow them as well. The `from-base()` routines take strings however, and normally underscores would be disallowed; this module has code to specifically allow (and ignore) underscores in numeric strings. Something like this would be valid: ``` say 'Raku_Rocks'.&from-base(62); # 6024625501917586 ``` equivalent to: ``` say 'RakuRocks'.&from-base(62); # 6024625501917586 ``` ##### IMAGINARY BASES `sub to-base()` will also handle converting to imaginary bases. The radix must be imaginary, not Complex, (any Real portion must be zero,) and it will only handle radicies ±2i through ±67i. The number to convert may be any positive or negative Complex number. Imaginary base encoded numbers never produce a negative or complex result. There is no support at this time for imaginary radices in the `to-base-hash` or `to-base-array` routines. The imaginary bases in general seem to be more of a curiosity than of any great use. #### CUSTOM DIGIT SETS If you want to use a custom, non-standard digit set, you may easily load a replacement set of glyphs to use for digits. `sub set-digits(String)` or `sub set-digits(List)` will alter the standard table of digits to whatever you pass in. There are some caveats. * The string (or list) may not have any repeated glyphs. Repeated glyphs would hinder reversibility. * Each element (for lists) must have only one character. * Custom digit sets disable imaginary base number routines. They are too fiddly to deal with possibly "out-of-order" characters. There is some error trapping but you are given a lot of leeway to shoot yourself in the foot. The digit set order determines which character represents which number. Note that the digit set may be larger than the base you are converting to. You may load 'A' .. 'Z', but then convert to base 8 which would only use 'A' through 'H'. 'A' .. 'Z' will support any base from 2 to 26. The custom characters can be any valid Unicode character, even multibyte characters, as long as they are detected as a single character by Raku. They may be in any order, and from any Unicode block, as long as they are unique and discernable. It is highly recommended that the characters be restricted to printable, standalone characters (no white-space, control, or combining characters) but it isn't forbidden. Do not be suprised if the standard routines do not deal well with them though. ``` set-digits < 😟 😀 >; say 1234.5678.&to-base(2); # 😀😟😟😀😀😟😀😟😟😀😟.😀😟😟😀😟😟😟😀😟😀😟😀😀😟😀 ``` You may change back to the standard digit set at any time with: `sub reset-digits();` This will revert back to the default digit set and re-enable any routines disabled while custom digits were loaded. #### HASH ENCODED ``` sub to-base-hash(Real $number, Integer $radix, :$precision = -15) ``` * Where $radix is any non ±1 or 0 Integer. Returns a hash with 3 elements: * :base(the base) * :whole(An array of the whole portion positive orders of magnitude in base 10) * :fraction(An array of the fractional portion negative orders of magnitude in base 10) For illustration, using base 10 to make it easier to follow: ``` my %hash = 123456789.987654321.&to-base-hash(10); ``` yields: ``` {base => 10, fraction => [0 9 8 7 6 5 4 3 2 1], whole => [1 2 3 4 5 6 7 8 9]} ``` The 'whole' array is in reverse order, the most significant 'digit' is to the left, the least significant to the right. Each 'digit' is the value in that position (order-of-magnitude) encoded in base 10. To convert it to a number, reverse the array, multiply each element by the corresponding order of magnitude then sum the values. ``` sum %hash<whole>.reverse.kv.map( { $^value * (%hash<base> ** $^key) } ); 123456789 ``` Do the same thing with the fractional portion. The 'fraction' array is not reversed. The most significant is to the left, least significant to the right. The first element is always zero so you don't need to worry about skipping it. Do the same operation but with negative powers of the radix. ``` sum %hash<fraction>.kv.map( { $^value * (%hash<base> ** -$^key) } ); 0.987654321 ``` Add the whole and fractional parts together and you get the original number back. ``` 123456789 + 0.987654321 == 123456789.987654321 ``` There is a provided sub `from-base-hash()` that does exactly this operation, so you don't need to do it manually. This was exposition to make it easier to understand what is going on behind the scenes. ``` sub from-base-hash( { :whole(@whole), :fraction(@fraction), :base($base) } ) ``` Round trip: ``` say 123456789.987654321.&to-base-hash(10).&from-base-hash; 123456789.987654321 ``` #### ARRAY ENCODED In the same vein, there is a set of subs that work with arrays. ``` sub to-base-array( Real $number, Integer $radix, :$precision = -15 ) ``` and ``` sub from-base-array( [ @whole, @fraction, $base ] ) ``` They do very nearly the same thing except `to-base-array()` returns the 'whole' Array, the 'fraction' Array and the base as a list of three positionals rather than a hash of named values, and `from-base-array()` takes an array of those three positionals. They work pretty much identically internally though. (And in fact, use the exact same code path.) Note that both the `to-base-hash()` and `to-base-array()` include the base as part of the encoded number so it is already include when round-tripping. Be aware. There are about twenty-two thousand tests done during install to exercise the module. Testing takes a while. Theoretically, the tests are highly parallelizable but the present ecosystem tooling doesn't seem to like it. # AUTHOR Steve Schulze (thundergnat) # COPYRIGHT AND LICENSE Copyright 2020 Steve Schulze This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-Garlandg-Universal-Errno.md # NAME Universal::Errno - Errno wrapper for Linux, Unix, and Windows # SYNOPSIS ``` use Universal::Errno; set_errno(2); say errno; say "failed: {errno}"; say +errno; #2 ``` # DESCRIPTION Universal::Errno is an extension of and wrapper around lizmat´s `Unix::errno`, and exports the same `errno` and `set_errno` interface. It works on Linux, Windows, and Macos. BSD support is untested, but should work. One added feature is the `strerror` method, which gets the string for the error in a thread-safe way. On platforms that support it, it uses POSIX `strerror_l`. This allows getting the error string that corresponds to the user´s set locale. On platforms that do not support it, strerror\_r (XSI) is used. On Windows, this is done using `GetLastError()` and `FormatMessageW`. Windows also has a `SetLastError` function which is used instead of masking the value. This module provides an Exception class, X::Errno. To check the type of error in a portable way, use the `symbol` method and smartmatch against an entry in the Errno enum. It also provides a trait: error-model. Mark a sub or method with `is error-model<errno>` and the trait will automatically box the errno for you and reset errno to 0. Important note: With a native sub, the `is native` trait must come before `is error-model`. For calls that return `-errno`, there is also the trait `is error-model<neg-errno>`. If high-performance is needed for a native sub that can return errno, use the `check-errno` and/or `check-neg-errno` subs. These subs are interchangeable with the traits, but cannot be directly applied to a nativecall subroutine. As an example of a real-world scenario, this code sets up a socket using socket(2) and handles the errors with a CATCH block. ``` use NativeCall; use Constants::Sys::Socket; use Universal::Errno; sub socket(int32, int32, int32) returns int32 is native is error-model<errno> { ... } my int32 $socket; try { $socket = socket(AF::INET, SOCK_DGRAM, 0); # Do something with $socket CATCH { when X::Errno { given .symbol { when Errno::EINVAL { die "Invalid socket type" } when Errno::EACCES { die "Permission denied" } ... } } } } ``` ## class X::Errno Base exception class for errno ### method message ``` method message() returns Mu ``` Get the Str message for this errno value. ### method symbol ``` method symbol() returns Mu ``` Get the symbol of this errno value. ### method Int ``` method Int() returns Mu ``` Get the integer that corresponds to this errno value. ### method Numeric ``` method Numeric() returns Mu ``` Get the numeric value of this errno value. ### multi method new ``` multi method new() returns Mu ``` Get a new Errno exception from errno. This resets errno to 0. # Subs ### multi sub trait\_mod: ``` multi sub trait_mod:<is>( Routine $s, :$error-model where { ... } ) returns Mu ``` Trait to check return value of subroutine and throw X::Errno if return value is less than 1. ### multi sub trait\_mod: ``` multi sub trait_mod:<is>( Routine $s, :$error-model where { ... } ) returns Mu ``` Trait to check return value of subroutine and throw abs(return value) as X::Errno if return value is less than 1. ### sub check-neg-errno ``` sub check-neg-errno( Int $result ) returns Mu ``` Check the result against the negative errno form. ### sub check-errno ``` sub check-errno( Int $result ) returns Mu ``` Check the result against the errno() form. # AUTHOR Travis Gibson [TGib.Travis@protonmail.com](mailto:TGib.Travis@protonmail.com) ## CREDIT Uses a heavily-modified `Unix::errno` module for Unix-like OSes. The Windows version module borrows its structure and interface from lizmat's `Unix::errno`. Universal::Errno::Unix contains all of the modified code, and this README also borrows the SYNOPSIS example above. The original README and COPYRIGHT information for lizmat's `Unix::errno` has been preserved in `Universal::Errno::Unix`. lizmat's `Unix::errno` can be found at <https://github.com/lizmat/Unix-errno> # COPYRIGHT AND LICENSE Copyright 2021 Travis Gibson This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-raku-community-modules-CoreHackers-Q.md [![Actions Status](https://github.com/raku-community-modules/CoreHackers-Q/workflows/test/badge.svg)](https://github.com/raku-community-modules/CoreHackers-Q/actions) # CoreHackers::Q QAST tree visualizer # DESCRIPTION Installs `q` command line script that parses out QAST trees from a program and makes an HTML file from them. The HTML page provides these extra features unavailable in plain `raku --target=ast` and `raku --target=optimize` output: * Control-click on individual tree nodes to collapse/expand them * Color coding: of sunk nodes, `QAST::Want` alternatives, static and non-static calls, etc. Example output: [An example](example.png) # USAGE ``` Usage: q a '[<args> ...]' q o '[<args> ...]' ``` ## `a` command ``` $ q a raku -e 'say "hello"' > out.html; google-chrome out.html ``` `a` stands for `--target=ast` and the args that follow is a `raku` invocation to run the script (the `--target=ast` argument will be inserted automatically). The script will parse QAST generated by the given `raku` program and output an HTML file to STDOUT. View the file in any browser to examine the QAST tree. ## `o` command ``` $ q o raku -e 'say "hello"' > out.html; google-chrome out.html ``` `o` stands for `--target=optimize` . Same as `a` , except parses `--target=optimize` QAST. Once again, you don't need to manually specify `--target` parameter. ## `z` command ``` $ q z raku -e 'say "hello"' ``` Just runs the raku command as is. Mnemonic: "zero". This command exists simply to easily switch between `a`/`o` runs and plain raku runs. --- ## Meta ### REPOSITORY Fork this module on GitHub: <https://github.com/raku-community-modules/CoreHackers-Q> ### BUGS To report bugs or request features, please use <https://github.com/raku-community-modules/CoreHackers-Q/issues> ### AUTHOR Originally Zoffix Znet, now maintained by the Raku Community Adoption Center. ### LICENSE You can use and distribute this module under the terms of the The Artistic License 2.0. See the `LICENSE` file included in this distribution for complete details. The `META6.json` file of this distribution may be distributed and modified without restrictions or attribution.
## dist_zef-lizmat-Test-Assertion.md [![Actions Status](https://github.com/lizmat/Test-Assertion/workflows/test/badge.svg)](https://github.com/lizmat/Test-Assertion/actions) # NAME provide 'is test-assertion' trait for older Rakus # SYNOPSIS ``` use Test; use Test::Assertion; sub foo-test() is test-assertion { # will never be compile-time error subtest "we do many tests" => { flunk "failed this one"; # <-- points here if doesn't work } } foo-test(); # <-- points here if test-assertion *does* work ``` # DESCRIPTION Test::Assertion is a module that provides the `is test-assertion` trait for subroutines, which was introduced in Rakudo 2020.10, to older versions of Raku. This allows module authors to use the `is test-assertion` trait in a module without having to worry whether the version of Raku actually supports that trait. If a distribution does not use any external testing functionality, then this module should probably be added as a dependency to the "test-depends" section of the META information of a module, as it will (most likely) only be needed during testing. If this module is used by a distribution that is geared towards offering additional testing facilities, then clearly this module must be listed in the "depends" section. Please note that this does **not** actually implement the `is test-assertion` error reporting logic: it merely makes sure that the use of the trait will not be a compile time error in the test-file where it is being used. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/Test-Assertion> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2020, 2021, 2024 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-JNTHN-OO-Monitors.md # OO::Monitors [![Build Status](https://travis-ci.org/jnthn/oo-monitors.svg?branch=master)](https://travis-ci.org/jnthn/oo-monitors) A monitor provides per-instance mutual exclusion for objects. This means that for a given object instance, only one thread can ever be inside its methods at a time. This is achieved by a lock being associated with each object. The lock is acquired automatically at the entry to each method in the monitor. Condition variables are also supported. ## Basic Usage A monitor looks like a normal class, but declared with the `monitor` keyword. ``` use OO::Monitors; monitor IPFilter { has %!active; has %!blacklist; has $.limit = 10; has $.blocked = 0; method should-start-request($ip) { if %!blacklist{$ip} || (%!active{$ip} // 0) == $.limit { $!blocked++; return False; } else { %!active{$ip}++; return True; } } method end-request($ip) { %!active{$ip}--; } } ``` That's about all there is to it. The monitor meta-object enforces mutual exclusion. ## Conditions Condition variables are declared with the `conditioned` trait on the monitor. To wait on a condition, use `wait-condition`. To signal that a condition has been met, use `meet-condition`. Here is an example of a bounded queue. ``` monitor BoundedQueue is conditioned(< not-full not-empty >) { has @!tasks; has $.limit = die "Must specify a limit"; method add-task($task) { while @!tasks.elems == $!limit { wait-condition <not-full>; } @!tasks.push($task); meet-condition <not-empty>; } method take-task() { until @!tasks { wait-condition <not-empty>; } meet-condition <not-full>; return @!tasks.shift; } } ``` When `wait-conditon` is used, the lock is released and the thread blocks until the condition is met by some other thread. By contrast, `meet-condition` just marks a waiting thread as unblocked, but retains the lock until the method is over. ## Circular waiting Monitors are vulnerable to deadlock, if you set up a circular dependency. Keep object graphs involving monitors simple and cycle-free, so far as is possible.
## dist_zef-lizmat-UNICODE-VERSION.md [![Actions Status](https://github.com/lizmat/UNICODE-VERSION/actions/workflows/test.yml/badge.svg)](https://github.com/lizmat/UNICODE-VERSION/actions) # NAME UNICODE-VERSION - Provide $?UNICODE-VERSION for older Raku versions # SYNOPSIS ``` use UNICODE-VERSION; say $?UNICODE-VERSION; # v13.0 e.g. ``` # DESCRIPTION UNICODE-VERSION checks the unicode database at compile time for certain marker codepoints that got added at certain unicode versions and exports a `%?UNICODE-VERSION` `Version` constant that indicates the version of Unicode that is currently being supported, as determined by those codepoints. Algorithm suggested by Stephen Schulze # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/UNICODE-VERSION> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2023 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## format.md class Format Convert values to a string given a format specification ```raku class Format { } ``` A `Format` is an immutable object containing the logic for converting a set of values to a string given a `sprintf` compatible format specification. Acts as a standard string in every way, except that it can also be called as a [`Callable`](/type/Callable) with arguments to produce a string, just as `sprintf`. Available as of the 2023.06 release of the Rakudo compiler. Requires language level `6.e`. ```raku use v6.e.PREVIEW; my $f = Format.new("'%5s'"); say $f; # OUTPUT: «'%5s'␤» say $f("foo"); # OUTPUT: «' foo'␤» ``` # [Methods](#class_Format "go to top of document")[§](#Methods "direct link") ## [method new](#class_Format "go to top of document")[§](#method_new "direct link") ```raku method new($format --> Format:D) ``` Creates a new `Format` object from a `sprintf` compatible format string. ```raku use v6.e.PREVIEW; my $d = Format.new("%05d"); say $d; # OUTPUT: «%05d␤» say $d(42); # OUTPUT: «00042␤» ``` ## [method Callable](#class_Format "go to top of document")[§](#method_Callable "direct link") ```raku method Callable(--> Callable:D) ``` Returns the [`Callable`](/type/Callable) that was created from the given format. Intended for introspection purposes only, as one can call the `Format` object directly. ## [method directives](#class_Format "go to top of document")[§](#method_directives "direct link") ```raku method directives(--> List:D) ``` Returns a list of the directives seen in the given format. Intended for introspection purposes. ```raku use v6.e.PREVIEW; my $d = Format.new("%05d%3x:%s"); say $d.directives; # OUTPUT: «(d x s)␤» ``` ## [method arity](#class_Format "go to top of document")[§](#method_arity "direct link") ```raku method arity(--> List:D) ``` Returns the **minimal** number of positional arguments that is needed for this format. Intended for introspection purposes. ```raku use v6.e.PREVIEW; my $d = Format.new("%05d%3x:%s"); say $d.arity; # OUTPUT: «3␤» ``` ## [method count](#class_Format "go to top of document")[§](#method_count "direct link") ```raku method count(--> List:D) ``` Returns the **maximal** number of positional arguments that is needed for this format. Intended for introspection purposes. ```raku use v6.e.PREVIEW; my $d = Format.new("%05d%3x:%s"); say $d.count; # OUTPUT: «3␤» ```
## dist_zef-bduggan-Duckie.md # NAME Duckie - A wrapper and native bindings for DuckDB # SYNOPSIS ``` use Duckie; Duckie.new.query('select name from META6.json').rows[0] # {name => Duckie} my $db = Duckie.new; say $db.query("select 1 as the_loneliest_number").column-data(0); # [1] with $db.query("select 1 as the_loneliest_number") -> $result { say $result.column-data('the_loneliest_number'); # [1] } else { # Errors are soft failures say "Failed to run query: $_"; } # DuckDB can query or import data from CSV or JSON files, HTTP URLs, # PostgreSQL, MySQL, SQLite databases and more. my @cols = $db.query('select * from data.csv').columns; my @rows = $db.query('select * from data.json').rows; $db.query: q[ attach 'postgres://secret:pw@localhost/dbname' as pg (type postgres)] $res = $db.query: "select * from pg.my_table" $db.query("install httpfs"); $db.query("load httpfs"); $res = $db.query: "select * from 'http://example.com/data.csv'"; # Joins between different types are also possible. $res = $db.query: q:to/SQL/ select * from pg.my_table one inner join 'http://example.com/data.csv' csv_data on one.id = csv_data.id inner join 'data.json' json_data on one.id = json_data.id SQL ``` # DESCRIPTION This module provides Raku bindings for [DuckDB](https://duckdb.org/). DuckDB is a "fast in-process analytical database". It provides an SQL interface for a variety of data sources. Result sets are column-oriented, with a rich set of types that are either inferred, preserved, or explicitly defined. `Duckie` also provides a row-oriented API. This module provides two sets of classes. * `Duckie::DuckDB::Native` is a low-level interface that directly maps to the [C API](https://duckdb.org/docs/api/c/api.html). Note that a number of the function calls there are either deprecated or scheduled for deprecation, so the implementation of the Raku interface favors the more recent mechanisms where possible. * `Duckie` provides a high level interface that handles things like memory management and native typecasting. While the Raku language supports native types, the results from `Duckie` do not currently expose them, preferring, for instance to return Integers instead of uint8s, int64s, etc, and using Rats for decimals, and Nums for floats. A future interface may expose native types. # EXPORTS If an argument to `use Duckie` is provided, a new `Duckie` object is created and returned. Also "-debug" will enable debug output. e.g. ``` use Duckie; # no exports use Duckie '$db'; # creates and exports "$db" use Duckie '$db', '-debug'; # creates and exports "$db" with debug output use Duckie 'db'; db.query("select 1 as the_loneliest_number").column-data(0); ``` # METHODS ### method new ``` method new( :$file = ':memory:' ) returns Duckie ``` Create a new Duckie object. The optional `:file` parameter specifies the path to a file to use as a database. If not specified, an in-memory database is used. The database is opened and connected to when the object is created. ### method query ``` method query( Str $sql ) returns Duckie::Result ``` Run a query and return a result. If the query fails, a soft failure is thrown. ### method DESTROY ``` method DESTROY() returns Mu ``` Close the database connection and free resources. # SEE ALSO * [Duckie::Result](https://github.com/bduggan/raku-duckie/blob/main/docs/lib/Duckie/Result.md) * [Duckie::DuckDB::Native](https://github.com/bduggan/raku-duckie/blob/main/docs/lib/Duckie/DuckDB/Native.md) # ENVIRONMENT Set `DUCKIE_DEBUG` to a true value to enable logging to `STDERR`. # AUTHOR Brian Duggan
## mop.md Metaobject protocol (MOP) Introspection and the Raku object system Raku is built on a metaobject layer. That means that there are objects (the *metaobjects*) that control how various object-oriented constructs (such as classes, roles, methods, attributes or enums) behave. The metaobject has a practical benefit to the user when a normal object's type is needed. For example: ```raku my $arr = [1, 2]; say $arr.^name; # OUTPUT: «Array␤» ``` To get a more in-depth understanding of the metaobject for a `class`, here is an example repeated twice: once as normal declarations in Raku, and once expressed through the [metamodel](/type/Metamodel/ClassHOW): ```raku class A { method x() { say 42 } } A.x(); ``` corresponds to: ```raku constant A := Metamodel::ClassHOW.new_type( name => 'A' ); # class A { A.^add_method('x', my method x(A:) { say 42 }); # method x() A.^compose; # } A.x(); ``` (except that the declarative form is executed at compile time, and the latter form does not). The metaobject behind an object can be obtained with `$obj.HOW`, where HOW stands for Higher Order Workings (or, *HOW the \*%@$ does this work?*). Here, the calls with `.^` are calls to the metaobject, so `A.^compose` is a shortcut for `A.HOW.compose(A)`. The invocant is passed in the parameter list as well, to make it possible to support prototype-style type systems, where there is just one metaobject (and not one metaobject per type, as standard Raku does it). As the example above demonstrates, all object oriented features are available to the user, not just to the compiler. In fact the compiler just uses such calls to metaobjects. # [Metamethods](#Metaobject_protocol_(MOP) "go to top of document")[§](#Metamethods "direct link") These are introspective macros that resemble method calls. Metamethods are generally named with ALLCAPS, and it is considered good style to avoid creating your own methods with ALLCAPS names (since they are used conventionally for things like [phasers](/syntax/Phasers). This will avoid conflicts with any metamethods that may appear in future versions of the language. ## [WHAT](#Metaobject_protocol_(MOP) "go to top of document")[§](#WHAT "direct link") The type object of the type. This is a pseudo-method that can be overloaded without producing error or warning, but will be ignored. For example `42.WHAT` returns the [`Int`](/type/Int) type object. ## [WHICH](#Metaobject_protocol_(MOP) "go to top of document")[§](#WHICH "direct link") The object's identity value. This can be used for hashing and identity comparison, and is how the `===` infix operator is implemented. ## [WHO](#Metaobject_protocol_(MOP) "go to top of document")[§](#WHO "direct link") The package supporting the object. ## [WHERE](#Metaobject_protocol_(MOP) "go to top of document")[§](#WHERE "direct link") The memory address of the object. Note that this is not stable in implementations with moving/compacting garbage collectors. Use `WHICH` for a stable identity indicator. ## [HOW](#Metaobject_protocol_(MOP) "go to top of document")[§](#HOW "direct link") Returns the metaclass object, as in "Higher Order Workings". ```raku say (%).HOW.^name # OUTPUT: «Perl6::Metamodel::ClassHOW+{<anon>}␤» ``` `HOW` returns an object of type `Perl6::Metamodel::ClassHOW` in this case; objects of this type are used to build classes. The same operation on the `&` sigil will return `Perl6::Metamodel::ParametricRoleGroupHOW`. You will be calling this object whenever you use the `^` syntax to access metamethods. In fact, the code above is equivalent to `say (&).HOW.HOW.name(&)` which is much more unwieldy. [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW) is part of the Rakudo implementation, so use with caution. ## [WHY](#Metaobject_protocol_(MOP) "go to top of document")[§](#WHY "direct link") The attached [Pod](/language/pod) value. ## [DEFINITE](#Metaobject_protocol_(MOP) "go to top of document")[§](#DEFINITE "direct link") The object has a valid concrete representation. This is a pseudo-method that can be overloaded without producing error or warning, but will be ignored. Returns `True` for instances and `False` for type objects. ## [VAR](#Metaobject_protocol_(MOP) "go to top of document")[§](#VAR "direct link") Returns the underlying [`Scalar`](/type/Scalar) object, if there is one. The presence of a [`Scalar`](/type/Scalar) object indicates that the object is "itemized". ```raku .say for (1, 2, 3); # OUTPUT: «1␤2␤3␤», not itemized .say for $(1, 2, 3); # OUTPUT: «(1 2 3)␤», itemized say (1, 2, 3).VAR ~~ Scalar; # OUTPUT: «False␤» say $(1, 2, 3).VAR ~~ Scalar; # OUTPUT: «True␤» ``` Please refer to the [section on item context](/language/contexts#Item_context) for more information. # [Metaclass methods](#Metaobject_protocol_(MOP) "go to top of document")[§](#Metaclass_methods "direct link") Same as you can define object and class methods (which do not have access to the instance variables), you can define metaclass methods, which will work on the metaclass. These are conventionally defined by a caret (`^`) at the front of the method identifier. These metaclass methods might return a type object or a simple object; in general, they are only conventionally related to the metaobject protocol and are, otherwise, simple methods with a peculiar syntax. These methods will get called with the type name as first argument, but this needs to be declared explicitly. ```raku class Foo { method ^bar( Mu \foo) { foo.^set_name( foo.^name ~ "[þ]" ); } } my $foo = Foo.new(); say $foo.^name; # OUTPUT: «Foo␤» Foo.^bar(); say $foo.^name; # OUTPUT: «Foo[þ]␤» ``` This metaclass method will, via invoking class metamethods, change the name of the class it's been declared. Since this has been acting on the metaclass, any new object of the same class will receive the same name; invoking `say Foo .new().^name` will return the same value. As it can be seen, the metaclass method is invoked with no arguments; `\foo` will, in this case, become the `Foo` when invoked. The metaclass methods can receive as many arguments as you want. ```raku class Foo { method ^bar( Mu \foo, Str $addenda) { foo.^set_name( foo.^name ~ $addenda ); } } Foo.new().^bar( "[baz]" ); my $foo = Foo.new(); say $foo.^name; # OUTPUT: «Foo[baz]␤» ``` Again, implicitly, the method call will furnish the first argument, which is the type object. Since they are metaclass methods, you can invoke them on a class (as above) or on an object (as below). The result will be exactly the same. # [Structure of the metaobject system](#Metaobject_protocol_(MOP) "go to top of document")[§](#Structure_of_the_metaobject_system "direct link") **Note:** this documentation largely reflects the metaobject system as implemented by the [Rakudo Raku compiler](https://rakudo.org/), since the [design documents](https://design.raku.org/) are very light on details. For each type declarator keyword, such as `class`, `role`, `enum`, `module`, `package`, `grammar` or `subset`, there is a separate metaclass in the `Metamodel::` namespace. (Rakudo implements them in the `Perl6::Metamodel::` namespace, and then maps `Perl6::Metamodel` to `Metamodel`). Many of these metaclasses share common functionality. For example roles, grammars and classes can all contain methods and attributes, as well as being able to do roles. This shared functionality is implemented in roles which are composed into the appropriate metaclasses. For example, the role [`Metamodel::RoleContainer`](/type/Metamodel/RoleContainer) implements the functionality that a type can hold roles and [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW), which is the metaclass behind the `class` keyword, does this role. Most metaclasses have a `compose` method that you must call when you're done creating or modifying a metaobject. It creates method caches, validates things and so on, and weird behavior ensues if you forget to call it, so don't :-). ## [Bootstrapping concerns](#Metaobject_protocol_(MOP) "go to top of document")[§](#Bootstrapping_concerns "direct link") You might wonder how [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW) can be a class, when being a class is defined in terms of [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW), or how the roles responsible for role handling can be roles. The answer is *by magic*. Just kidding. Bootstrapping is implementation specific. Rakudo does it by using the object system of the language in which itself is implemented, which happens to be (nearly) a subset of Raku known as [NQP](/language/faq#What_language_is_NQP_written_in?). NQP has a primitive, class-like kind called `knowhow`, which is used to bootstrap its own classes and roles implementation. `knowhow` is built on primitives that the virtual machine under NQP provides. Since the object model is bootstrapped in terms of lower-level types, introspection can sometimes return low-level types instead of the ones you expect, like an NQP-level routine instead of a normal [`Routine`](/type/Routine) object, or a bootstrap-attribute instead of [`Attribute`](/type/Attribute). ## [Composition time and static reasoning](#Metaobject_protocol_(MOP) "go to top of document")[§](#Composition_time_and_static_reasoning "direct link") In Raku, a type is constructed as it is parsed, so in the beginning, it must be mutable. However if all types were always mutable, all reasoning about them would get invalidated at any modification of a type. For example the list of parent types and thus the result of type checking can change during that time. So to get the best of both worlds, there is a time when a type transitions from mutable to immutable. This is called *composition*, and for syntactically declared types, it happens when the type declaration is fully parsed (so usually when the closing curly brace is parsed). If you create types through the metaobject system directly, you must call `.^compose` on them before they become fully functional. Most metaclasses also use composition time to calculate some properties like the method resolution order, publish a method cache, and other house-keeping tasks. Meddling with types after they have been composed is sometimes possible, but usually a recipe for disaster. Don't do it. ## [Power and responsibility](#Metaobject_protocol_(MOP) "go to top of document")[§](#Power_and_responsibility "direct link") The metaobject protocol offers much power that regular Raku code intentionally limits, such as calling private methods on classes that don't trust you, peeking into private attributes, and other things that usually simply aren't done. Regular Raku code has many safety checks in place; not so the metamodel. It is close to the underlying virtual machine, and violating the contracts with the VM can lead to all sorts of strange behaviors that, in normal code, would obviously be bugs. So be extra careful and thoughtful when writing metatypes. ## [Power, convenience and pitfalls](#Metaobject_protocol_(MOP) "go to top of document")[§](#Power,_convenience_and_pitfalls "direct link") The metaobject protocol is designed to be powerful enough to implement the Raku object system. This power occasionally comes at the cost of convenience. For example, when you write `my $x = 42` and then proceed to call methods on `$x`, most of these methods end up acting on the [integer](/type/Int) 42, not on the [scalar container](/type/Scalar) in which it is stored. This is a piece of convenience found in ordinary Raku. Many parts of the metaobject protocol cannot afford to offer the convenience of automatically ignoring scalar containers, because they are used to implement those scalar containers as well. So if you write `my $t = MyType; ... ; $t.^compose` you are composing the Scalar that the `$`-sigiled variable implies, not `MyType`. The consequence is that you need to have a rather detailed understanding of the subtleties of Raku in order to avoid pitfalls when working with the MOP, and can't expect the same ["do what I mean"](/language/glossary#DWIM) convenience that ordinary Raku code offers. # [Archetypes](#Metaobject_protocol_(MOP) "go to top of document")[§](#Archetypes "direct link") Typically, when multiple kinds of types share a property, it is implemented with a metarole to be mixed into their metaclasses. However, not all common properties of types can be implemented as mixins. Certain properties are common to various kinds of types, but do not share enough behavior to be possible to implement as mixins. These properties are known as *archetypes*. HOWs should provide an `archetypes` metamethod that takes no arguments and returns a `Metamodel::Archetypes` instance. This is used by the compiler to determine what archetypes are supported by metaobjects. The rest of this section will cover how each of the archetypes that exist in Rakudo work. ## [parametric](#Metaobject_protocol_(MOP) "go to top of document")[§](#parametric "direct link") Parametric types are incomplete types that may have an arbitrary number of type parameters. Here, type parameters refer to parameters of the type itself; these may be any object that a signature allows you to include, not just types alone. When parameterized with type arguments, parametric types will produce a more complete type of some sort. If a HOW supports parameterization, it should have the `parametric` archetype and must provide a `parameterize` metamethod. The `parameterize` metamethod must accept a metaobject and may accept any number of type parameters as arguments, returning a metaobject. For example, a `parameterize` metamethod that allows a type to be parameterized with any type arguments may have this signature: ```raku method parameterize(Mu $obj is raw, |parameters --> Mu) ``` ### [Parametric classes and grammars](#Metaobject_protocol_(MOP) "go to top of document")[§](#Parametric_classes_and_grammars "direct link") Because of how the parametric archetype is implemented, it's possible for classes and grammars to be augmented with support for parameterization by giving them a `parameterize` metamethod, despite the type not having the `parametric` archetype. This can be useful in cases where the features of roles make them inappropriate to use for a parametric type. One scenario where parametric classes and grammars are useful is when parameterizations of a type should override or add multiple dispatch candidates to existing methods or regexes on the original parametric type. This is the case with parameterizations of types like [`Array`](/type/Array) and [`Hash`](/type/Hash), which may optionally be parameterized to mix in more type-safe versions of their methods that work with instances' values directly. In Rakudo, these are implemented as parametric classes using the metamethods provided by [`Metamodel::Mixins`](/type/Metamodel/Mixins) and [`Metamodel::Naming`](/type/Metamodel/Naming) to create a mixin of the metaobject given and reset its name before returning it. This technique can be used to write extensible grammars when used in combination with multi tokens, for instance: ```raku grammar Bot::Grammar { token TOP { <topic> || .+ } proto token topic {*} multi token topic:sym<command> { <command> <.ws> <command-args> } token command { '$' <!ws>+ } token command-args { <!ws>+ % <.ws> } method ^parameterize(::?CLASS:U $this is raw, +roles) { my Str:D $name = self.name: $this; my Mu $mixin := $this.^mixin: |roles; $mixin.^set_name: [~] $name, '[', roles.map(*.^name).join(','), ']'; $mixin } } role Greetings[Str:D $name] { multi token topic:sym<greeting> { ^ [ 'hi' | 'hello' | 'hey' | 'sup' ] <.ws> $name } } my constant GreetBot = Bot::Grammar[Greetings['GreetBot']]; GreetBot.parse: 'sup GreetBot'; say ~$/; # OUTPUT: «sup GreetBot␤» ``` Parametric classes can also be used to simulate support for parameterization on other kinds. For instance, the [Failable](https://modules.raku.org/dist/Failable:cpan:KAIEPI) ecosystem module is a parametric class that produces a subset upon parameterization. While the module itself does some caching to ensure no more type objects are made than what's necessary, a more basic version of it can be implemented like so: ```raku class Failable { method ^parameterize(Failable:U $this is raw, Mu $obj is raw --> Mu) { Metamodel::SubsetHOW.new_type: name => $this.^name ~ '[' ~ $obj.^name ~ ']', refinee => Metamodel::Primitives.is_type($obj, Any) ?? Any !! Mu, refinement => $obj | Failure } } ```
## dist_cpan-CTILMES-LibCurl.md # Raku LibCurl [![Build Status](https://travis-ci.org/CurtTilmes/raku-libcurl.svg)](https://travis-ci.org/CurtTilmes/raku-libcurl) [Simple Examples](#simple-examples) [Options](#options) [Header Options](#header-options) [Special Options](#special-options) [Errors](#errors) [Info](#info) [Received headers](#received-header-fields) [Content](#content) [Proxies](#proxies) [Multi](#multi) A [Raku](https://raku.org/) interface to [libcurl](https://curl.haxx.se/libcurl/). ``` libcurl is a free and easy-to-use client-side URL transfer library, supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos), file transfer resume, http proxy tunneling and more! libcurl is highly portable, it builds and works identically on numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS and more... libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported, fast, thoroughly documented and is already used by many known, big and successful companies and numerous applications. ``` ## Simple Examples ``` use LibCurl::Easy; # GET print LibCurl::Easy.new(URL => 'http://example.com').perform.content; # GET (download a file) LibCurl::Easy.new(URL => 'http://example.com/somefile', download => 'somefile').perform; # HEAD say LibCurl::Easy.new(:nobody, URL => 'http://example.com') .perform.response-code; # PUT (upload a file) LibCurl::Easy.new(URL => 'http://example.com/somefile', upload => 'somefile').perform; # PUT (content from a string) LibCurl::Easy.new(URL => 'http://example.com/somefile', send => 'My Content').perform; # DELETE LibCurl::Easy.new(URL => 'http://example.com/file-to-delete', customrequest => 'DELETE').perform; # POST LibCurl::Easy.new(URL => 'http://example.com/form.html', postfields => 'name=foo&opt=value').perform; ``` ## LibCurl::HTTP If even those aren't easy enough, there is a tiny sub-class **LibCurl::HTTP** that adds aliases for the common HTTP methods: ``` use LibCurl::HTTP; my $http = LibCurl::HTTP.new; say $http.GET('http://example.com').perform.content; say $http.GET('http://example.com', 'myfile').perform.response-code; say $http.HEAD('http://example.com').perform.response-code; $http.DELETE('http://example.com').perform; $http.PUT('http://example.com', 'myfile').perform; $http.POST('http://example.com/form.html', 'name=foo&opt=value').perform; ``` LibCurl::HTTP methods also enable `failonerror` by default, so any HTTP response >= 400 will throw an error. You can even import very simple subroutines ala [WWW](https://github.com/zoffixznet/perl6-WWW): ``` use LibCurl::HTTP :subs; # Just GET content (will return Failure on failure): say get 'https://httpbin.org/get?foo=42&bar=x'; # GET and decode received data as JSON: say jget('https://httpbin.org/get?foo=42&bar=x')<args><foo>; # POST content (query args are OK; pass form as named args) say post 'https://httpbin.org/post?foo=42&bar=x', :some<form>, :42args; # And if you need headers, pass them inside a positional Hash: say post 'https://httpbin.org/post?foo=42&bar=x', %(:Some<Custom-Header>), :some<form>, :42args; # Same POST as above + decode response as JSON say jpost('https://httpbin.org/post', :some<form-arg>)<form><some>; ``` ## Fancier Example ``` my $curl = LibCurl::Easy.new(:verbose, :followlocation); $curl.setopt(URL => 'http://example.com', download => './myfile.html'); $curl.perform; say $curl.success; say $curl.Content-Type; say $curl.Content-Length; say $curl.Date; say $curl.response-code; say $curl.statusline; ``` Of course the full power of [libcurl](https://curl.haxx.se/libcurl) is available, so you aren't limited to HTTP URLs, you can use FTP, SMTP, TFTP, SCP, SFTP, and many, many more. ## Options Many of the libcurl [options](https://curl.haxx.se/libcurl/c/curl_easy_setopt.html) are available, mostly just skip the `CURLOPT_`, lowercase, and use '-' instead of '\_'. For example, instead of `CURLOPT_ACCEPT_ENCODING`, use `accept-encoding`. When the options are really boolean (set to 1 to enable and 0 to disable), you can treat them like option booleans if you want, `:option` to enable, and `:!option` to disable. Just like libcurl, the primary option is [URL](https://curl.haxx.se/libcurl/c/CURLOPT_URL.html), and can take many forms depending on the desired protocol. Options can be set on a handle either on initial creation with `new()`, or later with `.setopt()`. As a convenience, you can also just treat them like normal object methods. These are all equivalent: ``` my $curl = LibCurl::Easy.new(:verbose, :followlocation, URL => 'http://example.com'); $curl.setopt(:verbose, followlocation => 1); $curl.setopt(URL => 'http://example.com'); $curl.verbose(1); $curl.followlocation(1); $curl.URL('http://example.com'); ``` `postfields` is actually [CURLOPT\_COPYPOSTFIELDS](https://curl.haxx.se/libcurl/c/CURLOPT_COPYPOSTFIELDS.html) so it will always copy the fields. Some of the normal options have **\_LARGE** versions. LibCurl always maps the option to the **\_LARGE** option where they exist, so you don't have to worry about overflows. These are the current options (If you want one not in this list, let me know): [CAinfo](https://curl.haxx.se/libcurl/c/CURLOPT_CAINFO.html) [CApath](https://curl.haxx.se/libcurl/c/CURLOPT_CAPATH.html) [URL](https://curl.haxx.se/libcurl/c/CURLOPT_URL.html) [accepttimeout-ms](https://curl.haxx.se/libcurl/c/CURLOPT_ACCEPTTIMEOUT_MS.html) [accept-encoding](https://curl.haxx.se/libcurl/c/CURLOPT_ACCEPT_ENCODING.html) [address-scope](https://curl.haxx.se/libcurl/c/CURLOPT_ADDRESS_SCOPE.html) [append](https://curl.haxx.se/libcurl/c/CURLOPT_APPEND.html) [autoreferer](https://curl.haxx.se/libcurl/c/CURLOPT_AUTOREFERER.html) [buffersize](https://curl.haxx.se/libcurl/c/CURLOPT_BUFFERSIZE.html) [certinfo](https://curl.haxx.se/libcurl/c/CURLOPT_CERTINFO.html) [cookie](https://curl.haxx.se/libcurl/c/CURLOPT_COOKIE.html) [cookiefile](https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEFILE.html) [cookiejar](https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEJAR.html) [cookielist](https://curl.haxx.se/libcurl/c/CURLOPT_COOKIELIST.html) [customrequest](https://curl.haxx.se/libcurl/c/CURLOPT_CUSTOMREQUEST.html) [default-protocol](https://curl.haxx.se/libcurl/c/CURLOPT_DEFAULT_PROTOCOL.html) [dirlistonly](https://curl.haxx.se/libcurl/c/CURLOPT_DIRLISTONLY.html) [failonerror](https://curl.haxx.se/libcurl/c/CURLOPT_FAILONERROR.html) [followlocation](https://curl.haxx.se/libcurl/c/CURLOPT_FOLLOWLOCATION.html) [forbid-reuse](https://curl.haxx.se/libcurl/c/CURLOPT_FORBID_REUSE.html) [fresh-connect](https://curl.haxx.se/libcurl/c/CURLOPT_FRESH_CONNECT.html) [ftp-skip-pasv-ip](https://curl.haxx.se/libcurl/c/CURLOPT_FTP_SKIP_PASV_IP.html) [ftp-use-eprt](https://curl.haxx.se/libcurl/c/CURLOPT_FTP_USE_EPRT.html) [ftp-use-epsv](https://curl.haxx.se/libcurl/c/CURLOPT_FTP_USE_EPSV.html) [ftpport](https://curl.haxx.se/libcurl/c/CURLOPT_FTPPORT.html) [header](https://curl.haxx.se/libcurl/c/CURLOPT_HEADER.html) [http-version](https://curl.haxx.se/libcurl/c/CURLOPT_HTTP_VERSION.html) [httpauth](https://curl.haxx.se/libcurl/c/CURLOPT_HTTPAUTH.html) [httpget](https://curl.haxx.se/libcurl/c/CURLOPT_HTTPGET.html) [httpproxytunnel](https://curl.haxx.se/libcurl/c/CURLOPT_HTTPPROXYTUNNEL.html) [ignore-content-length)](https://curl.haxx.se/libcurl/c/CURLOPT_IGNORE_CONTENT_LENGTH.html) [infilesize](https://curl.haxx.se/libcurl/c/CURLOPT_INFILESIZE_LARGE.html) [localport](https://curl.haxx.se/libcurl/c/CURLOPT_LOCALPORT.html) [localportrange](https://curl.haxx.se/libcurl/c/CURLOPT_LOCALPORTRANGE.html) [low-speed-limit](https://curl.haxx.se/libcurl/c/CURLOPT_LOW_SPEED_LIMIT.html) [low-speed-time](https://curl.haxx.se/libcurl/c/CURLOPT_LOW_SPEED_TIME.html) [maxconnects](https://curl.haxx.se/libcurl/c/CURLOPT_MAXCONNECTS.html) [maxfilesize](https://curl.haxx.se/libcurl/c/CURLOPT_MAXFILESIZE_LARGE.html) [maxredirs](https://curl.haxx.se/libcurl/c/CURLOPT_MAXREDIRS.html) [max-send-speed](https://curl.haxx.se/libcurl/c/CURLOPT_MAX_SEND_SPEED_LARGE.html) [max-recv-speed](https://curl.haxx.se/libcurl/c/CURLOPT_MAX_RECV_SPEED_LARGE.html) [netrc](https://curl.haxx.se/libcurl/c/CURLOPT_NETRC.html) [nobody](https://curl.haxx.se/libcurl/c/CURLOPT_NOBODY.html) [noprogress](https://curl.haxx.se/libcurl/c/CURLOPT_NOPROGRESS.html) [nosignal](https://curl.haxx.se/libcurl/c/CURLOPT_NOSIGNAL.html) [password](https://curl.haxx.se/libcurl/c/CURLOPT_PASSWORD.html) [path-as-is](https://curl.haxx.se/libcurl/c/CURLOPT_PATH_AS_IS.html) [post](https://curl.haxx.se/libcurl/c/CURLOPT_POST.html) [postfields](https://curl.haxx.se/libcurl/c/CURLOPT_COPYPOSTFIELDS.html) [postfieldsize](https://curl.haxx.se/libcurl/c/CURLOPT_POSTFIELDSIZE_LARGE.html) [protocols](https://curl.haxx.se/libcurl/c/CURLOPT_PROTOCOLS.html) [proxy](https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html) [proxyauth](https://curl.haxx.se/libcurl/c/CURLOPT_PROXYAUTH.html) [proxyport](https://curl.haxx.se/libcurl/c/CURLOPT_PROXYPORT.html) [proxytype](https://curl.haxx.se/libcurl/c/CURLOPT_PROXYTYPE.html) [proxyuserpwd](https://curl.haxx.se/libcurl/c/CURLOPT_PROXYUSERPWD.html) [proxy-ssl-verifypeer](https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html) [proxy-ssl-verifyhost](https://curl.haxx.se/libcurl/c/CURLOPT_PROXY_SSL_VERIFYHOST.html) [range](https://curl.haxx.se/libcurl/c/CURLOPT_RANGE.html) [redir-protocols](https://curl.haxx.se/libcurl/c/CURLOPT_REDIR_PROTOCOLS.html) [referer](https://curl.haxx.se/libcurl/c/CURLOPT_REFERER.html) [request-target](https://curl.haxx.se/libcurl/c/CURLOPT_REQUEST_TARGET.html) [resume-from](https://curl.haxx.se/libcurl/c/CURLOPT_RESUME_FROM_LARGE.html) [ssl-verifyhost](https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYHOST.html) [ssl-verifypeer](https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html) [tcp-keepalive](https://curl.haxx.se/libcurl/c/CURLOPT_TCP_KEEPALIVE.html) [tcp-keepidle](https://curl.haxx.se/libcurl/c/CURLOPT_TCP_KEEPIDLE.html) [tcp-keepintvl](https://curl.haxx.se/libcurl/c/CURLOPT_TCP_KEEPINTVL.html) [timecondition](https://curl.haxx.se/libcurl/c/CURLOPT_TIMECONDITION.html) [timeout](https://curl.haxx.se/libcurl/c/CURLOPT_TIMEOUT.html) [timeout-ms](https://curl.haxx.se/libcurl/c/CURLOPT_TIMEOUT_MS.html) [timevalue](https://curl.haxx.se/libcurl/c/CURLOPT_TIMEVALUE.html) [unix-socket-path](https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html) [unrestricted-auth](https://curl.haxx.se/libcurl/c/CURLOPT_UNRESTRICTED_AUTH.html) [use-ssl](https://curl.haxx.se/libcurl/c/CURLOPT_USE_SSL.html) [useragent](https://curl.haxx.se/libcurl/c/CURLOPT_USERAGENT.html) [username](https://curl.haxx.se/libcurl/c/CURLOPT_USERNAME.html) [userpwd](https://curl.haxx.se/libcurl/c/CURLOPT_USERPWD.html) [verbose](https://curl.haxx.se/libcurl/c/CURLOPT_VERBOSE.html) [wildcardmatch](https://curl.haxx.se/libcurl/c/CURLOPT_WILDCARDMATCH.html) ## Header Options In addition to the normal libcurl special options that set headers ([useragent](https://curl.haxx.se/libcurl/c/CURLOPT_USERAGENT.html), [referer](https://curl.haxx.se/libcurl/c/CURLOPT_REFERER.html), [cookie](https://curl.haxx.se/libcurl/c/CURLOPT_COOKIE.html)), there are some extra options for headers: `Content-MD5`, `Content-Type`, `Content-Length`, `Host`, `Accept`, `Expect`, `Transfer-Encoding`. ``` $curl.Host('somewhere.com'); # or $curl.setopt(Host => 'somewhere.com') $curl.Content-MD5('...'); # or $curl.setopt(Content-MD5 => '...') ``` You can also add any other headers you like: ``` $curl.set-header(X-My-Header => 'something', X-something => 'foo'); ``` You can clear a standard header by setting the header to '', or send a header without content by setting the content to ';' ``` $curl.set-header(Accept => ''); # Don't send normal Accept header $curl.set-header(Something => ';'); # Send empty header ``` If you are reusing the handle, you can also clear the set headers: ``` $curl.clear-header(); ``` This only clears the 'extra' headers, not useragent/referer/cookie. ## Special Options In addition to the normal libcurl options, Raku LibCurl uses options for some special Raku functionality. `debugfunction` replaces the libcurl [CURLOPT\_DEBUGFUNCTION](https://curl.haxx.se/libcurl/c/CURLOPT_DEBUGFUNCTION.html) callback, with one that looks like this: ``` sub debug(LibCurl::Easy $easy, CURL-INFO-TYPE $type, Buf $buf) {...} $curl.setopt(debugfunction => &debug); ``` `xferinfo` replaces the libcurl [CURLOPT\_XFERINFOFUNCTION](https://curl.haxx.se/libcurl/c/CURLOPT_XFERINFOFUNCTION.html) (and [CURLOPT\_PROGRESSFUNCTION](https://curl.haxx.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html)) with one that looks like this: ``` sub xferinfo(LibCurl::Easy $easy, $dltotal, $dlnow, $ultotal, $ulnow) {...} $curl.setopt(xferinfofunction => &xferinfo); ``` `download` specifies a filename to download into. `upload` specifies a filename to upload from. `send` specifies a `Str` or a `Buf` to send content from. Finally there is a `private` option which replaces CURLOPT\_PRIVATE, and you can safely store any object in it. ## Errors In most circumstances, errors from libcurl functions will result in a thrown X::LibCurl exception. You can catch these with CATCH. You can see the string error, or cast to Int to see the [libcurl error code](https://curl.haxx.se/libcurl/c/libcurl-errors.html). For HTTP transfers, you can access the response code with `getinfo('response-code')` or just `.response-code`. You can also check that the response code is in the 2xx range with `.success`. You might find the [failonerror](https://curl.haxx.se/libcurl/c/CURLOPT_FAILONERROR.html) option useful to force an error if the HTTP code is equal to or larger than 400. That will cause an exception in those cases. On an error, you may find [extra human readable error messages](https://curl.haxx.se/libcurl/c/CURLOPT_ERRORBUFFER.html) with the `.error` method. ``` $curl.perform; CATCH { say "Caught!"; when X::LibCurl { say "$_.Int() : $_"; say $curl.response-code; say $curl.error; } } ``` ## Info After a transfer, you can retrieve internal information about the curl session with the [.getinfo](https://curl.haxx.se/libcurl/c/curl_easy_getinfo.html) method. You can explicitly request a single field, or a list of fields to get a hash, or just get all the fields as a hash. As in the options, there are also convenience methods for each info field. ``` say $curl.getinfo('effective-url'); say $curl.getinfo('response-code'); say $curl.getinfo(<effective-url response-code>); # Hash with those keys say $curl.getinfo; # Hash of all info fields say $curl.effective-url; say $curl.response-code; ``` Fields currently defined are: [appconnect\_time](https://curl.haxx.se/libcurl/c/CURLINFO_APPCONNECT_TIME.html) [certinfo](https://curl.haxx.se/libcurl/c/CURLINFO_CERTINFO.html) [condition-unmet](https://curl.haxx.se/libcurl/c/CURLINFO_CONDITION_UNMET.html) [connect-time](https://curl.haxx.se/libcurl/c/CURLINFO_CONNECT_TIME.html) [content-type](https://curl.haxx.se/libcurl/c/CURLINFO_CONTENT_TYPE.html) [cookielist](https://curl.haxx.se/libcurl/c/CURLINFO_COOKIELIST.html) [effective-url](https://curl.haxx.se/libcurl/c/CURLINFO_EFFECTIVE_URL.html) [ftp-entry-path](https://curl.haxx.se/libcurl/c/CURLINFO_FTP_ENTRY_PATH.html) [header-size](https://curl.haxx.se/libcurl/c/CURLINFO_HEADER_SIZE.html) [http-connectcode](https://curl.haxx.se/libcurl/c/CURLINFO_HTTP_CONNECTCODE.html) [httpauth-avail](https://curl.haxx.se/libcurl/c/CURLINFO_HTTPAUTH_AVAIL.html) [lastsocket](https://curl.haxx.se/libcurl/c/CURLINFO_LASTSOCKET.html) [local-ip](https://curl.haxx.se/libcurl/c/CURLINFO_LOCAL_IP.html) [local-port](https://curl.haxx.se/libcurl/c/CURLINFO_LOCAL_PORT.html) [namelookup-time](https://curl.haxx.se/libcurl/c/CURLINFO_NAMELOOKUP_TIME.html) [num-connects](https://curl.haxx.se/libcurl/c/CURLINFO_NUM_CONNECTS.html) [os-errno](https://curl.haxx.se/libcurl/c/CURLINFO_OS_ERRNO.html) [pretransfer-time](https://curl.haxx.se/libcurl/c/CURLINFO_PRETRANSFER_TIME.html) [primary-ip](https://curl.haxx.se/libcurl/c/CURLINFO_PRIMARY_IP.html) [primary-port](https://curl.haxx.se/libcurl/c/CURLINFO_PRIMARY_PORT.html) [proxyauth-avail](https://curl.haxx.se/libcurl/c/CURLINFO_PROXYAUTH_AVAIL.html) [redirect-url](https://curl.haxx.se/libcurl/c/CURLINFO_REDIRECT_URL.html) [request-size](https://curl.haxx.se/libcurl/c/CURLINFO_REQUEST_SIZE.html) [response-code](https://curl.haxx.se/libcurl/c/CURLINFO_RESPONSE_CODE.html) [rtsp-client-cseq](https://curl.haxx.se/libcurl/c/CURLINFO_RTSP_CLIENT_CSEQ.html) [rtsp-cseq-recv](https://curl.haxx.se/libcurl/c/CURLINFO_RTSP_CSEQ_RECV.html) [rtsp-server-cseq](https://curl.haxx.se/libcurl/c/CURLINFO_RTSP_SERVER_CSEQ.html) [rtsp-session-id](https://curl.haxx.se/libcurl/c/CURLINFO_RTSP_SESSION_ID.html) [size-download](https://curl.haxx.se/libcurl/c/CURLINFO_SIZE_DOWNLOAD.html) [size-upload](https://curl.haxx.se/libcurl/c/CURLINFO_SIZE_UPLOAD.html) [speed-download](https://curl.haxx.se/libcurl/c/CURLINFO_SPEED_DOWNLOAD.html) [speed-upload](https://curl.haxx.se/libcurl/c/CURLINFO_SPEED_UPLOAD.html) [ssl-engines](https://curl.haxx.se/libcurl/c/CURLINFO_SSL_ENGINES.html) [total-time](https://curl.haxx.se/libcurl/c/CURLINFO_TOTAL_TIME.html) ## Received header fields You can retrieve the header fields in several ways as well. ``` say $curl.receiveheaders<Content-Length>; # Hash of all headers say $curl.get-header('Content-Length'); say $curl.Content-Length; ``` ## Content If you did not specify the `download` option to download content into a file, the content will be stashed in memory in a Buf object you can access with the `.buf()` method. If you understand that the content is decodable as a string, you can call the `.content($encoding = 'utf-8')` method which will decode the content into a `Str`, by default with the **utf-8** encoding if not specified. ``` say "Got content", $curl.content; ``` ## Multi-part forms Forms now uses the libcurl MIME capability, but requires verison 7.56 or greater for forms. There is a special POST option for multipart/formdata. ``` my $curl = LibCurl::Easy.new(URL => 'http://...'); # normal field $curl.formadd(name => 'fieldname', contents => 'something'); # Use a file as content, but not as a file upload $curl.formadd(name => 'fieldname', filecontent => 'afile.txt'); # upload a file from disk, give optional filename or contenttype $curl.formadd(name => 'fieldname', file => 'afile.txt', filename => 'alternate.name.txt', contenttype => 'image/jpeg'); # Send a Blob of contents, but as a file with a filename $curl.formadd(name => 'fieldname', filename => 'some.file.name.txt', contents => "something".encode); $curl.perform; ``` This will automatically cause LibCurl to POST the data. ## Proxies [libcurl](https://curl.haxx.se/libcurl) has great proxy support, and you should be able to specify anything needed as options to LibCurl to use them. The easiest for most common cases is to just set the [proxy](https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html) option. By default, libcurl will also respect the environment variables **http\_proxy**, **ftp\_proxy**, **all\_proxy**, etc. if any of those are set. Setting the `proxy` string to `""` (an empty string) will explicitly disable the use of a proxy, even if there is an environment variable set for it. A proxy host string can also include protocol scheme (`http://`) and embedded user + password. ## Unix sockets `LibCurl` can be used to communicate with a unix socket by setting the `unix-socket-path` option. You must still specify a host, but it is ignored. For example, you could use the [docker REST API](https://docs.docker.com/engine/api/latest) like this: ``` use LibCurl::Easy; use JSON::Fast; my $docker = LibCurl::Easy.new(unix-socket-path => '/var/run/docker.sock'); my $info = from-json($docker.URL("http://localhost/info").perform.content); say $info<KernelVersion>; say $info<OperatingSystem>; ``` ## Streaming There is an experimental stream capability which can bind a Channel to the data stream. Instead of retrieving the buffered data at once, each time data comes in it is sent through to the Channel. This is useful for long-lived connections that periodically send more data. You can access it with Something like this: ``` my $curl = LibCurl::Easy.new(URL => ...); my $stream = $curl.stream-out; start react whenever $stream -> $in { say "in: ", $in; } $curl.perform; ``` Suggestions for improving the interface for this capability welcome! ## Multi Raku LibCurl also supports the libcurl [multi](https://curl.haxx.se/libcurl/c/libcurl-multi.html) interface. You still have to construct `LibCurl::Easy` (or `LibCurl::HTTP`) handles for each transfer, but instead of calling `.perform`, just add the handle to a `LibCurl::Multi`. ``` use LibCurl::Easy; use LibCurl::Multi; my $curl1 = LibCurl::Easy.new(:verbose, :followlocation, URL => 'http://example.com', download => './myfile1.html'); my $curl2 = LibCurl::Easy.new(:verbose, :followlocation, URL => 'http://example.com', download => './myfile2.html'); my $multi = LibCurl:Multi.new; $multi.add-handle($curl1); $multi.add-handle($curl2); $multi.perform; say $curl1.statusline; say $curl2.statusline; ``` You can also use an asynchronous callback to get a notification when an individual transfer has completed. The callback takes place in the same thread with all the transfers, so it should complete quickly (or start a new thread for heavy lifting as needed). You can add additional handles to the `LibCurl::Multi` at any time, even re-using completed LibCurl::Easy handles (after setting `URL`, etc. as needed). ``` use LibCurl::Easy; use LibCurl::Multi; my $curl1 = LibCurl::Easy.new(:followlocation, URL => 'http://example.com', download => 'myfile1.html'); my $curl2 = LibCurl::Easy.new(:followlocation, URL => 'http://example.com', download => 'myfile2.html'); sub callback(LibCurl::Easy $easy, Exception $e) { die $e if $e; say $easy.response-code; say $easy.statusline; } my $multi = LibCurl::Multi.new(callback => &callback); $multi.add-handle($curl1, $curl2); $multi.perform; ``` ## INSTALL `LibCurl` depends on [libcurl](https://curl.haxx.se/download.html), so you must install that prior to installing this module. It may already be installed on your system. * For debian or ubuntu: `apt-get install libcurl4-openssl-dev` * For alpine: `apk add libcurl` * For CentOS: `yum install libcurl` ## SEE ALSO There is another Raku interface to libcurl [Net::Curl](https://github.com/azawawi/perl6-net-curl) developed by Ahmad M. Zawawi. If you already use it and it works well for you, great, keep using it. Ahmad did a nice job developing it. I would encourage you to also take a look at this module. LibCurl provides a more 'rakuish' OO interface to libcurl than Net::Curl, and wraps things in a manner to make using it a little easier (IMHO). ## LICENSE Copyright © 2017 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S.Code. All Other Rights Reserved. See [NASA Open Source Agreement](../master/NASA_Open_Source_Agreement_1.3%20GSC-17847.pdf) for more details.
## dist_zef-guifa-DateTime-Timezones.md # DateTime::Timezones > Phileas Fogg avait, «sans s'en douter», gagné un jour sur son itinéraire, - et cela uniquement parce qu'il avait fait le tour du monde en allant vers l'est, et il eût, au contraire, perdu un jour en allant en sens inverse, soit vers l'ouest. > — *Le Tour du monde en quatre-vingts jours* (Jules Vernes) An module to extend the built in `DateTime` with timezone support. To use, simply include it at any point in your code: ``` use DateTime::Timezones; my $dt = DateTime.new: now; ``` This extends `DateTime` to include the following three new attributes whose names *are subject to change*. | attribute | type | information | | --- | --- | --- | | **`.olson-id`** | *Str* | The unique Olson ID for the timezone | | **`.tz-abbr`** | *Str* | An (mostly) unique abbreviation for the timezone | | **`.is-dst`** | *Bool* | Whether the timezone is in daylight savings time | The Olson IDs (or timezone identifiers) are maintained by the IANA and based around city names, in the format of *Region/City*, and occasionally *Region/Subregion/City*. They do not tend to align with popular usage. In the United States, for instance, what is commonly called Eastern Time is listed as America/New\_York). The timezone abbreviation is representative of popular usage, but isn't unique. It's appropriate for a quick timestamp as it adjusts for daylight savings time, but for other display purposes, you may want to look to `Intl::Format::DateTime`. The DST attribute returns whether the timezone is in what is commonly referred to as Daylight Saving Time (or Summer Time). In some time zones, `False` is the only value. ### Additional Information For the most part, once you enable it, you won't need to do anything different at all, as it is designed to be as discreet as possible. There are, nonetheless, a few things to note: * The default time zone is either **Etc/GMT**. * The attribute `timezone` has been modified slightly to be allomorphic. For creation, you may pass either an `Int` offset *or* a `Str` Olson ID. Integer offsets are taken into account but the resultant time will be zoned to GMT (eventually whole-hour offsets will be be given an appropriate `Etc/` zone). When accessing `.timezone`, you get an `IntStr` comprising the offset and the Olson ID, so it should Just Work™. If you absolutely must have a strict `Int` value, use `.offset`, and for a strict `Str` value, use `.olson-id` * The formatter is unchanged and only includes offset information, so round-tripping (`DateTime.new($datetime.Str)` may not preserve the Olson ID and DST information. * Using `.later()`, `.earlier()` methods are currently untested. You may get unexpected results if you use them and cross a timezone transition. * You should only use this on your executed script. Modules that wish to take advantage of `DateTime::Timezones` should *not* `use` it, and instead assume that the methods exist. If functionality is critical, you can try sticking in a `die unless DateTime.^can('is-dst')` that will be executed at runtime. This is due to a bug in Rakudo where the original methods of wrapped methods are deleted. I am working to create a workaround. ### Leapseconds Leapseconds are annoying for timekeeping and POSIX explicitly ignores them since future ones are unpredictable because weird physics. I do not have the expertise to ensure that leapseconds are handled correctly, but welcome any code review and/or pull requests to remedy this (particularly test cases). ## How does it work? While the module initially planned on `augment`ing `DateTime`, it turns out that has significant problems for things like precompilation (you can't) and requires enabling `MONKEY-TYPING` which just feels dirty. Instead, `DateTime.new` is wrapped with a new method that returns the same (or functionally the same) `DateTime` you would have expected and mixes in the parameterized `TimezoneAware` role. It has a few tricks to make sure it doesn't apply the role multiple times. ## Version history * **0.4.2** * Quickfix on dependency * **0.4.1** * Fix bug calling `.timezone` (entered infinite loop) * Fix bug affecting year/month/day handling * **0.4.0** * Timezone data reading moved to a new `Timezones::ZoneInfo` module * Links (in new module) are handled in code, reducing file size * Calculation errors fixed, especially for future dates, thanks to... * ...new handling of v.3 data files * Test files regarding accuracy moved to that module * Should "just work" when module is used inside of another module (though additional testing is still required here) * *Requires Rakudo 2021.10 or later* * **0.3.9** * Fixed an issue caused by changes to the ZIC compiler * The `-b fat` option is used for backwards compatibility * Upcoming 0.4 release will better understand TZif v2+ files and fix some calculation errors * Updated to the 2021e release * Minor (but urgent) update for Palestine * **0.3.8** * Updated to the 2021d release * Fiji updated (no DST for 2021–2022) * **0.3.7** * Updated to the 2021c release * Fixed typos for the **Atlantic/Jan\_Mayen** link (and **America/Virgin**, we ignore *backzones*). * **0.3.6** * Updated to the 2021b release * Jordan and Samoa updated * Zone mergers and renamings * Pre-1993 fixes for Malawi, Portugal, etc - **0.3.5** * Updated to the 2021a release * South Sudan, Russia (Volgograd), Turks and Caicos updated * Many other zones fixed for pre-1986 transitions * **0.3.4** * Added support for historical Olson IDs (mainly to provide better support with CLDR) * Updated updater script to automatically back link older IDs. * **0.3.3** * Upgraded database to the 2020d release * Minor (but urgent) update for Palestine * **0.3.2** * Upgraded database to the 2020c release * Minor update for Fiji * Fixed bugs (found by ZeroDogg) caused when creating DateTimes with values other than `Int` or `Instant` * **0.3.1** * Upgraded database to the 2020b release * Minor updates for Antarctica, Australia, Canada, and Morocco. * Fixed an install issue due to evil `.DS_Store` files (thanks to ZeroDogg for bringing it to my attention). * Minor adjustments to the updater script * **0.3** * Support for 'upgrading' timezone-unaware `DateTime` objects that may have been precompiled before this module's `use` statement. * Additional test files. * Added an example: see `world-clock.raku` and pass in your favorite timezones * **0.2.1** * Fixed creation from Instants by adding `.floor` * **0.2** * TZif files generated on our own directly from the TZ database. * Fixed error in parsing leapseconds from TZif files * Fixed offset calculation error caused by misreading C code * Added test files (but more are needed, esp for leapseconds) * Created automated updater script for ease of maintenance. * **0.1** * First release. * Basic support for creation of `DateTime` with timezone information.
## dist_zef-lizmat-IRC-Channel-Log.md [![Actions Status](https://github.com/lizmat/IRC-Channel-Log/workflows/test/badge.svg)](https://github.com/lizmat/IRC-Channel-Log/actions) # NAME IRC::Channel::Log - access to all logs of an IRC channel # SYNOPSIS ``` use IRC::Log::Colabti; # class implementing one day of logs use IRC::Channel::Log; my $channel = IRC::Channel::Log.new( logdir => "logs/raku", # directory containing logs class => IRC::Log::Colabti, # for example generator => -> $nick { RandomColor.new }, # generate color for nick ); say $channel.dates; # the dates for which there are logs available say $channel.problems.elems; # hash with problems / date .say for $channel.entries; # all entries of this channel .say for $channel.entries( :conversation, # only return conversational messages :control, # only return control messages :dates<2021-04-23>, # limit to given date(s) :nick-names<lizmat japhb>, # limit to given nick(s) :contains<foo>, # limit to containing given text :starts-with<m:>, # limit to starting with given text :matches(/ /d+ /), # limit to matching regex ); $channel.watch-and-update; # watch and process updates $channel.shutdown; # perform all necessary actions on shutdown ``` # DESCRIPTION IRC::Channel::Log provides a programmatic interface to the IRC log files of a channel. # CLASS METHODS ## new ``` use IRC::Log::Colabti; # class implementing one day of logs use IRC::Channel::Log; my $channel = IRC::Channel::Log.new( logdir => "logs/raku", # directory containing logs class => IRC::Log::Colabti, # class implementing log parsing logic generator => &generator, # generate color for nick name => "foobar", # name of channel, default: logdir.basename state => "state", # directory containing persistent state info batch => 1, # number of logs parsed / time, default: 16 degree => 8, # threads used, default: Kernel.cpu-cores/2 ); ``` The `new` class method returns an `IRC::Channel::Log` object. It takes four named arguments: ### :logdir The directory (either as a string or as an `IO::Path` object) in which log file of the channel is located, as created by a logger such as `IRC::Client::Plugin::Logger`. This expects the directories to be organized by year, with all the logs of each day of a year in that directory. For example, in the test of this module: ``` raku |-- 2021 |-- 2021-04-23 |-- 2021-04-24 ``` This argument is required. ### :batch The batch size to use when racing to read all of the log files of the given channel. Defaults to 16 as an apparent optimal values to optimize for wallclock and not have excessive CPU usage. You can use `:!batch` to indicate you do not want any multi-threading: this is equivalent to specifying `1` or `0` or `True`. ### :class The class to be used to interpret log files, e.g. `IRC::Log::Colabti`. This argument is also required. ### :degree The maximum number of threads to be used when racing to read all of the log files of the given channel. Defaults to `Kernel.cpu-cores/2` (aka half the number of CPU cores the system claims to have). ### :generator A `Callable` expected to take a nick and return a color to be associated with that nick. ### :name The name of the channel. Optional. Defaults to the base name of the directory specified with `logdir`. ### :state The directory (either as a string or as an `IO::Path` object) in which persistent state information of the channel is located. # INSTANCE METHODS ## active ``` say "$channel.name() is active" if $channel.active; ``` The `active` instance method returns whether the channel is considered to be active. If a `state` directory has been specified, and that directory contains a file named "inactive", then the channel is considered to **not** be active. ## aliases-for-nick-name ``` my @aliases = $channel.aliases-for-nick-name($nick); ``` The `aliases-for-nick-name` instance method returns a sorted list of nick names that are assumed to be aliases (aka, have the same color) for the given nick name. ## cleaned-nick ``` my $cleaned = $channel.cleaned-nick-name($nick); ``` The `cleaned-nick-name` instance method returns the cleaned version of the given nick nae, which is used to group together the aliases of a nick name. ## dates ``` say $channel.dates; # the dates for which there are logs available ``` The `dates` instance method returns a sorted list of dates (as strings in YYYY-MM-DD format) of which there are entries available. ## entries ``` .say for $channel.entries; # all entries in chronological order .say for $channel.entries(:reverse); # in reverse chronological order .say for $channel.entries(:contains<question>); # containing text .say for $channel.entries(:control); # control messages only .say for $channel.entries(:conversation); # conversational messages only .say for $channel.entries(:dates<2021-04-23>); # for one or more dates .say for $channel.entries(:matches(/ \d+ /); # matching regex .say for $channel.entries(:starts-with<m:>); # starting with text .say for $channel.entries(:contains<foo>); # containing string .say for $channel.entries(:words<foo>); # containing word .say for $channel.entries(:nicks<lizmat>); # for one or more nicks .say for $channel.entries(:before-target($target); # entries before target .say for $channel.entries(:from-target($target); # entries from target .say for $channel.entries(:after-target($target); # entries after target .say for $channel.entries(:around-target($target); # entries around target .say for $channel.entries(:@targets); # entries of given targets .say for $channel.entries( :dates<2021-04-23>, :nicks<lizmat japhb>, :contains<question answer>, :all, ); ``` The `entries` instance method is *the* workhorse for selecting entries from the log. It will always return messages in chronological order. It takes a number of (optional) named arguments that allows you to select the entries from the log that you need. Named arguments may be combined, although some combinations do not make a lot of sense (which will generally mean that some of them will be ignored). If no (valid) named arguments are specified, then **all** entries from the log will be produced: this allows you to do any ad-hoc filtering. The following named arguments are supported: ### :after-target ``` $channel.entries(:after-target<2021-04-23Z23:36>); ``` The `after-target` named argument can be used with any of the other named arguments (with the exception of `reverse`, which it overrides as `:!reverse`). It will limit any entries to those that have a `target` value **greater** than the value provided. Targets are formatted as `YYYY-MM-DDZHH:MM-NNNN` with the `-NNNN` removed if it would have been `-0000`. ### :all The `all` named argument can only be used in combination with the `contains` and `words` named arguments. If specified with a true value, it will force entries to only be selected if **all** conditions are true. ### :around-target ``` $channel.entries(:around-target<2021-04-23Z23:36>); # default 10 entries $channel.entries(:around-target<2021-04-23Z23:36>, :nr-entries(5)); ``` The `around-target` named argument can be used with any of the other named arguments (with the exception of `reverse`). It will return any entries before and after to the entry with the `target`. By default, **10** entries will be selected before **and** after the target (thus returning a maximum of 21 entries). The `nr-entries` named argument can be used to indicate the number of entries before / after should be fetched. Targets are formatted as `YYYY-MM-DDZHH:MM-NNNN` with the `-NNNN` removed if it would have been `-0000`. ### :before-target ``` $channel.entries(:after-target<2021-04-24Z02:50>); ``` The `before-target` named argument can be used with any of the other named arguments (with the exception of `reverse`, which it overrides as `:reverse`). It will limit any entries to those that have a `target` value **smaller** than the value provided. Targets are formatted as `YYYY-MM-DDZHH:MM-NNNN` with the `-NNNN` removed if it would have been `-0000`. ### :contains ``` # just "question" $channel.entries(:contains<question>); # "question" or "answer" $channel.entries(:contains<question answer>); # "question" or "answer" $channel.entries(:contains<question answer>, :ignorecase); # "question" and "answer" $channel.entries(:contains<question answer>, :all); ``` The `contains` named argument allows specification of one or more strings that an entry should contain. By default, an entry should only contain one of the specified strings to be selected. If you want an entry to contain **all** strings, then an additional `:all` named argument can be specified (with a true value). If comparisons need to be done in an case-insensitive manner, then the `ignorecase` named argument can be specified with a true value. Since this only applies to conversational entries, any additional setting of the `conversation` or `control` named arguments are ignored. ### :control ``` $channel.entries(:control); # control messages only $channel.entries(:!control); # all but control messages ``` The `control` named argument specifies whether to limit to control messages only or not. ### :conversation ``` $channel.entries(:conversation); # conversational messages only $channel.entries(:!conversation); # all but conversational messages ``` The `conversation` named argument specifies whether to limit to conversational messages only or not. ### :dates ``` $channel.entries(:dates<2021-04-23>); # just on one date my @dates = Date.today ... Date.today.earlier(:3days); $channel.entries(:@dates); # multiple dates ``` The `dates` named argument allows one to specify the date(s) from which entries should be selected. Dates can be specified in anything that will stringify in the YYYY-MM-DD format, but are expected to be in ascending sort order. ### :from-target ``` $channel.entries(:from-target<2021-04-23Z23:36>); ``` The `from-target` named argument can be used with any of the other named arguments (with the exception of `reverse`, which it overrides as `:!reverse`). It will limit any entries to those that have a `target` value **greater than or equal to** the value provided. Targets are formatted as `YYYY-MM-DDZHH:MM-NNNN` with the `-NNNN` removed if it would have been `-0000`. ### :ignorecase The `ignorecase` named argument can only be used in combination with the `starts-with`, `contains` and `words` named arguments. If specified with a true value, it will do all comparisons in a case-insensitive manner. ### :matches ``` $channel.entries(:matches(/ \d+ /); # matching regex ``` The `matches` named argument allows one to specify a `Regex` to indicate which entries should be selected. Since this only applies to conversational entries, any additional setting of the `conversation` or `control` named arguments are ignored. ### :nick-names ``` $channel.entries(:nick-names<lizmat>); # limit to "lizmat" $channel.entries(:nick-names<lizmat japhb>); # limit to "lizmat" or "japhb" ``` The `nick-names` named argument allows one to specify one or more nick names to indicate which entries should be selected. ### :nr-entries The `nr-entries` named argument can only be used in combination with the `around-target` argument. It specifies how many entries should be fetched before / after the given target. ### :reverse ``` .say for $channel.entries(:reverse); # all messages, most recent first .say for $channel.entries(:!reverse); # all messages, oldest first ``` The `reverse` named argument allows one to specify the order in which entries will be returned. If specified with a true value, it will return the most recent entries first, in reverse chronological order. ### :starts-with ``` # starts with "m:" $channel.entries(:starts-with<m:>); # starts with "how" in any case $channel.entries(:starts-with<how>, :ignorecase); # starts with "m:" or "j:" $channel.entries(:starts-with<m: j:>); ``` The `start-with` named argument allows specification of one or more strings that an entry should start with. If comparisons need to be done in an case-insensitive manner, then the `ignorecase` named argument can be specified with a true value. Since this only applies to conversational entries, any additional setting of the `conversation` or `control` named arguments are ignored. ### :targets ``` .say for $channel.entries(:@targets); ``` The `targets` named argument allows specification of one or more targets for which to return the associated entry. ### :words ``` # contains the word "foo" $channel.entries(:words<foo>); # contains the word "foo" or "bar" $channel.entries(:words<foo bar>); # contains the word "foo" or the word "bar" in any case $channel.entries(:words<foo bar>, :ignorecase); # contains the word "foo" *and* "bar" $channel.entries(:words<foo bar>, :all); ``` The `words` named argument allows specification of one or more words that an entry should contain. By default, an entry should only contain one of the specified words to be selected. If you want an entry to contain **all** words, then an additional `:all` named argument can be specified (with a true value). If comparisons need to be done in an case-insensitive manner, then the `ignorecase` named argument can be specified with a true value. Since this only applies to conversational entries, any additional setting of the `conversation` or `control` named arguments are ignored. ## initial-topic ``` say $channel.initial-topic($date); ``` The `initial-topic` instance method takes a date (either as a `Date` object or as a string) and returns the log entry of the topic (as a ::Topic object) of the channel on that date. Returns `Nil` if no topic is known for the given date. ## is-first-date-of-month ``` say $channel.is-first-date-of-month($date); ``` The `is-first-date-of-month` instance method takes a date (either as a `Date` object or as a string) and returns whether that date is the first date of the month, according to availability in the logs. ## is-first-date-of-year ``` say $channel.is-first-date-of-year($date); ``` The `is-first-date-of-month` instance method takes a date (either as a `Date` object or as astring) and returns whether that date is the first date of the year, according to availability in the logs. ## log ``` say $channel.log($date); # log object for given date ``` The `log` instance method takes a string representing a date, and returns the `class` object for that given date. Returns `Nil` if there is no log available on the specified date. ## next-date ``` say $channel.next-date($date); # date after the given date with a log ``` The `next-date` instance method takes a string representing a date, and returns a string with the **next** date of logs that are available. Returns `Nil` if the specified date is the last date or after that. ## nick-names ``` say $channel.nick-names; # the nick names for which there are logs available ``` The `nick-names` instance method returns a sorted list of all the nick names seen. ## prev-date ``` say $channel.prev-date($date); # date before the given date with a log ``` The `prev-date` instance method takes a string representing a date, and returns a string with the **previous** date of logs that are available. Returns `Nil` if the specified date is the first date or before that. ## problems ``` .say for $channel.problems; # the dates with log parsing problems ``` The `problems` instance method returns a sorted list of `Pair`s with the date (formatted as YYYY-MM-DD) as key, and a list of problem descriptions as value. ## sc ``` say "$channel.sc.elems() nick to color mappings are known"; ``` The `String::Color` object that contains the mapping of nick to color. ## shutdown ``` $channel.shutdown; ``` Performs all the actions needed to shutdown: specifically saves the nick to color mapping if a `state` directory was specified. ## state ``` say "state is saved in $channel.state()"; ``` The `IO` object of the directory in which persistent state will be saved. ## this-date ``` say $channel.this-date($date); # date after / before the given date ``` The `this-date` instance method takes a string representing a date, and returns a string with the **first** date of logs that are available. This could be either the given date, or the next date, or the previous date (if there was no next date). Returns `Nil` if no dates could be found, which would effectively mean that there are **no** dates in the log. ## watch-and-update ``` $channel.watch-and-update; $channel.watch-and-update post-process => { say "$channel.name(): $_.message()" } ``` The `watch-and-update` instance method starts a thread (and returns its `Promise` in which it watches for any updates in the most recent logs. If there are any updates, it will process them and make sure that all the internal state is correctly updated. It optionally takes a `post-process` named argument with a `Callable` that will be called with any `IRC::Log` entries that have been added to the channel log. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) # COPYRIGHT AND LICENSE Copyright 2021 Elizabeth Mattijsen Source can be located at: <https://github.com/lizmat/IRC-Channel-Log> . Comments and Pull Requests are welcome. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-ATROXAPER-LogP6.md ## Chunk 1 of 2 [![Build Status](https://github.com/atroxaper/p6-LogP6/workflows/Ubuntu/badge.svg)](https://github.com/atroxaper/p6-LogP6/actions/workflows/ubuntu.yml) [![Build Status](https://github.com/atroxaper/p6-LogP6/workflows/Windows/badge.svg)](https://github.com/atroxaper/p6-LogP6/actions/workflows/windows.yml) # NAME `LogP6` is a fully customizable and fast logging library inspired by the idea of separating logging and its configuration. You can use it not only in apps but even in your libraries. # TABLE OF CONTENTS * [NAME](#name) * [SYNOPSIS](#synopsis) * [DESCRIPTION](#description) * [Features](#features) * [Concepts](#concepts) * [Example](#example) * [Context](#context) * [Writer](#writer) * [Filter](#filter) * [Nested Diagnostic Context (NDC) and Mapped Diagnostic Context (MDC)](#nested-diagnostic-context-ndc-and-mapped-diagnostic-context-mdc) * [Logger](#logger) * [Logger Wrapper](#logger-wrapper) * [Synchronisation of configuration and Logger instance](#synchronisation-of-configuration-and-logger-instance) * [CONFIGURATION](#configuration) * [Logger retrieve](#logger-retrieve) * [Factory subroutines](#factory-subroutines) * [Configuration file](#configuration-file) * [Writer configuration](#writer-configuration) * [WriterConf](#writerconf) * [Standard WriterConf](#standard-writerconf) * [Pattern](#pattern) * [Async writing](#async-writing) * [Writer factory subroutines](#writer-factory-subroutines) * [Writer configuration file](#writer-configuration-file) * [Filter configuration](#filter-configuration) * [FilterConf](#filterconf) * [Standard FilterConf](#standard-filterconf) * [Filter factory subroutines](#filter-factory-subroutines) * [Filter configuration file](#filter-configuration-file) * [Defaults](#defaults) * [Defaults factory subroutines](#defaults-factory-subroutines) * [Defaults configuration file](#defaults-configuration-file) * [Cliche](#cliche) * [Cliche factory subroutines](#cliche-factory-subroutines) * [Cliche configuration file](#cliche-configuration-file) * [Default logger](#default-logger) * [Change configuration](#change-configuration) * [EXAMPLES](#examples) * [Use an external library that uses LogP6](#use-an-external-library-that-uses-logp6) * [Change console application verbosity level](#change-console-application-verbosity-level) * [Conditional log calls](#conditional-log-calls) * [Associate logs with concrete user](#associate-logs-with-concrete-user) * [Filter log by its content](#filter-log-by-its-content) * [Write one log in several outputs](#write-one-log-in-several-outputs) * [Write custom writer handle for your need](#write-custom-writer-handle-for-your-need) * [BEST PRACTICE](#best-practice) * [SEE OLSO](#seeolso) * [ROADMAP](#roadmap) * [AUTHOR](#author) * [COPYRIGHT AND LICENSE](#copyright-and-license) # SYNOPSIS A logger system has to be as transparent as possible. At the same time, it has to be fully customizable. It has to provide a possibility to change logging logic without changing any line of code. It is amazing if you can use logger system during developing a library and its user do not feel discomfort of it. `LogP6` logger library is all about that. # DESCRIPTION ## Features 1. Possibility to change logger configuration and its behavior without touching the code; 2. Configuring from the code and/or configuration files; 3. Possibility to use any IO::Handler, even for async or database work; 4. Possibility to use multiple loggers in one app; 5. Possibility to use multiply IO::Handler's in one logger; 6. Flexible filter system; 7. Stack and Map entities associated with each thread and possibility to use values from it in the logger; 8. Pretty fast work. Using pre-calculation as much as possible - logger layout pattern is parsed only once, reuse current DateTime objects and so on; 9. Possibility to use logger while development (dynamically change logger settings in runtime), and during production work (maximum fast, without any lock, excepts possible IO::Handle implementation's). ## Concepts * `writer` - an object which knows how and where logs must be written. In a simple case - which file and string format pattern will be used; * `filter` - an object which knows which logs must be written. In simple case - logs with which levels are allowed to pass to the `writer`; * `cliche` - template for creating `Logger`. Contains writers, filters, and other configurations for future Loggers; * `logger` - instance created using configuration from the `cliche`. Just Logger with standard functionality like `info()` method; * `logger trait` - string value describes the semantic purpose of concrete Logger. For example, the name of the class where the logger is used or the type of logged information (for example, 'internal-audit-subsystem'). `LogP6` uses `trait` to create the new or get already created logger; * `cliche's matcher` - unique field of the cliche. The field may be a literal string or regex. If the logger `trait` satisfies the `matcher` then the cliche will be used for creating the logger with the trait; * `context` - associated with each Thread object, which contains information for logging like your final log message, the exception you specified, log level, current date, thread name, and so on. Context can be used for storing some specific information you and `LogP6` library need while logging. ## Example Using logger: ``` use LogP6; # use library in general mode my \log = get-logger('audit'); # create or get logger with 'audit' trait log.info('property ', 'foo', ' setted as ', 5); # log string with concatenation log.infof('property %s setted as %d', 'foo', 5); # log sprintf like style ``` Configure the logger in code: ``` use LogP6 :configure; # use library in configure mode cliche( # create a cliche :name<cl>, # obligatory unique cliche name :matcher<audit>, # obligatory matcher grooves => ( # optional list of writer-filter pairs (or their names) writer(:pattern('%level| %msg'), :handle($*ERR)), # create anonymous (w/o name) writer configuration filter(:level($debug)))); # create anonymous (w/o name) filter configuration ``` Configure in the configuration file style (same as above): ``` { "writers": [{ "type": "std", "name": "w", "pattern": "%level | %msg", "handle": { "type": "std", "path": "err" } }], "filters": [{ "type": "std", "name": "f", "level": "debug" }], "cliches": [{ "name": "cl", "matcher": "audit", "grooves": [ "w", "f" ] }] } ``` ## Context LogP6 library adds an object associated with each Thread - `Logger Context` or just `context`. You can work with the context directly in the `filter` subsystem or in custom `writer` implementations. Also, `logger` has methods for working with `NDC` and `MDC` (see below in [Logger](#logger)). For more information, please look at the methods' declarators in `LogP6::Context`. ## Writer `Writer` is responsible for writing all corresponding data to corresponding output in some format. It has only one method: * `write($context){...}` - this method has to take all necessary data from the specified `context` and use it for writing. Note: the specified context will change its data after the method call. Do not cache the context itself (for example, for asynchronous writing) but only its data. ## Filter `Filter` is responsible for deciding to allow the corresponding `writer` to write a log or not. It has three methods: * `do-before($context){...}` - some code which decides allow the log to be pass to the writer or not. If it returns True then the log will be pass to the writer. Otherwise, the log will be discarded. * `reactive-level(){}` - in most cases filtering can be done only by log level. This method returns a log level, which allows logger to call `do-before` method. If the filtering log's level importance is less then returned reactive level, then the log will be discarded without calling `do-before` method. * `do-after($context){}` - any code which has to be executed after the writer work in case when `do-before` method returns True. ## Nested Diagnostic Context (NDC) and Mapped Diagnostic Context (MDC) There are cases when we want to trace some information through a group of log messages, but not only in one message, for example, user id, http session number, or so. In such cases, we have to store the information somewhere, pass it through logic subs and methods, and pass to log methods over and over again. Since the log system has to be separated from the main program logic, then we need a special place to store the information. That place is a `Nested Diagnostic Context` (`NDC`) - a stack structure and a `Mapped Diagnostic Context` (`MDC`) - a map structure. You can push/pop values in `NDC` and put/remove values in `MDC`. The standard writer has special placeholders for message pattern (see below in [Pattern](#pattern)) for put all values from `NDC` or some kay associated value from `MDC` to the final log message string. ## Logger A logger is an immutable object containing zero to several pairs of `writer` and `filter` (`grooves`). For each time you want to log some message (with or without arguments), the logger compiles message+arguments in one message string, updates the `context`, and goes through `grooves` - call filter's methods and, if it passes, then ask a writer to write the message. The writer takes all necessary information such as message, log level, NDC/MDC values, current date-time, and so from the context. Logger has the following methods: * `trait()` - returns logger trait; * `ndc-push($obj)`, `ndc-pop()`, `ndc-clean()` - work with `NDC`; * `mdc-put($key, $obj)`, `mdc-remove($key)`, `mdc-clean()` - work with `MDC`; * `dc-copy()`, `dc-restore($dc-copy)` - make copy of `NDC` and `MDC` and restore them from copy. The methods are useful when you want to share NDC and MDC values across multiple threads. * `trace(*@args, :$x)`, `debug(*@args, :$x)`, `info(*@args, :$x)`, `warn(*@args, :$x)`, `error(*@args, :$x)`, `level($level, *@args, :$x)` - logging the arguments with specified importance log level. `:$x` is an optional exception argument. `@args` - data for logging. Elements of the array will be concatenated with empty string; * `tracef(*@args, :$x)`, `debugf(*@args, :$x)`, `infof(*@args, :$x)`, `warnf(*@args, :$x)`, `errorf(*@args, :$x)`, `levelf($level, *@args, :$x)` - logging the arguments with specified importance log level. `:$x` is an optional exception argument. `@args` - data for logging. The first element is used as `sprintf` format and the rest element as `sprintf` args; * `trace-on()`, `debug-on()`, `info-on()`, `warn-on()`, `error-on()`, `level-on($level)` - help methods to use as condition. The method will return `Any` in case the specified log level if forbidden now and will return special object with `log(*@args, :$x)` and `logf(*@args, :$x)` methods which can be used for log with asked log level (see [example](#conditional-log-calls)). ## Logger Wrapper It is a system to wrap (or decorate) logger object into another and add additional logic. You can describe `logger wrapper factory`, which will wrap any created `logger`. ### Synchronisation of configuration and Logger instance An example of logger wrapper usage is synchronization a logger configuration and logger instance. It may be useful in the case of development or debug session to change logger configuration dynamically. Since a logger object is immutable and cannot know about configuration changes it produced, we need a logic that checks if the user updated the corresponding configuration and updates the logger instance. You can specify any wrapper for logger synchronization. There is a helper class `LogP6::Wrapper::SyncAbstract` to create your synchronization wrapper. For now, there are only two synchronization wrappers: * `LogP6::Wrapper::SyncTime::Wrapper` - checks the new configuration change each `X` seconds; * `LogP6::Wrapper::SyncEach::Wrapper` - checks the new configuration change each time you use the logger. # CONFIGURATION For working with the `LogP6` library, you need to `use LogP6;` module. Without any tags, it provides only the `get-logger($trait)` sub for retrieving a logger. `:configure` tag provides factory subroutines for configuring loggers from the code. Another option to configure logger is by using a configuration file. ## Logger retrieve To retrieve a logger, you need to use `LogP6` module and call the `get-logger($trait)` sub with the logger trait you need. Example: ``` use LogP6; my $log = get-logger('main'); # using $log ... ``` If you did not configure a `Cliche` for a specified logger trait ('main' in the example), the default logger would be returned (see [Default logger](#default-logger)). In other cases, the logger created by the cliche with matcher the trait satisfy will be returned. ## Factory subroutines `LogP6` provides subroutines for configure loggers from the code dynamically. To get access to them, you need to `use LogP6` with `:configure` tag. There are subroutines for configuring `filters`, `writers`, `cliches`, and any default values like `writer pattern`, `logger wrapper`, or so. Concrete subroutines will be described in the corresponding sections below. There is a `get-logger-pure($trait)` sub to retrieve pure logger without any wrappers. Also, five variables for five `LogP6::Level` enum values are exported as `$trace`, `$debug`, `$info`, `$warn` and `$error`. Example: ``` use LogP6 :configure; set-default-wrapper(LogP6::Wrapper::SyncTime::Wrapper.new(:60seconds)); # set default wrapper set-default-level($debug); # set default logger level as debug my $log = get-logger('main'); # get wrapped logger $log.debug('msg'); my $pure-log = get-logger-pure('main'); # this logger will not synchronize its configuration ``` ## Configuration file A better alternative (especially for production using) of configuration by factory subroutines is a configuration file. You can specify a path to it through `LOG_P6_JSON` system environment variable. In case the variable is empty, then standard path `./log-p6.json` will be used (if it exists). Or you can initialize `LogP6` library using `init-from-file($config-path)` factory subroutine. The configuration file is a `json` formatted file. Example: ``` { "default-pattern": "%msg", "default-level": "trace", "default-handle": { "type": "std", "path": "err" }, "writers": [{ "type": "std", "name": "w" }], "filters": [{ "type": "std", "name": "f" }], "cliches": [{ "name": "c2", "matcher": "main" }] } ``` The concrete format for concrete objects will be described in the corresponding sections below. Some objects like `writers`, `wrappers` or so have a `type` filed. Each object has its own list of available types. There is a type that can be used in any object - `custom`. It uses to describe the factory method or class which will be used to produce the object. It requires additional fields: * `require` - the name of the module with factory method or class; * `fqn-method` or `fqn-class` - the fully qualified name of method or class in `require` module; * `args` - list of named arguments which will be passed to `fqn-method()` or `fqn-class.new()`; * `positional` - list of positional arguments which will be passed to `fqn-method()` or `fqn-class.new()`. For example, creating IO::Handle by `create-handle` subroutine in `MyModule` with arguments `:path<out.txt>, :trait<rw>`: ``` { "default-handle": { "type": "custom", "require": "MyModule", "fqn-method": "MyModule::EXPORT::DEFAULT::&create-handle", "args": { "path": "out.txt", "trait": "rw" } } } ``` ## Writer configuration ### WriterConf `WriterConf` is a configuration object which contains all necessary information and algorithm for creating a concrete `writer` instance. For more information, please look at the methods' declarators in `LogP6::WriterConf`. ### Standard WriterConf Standard `WriterConf` (`LogP6::WriterConf::Std`) makes a writer that writes log message to abstract `IO::Handle`. It has a `pattern` - string with special placeholders for values like `ndc`, current `Thread` name, log message, etc. `Writer` will put all necessary values into `pattern` and write it to handle. Also, standard `WriterConf` has boolean `auto-exceptions` property - if it is `True`, then the placeholder for exception will be concatenated to the `pattern` automatically. Form of the exception placeholder can be configured separately (see [Defaults](#defaults) and [Cliche](#cliche)). ### Pattern Pattern placeholders start with `%` symbol following the placeholder name. If placeholder has arguments, they can be passed in curly brackets following placeholder name. The pattern can have the following placeholders: * `%trait`, `%trait{short=[package-delimeter]number}`, `%trait{sprintf=pattern}` - for the name of the logger trait. Additionally, you can specify one of two options of trait representation. `sprintf` option is useful for traits like `database`, `audit`, or so when you want to represent all traits with the same length. For example, `[%trait{sprintf=%s7}]` can be converted into `[ audit]`. `short` option is useful for traits like `Module::Packge1::Package2::Class`. You can specify package delimiter (instead of `::`) and how many packages will be displayed. For example, `%trait{short=[.]1` can be converted into `Class`, `%trait{short=[.]-1` - into `Packge1.Package2.Class` and `%trait{short=[.]2.4` - into `Modu.Pack.Package2.Class`. If `number` is a positive integer, then only `number` right elements will be displayed. If `number` is a negative integer, then `|number|` left elements will be deleted. If `number` is real, then left elements will be cut to fractional symbols; * `%tid` - for current `Thread` id; * `%tname` - for current `Thread` name; * `%msg` - for log message; * `%ndc` - for full NDC array joined by space symbol; * `%mdc{obj_key}` - for MDC value with `obj_key` key; * `%x{$msg $name $trace}` - for exception. String in curly brackets is used as subpattern. `$msg` - optional exception message, `$name` - optional exception name, `$trace` - optional exception stacktrace. For example, `'%x{($name "$msg") Trace: $trace}'` can be converted into `'(X::AdHoc "test exception") Trace: ...'`; * `%level{WARN=W DEBUG=D ERROR=E TRACE=T INFO=I length=2}` - log importance level. By default, the logger will use the level name in upper case, but you can specify synonyms for all or part of them in curly brackets in format `<LEVEL_NAME>=<sysnonym>`. You can specify a fixed length of the log level name. Default length is 0 - write level as is. For example `'[%level{WARN=hmm ERROR=alarm length=5}]'` can be converted into `'[hmm ]'`, `'[alarm]'`, `'[INFO ]'`, `'[DEBUG]'`; * `%color{TRACE=yellow DEBUG=green INFO=blue WARN=magenta ERROR=red}` - colorize log string after that placeholder. You can specify a color for any log level. The level you not specified color will use its default color (as in the example above). For example, `%color{ERROR=green}` means `%color{TRACE=yellow DEBUG=green INFO=blue WARN=magenta ERROR=green}`. You can use `yellow`, `green`, `blue`, `magenta`, `green` color names or color code (more [information](https://misc.flogisoft.com/bash/tip_colors_and_formatting). For example `%color{TRACE=35 DEBUG=30;48;5;82 INFO=green}`. You can use `%color` placeholder several times; * `%color{reset}` or `%creset` - reset log string colorizing after that placeholder; * `%date{$yyyy-$yy-$MM-$MMM-$dd $hh:$mm:$ss:$mss $z}` - current date and time. String in curly brackets is used as subpattern. * `$yyyy`, `$yy` - year in 4 and 2 digits format; * `$MM`, `$MMM` - month in 2 digits and short name format; * `$dd` - day in 2 digits format; * `$hh`, `$mm`, `$ss`, `$mss` - hours, minutes, seconds and milliseconds * `$z` - timezone * `%framefile` - for log caller frame file name. The same as `callframe().file` in log call block; * `%frameline` - for log caller frame file line. The same as `callframe().line` at the same log call line; * `%framename` - for log caller frame code name. The same as `callframe().code.name` in log call block; Note that using `%framefile`, `%frameline` or `%framename` in the pattern will slow your logging because it requires several `callframe()` calls on each resultative log call; ### Async writing `LogP6` provides writer and handle implementation for asynchronous writing. You can use `LogP6::Handle::Async.new(IO::Handle :$delegate!, Scheduler :$scheduler = $*SCHEDULER)` as a handle which will schedule `WRITE` method call of `delegate` handle. If it is not enough to wrap a handle, then you can wrap the whole writer. Use `LogP6::WriterConf::Async.new(LogP6::WriterConf :$delegate!, Scheduler :$scheduler = $*SCHEDULER), :$name, Bool :$need-callframe)` as writer configuration of another configuration. The final writer will schedule the `write` method call of `delegate` created writer with a copy of the current `logger context`. If you miss a `:name` parameter, then `delegate`'s name will be used. Pass boolean parameter `need-callframe` if you plan to use callframe information in the wrapped writer. Note that using callframe will slow your logging because it requires several `callframe()` calls on each resultative log call. ### Writer factory subroutines `LogP6` module has the following subs for manage writers configurations: * `get-writer(Str:D $name --> LogP6::WriterConf)` - gets writer with specified name; * `writer(:$name, :$pattern, :$handle, :$auto-exceptions, :create, :update, :replace --> LogP6::WriterConf)` - create, update, or replace standard `WriterConf` with a specified name. If you want to `:update` only concrete fields in an already created configuration, then the rest fields will not be changed. In the case of `:replace`, the new configuration will be created and replaced the old one. You can create configuration without a name - then the configuration will not be stored but only returned to you. The method returns the old writer configuration (`:update`, `:replace`) and the new one (`:create`); * `writer(LogP6::WriterConf:D $writer-conf, :create, :replace --> LogP6::WriterConf)` - save or replace any implementation of `WriterConf`. The configuration name will be retrieved from the `$writer-conf`. The method returns the old writer configuration (`:replace`) and the new one (`:create`); * `writer(:$name, :$remove --> LogP6::WriterConf)` - remove and return a configuration with specified name. ### Writer configuration file In the configuration file, writer configurations have to be listed in `writers` array. Only `std` (for standard configuration) and `custom` types are supported. In the case of standard configuration, all fields are optional excepts `name`. The handle can be: * `file` type for output into a file. You can specify `path`,`append` (`True` by default), and `out-buffer` arguments; * `std` type for output into `$*OUT` or `$*ERR`. You can specify `path` as `out` or `err`. * `custom` type. In the case of the `custom` writer type, the result writer configuration has to returns not empty name. Example: ``` { "writers": [ {"type": "std", "name": "w1", "pattern": "%msg", "handle": {"type": "std", "path": "out"}}, {"type": "std", "name": "w2", "handle": {"type": "file", "path": "log.txt", "append": false}}, {"type": "custom", "require": "Module", "fqn-method": "Module::EXPORT::DEFAULT::&writer", "args": { "name": "w3" }} ] } ``` ## Filter configuration ### FilterConf `Filter` creates by `FilterConf` - a configuration object which contains all necessary information and algorithm for creating a concrete `filter` instance. For more information, please look at the methods' declarators in `LogP6::FilterConf`. ### Standard FilterConf Standard `FilterConf` (`LogP6::FilterConf::Std`) has array for `do-before` subs and array for `do-after` subs. `Filter` made by standard `FilterConf` calls each `do-before` sub and stop at the first `False` returned value. If all `do-before` subs returned `True`, then the filter's `do-before` method returns `True`. The `do-after` works in the same way. Also, there is a `first-level-check` property. If it is set to `True`, then the sub for checking log level will be added automatically as the first element in `do-before` array; if the property set to `False` then the sub will be added automatically as the last element in `do-before` array. ### Filter factory subroutines `LogP6` module has the following subs for manage filters configurations: * `get-filter(Str:D $name --> LogP6::FilterConf)` - gets filter with specified name * `filter(:$name, :$level, :$first-level-check, List :$before-check, List :$after-check, :create, :update, :replace --> LogP6::FilterConf)` - create, update, or replace standard `FilterConf` with a specified name. If you want to `:update` only concrete fields in already created configuration then the rest fields will not be changed. In the case of `:replace`, the new configuration will be created and replaced the old one. You can create a configuration without a name - then the configuration will not be stored but only returned to you. The method returns the old filter configuration (`:update`, `:replace`) and the new one (`:create`); * `level($level --> LogP6::FilterConf:D)` - the short form for `filter(:level($level), :create)`; * `filter(LogP6::FilterConf:D $filter-conf, :create, :replace)` - save or replace any implementation of `FilterConf`. The configuration name will be retrieved from the `$filter-conf`. The method returns the old filter configuration (`:replace`) and the new one (`:create`); * `filter(:$name, :$remove)` - remove and return a configuration with specified name. ### Filter configuration file In the configuration file, filter configurations have to be listed in the `filters` array. Only `std` (for standard configuration) and `custom` types are supported. In the case of standard configuration, all fields are optional excepts `name`. `before-check` and `after-check` are arrays with `custom` typed elements. In the case of the `custom` filter type, the result filter configuration has to returns not empty name. Example: ``` { "filters": [ {"type": "std", "name": "f1", "level": "error", "first-level-check": false}, {"type": "std", "name": "f2", "level": "info", "before-check": [{ "require": "MyModule", "fqn-method": "MyModule::EXPORT::DEFAULT::&before-check" }]}, {"type": "custom", "require": "MyModule", "fqn-class": "MyModule::MyFilter", "args": { "name": "f3" }} ] } ``` ## Defaults Standard filters and writers have fields and options which affect their work. Some of them you can specify in factory subroutines or configuration file fields. If such arguments are omitted, then the default values of it will be used. Other fields and options cannot be setter this way. For example, the pattern for an exception that will be concatenated to the main pattern in the standard writer when `auto-exceptions` sets to `True` (see [Standard WriterConf](#standard-writerconf)). Such properties have default values too. All the defaults can be set through factory subroutines or fields in the configuration file. Configuring default values is useful in case you what to avoid many boilerplate configurations. ### Defaults factory subroutines There are the following factory subs for set defaults values: * `set-default-pattern(Str:D $pattern)` - set default pattern for the standard `WriterConf`. Default value is `'[%date{$hh:$mm:$ss}][%level] %msg'`; * `set-default-auto-exceptions(Bool:D $auto-exceptions)` - set default `auto-exceptions` property value for the standard `WriterConf`. Default value is `True`; * `set-default-handle(IO::Handle:D $handle)` - set default handle for the standard `WriterConf`. Default value is `$*OUT`; * `set-default-x-pattern(Str:D $x-pattern)` - set pattern for exception that will be concatenated to the main pattern in standard `WriterConf` in case `auto-exceptions` sets to `True` (see [Standard WriterConf](#standard-writerconf)). Default value is `'%x{ Exception $name: $msg' ~ "\n" ~ '$trace}'` * `set-default-level(LogP6::Level:D $level)` - set default level for the standard `WriterConf`. Default value is `LogP6::Level::error`; * `set-default-first-level-check(Bool:D $first-level-check)` - set default value of `first-level-check` property of the standard `FilterConf` (see [Standard FilterConf](#standard-filterconf)). Default value is `True`; * `set-default-wrapper(LogP6::Wrapper $wrapper)` - set wrapper for loggers (see [Logger Wrapper](#logger-wrapper)). Default value is `LogP6::Wrapper::Transparent::Wrapper.new`. ### Defaults configuration file You can configure default values in the configuration file through the following json fields of a root object: * `"default-pattern": <string>` - for default pattern for writers with `std` type; * `"default-auto-exceptions": <boolean>` - for default `auto-exceptions` field value for writers with `std` type; * `"default-handle": <handle>` - for default handle for writers with `std` type; * `"default-x-pattern": <string>` - for default exceptions pattern for writers with `std` type; * `"default-level": <level-name>` - for default level for filters with `std` type; * `"default-first-level-check": <boolean>` - for `first-level-check` value for filters with `std` type; * `"default-wrapper": <wrapper>` - for wrapper for loggers. `Wrapper` can be: * `time` type for `LogP6::Wrapper::SyncTime::Wrapper`. It takes obligatory `"seconds": <num>` and optional `"config-path": <string>` addition fields; * `each` type for `LogP6::Wrapper::EachTime::Wrapper`. It takes optional `"config-path": <string>` addition field; * `transparent` type for `LogP6::Wrapper::Transparent::Wrapper`; * `custom` type. ## Cliche `Cliche` is a template for creating Logger. Each `cliche` has `cliche's matcher` - literal or regex field. When you what to get logger for some `logger trait`, then the logger system tries to find a `cliche` with `matcher` the `trait` satisfies (by smartmatch). If there is more than one such cliche, then the most recent created will be picked. The picked `cliche`'s content will be used for making the new logger. Cliche contains writers and filters configurations pairs called `grooves` and own `defaults` values which overrides global `defaults` values (see [Defaults](#defaults)). You can use the same writer and/or filter in several `grooves`. If the `grooves` list is empty or missed, the created logger will drop all logs you pass to it; ### Cliche factory subroutines `LogP6` module has the following subs for manage cliches configurations: * `cliche(:$name!, :$matcher!, Positional :$grooves, :$wrapper, :$default-pattern, :$default-auto-exceptions, :$default-handle, :$default-x-pattern, :$default-level, :$default-first-level-check, :create, :$replace)` - create or replace cliche with specified name and matcher. All passed `defaults` overrides globals `defaults` in within the cliche. `$grooves` is a `Positional` variable with alternating listed `writers` and `filters`. `$grooves` will be flatted before analysis - you can pass into it a list of two elements lists or any structure you want. Elements of `$grooves` can be either name of already stored writers and filters, already stored writers and filters with names, or writers and filters without names. In the last case, the writer or filter will be stored with a generated UUID name automatically. The method returns the old cliche (`:replace`) and the new one (`:create`); * `cliche(LogP6::Cliche:D $cliche, :create, :replace
## dist_cpan-ATROXAPER-LogP6.md ## Chunk 2 of 2 )` - save or replace cliche; * `cliche(:$name!, :remove)` - remove and return a cliche with specified name. ### Cliche configuration file In the configuration file, cliches have to be listed in the `cliches` array. It has the following fields: * `"name": <string>` - obligatory name of cliche; * `"matcher": <string>` - cliche matcher. If the matcher value starts and ends with `/` symbol, then the matcher is interpreted as regex; in another case, it is a literal; * `"grooves": [<writer1-name>, <filter1-name>, <writer2-name>, <filter2-name>, ... ]` - grooves, list of writers' and filters' names; * defaults - the same fields with the same possible values as described in [Defaults configuration file](#defaults-configuration-file) excepts `default-wrapper` - you need to use the `wrapper` field name. Example: ``` { "cliches": [{ "name": "c1", "matcher": "/bo .+ om/", "grooves": [ "w1", "f1", "w2", "f1" ], "wrapper": { "type": "transparent" }, "default-pattern": "%level %msg" }] } ``` ## Default logger In any way you configured your cliches by the factory routines or configuration file or did not use non of them, the `default cliche` will be in the logger library. Default cliche corresponds to the following configuration: `cliche(:name(''), :matcher(/.*/), grooves => (writer(:name('')), filter(:name(''))))`. In other words, default cliche has an empty string name, matches any trait, has only one groove with empty (uses all defaults) writer with an empty string name and with empty (uses all defaults) filter with an empty string name. It means, by default, you do not need to configure anything at all. But you can change the default cliche or default writer and filter by factory subroutines or in the configuration file. Note that if the `LogP6` library does not find cliche with matcher logger trait satisfies, then an exception will be thrown. ## Change configuration Sometimes you may need to change logger configuration in runtime execution. It can be simply done by factory subroutines. After calling any factory subroutine, all loggers for already used `logger traits` will be recreated, and you can get it by `get-logger($trait)` sub. If you already got logger, use synchronization wrapper, then the wrapper will sync the logger himself correspond to its algorithm. Another way of change configuration is by using configuration file modification. Changes in the configuration file will be detected only if you are already using any of the synchronization wrappers (in `defaults` or one of `cliches`). After any change detection, all already configured configuration will be dropped and created new from the file. # EXAMPLES Lets explore a few general use cases: ## Use an external library that uses LogP6 `LogP6` can be used during library development, and a user of the library wants entirely turn off any logs from the library. Let's imagine that all library loggers' traits start with `LIBNAME` letters. In this case, we can create a `cliche` with corresponding `matcher` and empty `grooves` - all library logs will be dropped. In `Raku`: ``` use LogP6 :configure; cliche(:name('turn off LIBNAME'), :matcher(/^LIBNAME .*/), :wrapper(LogP6::Wrapper::Transparent::Wrapper.new)); ``` Or in the configuration file: ``` { "cliches": [{"name": "turn off LIBNAME", "matcher": "/^LIBNAME .*/", "wrapper": {"type": "transparent"}}] } ``` We use wrapper without synchronization (transparent) because we do not plan to change the library loggers' configuration. ## Change console application verbosity level Let's imagine we are writing a console application, and we want to add the flag `--verbose` for getting a more detailed output. Lets using a particular logger for application console output instead of using simple `say` and change filter level according to the user's choice: In `Raku`: ``` use LogP6 :configure; cliche(:name<output>, :matcher<say>, grooves => ( writer(:pattern('%msg'), :handle($*OUT)), filter(:name<verbosity>, :level($info)) )); sub MAIN(Bool :$verbose) { filter(:name<verbosity>, :level($debug), :update) if $verbose; my $say = get-logger('say'); $say.info('Greetings'); $say.debugf('You set verbose flag to %s value', $verbose); } ``` In that case, we do not need to use the configuration file. But if you want, then you can remove the line with `cliche` creation and add the following configuration file: ``` { "writers": [{ "type": "std", "name": "say", "pattern": "%msg", "handle": { "type": "std", "path": "out" }}], "filters": [{ "type": "std", "name": "verbosity", "level": "info"}], "cliches": [{ "name": "output", "matcher": "say", "grooves": [ "say", "verbosity" ]}] } ``` ## Conditional log calls Sometimes you may need to log information that required additional calculation. It is useful to know whether the log will be written or not before the calculation. Logger's `-on` methods were created especially for that. It will return a particular object (or Any) with `log` and `logf` methods you can use to log with the corresponding log level. Please look at the example below: ``` use LogP6 :configure; # set logger allowed level as INFO filter(:name(''), :level($info), :update); my $log = get-logger('condition'); my %map; my $str; # ... # to-json will not be called here, because .debug-on returned Any for now .log(to-json(%map, :pretty, :sorted-keys)) with $log.debug-on; # from-json will be called here, because .warn-on returned a little logger # log will be with WARN level .log(from-json($str)<key>) with $log.warn-on; with $log.trace-on { # this block will not be executed for now my $user-id = retrive-the-first-user-id-from-db(); # use logf method to use sprintf-style logs .logf('the first user id in the database is %d', $user-id); } # Be careful with '.?' operator. Sins it is not an operator but syntax-sugar # to-json will be called in any case, but log will not be written for now. $log.debug-on.?log(to-json(%map, :pretty, :sorted-keys)); ``` ## Associate logs with concrete user Let's imagine we write a server application. Many users can connect to the server simultaneously and do some action, which produces log messages in a log file. If some exception will be caught and log, we want to reconstruct the user's execution flow to understand what went wrong. But needful records in the log file will be alongside logs from other users' actions. In such cases, we need to associate each log entry with some user id. Then we can grep the log file for the user id. For that, use `MDC`. In `Raku`: ``` use LogP6 :configure; cliche(:name<logfile>, :matcher<server-log>, grooves => ( writer( :pattern('[%date{$hh:$mm:$ss:$mss}][user:%mdc{user-id}]: %msg'), :handle('logfile.log'.IO.open)), level($info) )); my $server-log = get-logger('server-log'); sub database-read() { # note we do not pass $user in the sub $server-log.info('read from database'); # [23:35:43:1295][user:717]: read from database # read CATCH { default { $server-log.error('database fail', :x($_)); # [23:35:44:5432][user:717]: database fail Exception X::AdHoc "database not found" <trace> }} } sub enter(User $user) { $server-log.mdc-put('user-id', $user.id); $server-log.info('connected'); # [23:35:43:1245][user:717]: connected database-read(); $server-log.info('disconnected'); # [23:35:44:9850][user:717]: disconnected $server-log.mdc-remove('user-id'); # it is not necessary to remove 'user-id' value from MDC } ``` The same configuration you can write in the configuration file: ``` { "writers": [{ "type": "std", "name": "logfile", "pattern": "[%date{$hh:$mm:$ss:$mss}][user:%mdc{user-id}]: %msg", "handle": { "type": "file", "path": "logfile.log" }}], "filters": [{ "type": "std", "name": "logfile", "level": "info"}], "cliches": [{ "name": "logfile", "matcher": "server-log", "grooves": [ "logfile", "logfile" ]}] } ``` ## Filter log by its content Imagine we have an application that may write sensible content to log files, for example, user passwords. And we want to drop such sensible logs. We can use a particular sub in `do-before` action of log's `filter`. In `Raku`: ``` unit module Main; use LogP6 :configure; sub drop-passwords($context) is export {...} cliche(:name<sensible>, :matcher<log>, grooves => ( writer(:pattern('%msg'), :handle('logfile.log'.IO.open)), filter(:level($info), before-check => (&drop-passwords)) )); sub drop-passwords($context) { return False if $context.msg ~~ / password /; # If you want to remove a password from the log entry instead of dropping it, # you can remove the password from the message and store it in the context like: # # $context.msg-set(remove-password($context.msg)); True; } sub connect(User $user) { get-logger('log').infof('user with name %s and password %s connected', $user.id, $user.passwd); } ``` The same configuration you can write in the configuration file: ``` { "writers": [{ "type": "std", "name": "writer", "pattern": "%msg", "handle": { "type": "file", "path": "logfile.log" }}], "filters": [{ "type": "std", "name": "pass-filter", "level": "info", "before-check": [{ "require": "Main", "fqn-method": "Main::EXPORT::DEFAULT::&drop-passwords" }]}], "cliches": [{ "name": "logfile", "matcher": "server-log", "grooves": [ "writer", "pass-filter" ]}] } ``` ## Write one log in several outputs Let's imagine we have an application that works with several types of a database -- for example, Oracle and SQLite. We want to log work with the databases. But we want to store Oracle related logs in `oracle.log` and `database.log` files, and SQLite related records only in `database.log`. In this case, we need a straightforward logger for SQLite related logs and another one (with two grooves) for Oracle associated logs. In `Raku`: ``` use LogP6 :configure; set-default-pattern('%msg'); writer(:name<database>, :handle('database.log'.IO.open)); writer(:name<oracle>, :handle( 'oracle.log'.IO.open)); filter(:name<filter>, :level($info)); cliche(:name<oracle>, :matcher<oracle>, grooves => ('database', 'filter', 'oracle', 'filter')); cliche(:name<sqlite>, :matcher<sqlite>, grooves => ('database', 'filter')); sub oracle-db-fetch() { get-logger('oracle').info('fetch data'); # fetch } sub sqlite-db-fetch() { get-logger('sqlite').info('fetch data'); # fetch } ``` The same configuration you can write in the configuration file: ``` { "default-pattern": "%msg", "writers": [ { "name": "database", "type": "std", "handle": { "type": "file", "path": "database.log"}}, { "name": "oracle", "type": "std", "handle": { "type": "file", "path": "oracle.log" }} ], "filters": [{ "name": "filter", "type": "std", "level": "info" }], "cliches": [ { "name": "oracle", "matcher": "oracle", "grooves": [ "database", "filter", "oracle", "filter" ]}, { "name": "sqlite", "matcher": "sqlite", "grooves": [ "database", "filter" ]} ] } ``` ## Write logs in journald Let's imagine you want to store logs in journald service. You can use `LogP6::Writer::Journald` module for that. For more information, please look at the writer module README. Example of configuration: In `Raku`: ``` use LogP6 :configure; writer(LogP6::WriterConf::Journald.new( # name, pattern and auto-exceptions as in standard writer :name<to-journald>, :pattern('%msg'), :auto-exeptions # which additional information must be written :use-priority, # write 'PRIORITY=' field to journald automatically :use-mdc # write all MDC contend as field to journald in 'key=value' format )); ``` The same configuration you can write in the configuration file: ``` {"writers": [{ "type": "custom", "require": "LogP6::WriterConf::Journald", "fqn-class": "LogP6::WriterConf::Journald", "args": { "name": "to-journald", "pattern": "%msg", "auto-exceptions": true, "use-priority": true, "use-mdc": true } }]} ``` ## Write custom writer handle for your need Sometimes you may need to write log to some exotic place. In this case you will need to implement your own `Writer` and its `WriterConf`. In simple cases, it would be enough to implement your own `IO::Handle` for the standard writer. For example, there is no de-facto must-use library for working with databases yet. That is why there is no particular writer for it in `LogP6`. But let's try to write it now: Imagine we decided to use `SQLite` database and `DB::SQLite` library. We can ask the standard writer to prepare SQL insert expression for us. Therefore we can only write custom `IO::Handle`. Fortunately, it is easy in `6.d` version: ``` unit module MyDBHandle; use DB; use DB::SQLite; class DBHandle is IO::Handle { has Str $.filename is required; has DB $!db; submethod TWEAK() { self.encoding: 'utf8'; # open database file and create table for logging $!db = DB::SQLite.new(:$!filename); $!db.execute('create table if not exists logs (date text, level text, log text)'); } method WRITE(IO::Handle:D: Blob:D \data --> Bool:D) { # decode Blob data and execute. we expect the valid sql dml expression in data. $!db.execute(data.decode()); True; } method close() { $!db.finish } # close database method READ(|) { #`[do nothing] } method EOF { #`[do nothing] } } ``` It is all we need. Now we can write the `LogP6` configuration. In `Raku`: ``` use MyDBModule; use LogP6 :configure; writer( :name<db>, # pattern provides us a valid sql dml expression :pattern('insert into logs (date, level, log) values (\'%date\', \'%level\', \'%msg%x{ - $name $msg $trace}\')'), # handle with corresponding database filename handle => DBHandle.new(:filename<database-log.sqlite>), # turn off auto-exceptions because it will corrupt our sql dml expression :!auto-exceptions ); cliche(:name<db>, :matcher<db>, grooves => ('db', level($trace))); my $log-db = get-logger('db'); $log-db.info('database logging works well'); ``` The same configuration you can write in the configuration file: ``` { "writers": [{ "type": "std", "name": "db", "pattern": "insert into logs (date, level, log) values ('%date', '%level', '%msg%x{ - $name $msg $trace}'", "handle": { "type": "custom", "require": "MyDBModule", "fqn-class": "MyDBModule::DBHandle", "args": { "filename": "database-log.sqlite" } }, "auto-exceptions": false }], "filters": [{ "name": "filter", "type": "std", "level": "trace" }], "cliches": [{ "name": "db", "matcher": "db", "grooves": [ "db", "filter" ] }] } ``` ## Rollover log files Log files tend to grow in size. There is `IO::Handle::Rollover` module to prevent such uncontrolled growth. For example, you decided to store only 30MB of logs separated into three files for convenience. For that, you only need to create a custom handle with an `open` routine like that: In `Raku`: ``` use IO::Handle::Rollover; my $handle = open("log.txt", :w, :rollover, :file-size<10M>, :3history-size); ``` The same initialization you can write in the configuration file: ``` { ... "handle": { "type": "custom", "require": "IO::Handle::Rollover", "fqn-method": "IO::Handle::Rollover::EXPORT::DEFAULT::&open", "positional": [ "log.txt" ], "args": { "w": true, "rollover": true, "file-size": "10M", "history-size": 3 } } ... } ``` You can use the handle as any other output handles, for example, in LogP6 writers. For more information, see the documentation for the `IO::Handle::Rollover` module. # BEST PRACTICE Try to use good traits for your loggers. If you use loggers in your library, then probably using one prefix in all your traits is the best option. It allows users of your library to manage your loggers easily. Try to choose a logger trait according to logger semantic or location. For example, you can use `$?CLASS.^name` as a logger trait in any of your classes or traits like `database`, `user management`, or so. If you use logger within a class then make the logger be a class field like `has $!log = get-logger('$?CLASS.^name');` If you use logger withing a subroutines logic then make a special sub for retrieve logger like `sub log() { state $log = get-logger('trait'); }`. Then use it like `log.info('msg');` It prevents any side effects caused by precompilation. # SEE OLSO * [LogP6::Writer::Journald](https://modules.raku.org/dist/LogP6-Writer-Journald:cpan:ATROXAPER) * [IO::Handle::Rollover](https://modules.raku.org/dist/IO-Handle-Rollover:cpan:ATROXAPER) # ROADMAP * Add a `Cro::Transform` for using `LogP6` in `cro` applications. # AUTHOR Mikhail Khorkov [atroxaper@cpan.org](mailto:atroxaper@cpan.org) Source can be located at: [github](https://github.com/atroxaper/p6-LogP6). Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2020 Mikhail Khorkov This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-librasteve-App-Crag.md [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) # raku App::Crag Calculator using RAku Grammars for the command line NB. The syntax for measures changed from `:<...>` to `^<...>` to avoid clashes with the colon ## Install ``` zef install --verbose App::Crag ``` ## Usage ``` crag [--help] <cmd> ``` ## Examples ``` [1] > crag 'say (1.6km / (60 * 60 * 1s)).in: <mph>' #0.99mph [2] > crag '$m=95kg; $a=^<9.81 m/s^2>; $f=$m*$a; say $f' #931.95N [3] > crag 'say ^<12.5 ft ±3%> .in: <mm>' #3810mm ±114.3 [4] > crag '$λ=2.5nm; $ν=c/$λ; say $ν.norm' #119.91PHz [5] > crag '$c=^<37 °C>; $f=^<98.6 °F>; say $f cmp $c' #Same [6] > crag 'say @physics-constants-symbols.join: "\n"' # ... ``` * crag goes `subst( '^<' => '♎️<' )` * crag goes `sub r( $x = 0.01 ) { $Physics::Measure::round-val = $x }` * crag goes `subst( '§|(.+?)|' => 'Q|$0|.AST.EVAL' )` * crag goes `subst( (\w)’^’ => $0\c[Combining Right Arrow Above] )` * `echo RAKULANG='en_US'` for us gallons, pints, mpg, etc. ## More Info * <https://github.com/librasteve/raku-Physics-Measure.git> * <https://github.com/librasteve/raku-Physics-Unit.git> * <https://github.com/librasteve/raku-Physics-Error.git> * <https://github.com/librasteve/raku-Physics-Constants.git> * <https://github.com/raku-community-modules/Time-Duration-Parser> * <https://github.com/raku-community-modules/Slang-Roman> * <https://github.com/antononcube/Raku-Chemistry-Stoichiometry> ### Copyright copyright(c) 2023-2024 Henley Cloud Consulting Ltd.
## dist_zef-CIAvash-WebService-TMDB.md # NAME WebService::TMDB - A module for accessing [The Movie Database](https://themoviedb.org) data. # SYNOPSIS ``` use WebService::TMDB; my $tmdb = WebService::TMDB.new: :access_token<1234>; my $search = $tmdb.search_movie: query => 'legend of 1900'; say $search.results[0].title; my $movie = $tmdb.movie: 10775, :append(['credits']); say $movie.title; say $movie.credits.cast[0].name; my $find = $tmdb.find_by: ExternalSources::IMDB, :external_id<tt4540710>; say $find.movie_results[0].title; ``` # INSTALLATION You need to have [Raku](https://www.raku-lang.ir/en) and [zef](https://github.com/ugexe/zef), then run: ``` zef install "WebService::TMDB:auth<zef:CIAvash>" ``` or if you have cloned the repo: ``` zef install . ``` # TESTING ``` prove -ve 'raku -I.' --ext rakutest ``` # DESCRIPTION WebService::TMDB is a module for interfacing with the [TMDB API](https://developers.themoviedb.org/3/). An access token is required to use the API. # ATTRIBUTES/METHODS ### has Str $.access\_token Access token required by themoviedb.org ### has WebService::TMDB::Role::Request $.request handles('language', 'set\_language') An object for making requests to themoviedb.org ### method find\_by ``` method find_by( WebService::TMDB::ExternalSources(Str) $external_source, Str :$external_id! ) returns WebService::TMDB::Find ``` Find movie, TV, TV season and episode by external ID ### method movie ``` method movie( Int $id, :@append where { ... } ) returns WebService::TMDB::Movie ``` Get a specific movie by its ID. Credits and external IDs can be appended to response. ### method movie\_credits ``` method movie_credits( Int $id ) returns WebService::TMDB::Credits ``` Get credits for a movie ### method movie\_external\_ids ``` method movie_external_ids( Int $id ) returns WebService::TMDB::ExternalID ``` Get external IDs for a movie ### method movie\_upcoming ``` method movie_upcoming( *%params ) returns WebService::TMDB::Movie::Upcoming ``` Get upcoming movies ### method movie\_now\_playing ``` method movie_now_playing( *%params ) returns WebService::TMDB::Movie::Upcoming ``` Get movies that are in theatres ### method search\_movie ``` method search_movie( *%params ) returns WebService::TMDB::Movie::Search ``` Search for movies ### method discover\_movie ``` method discover_movie( *%params ) returns WebService::TMDB::Movie::Search ``` Discover movies ### method tv ``` method tv( Int $id, :@append where { ... } ) returns WebService::TMDB::TV ``` Get a TV show by its ID. Credits and external IDs can be appended to response. ### method season ``` method season( Int :$tv, Int :$season, :@append where { ... } ) returns WebService::TMDB::TV::Season ``` Get a TV season. Credits can be appended to response. ### method episode ``` method episode( Int :$tv, Int :$season, Int :$episode, :@append where { ... } ) returns WebService::TMDB::TV::Episode ``` Get a TV episode. Credits can be appended to response. ### method tv\_airing\_today ``` method tv_airing_today( *%params ) returns WebService::TMDB::TV::Search ``` Get TV shows that are airing today ### method tv\_on\_the\_air ``` method tv_on_the_air( *%params ) returns WebService::TMDB::TV::Search ``` Get TV shows that are currently on the air ### method search\_tv ``` method search_tv( *%params ) returns WebService::TMDB::TV::Search ``` Search TV shows ### method discover\_tv ``` method discover_tv( *%params ) returns WebService::TMDB::TV::Search ``` Discover TV shows ### method person ``` method person( Int $id, :@append where { ... } ) returns WebService::TMDB::Person ``` Get a person by its ID. Movie & TV credits and external IDs can be appended to response. ### method person\_movie\_credits ``` method person_movie_credits( Int $id ) returns WebService::TMDB::Person::MovieCredits ``` Get a person's movie credits ### method person\_tv\_credits ``` method person_tv_credits( Int $id ) returns WebService::TMDB::Person::TVCredits ``` Get a person's TV credits ### method person\_external\_ids ``` method person_external_ids( Int $id ) returns WebService::TMDB::ExternalID ``` Get a person's external IDs ### method search\_person ``` method search_person( *%params ) returns WebService::TMDB::Person::Search ``` Search people ### method genre\_movie\_list ``` method genre_movie_list() returns WebService::TMDB::Genre::List ``` Get genre list for movies ### method genre\_tv\_list ``` method genre_tv_list() returns WebService::TMDB::Genre::List ``` Get genre list for TV shows ### method certification\_movie\_list ``` method certification_movie_list() returns WebService::TMDB::CertificationList ``` Get certification list for movies ### method certification\_tv\_list ``` method certification_tv_list() returns WebService::TMDB::CertificationList ``` Get certification list for TV shows ### method configuration ``` method configuration() returns WebService::TMDB::Configuration ``` Get themoviedb.org configuration. themoviedb.org recommends caching this data and checking for updates every few days. # ERRORS `HTTP::UserAgent` module is used with exception throwing enabled. So exceptions will be thrown in case of non-existent resources, out of range values, etc. See <http://modules.raku.org/dist/HTTP::UserAgent>. When an exception of type `X::HTTP::Response` is caught, and the response received from themoviedb.org contains an error message, an attribute named `tmdb_status_message` or `tmdb_errors` will be added to the exception containing that error message. # ENVIRONMENT Some live tests will run when `NETWORK_TESTING` environment variable is set. # REPOSITORY <https://codeberg.org/CIAvash/WebService-TMDB> # BUGS <https://codeberg.org/CIAvash/WebService-TMDB/issues> # AUTHOR Siavash Askari Nasr - <https://siavash.askari-nasr.com> # COPYRIGHT AND LICENSE Copyright © Siavash Askari Nasr WebService::TMDB is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WebService::TMDB is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with WebService::TMDB. If not, see <http://www.gnu.org/licenses/>.
## unwrap.md unwrap Combined from primary sources listed below. # [In Routine](#___top "go to top of document")[§](#(Routine)_method_unwrap "direct link") See primary documentation [in context](/type/Routine#method_unwrap) for **method unwrap**. ```raku method unwrap($wraphandle) ``` Restores the original routine after it has been wrapped with [wrap](/routine/wrap). While the signature allows any type to be passed, only the [`Routine::WrapHandle`](/type/Routine/WrapHandle) type returned from `wrap` can usefully be.
## d.md d Combined from primary sources listed below. # [In IO::Special](#___top "go to top of document")[§](#(IO::Special)_method_d "direct link") See primary documentation [in context](/type/IO/Special#method_d) for **method d**. ```raku method d(IO::Special:D: --> False) ``` The 'directory' file test operator, always returns `False`. # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_d "direct link") See primary documentation [in context](/type/IO/Path#method_d) for **method d**. ```raku method d(IO::Path:D: --> Bool:D) ``` Returns `True` if the invocant is a path that exists and is a directory. The method will [`fail`](/routine/fail) with [`X::IO::DoesNotExist`](/type/X/IO/DoesNotExist) if the path points to a non-existent filesystem entity.
## precompilationrepository.md role CompUnit::PrecompilationRepository CompUnit::PrecompilationRepository This class provides stubs for each of the following methods. The methods are provided by sub-classes, such as `PrecompilationRepository::File`. Sub-classes are implementation dependent. # [Methods](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#Methods "direct link") ## [method new-unit](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_new-unit "direct link") ```raku method new-unit(| --> CompUnit::PrecompilationUnit:D) { ... } ``` Prepare a new implementation specific PrecompilationUnit for storage ## [method load-unit](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_load-unit "direct link") ```raku method load-unit(CompUnit::PrecompilationId $compiler-id, CompUnit::PrecompilationId $precomp-id) { ... } ``` Load the precompilation identified by the pairing of the specified compiler and precompilation ID. ## [method load-repo-id](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_load-repo-id "direct link") ```raku method load-repo-id(CompUnit::PrecompilationId $compiler-id, CompUnit::PrecompilationId $precomp-id) { ... } ``` Return the repository id for which the specified precomp file's dependencies have been validated ## [method store-file](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_store-file "direct link") ```raku method store-file(CompUnit::PrecompilationId $compiler-id, CompUnit::PrecompilationId $precomp-id, IO::Path:D $path, :$extension = '') { ... } ``` Store the file at the specified path in the precompilation store, under the given compiler ID and precompilation ID. ## [method store-unit](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_store-unit "direct link") ```raku method store-unit(CompUnit::PrecompilationId $compiler-id, CompUnit::PrecompilationId $precomp-id, CompUnit::PrecompilationUnit $unit) { ... } ``` Store the given precompilation unit in the precompilation store under the given compiler ID and precompilation ID. ## [method store-repo-id](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_store-repo-id "direct link") ```raku method store-repo-id(CompUnit::PrecompilationId $compiler-id, CompUnit::PrecompilationId $precomp-id, :$repo-id!) { ... } ``` Store the given repo-id for a precompilation under the given compiler ID and precompilation ID. ## [method delete](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_delete "direct link") ```raku method delete(CompUnit::PrecompilationId $compiler-id, CompUnit::PrecompilationId $precomp-id) { ... } ``` Delete an individual precompilation. ## [method delete-by-compiler](#role_CompUnit::PrecompilationRepository "go to top of document")[§](#method_delete-by-compiler "direct link") ```raku method delete-by-compiler(CompUnit::PrecompilationId $compiler-id) { ... } ``` Delete all precompilations for a particular compiler.
## telemetry.md class Telemetry Collect performance state for analysis ```raku class Telemetry { } ``` **Note:** This class is a Rakudo-specific feature and not standard Raku. On creation, a `Telemetry` object contains a snapshot of various aspects of the current state of the virtual machine. This is in itself useful, but generally one needs two snapshots for the difference (which is a [`Telemetry::Period`](/type/Telemetry/Period) object). The Telemetry object is really a collection of snapshots taken by different "instruments". By default, the [`Telemetry::Instrument::Usage`](/type/Telemetry/Instrument/Usage) and [`Telemetry::Instrument::ThreadPool`](/type/Telemetry/Instrument/ThreadPool) instruments are activated. The `Telemetry` (and [`Telemetry::Period`](/type/Telemetry/Period)) object also [`Associative`](/type/Associative). This means that you can treat a Telemetry object as a read-only [`Hash`](/type/Hash), with all of the data values of the instruments as keys. You can determine which instruments `Telemetry` should use by setting the `$*SAMPLER` dynamic variable, which is a [`Telemetry::Sampler`](/type/Telemetry/Sampler) object. Currently, the following instruments are supported by the Rakudo core: * Telemetry::Instrument::Usage Provides (in alphabetical order): `cpu`, `cpu-sys`, `cpu-user`, `cpus`, `id-rss`, `inb`, `invcsw`, `is-rss`, `ix-rss`, `majf`, `max-rss`, `minf`, `mrcv`, `msnd`, `nsig`, `nswp`, `volcsw`, `outb`, `util%` and `wallclock`. For complete documentation of the meaning of these data values, see [`Telemetry::Instrument::Usage`](/type/Telemetry/Instrument/Usage). * Telemetry::Instrument::Thread Provides (in alphabetical order): `tad`, `tcd`, `thid`, `tjd`, `tsd` and `tys`. For complete documentation of the meaning of these data values, see [`Telemetry::Instrument::Thread`](/type/Telemetry/Instrument/Thread). * Telemetry::Instrument::ThreadPool Provides (in alphabetical order): `atc`, `atq`, `aw`, `gtc`, `gtq`, `gw`, `s`, `ttc`, `ttq` and `tw`. For complete documentation of the meaning of these data values, see [`Telemetry::Instrument::ThreadPool`](/type/Telemetry/Instrument/ThreadPool). * Telemetry::Instrument::AdHoc Does not provide any data by itself: one must indicate which variables are to be monitored, which will then become available as methods with the same name on the instrument. ## [routine T](#class_Telemetry "go to top of document")[§](#routine_T "direct link") ```raku sub T() ``` Shortcut for `Telemetry.new`. It is exported by default. Since the `Telemetry` class also provides an [`Associative`](/type/Associative) interface, one can easily interpolate multiple values in a single statement: ```raku use Telemetry; say "Used {T<max-rss cpu>} (KiB CPU) so far"; ``` ## [routine snap](#class_Telemetry "go to top of document")[§](#routine_snap "direct link") ```raku multi snap(--> Nil) multi snap(Str:D $message --> Nil) multi snap(Str $message = "taking heap snapshot...", :$heap!) multi snap(@s --> Nil) ``` The `snap` subroutine is shorthand for creating a new `Telemetry` object and pushing it to an array for later processing. It is exported by default. From release 2021.12, it returns the filename it's storing the snapshots in the case it's provided with a `:$heap` associative parameter. ```raku use Telemetry; my @t; for ^5 { snap(@t); # do some stuff LAST snap(@t); } ``` If no array is specified, it will use an internal array for convenience. ## [routine snapper](#class_Telemetry "go to top of document")[§](#routine_snapper "direct link") ```raku sub snapper($sleep = 0.1, :$stop, :$reset --> Nil) ``` The `snapper` routine starts a separate thread that will call `snap` repeatedly until the end of program. It is exported by default. By default, it will call `snap` every **0.1** second. The only positional parameter is taken to be the delay between `snap`s. Please see the [snapper module](#module_snapper) for externally starting a snapper without having to change the code. Simply adding `-Msnapper` as a command line parameter, will then start a snapper for you. ## [routine periods](#class_Telemetry "go to top of document")[§](#routine_periods "direct link") ```raku multi periods( --> Seq) multi periods(@s --> Seq) ``` The `periods` subroutine processes an array of `Telemetry` objects and generates a [`Seq`](/type/Seq) of [`Telemetry::Period`](/type/Telemetry/Period) objects out of that. It is exported by default. ```raku .<cpu wallclock>.say for periods(@t); # OUTPUT: # ==================== # (164 / 160) # (23 / 21) # (17 / 17) # (15 / 16) # (29 / 28) ``` If no array is specified, it will use the internal array of `snap` without parameters **and** will reset that array upon completion (so that new `snap`s can be added again). ```raku use Telemetry; for ^5 { snap; LAST snap; } say .<cpu wallclock>.join(" / ") for periods; # OUTPUT: # ==================== # 172 / 168 # 24 / 21 # 17 / 18 # 17 / 16 # 27 / 27 ``` If only one `snap` was done, another `snap` will be done to create at least one [`Telemetry::Period`](/type/Telemetry/Period) object. ## [routine report](#class_Telemetry "go to top of document")[§](#routine_report "direct link") ```raku multi report(:@columns, :$legend, :$header-repeat, :$csv, :@format) ``` The `report` subroutine generates a report about an array of `Telemetry` objects. It is exported by default. These can have been created by regularly calling `snap`, or by having a [snapper](/routine/snapper) running. If no positional parameter is used, it will assume the internal array to which the parameterless `snap` pushes. Below are the additional named parameters of `report`. * `:columns` Specify the names of the columns to be included in the report. Names can be specified with the column name (e.g. `gw`). If not specified, defaults to what is specified in the `RAKUDO_REPORT_COLUMNS` environment variable. If that is not set either, defaults to: 「text」 without highlighting ``` ``` wallclock util% max-rss gw gtc tw ttc aw atc ``` ``` * `:header-repeat` Specifies after how many lines the header should be repeated in the report. If not specified, defaults to what is specified in the `RAKUDO_REPORT_HEADER_REPEAT` environment variable. If that is not set either, defaults to 32. * `:legend` Specifies whether a legend should be added to the report. If not specified, defaults to what is specified in the `RAKUDO_REPORT_LEGEND` environment variable. If that is not set either, defaults to True. If there are `snap`s available in the internal array at the end of the program, then `report` will be automatically generated and printed on `STDERR`. ## [module snapper](#class_Telemetry "go to top of document")[§](#module_snapper "direct link") Start a thread taking repeated system state snapshots. This module contains no subroutines or methods or anything. It is intended as a shortcut for starting the [snapper](/routine/snapper) subroutine of the `Telemetry` module, allowing taking snapshots of the execution of a program without needing to change the program. Simple loading the module with `-Msnapper` will do all that is needed to start the snapper, and have a report printed on STDERR upon completion of the program. The `RAKUDO_SNAPPER` environment variable can be set to indicate the time between snapshots. If not specified, it will default to **0.1** seconds. The `snapper` module assumes an orderly shutdown of the process. Killing the process (for instance by pressing Control-c) will **not** produce a report. ## [module safe-snapper](#class_Telemetry "go to top of document")[§](#module_safe-snapper "direct link") Available as of the 2021.09 release of the Rakudo compiler. This module provides a safe alternative to the `snapper` module: killing a process by pressing Control-c **will** produce a report. It is able to do so by installing a [signal handler](/type/Supply#sub_signal), which **may** interfere with normal functioning of interactive programs. Killing a process in any other way, will **not** produce a report. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Telemetry` raku-type-graph Telemetry Telemetry Any Any Telemetry->Any Mu Mu Any->Mu Associative Associative Telemetry::Period Telemetry::Period Telemetry::Period->Telemetry Telemetry::Period->Associative [Expand chart above](/assets/typegraphs/Telemetry.svg)
## dist_zef-jonathanstowe-Doublephone.md # Doublephone Implementation of the Double Metaphone phonetic encoding algorithm. ## Synopsis ``` use Doublephone; say double-metaphone("SMITH"); # (SM0 XMT) say double-metaphone("SMIHT"); # (SMT XMT) ``` ## Description This implements the [Double Metaphone](https://en.wikipedia.org/wiki/Metaphone#Double_Metaphone) algorithm which can be used to match similar sounding words. It is an improved version of Metaphone (which in turn follows on from soundex,) and was first described by Lawrence Philips in the June 2000 issue of the C/C++ Users Journal. It differs from some other similar algorithms in that a primary and secondary code are returned which allows the comparison of words (typically names,) with some common roots in different languages as well as dealing with ambiguities. So for instance "SMITH", "SMYTH" and "SMYTHE" will yield (SM0 XMT) as the primary and secondary, whereas "SCHMIDT", "SCHMIT" will yield (XMT SMT) so if a "cross language" comparison is required then either of the primary or secondary codes can be matched to the target primary or secondary code - this will also deal with, for example, transpositions in typed names. This is basically a Raku binding to the original C implementation I extracted from the Perl 5 [Text::DoubleMetaphone](https://metacpan.org/release/Text-DoubleMetaphone). The algorithm itself isn't designed for unicode strings and making something that is is probably best left to another module using a different technique. Though this is described as a "phonetic" encoding it is only approximately so, rather it is optimised for comparison and not as a guide to how something might be pronounced. ## Installation If you have a working installation of Rakudo with `zef` installed then you should be able to install this with either: ``` zef install Doublephone # or from a local clone zef install . ``` Though other installers may become available that should work equally. ## Support Almost all of the functionality of this is in the C library which has a fairly long heritage, so is less likely to be buggy than the way in which I am using it. Please feel free to report any bugs/send patches or just make suggestions to <https://github.com/jonathanstowe/Doublephone/issues> I would also like more tests for the correct output if anyone finds a good data source for these. # Licence and Copyright This is free software, please see the <LICENCE> file in the distribution. © Jonathan Stowe, 2016 - 2021 The C portions from Text::DoubleMetaphone have the following copyright text: Copyright 2000, Maurice Aubrey [maurice@hevanet.com](mailto:maurice@hevanet.com). All rights reserved. This code is based heavily on the C++ implementation by Lawrence Philips and incorporates several bug fixes courtesy of Kevin Atkinson [kevina@users.sourceforge.net](mailto:kevina@users.sourceforge.net). This module is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
## now.md now Combined from primary sources listed below. # [In Terms](#___top "go to top of document")[§](#(Terms)_term_now "direct link") See primary documentation [in context](/language/terms#term_now) for **term now**. Returns an [`Instant`](/type/Instant) object representing the current time. It includes [leap seconds](https://en.wikipedia.org/wiki/Leap_second) and as such is a few dozen seconds larger than [time](/language/terms#term_time): ```raku say (now - time).Int; # OUTPUT: «37␤» ``` # [In DateTime](#___top "go to top of document")[§](#(DateTime)_method_now "direct link") See primary documentation [in context](/type/DateTime#method_now) for **method now**. ```raku method now(:$timezone = $*TZ, :&formatter --> DateTime:D) ``` Creates a new `DateTime` object from the current system time. A custom [formatter](/routine/formatter) and [timezone](/routine/timezone) can be provided. The `:$timezone` is the offset **in seconds** from [GMT](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) and defaults to the value of [`$*TZ` variable](/language/variables#index-entry-%24*TZ). ```raku say DateTime.now; # OUTPUT: «2018-01-08T13:05:32.703292-06:00␤» ``` Note that one may use the methods shown below chained to the `.now` to easily express current values, e.g., ```raku say DateTime.now.year; # OUTPUT: «2018␤» ```
## dist_zef-lizmat-Code-Coverable.md [![Actions Status](https://github.com/lizmat/Code-Coverable/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Code-Coverable/actions) [![Actions Status](https://github.com/lizmat/Code-Coverable/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Code-Coverable/actions) [![Actions Status](https://github.com/lizmat/Code-Coverable/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Code-Coverable/actions) # NAME Code::Coverable - Produce overview of coverable lines of code # SYNOPSIS ``` use Code::Coverable; say coverable-lines($path.IO); # (3 5 11 24) say coverable-lines($source); # (7 9 23 25) my @coverables = coverables(@paths); ``` # DESCRIPTION Code::Coverable contains logic for producing code coverage reports. This is still a work in progress. At the moment it will only export subroutines and install a script "coverage-lines". # SUBROUTINES ## coverable-lines ``` say coverable-lines($path.IO); # (3 5 11 24) say coverable-lines($source); # (7 9 23 25) ``` The `coverable-lines` subroutine takes a single argument which is either a `IO::Path` or a `Str`, uses its contents (slurped in case of an `IO::Path`), tries to build an AST from that and returns a sorted list of line numbers that appear to have coverable code. ## coverables ``` for coverables(@targets) -> $cc { say $cc.target; say $cc.key; say $cc.line-numbers; say $cc.source; } ``` The `coverables` subroutine takes any number of positional arguments, each of which is assumed to be a target specification, which can be: * a `Str` specification of a Raku source file * an `IO::Path` object specifying a Raku source file * a `use` target (identity) such as "Foo::Bar:ver<0.0.2+>" It returns a `Seq` of `Code::Coverable` objects. Note that it **is** possible that even a single target produces more than one `Code::Coverable` object, if the source of the target has used `#line 42 filename` directives. ``` for coverables("String::Utils", :repo<.>, :raw) -> $cc { say $cc.target; say $cc.key; say $cc.line-numbers; say $cc.source; } ``` If `use` targets (identities) are specified, a `:repo` named argument can be specified to indicate the repository to be used, which can be an object of type: * Str - indicate a path for a ::FileSystem repo, just as with -I. * IO::Path - indicate a path for a ::FileSystem repo * CompUnit::Repository - the actual repo to use The default is to use the current `$*REPO` setting to resolve any identity given. The `raw` named argument can be used to indicate that no heuristics should be applied to mark lines (that are marked as "coverable" by the original discovery method) as **not** coverable by a set of heuristics. The default is to apply the heuristics. If a `True` value is specified, then the chance of false negatives in coverage reports is significantly increased. If a line in the source can not be recognized automatically, then the module developer can add the exact string `# UNCOVERABLE` at the **end** of the line that can not be covered. ## key2source ``` print .slurp with key2source($key); # show source for the given key ``` The `key2source` subroutine converts a given coverage key to a `IO::Path` of the source file (if possible), or returns `Nil`. # CLASSES ## Code::Coverable The `Code::Coverable` object is generally created by the `coverables` subroutine, but could also be created manually. ``` my $cc = Code::Coverable.new( target => "Identity::Utils", line-numbers => (1,14,19,...), key => "site#sources/072CEA63F659CFD963095494CEA22A46E4F93A95 (Identity::Utils)" source => "/.../site/sources/072CEA63F659CFD963095494CEA22A46E4F93A95".IO, ); ``` The following public attributes are available: ### target Mandatory: a string with the target for these coverables: this can either be `use` target (identity), or a path to a source file. ### line-numbers Mandatory: a `List` of unique integer values of the line numbers that **could** potentially be covered in a coverage log. ### key Optional: a string that should match in the coverage log to mark a line as being "covered". Defaults to the target given. ### source Optional: an `IO::Path` object of the Raku source file. If not specified, will be derived from the information specified for the key. # SCRIPTS ## coverable-lines ``` $ coverable-lines t/01-basic.rakutest t/01-basic.rakutest: 1,3,5,7,8,9,10,13,14,15,16,17 $ coverable-lines snapper core#sources/0D09916411FC21C59FC3C0980C68547D31562E01 (snapper): 1,8,10 ``` The `coverable-lines` script accepts any number of paths or `use` targets and will attempt to produce one line of output with the coverage key and the line numbers of the lines that may appear in a coverage report. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) # COPYRIGHT AND LICENSE Copyright 2024, 2025 Elizabeth Mattijsen Source can be located at: <https://github.com/lizmat/Code-Coverable> . Comments and Pull Requests are welcome. If you like this module, or what I'm doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-ARNE-Game-Amazing.md # NAME Game::Amazing - Create, edit and check mazes for traversability # SYNOPSIS ``` use Game::Amazing; ``` # DESCRIPTION Game::Amazing can generate mazes, and check them for traversability (with the Shortest Path and the Wall Follower Algorithms). The module comes with some sample programs, including two games and a maze editor, described in the EXAMPLES section. See <https://raku-musings.com/amazing.html> for more information. # METHODS ## new Generate a new maze. There are two versions: ``` my $m = Game::Amazing::new($file); ``` This call loads an existing maze from a file. The filename must end with «.maze». ``` my $m = Game::Amazing::new(rows => 25, cols => 25, scale => 7, ensure-traversable => False); ``` This one generates a randon maze, with the given size. It is also possible to generate a new maze with an existing object with this one: ``` $m.new(rows => 25, cols => 25, scale => 7, ensure-traversable => False); ``` This is done by the «amazing-termbox» program when a new game is initiated, as letting the original maze object go out of scope terminates the program (without explanation). ## new-embed This method takes a string and uses that to build the maze. Illegal characters are ok, as it is (mostly) meant for testing of maze transformations. An empty string will give an empty maze. ``` my $m = Game::Amazing::new-embed("ABC\nDEF\nGHI\n"); ``` ## save Save the maze. There are three (or four) versions of this method. Tou can pass it a filehandle (to a file open for writing): ``` my IO::Handle $fh = open :w, 'my-maze.maze'; $m.save ($fh); $fh.close; ``` Or you can specify a filename: ``` $m.save ('my-maze.maze'); ``` The filename must end with «.maze». This version has no positional argument, and will save the maze with a randomly generated filename. The filename is returned. ``` my $filname = $m.save; say $filename; # -> /tmp/8spgH2MQBT.maze ``` You can add the «with-size» option to get the size of the maze added to the filename ``` my $filname = $m.save(with-size); say $filename; # -> /tmp/AZPNWawtTz-25x25.maze ``` ## as-string Return the maze as a single string with embedded newlines. It is used internally by the save method, but can be used by user code as well. ``` my $string = $m.as-string; ``` ## set-cell Change the symbol for the cell with the specified row and column. This works directly on the maze, changing the affect of future calls to the methods `get-directions`, `has-direction`, `is-traversable` and `is-traversable-wall`. ``` $m.set-cell($row, $col, $symbol); ``` This method is used by «amazing-gtk» to change cell values in edit mode. Note that there is not check on the legality of the new symbol, nor the length of the value. This is on purpose, making it possible to add markup to the maze itself before printing it. This is done by «maze-solver-spa». This is subject to change. ## get-cell Get the symbol at the given postition. ``` my $symbol = $m.get-cell($row, $col); ``` ## get-size Get the size (number of rows and columns) of the maze. ``` my ($rows, $cols) = $m.get-size; ``` ## fix-corners This method will ensure that the maze has exactly one entrance and one exit. The randomly generated mazes have two exit symbols, and «amazing-gtk» will change the top left one to an entrance symbol. («amazing-termbox» checks for the coordinates and not the cell value, and does not use this functionality.) Saving a maze in «amazing-gtk» ``` $m.fix-corners; ``` Note that the method does not check for entrance end exits symbols in other positions in the maze (than the four corners), but should herhaps do so. It is possible to swap the entreance and exit. by using the *upside-down* argument. ``` $m.fix-corners(upside-down => True); ``` **More explanation** ## get-directions This method return a string of directions from the specified cell. The letters are «N» (north), «E» (east), «S» (south) and «W» (west). Note that this method consider the neighbouring cells, so an exit in the current cell towards a neighbouring cell that does not have a corresponding entrance (exit) will be ignored. ``` my $directions = $m.get-directions ($row, $col); ``` ## has-direction Check if the specified cell has an exit in the given direction, where the direction is one of «N» (north), «E» (east), «S» (south) and «W» (west). Note that this method looks at the current cell only, without considering the neighbouring cellsm, so it is mainly for internal use. Use `get-directions` to get directions that actually exist. ``` my $boolean = $.has-direction($row, $col, $direction); ``` ## remove-direction Remove the specified direction (on the form «N», «E», «S» or «W») from the specified cell. It returns False if it was unable to change the character, and True on success. If the cell had two exits, the result of removing one of them is an empty cell (a space symbol). ``` my $boolean = $.remove-direction($row, $col, $direction); ``` This method does not work on the entrance or exit. ## add-direction Add the specified direction (on the form «N», «E», «S» or «W») to the specified cell. It returns False if it was unable to change the character, and True on success. Nothing is done if the cell is empty (a space symbol). ``` my $boolean = $.remove-direction($row, $col, $direction); ``` This method does not work on the entrance or exit. ## toggle-direction Remove the specified direction (on the form «N», «E», «S» or «W») to the specified cell, if it is there, and add it otherwise. Removing a direction from a cell with two exits removes both, and adding a direction to an empty cell will fail. The method returns True if it was able to change the cell. ``` my $boolean = $.toggle-direction($row, $col, $direction); ``` ## is-traversable Check if the maze is traversable, using the Shortest Path Algorithm. ``` my $boolean = $m.is-traversable; ``` The module will not calculate the value *before* you call the method. Then the value (as well as the path or coverage map) is cached. Use the «:force» argument to force the program to check the path again: ``` my $boolean = $m.is-traversable(:force); ``` This is used by the maze editor, whenever the user changes a symbol. *Note that this method assumes that the entrance and exit are located in the upper left and lower right corners (or vice versa).* ## get-path This gives the path, if the maze is traversable, and an empty string if not. The path is a string of directional letters. Start at the entrance and apply them one by one to get the actual path. The length of the string gives the number of steps. ## get-coverage This gives the coverage, i.e. a list of cells that are reachable from the entrance. This is given as a two-dimentional array, e.g. ``` my @coverage = $m.get-coverage; my $row = 10; my $col = 8; say "Been there" if @coverage[$row][$col]; ``` *Note that this method assumes that the entrance is located in the upper left corner.* ## is-traversable-wall Check if the maze is traversable, using the Wall Follower Algorithm. Note that this method does not cache the values (as opposed to «is-traversable»). ``` my $boolean = $m.is-traversable-wall (:$get-path, :$left, :$verbose) ``` You can get the path with the «:get-path» option. The path will usually be rather convoluted, so the result here is a coverage array regardless of traversability. ``` my ($boolean, $path) = $m.is-traversable-wall(:get-path); my @visited = @($path); ``` The method follows the right wall by default. Specify «:left» to override this: ``` my $boolean = $m.is-traversable-wall (:left) ``` Note that the Wall Follower Algorith will return you to the entrance if the maze is untraversable. The Left and Right variants will thus give the same result on an untraversable maze (but from opposite directions). It is possible to get some verbose output from the method, with the «:verbose» option. ``` my $boolean = $m.is-traversable-wall(:verbose); ``` This is normally not very useful to end users. An example, where the `<red>` tag should not be taken literally: ``` my ($boolean, $path) = $m.is-traversable-wall(:get-path); my @visited = @($path); for ^$m.rows -> $row { for ^$m.cols -> $col { print @visited[$row][$col] ?? '<red>' ~ $m.maze[$row][$col] ~ '</red>' ?? $m.maze[$row][$col]; } say ''; } ``` *Note that this method assumes that the entrance and exit are located in the upper left and lower right corners (or vice versa).* ## transform Transform the maze in the specified way. This will generate a new maze, which is the return value, and will not affect the current maze. The method takes one argument, which is one of: * **R** or **90** - rotate 90 degrees to the right * **D** or **180** - rotate 180 degrees (down) * **L** or **270** - rotate 90 degrees to the left * **H** - flip horizonatally * **V** - flip vertically ``` my $new = $m.transform("R"); ``` Note that the entrance and exit symbols (which are identical) will not be fixed when moved to the *wrong* corners, but this can be fixed by using the «corners» option: ``` my $new = $m.transform("R", :corners); ``` The corners that are un-entrancified and un-exitified get a symbol with two exits. This will actually roundtrip, as long as the original maze does not have any spurious exits (exits leading out of the maze). Scroll down to «An Even More Amazing Program» in <https://raku-musings.com/amazing1.html> for more information. # EXAMPLES The *bin* directory has some programs that will be installed on installation. *zef* will tell you where they are installed, so that you can choose to add the directory to the path. Below is a short description. You can run any of them with the «-h» command line option to get more information. The programs: ## mazemaker Generate a random maze. ## maze-solver-spa Check if a given maze is traversable, using the «Shortest Path Algorithm». ## maze-solver-wall Check if a given maze is traversable, using the «Wall Follower Algorithm». ## maze-solver-summary Check if one or more mazes are traversable, and report how difficult they are. ## amazing-termbox A game. Traverse the maze in your terminal window. It sses the «Termbox» module. ## amazing-gtk Another game. Traverse the maze in a graphical window. It uses the «Gnome::GTK» module. This program can also edit mazes. ## maze-transform Transform a maze file. It supports rotation (90, 180 and 270 degrees) and flipping (horizontal and vertical). By default it doesn't move the entrance and exit, but this can be done with a command line option. # AUTHOR Arne Sommer [arne@perl6.eu](mailto:arne@perl6.eu) # COPYRIGHT AND LICENSE Copyright 2020 Arne Sommer This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-guifa-Intl-UserLanguage.md ![](docs/logo.png) This is a incredibly simple module for Raku designed to do one thing and one thing only: obtain the current user’s preferred language(s). There is no universal way to do this, so this module aims to be the one-stop shop to get that information. To use, simply ask for the preferred language (if you just want one) or preferred languages (more common). ``` use Intl::UserLanguage; user-language; # ↪︎ [ast-US] (on my system) user-languages; # ↪︎ [ast-US], [es-US], [en-US], [pt-PT] (on my system) # (sidenote: no idea why Apple adds -US onto ast…) # (sidenote: Microsoft makes it ast-Latn… weird.) ``` In truth, the preferred language is just a wrapper for calling `.head` on the list. I'd recommend against using `user-language`, as most times when you need the languages (HTTP request headers, localization frameworks) there needs to be a negotiation to find a best match. In any case, both functions allow you to supply a default code which may be a string in BCP47 format or a LanguageTag. This is useful in case for some reason the user’s language(s) cannot be determined, for example, if the user is running an operating system that has not had its settings cataloged in this module. If you do not provide a default, and no language can be found, the *default* default language is **en** (English). As a final option, particularly if you want to test your code with other languages, you can override the user’s system languages: ``` use Intl::UserLanguage :override; # imports override functions user-languages; # ↪︎ [ast-US], [es-US], [en-US], [pt-PT] (on my system) override-user-languages('jp','zh'); user-languages; # ↪︎ [jp], [zh] ``` The override can be cleared at any time with `clear-user-language-override`. Note that the override is *global*, and there is no current way to lexically scope it; # Support Support is current available for the following OSes: * **macOS** Full list of languages (as defined in *System Preferences → Language & Region → Preferred Languages*). Paralinguistic preferences (e.g. calendar type) are not set on a per-language basis, so they carry to all languages. * **Linux**: If `$LANGUAGE` is set, then an ordered list is provided. Otherwise, it falls back to the more universal `$LANG`, which only provides a single language. * **Windows**: If the registry value `Languages` is set in `HKCU\Control Panel\International\User Profile`, uses the ordered list found there. Otherwise, it falls back to the registry value `LocaleName` found in at `HKCU\Control Panel\International`. Support is not available for \*nix machines right now, but only because I am not sure what the `$*DISTRO` value is for those systems. I imagine detection will be similar if not identical to Linux. Please contact me with your `$*DISTRO` value and how to detect your system language(s) and I'll gladly add it. # Lightweight mode (under development) If your program only needs the language code to pass it through to something that only employs strings (e.g. to directly create a , it may be useful to `use` the module in `:light` mode. Instead of receiving a `LanguageTag` object, you will get a `Str` that can be passed into other modules. # Version History * 0.4.0 * Moved individual OS versions into separate submodules. This will be more maintainable long term * Adjusted OS detection for macOS (Rakudo no longer reports it as `macosx` but rather `macos`) * Completely rewritten Mac code to support some extended attributes. * Sets up a model for using NativeCall when possible, and falling back to a slower method if not (Windows will eventually adopt a similar approach) * 0.3 * Cache language(s) on first call to `user-language[s]` This should provide a substantial speed up for modules like `Intl::*` that call this frequently as a fall back. # Licenses and Legal Stuff This module is licensed under the Artistic License 2.0 which is included with the source. Camelia (the butterfly) is a trademark belonging to Larry Walls and used in accordance with his terms.
## dist_zef-raku-community-modules-Net-IMAP.md [![Actions Status](https://github.com/raku-community-modules/Net-IMAP/workflows/test/badge.svg)](https://github.com/raku-community-modules/Net-IMAP/actions) # Net-IMAP An IMAP client library. ## Example Usage ``` my $i = Net::IMAP.new(:$server); $i.authenticate($user, $pass); $i.select('INBOX'); my @messages = $i.search(:all); for @messages { say .mime.header('subject'); } ``` ## Simple interface methods * `new(:$server, :$port = 143, :$debug, :$socket, :$ssl, :$starttls, :$plain)` * `authenticate($user, $pass)` * `mailboxes(:$subscribed)` * `create($mailbox)` * `delete($mailbox)` * `rename($old-box, $new-box)` * `subscribe($mailbox)` * `unsubscribe($mailbox)` * `select($mailbox)` * `append($message)` * `get-message(:$sid, :$uid)` * `search(*%params)` * `logout()`, `quit()` ### Net::IMAP::Message methods * `sid` * `uid` * `flags(@new?)` * `copy($mailbox)` * `delete` * `data` * `mime-headers` * `mime` ## Raw interface methods * `get-response` * `capability` * `noop` * `logout` * `starttls` * `switch-to-ssl` * `login($user, $pass)` * `select($mailbox)` * `examine($mailbox)` * `create($mailbox)` * `delete($mailbox)` * `rename($oldbox, $newbox)` * `subscribe($mailbox)` * `unsubscribe($mailbox)` * `list($ref, $mbox)` * `lsub($ref, $mbox)` * `status($mbox, $type)` * `append($name, $message, :$flags, :$datetime)` * `check` * `close` * `expunge` * `uid-search(*%query)` * `search(*%query)` * `uid-fetch($seq, $items)` * `fetch($seq, $items)` * `uid-store($seq, $action, $values)` * `store($seq, $action, $values)` * `uid-copy($seq, $mbox)` * `copy($seq, $mbox)` # AUTHOR Andrew Egeler Source can be located at: <https://github.com/raku-community-modules/Net-IMAP> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2014 - 2018 Andrew Egeler Copyright 2019 - 2022 Raku Community All files in this repository are licensed under the terms of Create Commons License; for details please see the LICENSE file
## dist_zef-lizmat-Array-Agnostic.md [![Actions Status](https://github.com/lizmat/Array-Agnostic/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Array-Agnostic/actions) [![Actions Status](https://github.com/lizmat/Array-Agnostic/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Array-Agnostic/actions) [![Actions Status](https://github.com/lizmat/Array-Agnostic/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Array-Agnostic/actions) # NAME Array::Agnostic - be an array without knowing how # SYNOPSIS ``` use Array::Agnostic; class MyArray does Array::Agnostic { method AT-POS() { ... } method elems() { ... } } my @a is MyArray = 1,2,3; ``` # DESCRIPTION This module makes an `Array::Agnostic` role available for those classes that wish to implement the `Positional` role as an `Array`. It provides all of the `Array` functionality while only needing to implement 2 methods: ## Required Methods ### method AT-POS ``` method AT-POS($position) { ... } # simple case method AT-POS($position) { Proxy.new( FETCH => { ... }, STORE => { ... } } ``` Return the value at the given position in the array. Must return a `Proxy` that will assign to that position if you wish to allow for auto-vivification of elements in your array. ### method elems ``` method elems(--> Int:D) { ... } ``` Return the number of elements in the array (defined as the index of the highest element + 1). ## Optional Methods (provided by role) You may implement these methods out of performance reasons yourself, but you don't have to as an implementation is provided by this role. They follow the same semantics as the methods on the [Array object](https://docs.perl6.org/type/Array). In alphabetical order: `append`, `Array`, `ASSIGN-POS`, `end`, `gist`, `grab`, `iterator`, `keys`, `kv`, `list`, `List`, `new`, `pairs`, `perl`, `pop`, `prepend`, `push`, `shape`, `shift`, `Slip`, `STORE`, `Str`, `splice`, `unshift`, `values` ## Optional Internal Methods (provided by role) These methods may be implemented by the consumer for performance reasons or to provide a given capability. ### method BIND-POS ``` method BIND-POS($position, $value) { ... } ``` Bind the given value to the given position in the array, and return the value. Will throw an exception if called and not implemented. ### method DELETE-POS ``` method DELETE-POS($position) { ... } ``` Mark the element at the given position in the array as absent (make `EXISTS-POS` return `False` for this position). Will throw an exception if called and not implemented. ### method EXISTS-POS ``` method EXISTS-POS($position) { ... } ``` Return `Bool` indicating whether the element at the given position exists (aka, is **not** marked as absent). If not implemented, Will call `AT-POS` and return `True` if the returned value is defined. ### method CLEAR ``` method CLEAR(--> Nil) { ... } ``` Reset the array to have no elements at all. By default implemented by repeatedly calling `DELETE-POS`, which will by all means, be very slow. So it is a good idea to implement this method yourself. ### method move-indexes-up ``` method move-indexes-up($up, $start = 0) { ... } ``` Add the given value to the **indexes** of the elements in the array, optionally starting from a given start index value (by default 0, so all elements of the array will be affected). This functionality is needed if you want to be able to use `shift`, `unshift` and related functions. ### method move-indexes-down ``` method move-indexes-down($down, $start = $down) { ... } ``` Subtract the given value to the **indexes** of the elements in the array, optionally starting from a given start index value (by default the same as the number to subtract, so that all elements of the array will be affected. This functionality is needed if you want to be able to use `shift`, `unshift` and related functions. ## Exported subroutines ### sub is-container ``` my $a = 42; say is-container($a); # True say is-container(42); # False ``` Returns whether the given argument is a container or not. This can be handy for situations where you want to also support binding, **and** allow for methods such as `shift`, `unshift` and related functions. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/Array-Agnostic> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2018, 2020, 2021, 2023, 2024 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-antononcube-WWW-MermaidInk.md # WWW::MermaidInk Raku package The function `mermaid-ink` of the Raku package ["WWW::MermaidInk"](https://github.com/antononcube/Raku-WWW-MermaidInk) gets images corresponding to Mermaid-js specifications via the web [Mermaid-ink](https://mermaid.ink) interface of [Mermaid-js](https://mermaid.js.org). For a "full set" of examples see the file [MermaidInk\_woven.html](https://htmlpreview.github.io/?https://github.com/antononcube/Raku-WWW-MermaidInk/blob/main/docs/MermaidInk_woven.html). --- ## Usage `use WWW::MermaidInk` loads the package. `mermaid-ink($spec)` retrieves an image defined by the spec `$spec` from Mermaid's Ink Web interface. `mermaid-ink($spec format => 'md-image')` returns a string that is a Markdown image specification in Base64 format. `mermaid-ink($spec format => 'md-url')` returns a string that is a Markdown image link specification. `mermaid-ink($spec format => 'svg')` returns a string that is a Scalable Vector Graphics (SVG) code. `mermaid-ink($spec format => 'hash')` returns a Hash object (the result of `HTTP::Tiny.get`.) `mermaid-ink($spec file => fileName)` exports the retrieved image into a specified PNG file. `mermaid-ink($spec file => Whatever)` exports the retrieved image into the file `$*CMD ~ /out.png`. ### Details & Options * Mermaid lets you create diagrams and visualizations using text and code. * Mermaid has different types of diagrams: Flowchart, Sequence Diagram, Class Diagram, State Diagram, Entity Relationship Diagram, User Journey, Gantt, Pie Chart, Requirement Diagram, and others. It is a JavaScript based diagramming and charting tool that renders Markdown-inspired text definitions to create and modify diagrams dynamically. * `mermaid-ink` uses the Mermaid's functionalities via the Web interface "https://mermaid.ink/img". * The first argument can be a string (that is, a mermaid-js specification) or a list of pairs. * The option "directive" can be used to control the layout of Mermaid diagrams if the first argument is a list of pairs. * `mermaid-ink` produces images or Hash objects (the result of `HTTP::Tiny.get`.) --- ## Examples ### Basic Examples Generate a flowchart from a Mermaid specification: ``` use WWW::MermaidInk; 'graph TD WL --> |ZMQ|Python --> |ZMQ|WL' ==> mermaid-ink(format=>'md-url') ``` ![](https://mermaid.ink/img/Z3JhcGggVEQgCiAgIFdMIC0tPiB8Wk1RfFB5dGhvbiAtLT4gfFpNUXxXTA==?bgColor=FFFFFF) Create a Markdown image expression from a class diagram: ``` my $spec = q:to/END/; classDiagram Animal <|-- Duck Animal <|-- Fish Animal <|-- Zebra Animal : +int age Animal : +String gender Animal: +isMammal() Animal: +mate() class Duck{ +String beakColor +swim() +quack() } class Fish{ -int sizeInFeet -canEat() } class Zebra{ +bool is_wild +run() } END mermaid-ink($spec, format=>'md-url') ``` ![](https://mermaid.ink/img/Y2xhc3NEaWFncmFtCiAgICBBbmltYWwgPHwtLSBEdWNrCiAgICBBbmltYWwgPHwtLSBGaXNoCiAgICBBbmltYWwgPHwtLSBaZWJyYQogICAgQW5pbWFsIDogK2ludCBhZ2UKICAgIEFuaW1hbCA6ICtTdHJpbmcgZ2VuZGVyCiAgICBBbmltYWw6ICtpc01hbW1hbCgpCiAgICBBbmltYWw6ICttYXRlKCkKICAgIGNsYXNzIER1Y2t7CiAgICAgICAgK1N0cmluZyBiZWFrQ29sb3IKICAgICAgICArc3dpbSgpCiAgICAgICAgK3F1YWNrKCkKICAgIH0KICAgIGNsYXNzIEZpc2h7CiAgICAgICAgLWludCBzaXplSW5GZWV0CiAgICAgICAgLWNhbkVhdCgpCiAgICB9CiAgICBjbGFzcyBaZWJyYXsKICAgICAgICArYm9vbCBpc193aWxkCiAgICAgICAgK3J1bigpCiAgICB9Cg==?bgColor=FFFFFF) ### Scope The first argument can be a list of pairs -- the corresponding Mermaid-js graph is produced. Here are the edges of directed graph: ``` my @edges = ['1' => '3', '3' => '1', '1' => '4', '2' => '3', '2' => '4', '3' => '4']; ``` [1 => 3 3 => 1 1 => 4 2 => 3 2 => 4 3 => 4] Here is the corresponding mermaid-js image: ``` mermaid-ink(@edges, format=>'md-url') ``` ![](https://mermaid.ink/img/Z3JhcGgKMSAtLT4gMwozIC0tPiAxCjEgLS0+IDQKMiAtLT4gMwoyIC0tPiA0CjMgLS0+IDQ=?bgColor=FFFFFF) Scalable Vector Graphics (SVG) code can be generated with `format => 'svg'`: ``` mermaid-ink(@edges, format=>'svg') ``` ``` # <svg id="mermaid-svg" width="100%" xmlns="http://www.w3.org/2000/svg" style="max-width: 124.205px; background-color: rgb(255, 255, 255);" viewBox="-9.423566102981567 -8 124.20481872558594 218" role="graphics-document document" aria-roledescription="flowchart-v2" xmlns:xlink="http://www.w3.org/1999/xlink"><style>#mermaid-svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg .error-icon{fill:#552222;}#mermaid-svg .error-text{fill:#552222;stroke:#552222;}#mermaid-svg .edge-thickness-normal{stroke-width:2px;}#mermaid-svg .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg .marker{fill:#333333;stroke:#333333;}#mermaid-svg .marker.cross{stroke:#333333;}#mermaid-svg svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg .cluster-label text{fill:#333;}#mermaid-svg .cluster-label span,#mermaid-svg p{color:#333;}#mermaid-svg .label text,#mermaid-svg span,#mermaid-svg p{fill:#333;color:#333;}#mermaid-svg .node rect,#mermaid-svg .node circle,#mermaid-svg .node ellipse,#mermaid-svg .node polygon,#mermaid-svg .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg .flowchart-label text{text-anchor:middle;}#mermaid-svg .node .label{text-align:center;}#mermaid-svg .node.clickable{cursor:pointer;}#mermaid-svg .arrowheadPath{fill:#333333;}#mermaid-svg .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg .cluster text{fill:#333;}#mermaid-svg .cluster span,#mermaid-svg p{color:#333;}#mermaid-svg div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}</style><g><marker id="mermaid-svg_flowchart-pointEnd" class="marker flowchart" viewBox="0 0 10 10" refX="6" refY="5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></path></marker><marker id="mermaid-svg_flowchart-pointStart" class="marker flowchart" viewBox="0 0 10 10" refX="4.5" refY="5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto"><path d="M 0 5 L 10 10 L 10 0 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></path></marker><marker id="mermaid-svg_flowchart-circleEnd" class="marker flowchart" viewBox="0 0 10 10" refX="11" refY="5" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></circle></marker><marker id="mermaid-svg_flowchart-circleStart" class="marker flowchart" viewBox="0 0 10 10" refX="-1" refY="5" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></circle></marker><marker id="mermaid-svg_flowchart-crossEnd" class="marker cross flowchart" viewBox="0 0 11 11" refX="12" refY="5.2" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><path d="M 1,1 l 9,9 M 10,1 l -9,9" class="arrowMarkerPath" style="stroke-width: 2; stroke-dasharray: 1, 0;"></path></marker><marker id="mermaid-svg_flowchart-crossStart" class="marker cross flowchart" viewBox="0 0 11 11" refX="-1" refY="5.2" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><path d="M 1,1 l 9,9 M 10,1 l -9,9" class="arrowMarkerPath" style="stroke-width: 2; stroke-dasharray: 1, 0;"></path></marker><g class="root"><g class="clusters"></g><g class="edgePaths"><path d="M3.6,34L1.616,38.167C-0.368,42.333,-4.336,50.667,2.099,60.135C8.534,69.604,25.372,80.207,33.791,85.509L42.21,90.811" id="L-1-3-0" class=" edge-thickness-normal edge-pattern-solid flowchart-link LS-1 LE-3" style="fill:none;" marker-end="url(#mermaid-svg_flowchart-pointEnd)"></path><path d="M52.988,84L51.664,79.833C50.34,75.667,47.691,67.333,43.308,59.313C38.924,51.294,32.805,43.587,29.746,39.734L26.686,35.881" id="L-3-1-0" class=" edge-thickness-normal edge-pattern-solid flowchart-link LS-3 LE-1" style="fill:none;" marker-end="url(#mermaid-svg_flowchart-pointEnd)"></path><path d="M11.695,34L11.695,38.167C11.695,42.333,11.695,50.667,11.695,61.833C11.695,73,11.695,87,11.695,101C11.695,115,11.695,129,14.755,139.853C17.814,150.706,23.933,158.413,26.993,162.266L30.052,166.119" id="L-1-4-0" class=" edge-thickness-normal edge-pattern-solid flowchart-link LS-1 LE-4" style="fill:none;" marker-end="url(#mermaid-svg_flowchart-pointEnd)"></path><path d="M85.636,34L83.319,38.167C81.003,42.333,76.371,50.667,72.998,58.158C69.625,65.65,67.512,72.299,66.455,75.624L65.398,78.949" id="L-2-3-0" class=" edge-thickness-normal edge-pattern-solid flowchart-link LS-2 LE-3" style="fill:none;" marker-end="url(#mermaid-svg_flowchart-pointEnd)"></path><path d="M99.134,34L100.126,38.167C101.118,42.333,103.102,50.667,104.094,61.833C105.086,73,105.086,87,105.086,101C105.086,115,105.086,129,97.752,141.13C90.418,153.26,75.749,163.521,68.415,168.651L61.081,173.781" id="L-2-4-0" class=" edge-thickness-normal edge-pattern-solid flowchart-link LS-2 LE-4" style="fill:none;" marker-end="url(#mermaid-svg_flowchart-pointEnd)"></path><path d="M58.391,118L58.391,122.167C58.391,126.333,58.391,134.667,57.334,142.158C56.277,149.65,54.164,156.299,53.107,159.624L52.051,162.949" id="L-3-4-0" class=" edge-thickness-normal edge-pattern-solid flowchart-link LS-3 LE-4" style="fill:none;" marker-end="url(#mermaid-svg_flowchart-pointEnd)"></path></g><g class="edgeLabels"><g class="edgeLabel"><g class="label" transform="translate(0, 0)"><foreignObject width="0" height="0"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g class="label" transform="translate(0, 0)"><foreignObject width="0" height="0"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g class="label" transform="translate(0, 0)"><foreignObject width="0" height="0"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g class="label" transform="translate(0, 0)"><foreignObject width="0" height="0"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g class="label" transform="translate(0, 0)"><foreignObject width="0" height="0"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g class="label" transform="translate(0, 0)"><foreignObject width="0" height="0"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="edgeLabel"></span></div></foreignObject></g></g></g><g class="nodes"><g class="node default default flowchart-label" id="flowchart-1-0" transform="translate(11.6953125, 17)"><rect class="basic label-container" style="" rx="0" ry="0" x="-11.6953125" y="-17" width="23.390625" height="34"></rect><g class="label" style="" transform="translate(-4.1953125, -9.5)"><rect></rect><foreignObject width="8.390625" height="19"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="nodeLabel">1</span></div></foreignObject></g></g><g class="node default default flowchart-label" id="flowchart-2-6" transform="translate(95.0859375, 17)"><rect class="basic label-container" style="" rx="0" ry="0" x="-11.6953125" y="-17" width="23.390625" height="34"></rect><g class="label" style="" transform="translate(-4.1953125, -9.5)"><rect></rect><foreignObject width="8.390625" height="19"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="nodeLabel">2</span></div></foreignObject></g></g><g class="node default default flowchart-label" id="flowchart-3-1" transform="translate(58.390625, 101)"><rect class="basic label-container" style="" rx="0" ry="0" x="-11.6953125" y="-17" width="23.390625" height="34"></rect><g class="label" style="" transform="translate(-4.1953125, -9.5)"><rect></rect><foreignObject width="8.390625" height="19"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="nodeLabel">3</span></div></foreignObject></g></g><g class="node default default flowchart-label" id="flowchart-4-5" transform="translate(45.04296875, 185)"><rect class="basic label-container" style="" rx="0" ry="0" x="-11.6953125" y="-17" width="23.390625" height="34"></rect><g class="label" style="" transform="translate(-4.1953125, -9.5)"><rect></rect><foreignObject width="8.390625" height="19"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; white-space: nowrap;"><span class="nodeLabel">4</span></div></foreignObject></g></g></g></g></g><style>@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css");</style></svg> ``` ### Options When `format => 'svg'` and `subdomain => Whatever`, then `subdomain` is automatically determined to be "svg". The argument `subdomain` can take the values "base64", "hash", "md-image", "md-url", "svg", `Whatever`. Background color can be specified with the optional argument `background`. Here is an example of using "md-url" as a format and background "Cornsilk": ``` 'graph LR CompSci[Computational Science] --> Physics CompSci --> Math[Mathematics] Physics --> Philosophy Math --> Philosophy' ==> mermaid-ink(format=>'md-url', background=>'Cornsilk') ``` ![](https://mermaid.ink/img/Z3JhcGggTFIKICAgQ29tcFNjaVtDb21wdXRhdGlvbmFsIFNjaWVuY2VdIC0tPiBQaHlzaWNzCiAgIENvbXBTY2kgLS0+IE1hdGhbTWF0aGVtYXRpY3NdCiAgIFBoeXNpY3MgLS0+IFBoaWxvc29waHkgCiAgIE1hdGggLS0+IFBoaWxvc29waHk=?bgColor=!Cornsilk) --- ## Command Line Interface (CLI) The package provides the CLI script `mermaid-ink`. Here is its help message: ``` mermaid-ink --help ``` ``` # Usage: # mermaid-ink <spec> [-o|--file=<Str>] [--format=<Str>] -- Diagram image for Mermaid-JS spec (via mermaid.ink). # mermaid-ink [<words> ...] [-o|--file=<Str>] [--format=<Str>] -- Command given as a sequence of words. # # <spec> Mermaid-JS spec. # -o|--file=<Str> File to export the image to. [default: ''] # --format=<Str> Format of the result; one of "asis", "base64", "md-image", or "none". [default: 'md-image'] ``` --- ## Flowchart This flowchart summarizes the execution path of obtaining Mermaid images in a Markdown document: ``` graph TD UI[/User input/] MS{{Mermaid-ink server}} Raku{{Raku}} MDnb>Markdown document] MDIC[[Input cell]] MDOC[[Output cell]] MI[mermaid-ink] TCP[[Text::CodeProcessing]] UI --> MDIC -.- MDnb MDIC --> MI -.- TCP MI --> |spec|MS MS --> |image|MI MI --> MDOC -.- MDnb MDnb -.- TCP -.- Raku ``` --- ## References ### Articles [AA1] Anton Antonov, ["Interactive Mermaid diagrams generation via Markdown evaluation"](https://rakuforprediction.wordpress.com/2022/11/22/interactive-mermaid-diagrams-generation-via-markdown-evaluation/), (2022), [RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com). ### Functions and packages [AAf1] Anton Antonov, [MermaidInk Mathematica resource function](https://www.wolframcloud.com/obj/antononcube/DeployedResources/Function/MermaidInk/), (2022-2023), [Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository/). ### Mermaid resources * [GitHub - mermaid-js/mermaid: Generation of diagram and flowchart from text in a similar manner as markdown](https://github.com/mermaid-js/mermaid) * [mermaid - Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.](https://mermaid-js.github.io/mermaid) * [GitHub - mermaid-js/mermaid-cli: Command line tool for the Mermaid library](https://github.com/mermaid-js/mermaid-cli) * [Online FlowChart & Diagrams Editor - Mermaid Live Editor](https://mermaid.live/)
## dist_zef-p6steve-Physics-Measure.md ![Test Status](https://github.com/p6steve/raku-Physics-Measure/actions/workflows/prove6.yml/badge.svg) # raku-Physics-Measure Provides Measure objects that have value, units and error and can be used in many common physics calculations. Uses [Physics::Unit](https://github.com/p6steve/raku-Physics-Unit) and [Physics::Error](https://github.com/p6steve/raku-Physics-Error). # Instructions `zef --verbose install Physics::Measure` and, conversely, `zef uninstall Physics::Measure` # Synopsis ``` use lib '../lib'; use Physics::Measure :ALL; # Basic mechanics example (SI units)... # Define a distance and a time my \d = 42m; say ~d; #42 m (Length) my \t = 10s; say ~t; #10 s (Time) # Calculate speed and acceleration my \u = d / t; say ~u; #4.2 m/s (Speed) my \a = u / t; say ~a; #0.42 m/s^2 (Acceleration) # Define mass and calculate force my \m = 25kg; say ~m; #25 kg (Mass) my \f = m * a; say ~f; #10.5 N (Force) # Calculate final speed and distance travelled my \v = u + a*t; say ~v; #8.4 m/s (Speed) my \s = u*t + (1/2) * a * t*t; say ~s; #63 m (Length) # Calculate potential energy my \pe = f * s; say ~pe; #661.5 J (Energy) # Calculate kinetic energy my \ke1 = (1/2) * m * u*u; my \ke2 = (1/2) * m * v*v; # Calculate the delta in kinetic energy my \Δke = ke2 - ke1; # Compare potential vs. delta kinetic energy (pe cmp Δke).say; #Same ``` This example shows some key features of Physics::Measure... * support for SI prefixes, base and derived units (cm, kg, ml and so on) * imported as raku postfix operators for convenience and clarity * custom math operators `(+-*/)` for easy inclusion in calculations * inference of type class (Length, Time, Mass, etc.) from units * derivation of type class of results (Speed, Acceleration, etc.) # Use Cases The Physics::Measure and Physics::Unit modules were designed with the following use cases in mind: * convenient use for practical science - lab calculations and interactive presentation of data sets * a framework for educators and students to interactively explore basic physics via a modern OO language * an everyday unit conversion and calculation tool (not much point if it can't convert miles to km and so on) Some other use cases - use for physical chemistry calculations (eg. environmental) and for historic data ingestion - have also been seen on the horizon and the author would be happy to work with you to help adapt to meet a wider set of needs. # Design Model To address the Use Cases, the following consistent functional parts have been created: * a raku Class and Object model to represent Units and Measurements * methods for Measure math operations, output, comparison, conversion, normalisation and rebasing * a Unit Grammar to parse unit expressions and cope with textual variants such as ‘miles per hour’ or ‘mph’, or ‘m/s’, ‘ms^-1’, ‘m.s-1’ * an extensible library of about 800 built in unit types covering SI base, derived, US and imperial * a set of "API" options to meet a variety of consumption needs Together Physics::Measure and Physics::Unit follow this high level class design model: ``` class Unit { has Str $.defn; #... } class Measure { has Real $.value; has Unit $.units; has Error $.error; #... } class Length is Measure {} class Time is Measure {} class Speed is Measure {} #and so on ``` Type classes represent physical measurement such as (Length), (Time), (Speed), etc. They are child classes of the (Measure) parent class. You can do math operations on (Measure) objects - (Length) can add/subtract to (Length), (Time) can add/subtract to (Time), and so on. A mismatch like adding a (Length) to a (Time) gives a raku Type error *cannot convert in to different type Length*. You can, however, divide e.g. (Length) by (Time) and then get a (Speed) type back. (Length) \*\* 2 => (Area). (Length) \*\* 3 => (Volume). And so on. There are 36 pre-defined types provided. Methods are provided to create custom units and types. Therefore, in the normal course, please make your objects as instances of the Child type classes. # Three Consumer Options ## Option 1: Postfix Operator Syntax (SI Units) As seen above, if you just want SI prefixes, base and derived units (cm, kg, ml and so on), the :ALL export label provides them as raku postfix:<> custom operators. This option is intended for scientist / coders who want fast and concise access to a modern Unit library. Here is another example, basic wave mechanics, bringing in the [Physics::Constants](https://github.com/p6steve/raku-Physics-Constants) module: ``` use Physics::Constants; #<== must use before Physics::Measure use Physics::Measure :ALL; $Physics::Measure::round-to = 0.01; my \λ = 2.5nm; my \ν = c / λ; my \Ep = ℎ * ν; say "Wavelength of photon (λ) is " ~λ; #2.5 nm say "Frequency of photon (ν) is " ~ν.norm; #119.92 petahertz say "Energy of photon (Ep) is " ~Ep.norm; #79.46 attojoule ``` The following SI units are provided in all Prefix-Unit combinations: | SI Base Unit (7) | SI Derived Unit (20) | SI Prefix (20) | | --- | --- | --- | | 'm', 'metre', | 'Hz', 'hertz', | 'da', 'deka', | | 'g', 'gram', | 'N', 'newton', | 'h', 'hecto', | | 's', 'second', | 'Pa', 'pascal', | 'k', 'kilo', | | 'A', 'amp', | 'J', 'joule', | 'M', 'mega', | | 'K', 'kelvin', | 'W', 'watt', | 'G', 'giga', | | 'mol', 'mol', | 'C', 'coulomb', | 'T', 'tera', | | 'cd', 'candela', | 'V', 'volt', | 'P', 'peta', | | | 'F', 'farad', | 'E', 'exa', | | | 'Ω', 'ohm', | 'Z', 'zetta', | | | 'S', 'siemens', | 'Y', 'yotta', | | | 'Wb', 'weber', | 'd', 'deci', | | | 'T', 'tesla', | 'c', 'centi', | | | 'H', 'henry', | 'm', 'milli', | | | 'lm', 'lumen', | 'μ', 'micro', | | | 'lx', 'lux', | 'n', 'nano', | | | 'Bq', 'becquerel', | 'p', 'pico', | | | 'Gy', 'gray', | 'f', 'femto', | | | 'Sv', 'sievert', | 'a', 'atto', | | | 'kat', 'katal', | 'z', 'zepto', | | | 'l', 'litre', | 'y', 'yocto', | #litre included due to common use of ml, dl, etc. ## Option 2: Object Constructor Syntax In addition to the SI units listed above, Physics::Measure (and Physics::Unit) offers a comprehensive library of non-metric units. US units and Imperial units include feet, miles, knots, hours, chains, tons and over 200 more. The non-metric units are not exposed as postfix operators. ``` my Length $d = Length.new(value => 42, units => 'miles'); say ~$d; #42 mile my Time $t = Time.new( value => 7, units => 'hours'); say ~$t; #7 hr my $s = $d / $t; say ~$s.in('mph'); #6 mph ``` A flexible unit expression parser is included to cope with textual variants such as ‘miles per hour’ or ‘mph’; or ‘m/s’, ‘ms^-1’, ‘m.s-1’ (the SI derived unit representation) or ‘m⋅s⁻¹’ (the SI recommended string representation, with superscript powers). The unit expression parser decodes a valid unit string into its roots, extracting unit dimensions and inferring the appropriate type. ``` #Colloquial terms or unicode superscripts can be used for powers in unit declarations #square, sq, squared, cubic, cubed #x¹ x² x³ x⁴ and x⁻¹ x⁻² x⁻³ x⁻⁴ ``` Of course, the standard raku object constructor syntax may be used for SI units too: ``` my Length $l = Length.new(value => 42, units => 'μm'); say ~$l; #42 micrometre ``` This syntax option is the most structured and raku native. For example, it helps educators to use units and basic physics exercises as a way to introduce students to formal raku Object Orientation principles. ## Option 3: Libra Shorthand Syntax In many cases, coders will want the flexibility of the unit expression parser and the wider range of non-metric units but they also want a concise notation. In this case, the unicode libra emoji ♎️ is provided as raku prefix for object construction: ``` #The libra ♎️ is shorthand to construct objects... my $a = ♎️ '4.3 m'; say "$a"; #4.3 m my $b = ♎️ '5e1 m'; say "$b"; #50 m my $c = $a; say "$c"; #4.3 m my Length $l = ♎️ 42; say "$l"; #42 m (default to base unit of Length) #...there is an ASCII variant of <♎️> namely <libra> ``` *Use the emoji editor provided on your system (or just cut and paste)* ``` #About 230 built in units are included, for example... my $v2 = ♎️ '7 yards^3'; #7 yard^3 (Volume) my $v3 = $v2.in( 'm3' ); #5.352 m^3 (Volume) my $dsdt = $s / $t; #0.000106438 m/s^2 (Acceleration) my $sm = ♎️ '70 mph'; #70 mph (Speed) my $fo = ♎️ '27 kg m / s2'; #27 N (Force) my $en = ♎️ '26 kg m^2 / s^2'; #26 J (Energy) my $po = ♎️ '25 kg m^2 / s^3'; #25 W (Power) ``` # Special Measure Types ## Angles ``` #Angles use degrees/minutes/seconds or decimal radians my $θ1 = ♎️ <45°30′30″>; #45°30′30″ (using <> to deconfuse quotation marks) my $θ2 = ♎️ '2.141 radians'; #'2.141 radian' #NB. The unit name 'rad' is reserved for the unit of radioactive Dose # Trigonometric functions sin, cos and tan (and arc-x) handle Angles my $sine = sin( $θ1 ); #0.7133523847299412 my $arcsin = asin( $sine, units => '°' ); #45°30′30″ #NB. Provide the units => '°' tag to tell asin you want degrees back ``` ## Time ``` #The Measure of Time has a raku Duration - i.e. the difference between two DateTime Instants: my $i1 = DateTime.now; my $i2 = DateTime.new( '2020-08-10T14:15:27.26Z' ); my $i3 = DateTime.new( '2020-08-10T14:15:37.26Z' ); my Duration $dur = $i3-$i2; #Here's how to us the libra assignment operator ♎️ for Time... my Time $t1 = ♎️ '5e1 s'; #50 s my Time $t2 = ♎️ $dur; #10 s my $t3 = $t1 + $t2; #60 s my Time $t4 = ♎️ '2 hours'; #2 hr $dur = $t4.Duration; #7200 ``` # Unit Conversion ``` #Unit Conversion uses the .in() method - specify the new units as a String my Length $df = ♎️ '12.0 feet'; #12 ft my $dm = $df.in( 'm' ); #3.658 m $dm = $df.in: <m>; #alternate form my Temperature $deg-c = ♎️ '39 °C'; my $deg-k = $deg-c.in( 'K' ); #312.15 K my $deg-cr = $deg-k.in( '°C' ); #39 °C #Use arithmetic to get high order or inverse Unit types such as Area, Volume, Frequency, etc. my Area $x = $a * $a; #18.49 m^2 my Speed $s = $a / $t2; #0.43 m/s my Frequency $f = 1 / $t2; #0.1 Hz #Use powers & roots with Int or Rat (<1/2>, <1/3> or <1/4>) my Volume $v = $a ** 3; #79.507 m^3 my Length $d = $v ** <1/3>; #0.43 m ``` The ① symbol is used to denote Dimensionless units. # Rounding & Normalisation ``` #Set rounding precision (or reset with Nil) - does not reduce internal precision $Physics::Measure::round-to = 0.01; #Normalize SI Units to the best SI prefix (from example above) say "Frequency of photon (ν) is " ~ν.norm; #119.92 petahertz #Reset to SI base type with the .rebase() method my $v4 = $v2.rebase; #5.35 m^3 ``` # Comparison Methods ``` #Measures can be compared with $a cmp $b my $af = $a.in: 'feet'; #4.3 m => 14.108 feet say $af cmp $a; #Same #Measures can be tested for equality with Numeric ==,!= say $af == $a; #True say $af != $a; #False #Use string equality eq,ne to distinguish different units with same type say $af eq $a; #False say $af ne $a; #True ``` # Output Methods To see what you have got, then go: ``` my $po = 25W; say ~$po; say "$po"; say $po.Str; #25 W (defaults to derived unit) say +$po; say $po.value; say $po.Real; #25 say $po.WHAT; #(Power) say $po.canonical; #25 m2.s-3.kg (SI base units) say $po.pretty; #25 m²⋅s⁻³⋅kg (SI recommended style) ^...^......unicode Dot Operator U+22C5 ``` # Dealing with Ambiguous Types In a small number of case, the same units are used by different unit Types. Type hints steer type inference: ``` our %type-hints = %( Area => <Area FuelConsumption>, Energy => <Energy Torque>, Momentum => <Momentum Impulse>, Frequency => <Frequency Radioactivity>, ); ``` To adjust this, you can delete the built in key and replace it with your own: ``` my %th := %Physics::Unit::type-hints; #default type-hints my $en1 = ♎️'60 J'; #'$en1 ~~ Energy'; my $tq1 = ♎️'5 Nm'; #'$tq1 ~~ Torque'; #altered type-hints %th<Energy>:delete; %th<Torque> = <Energy Torque>; my $fo3 = ♎️'7.2 N'; my $le2 = ♎️'2.2 m'; my $tq2 = $fo3 * $le2; #'$tq2 ~~ Torque'; ``` # Custom Measures To make a custom Measure, you can use this incantation: ``` GetMeaUnit('nmile').NewType('Reach'); class Reach is Measure { has $.units where *.name eq <nm nmile nmiles>.any; #| override .in to perform identity 1' (Latitude) == 1 nmile method in( Str $s where * eq <Latitude> ) { my $nv = $.value / 60; Latitude.new( value => $nv, compass => <N> ) } } ``` # Summary The family of Physics::Measure, Physics::Unit and Physics::Constants raku modules is a consistent and extensible toolkit intended for science and education. It provides a comprehensive library of both metric (SI) and non-metric units, it is built on a Type Object foundation, it has a unit expression Grammar and implements math, conversion and comparison methods. Any feedback is welcome to p6steve / via the github Issues above.
## dist_zef-thundergnat-App-pixel-pick.md # NAME pixel-pick Get the color of any screen pixel in an X11 environment. Simple command-line app to allow you to get the RGB color of ***any*** screen pixel in an X11 environment, even those controlled by another application. ### Install ``` zef install App::pixel-pick ``` Needs to have the `import` utility available. Installed part of the `MagickWand` package. Most Linuxes have it already, if not, install `libmagickwand`. May want to install `libmagickwand-dev` as well, though it isn't strictly necessary for this app. ``` sudo apt-get install libmagickwand-dev ``` For Debian based distributions. Uses the `X11::libxdo` module for mouse interaction so will only run in an X11 environment. ## Use ### Interactive: ``` pixel-pick <--distance=Int> <--list=COLOR,LISTS> ``` If invoked with no positional parameters, runs in interactive mode. Will get the color of the pixel under the mouse pointer and show the RGB values in both decimal and hexadecimal formats and will display a small block colored to that value. Will also display colored blocks of "Named colors", along with their RGB values, that are "near" the selected color. Will accept an Integer "distance" parameter at the command line to fine tune the cutoff for what is "near". (Defaults to 20. More than about 80 or so is not recommended. You'll get unusefully large numbers of matches.) Will always return at least one "nearest" color, no matter what the threshold is. The colors may not be exact, they are just the nearest found in the list. Uses the XKCD CSS3 and X11 color name lists from the Color::Names module by default as its list of known colors. See [XKCD color blocks](https://www.w3schools.com/colors/colors_xkcd.asp), [W3 CSS 3 standard web colors](https://www.w3schools.com/cssref/css_colors.asp), and [X11 color blocks](https://www.w3schools.com/colors/colors_x11.asp). If different color lists are desired, pass in a comma joined list of names. Any of the lists supported by `Color::Names:api<2>` may be used. ``` X11 XKCD CSS3 X11-Grey NCS NBS Crayola Resene RAL-CL RAL-DSP FS595B FS595C ``` as of this writing. The (case-sensitive) names must be in one contiuous string joined by commas. E.G. ``` pixel-pick --list=Crayola,XKCD ``` Updates moderately slowly as the mouse is moved. There is some delay just to slow down the busy loop of checking to see if the mouse has moved. Will not attempt to update if the mouse has not moved. Uses the `X11::xdo` module to capture mouse motion so will only work in an X11 environment. Note that screen sub-pixel dithering may lead to some unexpected values being returned, especially around small text. The utility returns what the pixel color ***is***, not what it is perceived to be. When in interactive mode, you need to send an abort signal to exit the utility. Control-C will reset your terminal to its previous settings and do a full clean-up. If you want to keep the color block and values around, do Control-Z instead. That will also reset the terminal, but will not clean up as much, effectively leaving the last values displayed. ### Non-interactive: (Get the color of the pixel at 100, 200) ``` pixel-pick 100 200 (--distance=Int) ``` If invoked with X, Y coordinates, (--distance parameter optional) runs non-interactive. Gets the pixel color at that coordinate and exits immediately, doing the partial cleanup as you would get from Control-Z. ### Non-interactive, quiet: (Get the RGB values of the pixel at 100, 200) ``` pixel-pick 100 200 q ``` Add a truthy value as a "quiet" parameter to not return the standard color parameters and block. Only returns the RGB values in base 10 separated by colons. EG. `RRR:GGG:BBB` If you would prefer to receive hex values, use an 'h' as the quiet parameter. Returns the RGB values in hexadecimal, separated by colons; `RR:GG:BB`. ``` pixel-pick 100 200 h ``` # Author 2019 thundergnat (Steve Schulze) This package is free software and is provided "as is" without express or implied warranty. You can redistribute it and/or modify it under the same terms as Perl itself. # License Licensed under The Artistic 2.0; see LICENSE.
## privatemethodcontainer.md role Metamodel::PrivateMethodContainer Metaobject that supports private methods ```raku role Metamodel::PrivateMethodContainer { ... } ``` *Warning*: this role is part of the Rakudo implementation, and is not a part of the Raku language specification. In Raku, classes, roles and grammars can have private methods, that is, methods that are only callable from within it, and are not inherited by types derived by inheritance. ```raku class A { # the ! declares a private method method !double($x) { say 2 * $x; } method call-double($y) { # call with ! instead of . self!double($y); } } ``` For the purposes of dispatching and scoping, private methods are closer to subroutines than to methods. However they share access to `self` and attributes with methods. # [Methods](#role_Metamodel::PrivateMethodContainer "go to top of document")[§](#Methods "direct link") ## [method add\_private\_method](#role_Metamodel::PrivateMethodContainer "go to top of document")[§](#method_add_private_method "direct link") ```raku method add_private_method($obj, $name, $code) ``` Adds a private method `$code` with name `$name`. ## [method private\_method\_table](#role_Metamodel::PrivateMethodContainer "go to top of document")[§](#method_private_method_table "direct link") ```raku method private_method_table($obj) ``` Returns a hash of `name => &method_object` ## [method private\_methods](#role_Metamodel::PrivateMethodContainer "go to top of document")[§](#method_private_methods "direct link") ```raku method private_methods($obj) ``` Returns a list of private method names. ## [method private\_method\_names](#role_Metamodel::PrivateMethodContainer "go to top of document")[§](#method_private_method_names "direct link") ```raku method private_method_names($obj) ``` Alias to `private_methods`. ## [method find\_private\_method](#role_Metamodel::PrivateMethodContainer "go to top of document")[§](#method_find_private_method "direct link") ```raku method find_private_method($obj, $name) ``` Locates a private method. Otherwise, returns [`Mu`](/type/Mu) if it doesn't exist.
## dist_zef-jonathanstowe-FastCGI-NativeCall.md # FastCGI::NativeCall This is an implementation of FastCGI for Raku using NativeCall ![Build Status](https://github.com/jonathanstowe/raku-fastcgi-nativecall/workflows/CI/badge.svg) ## Synopsis ``` use FastCGI::NativeCall; my $fcgi = FastCGI::NativeCall.new(path => "/tmp/fastcgi.sock", backlog => 32 ); my $count = 0; while $fcgi.accept() { say $fcgi.env; $fcgi.header(Content-Type => "text/html"); $fcgi.Print("{ ++$count }"); } ``` There is an example [nginx](http://nginx.org/) configuration in the <examples> directory. If you are using Apache httpd with [mod\_fcgid](https://httpd.apache.org/mod_fcgid/mod/mod_fcgid.html) your script will be executed by the server with its STDIN (file descriptor 0) opened as the listening socket so you don't need to create your own socket and the script above becomes something like: ``` use FastCGI::NativeCall; my $fcgi = FastCGI::NativeCall.new(socket => 0 ); my $count = 0; while $fcgi.accept() { say $fcgi.env; $fcgi.header(Content-Type => "text/html"); $fcgi.Print("{ ++$count }"); } ``` There is a snippet of Apache configuration in the [examples](examples/apache.conf) directory. You will almost certainly want to tweak that to your own requirements. ## Description [FastCGI](https://fastcgi-archives.github.io/) is a protocol that allows an HTTP server to communicate with a persistent application over a socket, thus removing the process startup overhead of, say, traditional CGI applications. It is supported as standard (or through supporting modules,) by most common HTTP server software (such as Apache, nginx, lighthttpd and so forth.) This module provides a simple mechanism to create FastCGI server applications in Raku. The FastCGI servers are single threaded, but with good support from the front end server and tuning of the configuration it can be quite efficient. ## Installation In order to use this properly you will need some front end server that supports FastCGI using unix domain sockets. Assuming you have a working Rakudo installation you should be able to install this with *zef*: ``` zef install FastCGI::NativeCall # Or from a local clone of the distribution zef install . ``` ## Support I'm probably not the right person to ask about configuring various HTTP servers for FastCGI. Though I'd be interested in sample configurations if anyone wants to provide any. If you are running under SELinux with Apache you may find that it won't run your script and you will need to do something like: ``` chcon -R -t httpd_sys_script_exec_t /var/www/fcgi ``` obviously adjusting this to your own circumstances. Also the tests are a bit rubbish, I haven't worked out how to mock an HTTP server that does FastCGI yet. If you have any suggestions/bugs etc please report them at <https://github.com/jonathanstowe/raku-fastcgi-nativecall/issues> ## Licence and Copyright This is free software please see the <LICENSE> file in the distribution. © carbin 2015 © Jonathan Stowe 2016 - 2021 The FastCGI C application library is distributed under its own license. See "ext/LICENSE.TERMS" for the license.
## dist_zef-raku-community-modules-App-MoarVM-Debug.md [![Actions Status](https://github.com/raku-community-modules/App-MoarVM-Debug/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/App-MoarVM-Debug/actions) [![Actions Status](https://github.com/raku-community-modules/App-MoarVM-Debug/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/App-MoarVM-Debug/actions) [![Actions Status](https://github.com/raku-community-modules/App-MoarVM-Debug/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/App-MoarVM-Debug/actions) # App::MoarVM::Debug The interactive MoarVM debugger installs a script called `raku-remote-debug` that allows a developer to start a Raku program in debugger mode, while in another window allows the developer to step through the program and perform various types of introspection. ## Starting in debugger mode ``` $ raku-remote-debug your-program.raku arg1 arg2 ``` Starting a program in debugger mode is as simple as replacing `raku` by `raku-remote-debug` on the command line. That's it. When it is started this way, it will show a text on STDERR such as: ``` Running with debugging enabled at localhost port 27434 ``` Your program will not actually execute until you have entered the `resume` command in the debugger. ## Starting the debugger ``` $ raku-remote-debug ``` To start the debugger, call `raku-remote-debug` **without** any arguments. It will show you a text such as: ``` Welcome to the MoarVM Remote Debugger Connecting to MoarVM remote on localhost port 27434 success! > ``` You would typically then set breakpoints or do some introspection. And then start the program by typing "resume" to lift the suspension of all threads in the program. Type "help" in the debugger's CLI to see what commands are available to you. ## Limitations The debugger uses a single port to communicate between your program and the debugger. By default this is port `27434`. This means that on any given computer, only one program can be debugged this way, and only one debugger can run at the same time. Should you need to have more debuggers running at the same time, or for some reason you need to use another port, you can set the environment variable `MVM_DEBUG_PORT` to the port you'd like to use. To start your program: ``` $ MVM_DEBUG_PORT=4242 raku-remote-debug your-program.raku arg1 arg2 ``` To start the debugger: ``` $ MVM_DEBUG_PORT=4242 raku-remote-debug ``` ## Some hints * (Optional) Write `assume thread 1` to assume tracking of first (main) thread * Set a breakpoint > breakpoint "my-script.raku" 1234 1 1 The string is the filename and `1234` is the line number (`1 1` is the secret ingredient). Ensure the line number doesn't point to an empty line. * Type `resume` to run your script. * The breakpoint will trigger, you can type `all lexicals` to view all lexicals. The numbers shown next to them in bold are "handle" numbers. * Find the object you want to dump and type `metadata 1234` (`1234` is the handle number). If the features includes `attributes`, you can enter `attributes 1234` for this object to get information about the object's attributes. If the features includes `positional`, you can enter `positionals 1234` to get information about the positional elements of the object. If the features includes `associative`, you can enter `associatives 1234` to get information about the associative elements (keys and values) of the object. The `metadata` command is only needed if you don't know which of these commands is useful for any given type. * Type `help` to see all of the available commands. ## Known Issues The only stepping mode currently available is Step Into. Backtraces will show incorrect line numbers. # AUTHOR * Timo Paulssen Source can be located at: <https://github.com/raku-community-modules/App-MoarVM-Debug> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2017 - 2020 Edument AB Copyright 2024 The Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-P5tie.md [![Actions Status](https://github.com/lizmat/P5tie/workflows/test/badge.svg)](https://github.com/lizmat/P5tie/actions) # NAME Raku port of Perl's tie() built-in # SYNOPSIS ``` use P5tie; # exports tie(), tied() and untie() tie my $s, Tie::AsScalar; tie my @a, Tie::AsArray; tie my %h, Tie::AsHash; $object = tied $s; untie $s; ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `tie` and related built-ins as closely as possible in the Raku Programming Language. # ORIGINAL PERL 5 DOCUMENTATION ``` tie VARIABLE,CLASSNAME,LIST This function binds a variable to a package class that will provide the implementation for the variable. VARIABLE is the name of the variable to be enchanted. CLASSNAME is the name of a class implementing objects of correct type. Any additional arguments are passed to the appropriate constructor method of the class (meaning "TIESCALAR", "TIEHANDLE", "TIEARRAY", or "TIEHASH"). Typically these are arguments such as might be passed to the "dbm_open()" function of C. The object returned by the constructor is also returned by the "tie" function, which would be useful if you want to access other methods in CLASSNAME. Note that functions such as "keys" and "values" may return huge lists when used on large objects, like DBM files. You may prefer to use the "each" function to iterate over such. Example: # print out history file offsets use NDBM_File; tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } untie(%HIST); A class implementing a hash should have the following methods: TIEHASH classname, LIST FETCH this, key STORE this, key, value DELETE this, key CLEAR this EXISTS this, key FIRSTKEY this NEXTKEY this, lastkey SCALAR this DESTROY this UNTIE this A class implementing an ordinary array should have the following methods: TIEARRAY classname, LIST FETCH this, key STORE this, key, value FETCHSIZE this STORESIZE this, count CLEAR this PUSH this, LIST POP this SHIFT this UNSHIFT this, LIST SPLICE this, offset, length, LIST EXTEND this, count DELETE this, key EXISTS this, key DESTROY this UNTIE this A class implementing a filehandle should have the following methods: TIEHANDLE classname, LIST READ this, scalar, length, offset READLINE this GETC this WRITE this, scalar, length, offset PRINT this, LIST PRINTF this, format, LIST BINMODE this EOF this FILENO this SEEK this, position, whence TELL this OPEN this, mode, LIST CLOSE this DESTROY this UNTIE this A class implementing a scalar should have the following methods: TIESCALAR classname, LIST FETCH this, STORE this, value DESTROY this UNTIE this Not all methods indicated above need be implemented. See perltie, Tie::Hash, Tie::Array, Tie::Scalar, and Tie::Handle. Unlike "dbmopen", the "tie" function will not "use" or "require" a module for you; you need to do that explicitly yourself. See DB_File or the Config module for interesting "tie" implementations. For further details see perltie, "tied VARIABLE". tied VARIABLE Returns a reference to the object underlying VARIABLE (the same value that was originally returned by the "tie" call that bound the variable to a package.) Returns the undefined value if VARIABLE isn't tied to a package. untie VARIABLE Breaks the binding between a variable and a package. (See tie.) Has no effect if the variable is not tied. ``` # PORTING CAVEATS Please note that there are usually better ways attaching special functionality to arrays, hashes and scalars in Raku than using `tie`. Please see the documentation on [Custom Types](https://docs.raku.org/language/subscripts#Custom_types) for more information to handling the needs that Perl's `tie` fulfills in a more efficient way in Raku. ## Subs versus Methods In Raku, the special methods of the tieing class, can be implemented as Raku `method`s, or they can be implemented as `our sub`s, both are perfectly acceptable. They can even be mixed, if necessary. But note that if you're depending on subclassing, that you must change the `package` to a `class` to make things work. ## Untieing Because Raku does not have the concept of magic that can be added or removed, it is **not** possible to `untie` a variable. Note that the associated `UNTIE` sub/method **will** be called, so that any resources can be freed. Potentially it would be possible to actually have any subsequent accesses to the tied variable throw an exception: perhaps it will at some point. ## Scalar variable tying versus Proxy Because tying a scalar in Raku **must** be implemented using a `Proxy`, and it is currently not possible to mix in any additional behaviour into a `Proxy`, it is alas impossible to implement `UNTIE` and `DESTROY` for tied scalars at this point in time. Please note that `UNTIE` and `DESTROY` **are** supported for tied arrays and hashes. ## Tieing a file handle Tieing a file handle is not yet implemented at this time. Mainly because I don't grok yet how to do that. As usual, patches and Pull Requests are welcome! # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/P5tie> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen Re-imagined from Perl as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-l10n-L10N-EN.md # NAME L10N::EN - English localization of Raku # SYNOPSIS ``` use L10N::NL; zeg "Hallo wereld"; { gebruik L10N::EN; # Note: -use- needs to be in outer localization say "Hello World"; } ``` # DESCRIPTION L10N::EN contains the logic to provide a English localization of the Raku Programming Language. Note that this is the same mapping as the core. This localization is mainly intended to allow switching back to the core language in a scope, while being in another localization. # AUTHORS Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) # COPYRIGHT AND LICENSE Copyright 2023 Raku Localization Team This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-guifa-Intl-LanguageTaggish.md # Intl::LanguageTaggish A role to be implemented by different representations of a language/locale identifier. It provides for the following three methods/attributes: * `language` The language, generally in ISO 639 format (as either a `Str` or something that coerces accordingly) * `region` The region, generally in ISO 3166/UN M.49 format (as either a `Str` or something that coerces accordingly) * `bcp47` A BCP-47 representation of the tag, to the extent possible (as a `Str`). May be lossy. ## Raison d’être While there are not many language tag standards, there are several in common use. This role aims to define some common features to aid their interaction. A `bcp47` method should provide conversion into a BCP-47-compliant string. For example, Apple allows "English" or "Spanish" as valid identifiers for its `.lproj` identifiers. So a theoretical `AppleLProj` class that does `LanguageTaggish` would output **English** for `.language`, but for `bcp47`, would output **en**. It is expected that class implementing `LanguageTaggish` will add additional methods and attributes. In keeping with tradition established by other language tag frameworks (in particular ICU), requested values not present should return the empty string. The role handles this by default via its `FALLBACK` method. In addition, each `LanguageTaggish` implementor is expected to also provide a method ` ## Coercions into `LanguageTaggish` Classes implementing `LanguageTaggish` register themselves on the first `use` statement to be available for coercion. Optimally, programmers in international environments will know what tag is needed, however, when it's not possible, the `COERCE` method aims to do its best. In priority order, classes judge whether they can handle the tag, and if so, will do the coercion. **This approach is not (as of v0.1) finalized and may be adjusted.** * `Intl::LanguageTag::BCP-47` (**:100priority**) This IETF BCP-47 representation (uses hyphens and subtags are limited to 8 characters). * `Intl::LanguageTag::Unicode` (**:75priority**) The Unicode language tag standard (uses underscores generally, subtags may have any number of characters) * `Intl::LanguageTag::POSIX` (**:50priority**) The standard langauge tag as used in POSIX (underscores, at symbols, and dots may delineate subtags) * `Intl::LanguageTag::UnicodeLegacy` (**:25priority**) The legacy style Unicode langauge tag (underscores and at symbols delineate subtags, special characters like slash are valid as variant values) * `Intl::LanguageTaggish::Fallback` (**:0priority**) A fallback that detects the first (and possible second) sequence of alpha characters as the language (and possible region). Note that if you `use Intl::LanguageTag`, you will get the BCP-47 implementation, as it is currently the most common format.
## dist_github-labster-File-Spec-Case.md # p6-File-Spec-Case Check if your filesystem is case sensitive or case tolerant (insensitive) ## SYNOPSIS ``` use File::Spec::Case; say File::Spec::Case.tolerant; #tests case tolerance in $*CWD my $folder = "/path/to/folder"; say "case sensitive" if File::Spec::Case.sensitive($folder, :no-write); say "$folder is case-{ File::Spec::insensitive($folder) ?? 'in' !! ''}sensitive"; ``` ## DESCRIPTION Given a directory, this module attempts to determine whether that particular part of the filesystem is case sensitive or insensitive. In order to be platform independendent, this module interacts with the filesystem to attempt to determine case, because nowadays it's entirely possible to support multiple case filesystems on Windows, Linux, and Mac OS X. This module splits little-used functionality off from [File::Spec](https://github.com/FROGGS/p6-File-Spec), and has moved to its own module if you need it. Unlike in Perl 5, it now applies only to a specific directory -- with symlinks and multiple partitions, you can't assume anything beyond that. ## METHODS ### tolerant ``` method tolerant (Str:D $path = $*CWD, :$no_write = False ) ``` Method `tolerant` now requires a path (as compared to Perl 5 File::Spec->case\_tolerant), below which it tests for case sensitivity. The default path it tests is $\*CWD. A :no-write parameter may be passed if you want to disable writing of test files (which is tried last). ``` File::Spec::Case.tolerant('foo/bar'); File::Spec::Case.tolerant('/etc', :no-write); ``` It will find case (in)sensitivity if any of the following are true, in increasing order of desperation: * The $path passed contains <alpha> and no symbolic links. * The $path contains <alpha> after the last symlink. * Any folders in the path (under the last symlink, if applicable) contain a file matching <alpha>. * Any folders in the path (under the last symlink, if applicable) are writable. Otherwise, it returns the platform default. ### insensitive A synonym for `.tolerant`. ### sensitive An antonym for `.tolerant` -- that is, it returns `not tolerant`. Takes the same arguments as tolerant. ### default-case-tolerant The method of last resort for `.tolerant`, this returns the default value for whether the platform is insensitive to case. If passed an OS string, it will look for the default on that OS instead. The default is essentially what you'll get if you do a default install of your operating system. ### always-case-tolerant Returns True if your OS is on the list of þe olde Turing machine systems of operating with case tolerance, False otherwise. If you pass another OS string, it will check that instead of your own OS. This is used as a shortcut in `.tolerant` for machines which never support case-sensitive file naming. ## SEE ALSO * [File::Spec](https://github.com/FROGGS/p6-File-Spec) ## AUTHOR Brent "Labster" Laabs, 2013. Contact the author at [bslaabs@gmail.com](mailto:bslaabs@gmail.com) or as labster on #perl6. File [bug reports](https://github.com/labster/p6-IO-File-Spec-Case/issues) on github. ## COPYRIGHT This code is free software, licensed under the same terms as Perl 6; see the LICENSE file for details.
## dist_github-retupmoca-Crust-Middleware-Syslog.md # Crust::Middleware::Syslog ``` use Crust::Builder; use Crust::Middleware::Syslog; builder { enable 'Syslog', ident => 'MyApp'; $app; } ``` or ``` use Crust::Middleware::Syslog; $app = Crust::Middleware::Syslog.new($app); ``` And in your app: ``` %env<p6sgix.logger>('debug', 'Things happened!'); ```
## dist_cpan-KAIEPI-Net-LibIDN.md [![Build Status](https://travis-ci.org/Kaiepi/p6-Net-LibIDN.svg?branch=master)](https://travis-ci.org/Kaiepi/p6-Net-LibIDN) # NAME Net::LibIDN - Perl 6 bindings for GNU LibIDN # SYNOPSIS ``` use Net::LibIDN; my $idna := Net::LibIDN.new; my $domain := "m\xFC\xDFli.de"; my Int $code; my $ace := $idna.to_ascii_8z($domain, 0, $code); say "$ace $code"; # xn--mssli-kva.de 0 my $domain2 := $idna.to_unicode_8z8z($domain, 0, $code); say "$domain2 $code"; # müssli.de 0 ``` # DESCRIPTION Net::LibIDN is a wrapper for the GNU LibIDN library. It provides bindings for its IDNA, Punycode, stringprep, and TLD functions. See Net::LibIDN::Punycode, Net::LibIDN::StringPrep, and Net::LibIDN::TLD for more documentation. # METHODS * **Net::LibIDN.to\_ascii\_8z**(Str *$input* --> Str) * **Net::LibIDN.to\_ascii\_8z**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN.to\_ascii\_8z**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Converts a UTF8 encoded string *$input* to ASCII and returns the output. *$code*, if provided, is assigned to *IDNA\_SUCCESS* on success, or another error code otherwise. * **Net::LibIDN.to\_unicode\_8z8z**(Str *$input* --> Str) * **Net::LibIDN.to\_unicode\_8z8z**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN.to\_unicode\_8z8z**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Converts an ACE encoded domain name *$input* to UTF8 and returns the output. *$code*, if provided, is assigned to *IDNA\_SUCCESS* on success, or another error code otherwise. # CONSTANTS * Int **IDNA\_ACE\_PREFIX** String containing the official IDNA prefix, "xn--". ## FLAGS * Int **IDNA\_ALLOW\_UNASSIGNED** Allow unassigned Unicode codepoints. * Int **IDNA\_USE\_STD3\_ASCII\_RULES** Check output to ensure it is a STD3 conforming hostname. ## ERRORS * Int **IDNA\_SUCCESS** Successful operation. * Int **IDNA\_STRINGPREP\_ERROR** Error during string preparation. * Int **IDNA\_PUNYCODE\_ERROR** Error during punycode operation. * Int **IDNA\_CONTAINS\_NON\_LDH** *IDNA\_USE\_STD3\_ASCII\_RULES* flag was passed, but the given string contained non-LDH ASCII characters. * Int **IDNA\_CONTAINS\_MINUS** *IDNA\_USE\_STD3\_ASCII\_RULES* flag was passed, but the given string contained a leading or trailing hyphen-minus (u002D). * Int **IDNA\_INVALID\_LENGTH** The final output string is not within the range of 1 to 63 characters. * Int **IDNA\_NO\_ACE\_PREFIX** The string does not begin with *IDNA\_ACE\_PREFIX* (for ToUnicode). * Int **IDNA\_ROUNDTRIP\_VERIFY\_ERROR** The ToASCII operation on the output string does not equal the input. * Int **IDNA\_CONTAINS\_ACE\_PREFIX** The input string begins with *IDNA\_ACE\_PREFIX* (for ToASCII). * Int **IDNA\_ICONV\_ERROR** Could not convert string to locale encoding. * Int **IDNA\_MALLOC\_ERROR** Could not allocate buffer (this is typically a fatal error). * Int **IDNA\_DLOPEN\_ERROR** Could not dlopen the libcidn DSO (only used internally in LibC). # AUTHOR Ben Davies [kaiepi@outlook.com](mailto:kaiepi@outlook.com) # COPYRIGHT AND LICENSE Copyright 2018 Ben Davies This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-titsuki-Algorithm-BinaryIndexedTree.md [![Actions Status](https://github.com/titsuki/raku-Algorithm-BinaryIndexedTree/workflows/test/badge.svg)](https://github.com/titsuki/raku-Algorithm-BinaryIndexedTree/actions) # NAME Algorithm::BinaryIndexedTree - data structure for cumulative frequency tables # SYNOPSIS ``` use Algorithm::BinaryIndexedTree; my $BIT = Algorithm::BinaryIndexedTree.new(); $BIT.add(5,10); $BIT.get(0).say; # 0 $BIT.get(5).say; # 10 $BIT.sum(4).say; # 0 $BIT.sum(5).say; # 10 $BIT.add(0,10); $BIT.sum(5).say; # 20 ``` # DESCRIPTION Algorithm::BinaryIndexedTree is the data structure for maintainig the cumulative frequencies. ## CONSTRUCTOR ### new ``` my $BIT = Algorithm::BinaryIndexedTree.new(%options); ``` #### OPTIONS * `size => $size` Sets table size. Default is 1000. ## METHODS ### add ``` $BIT.add($index, $value); ``` Adds given value to the index `$index`. ### sum ``` my $sum = $BIT.sum($index); ``` Returns sum of the values of items from index 0 to index `$index` inclusive. ### get ``` my $value = $BIT.get($index); ``` Returns the value at index `$index`. # AUTHOR titsuki [titsuki@cpan.org](mailto:titsuki@cpan.org) # COPYRIGHT AND LICENSE Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. The algorithm is from Fenwick, Peter M. "A new data structure for cumulative frequency tables." Software: Practice and Experience 24.3 (1994): 327-336.
## dist_zef-FRITH-Desktop-Notify-Progress.md [![Actions Status](https://github.com/frithnanth/Perl6-Desktop-Notify-Progress/workflows/test/badge.svg)](https://github.com/frithnanth/Perl6-Desktop-Notify-Progress/actions) # NAME Desktop::Notify::Progress - Show the progress of processing in a notification popup # SYNOPSIS ``` use Desktop::Notify::Progress; my $fh = 'BigDataFile'.IO.open; my $p := Desktop::Notify::Progress.new: :$fh, :title('Long data processing'), :timeout(2); for $p -> $line { painfully-process($line); } ``` ``` use Desktop::Notify::Progress; my @p = Seq.new(Desktop::Notify::Progress.new: :filename('BigDataFile')); for @p -> $line { painfully-process($line); } ``` # DESCRIPTION Desktop::Notify::Progress is a small class that provides a way to show the progress of file processing using libnotify ## new(Str :$filename!, Str :$title?, Int :$timeout? = 0) ## new(IO::Handle :$fh!, :$title!, Int :$timeout? = 0) ## new(:&get!, Int :$size?, Str :$title!, Int :$timeout? = 0) Creates a **Desktop::Notify::Progress** object. The first form takes one mandatory argument: **filename**, which will be used as the notification title. Optionally one can pass an additional string which will be used as the notification title: **title**. Another optional parameter **timeout**, the number of seconds the notification will last until disappearing. The default is for the notification not to disappear until explicitly closed. The second form requires both an opened file handler **fh** and the notification **title**. An optional **timeout** can be specified. The third form takes a mandatory function **&get** which retrieves the next element, an optional total number of elements **$size**, and an optional **timeout**. If the **$size** parameter has been provided, the notification will show a percentage, otherwise it will show the current element number. ## Usage A Desktop::Notify::Progress object has an **Iterable** role, so it can be used to read a file line by line. When initialized the object will read the file size, so it will be able to update the computation progress as a percentage in the notification window. # Prerequisites This module requires the libnotify library to be installed. Please follow the instructions below based on your platform: ## Debian Linux ``` sudo apt-get install libnotify4 ``` # Installation To install it using zef (a module management tool): ``` $ zef install Desktop::Notify::Progress ``` This will install the Desktop::Notify module if not yet present. # Testing To run the tests: ``` $ prove -e "raku -Ilib" ``` # AUTHOR Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com) # COPYRIGHT AND LICENSE Copyright 2019 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-azawawi-NCurses.md # NCurses [![Actions Status](https://github.com/azawawi/raku-ncurses/workflows/test/badge.svg)](https://github.com/azawawi/raku-ncurses/actions) NCurses provides a Raku native interface to the `ncurses` library for terminal-independent screen I/O. ## Example ``` use NCurses; # Initialize curses window my $win = initscr() or die "Failed to initialize ncurses\n"; start_color; # Initialize colors init_pair(1, COLOR_WHITE, COLOR_RED); init_pair(2, COLOR_WHITE, COLOR_BLUE); # Print Hello World color_set(1, 0); mvaddstr( 10, 10, " Hello world " ); color_set(2, 0); mvaddstr( LINES() - 2, 2, "Press any key to exit..." ); # Refresh (this is needed) nc_refresh; # Wait for a keypress getch; # Cleanup LEAVE { delwin($win) if $win; endwin; } ``` For more examples, please see the <examples> folder. ## Installation * On Debian-based linux distributions, please use the following command: ``` $ sudo apt-get install libncurses6 ``` * On Mac OS X, please use the following command: ``` $ brew update $ brew install ncurses ``` * Using zef (a module management tool bundled with Rakudo Star): ``` $ zef install NCurses ``` ## Environment variables The following environment variables can be used to specify the location of the different `ncurses` libraries: * `RAKU_NCURSES_LIB` * `RAKU_NCURSES_PANEL_LIB` * `RAKU_NCURSES_MENU_LIB` * `RAKU_NCURSES_FORM_LIB` ## Troubleshooting * To fix a broken or messed up terminal after a crash, please type `reset` to reset your terminal into its original state. ## Testing * To run tests: ``` $ prove -ve "raku -Ilib" ``` * To run all tests including author tests (Please make sure [Test::Meta](https://github.com/jonathanstowe/Test-META) is installed): ``` $ zef install Test::META $ AUTHOR_TESTING=1 prove -e "raku -Ilib" ``` ## Author Ahmad M. Zawawi, azawawi on #raku, <https://github.com/azawawi/> ## License MIT License
## dist_zef-grondilu-Bitcoin.md # Bitcoin raku tools ## Synopses ### Bitcoin ``` use Bitcoin; # A private key is just a 256-bits integer say ^2**256 .pick; # mix it with the Bitcoin::PrivateKey role to add bitcoin-related methods say my $key = ^2**256 .pick but Bitcoin::PrivateKey; # There is a very small chance that mixing will fail as the key range does not # quite go up to 2**256. See documentation about secp256k1 for details. my $key = 2**256 - 123 but Bitcoin::PrivateKey; # dies with 'index out of range' message # Otherwise, the Bitcoin::PrivateKey role mainly defines a wif and address method. # So far, the generated address is always the P2PKH one. say $key.wif; # L2sJY3d2U5kzZSXrREDACTEDW3TbBidYQPvt3REDACTED84e55wr say $key.wif: :uncompressed; # 5K6WMB7MGenK2TdScgSp2B5REDACTEDyxbeamdaREDACTEDPvbt say $key.address; # 1JGoEGREDACTEDzGTBQhDu15pWa5WgDjLa say $key.address: :uncompressed; # 13UpWYvdnJZuMREDACTEDDTNQEsrLpyGWd ``` ### BIP32 ``` use BIP32; # master key generation # - random, defaut entropy is 16 bytes my MasterKey $m .= new; # - from a seed my MasterKey $m .= new: my $seed = blob8.new: ^256 .roll: 32; # key derivation print $m/0; print $m/0/0h; ``` ### BIP39 ``` use BIP39; # create random mnemonics say Mnemonic.new: 24; # twenty four words say Mnemonic.new; # default is twelve # create mnemonics from entropy my blob8 $entropy .= new: 0 xx 16; say Mnemonic.new: $entropy; # (abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about) %*ENV<LANG>='zh_CN'; say Mnemonic.new: $entropy; # 的的的的的的的的的的的在 %*ENV<LANG>='fr_FR'; say Mnemonic.new: $entropy; # (abaisser abaisser abaisser abaisser abaisser abaisser abaisser abaisser abaisser abaisser abaisser abeille) # extract a BIP32-compatible seed say Mnemonic.new.Blob; # same, but with a passphrase say Mnemonic.new.Blob('sezame'); ``` ## LICENSE This library is free software. It is released on the same terms as Raku itself. See the 'COPYRIGHT' and 'LICENSE' files for more information. THIS SOFTWARE IS PROVIDED WITH NO WARRANTY WHATSOEVER. USE AT YOUR OWN RISK.
## parametricrolehow.md role Metamodel::ParametricRoleHOW Represents a non-instantiated, parameterized, role. ```raku class Metamodel::ParametricRoleHOW does Metamodel::Naming does Metamodel::Documenting does Metamodel::Versioning does Metamodel::MethodContainer does Metamodel::PrivateMethodContainer does Metamodel::MultiMethodContainer does Metamodel::AttributeContainer does Metamodel::RoleContainer does Metamodel::MultipleInheritance does Metamodel::Stashing does Metamodel::TypePretense does Metamodel::RolePunning does Metamodel::ArrayType {} ``` *Warning*: this class is part of the Rakudo implementation, and is not a part of the language specification. A `Metamodel::ParametricRoleHOW` represents a non-instantiated, possibly parameterized, role: ```raku (role Zape[::T] {}).HOW.say;# OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤» (role Zape {}).HOW.say; # OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤» ``` As usual, `.new_type` will create a new object of this class. ```raku my \zipi := Metamodel::ParametricRoleHOW.new_type( name => "zape", group => "Zape"); say zipi.HOW; # OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤» ``` The extra `group` argument will need to be used to integrate it in a parametric role group, which will need to be defined in advance. *Note*: As most of the `Metamodel` classes, this one is here mainly for illustration purposes and it's not intended for the final user to instantiate, unless their intention is really to create a parametric role group.
## dist_cpan-JGOFF-Pod-To-HTMLBody.md # Pod-To-HTMLBody [Build Status](http://travis-ci.org/drforr/perl6-Pod-To-HTMLBody) # Pod-To-HTMLBody Generates a HTML fragment Please note that there's a Pod::To::Tree module that will get broken out once it handles the test cases, and Pod::To::HTMLBody will use that instead of surrounding the ::To::Tree module. # Installation * Using zef (a module management tool bundled with Rakudo Star): ``` zef update && zef install Pod::To::HTMLBody ``` ## Testing To run tests: ``` prove -e perl6 ``` ## Author Jeffrey Goff, DrForr on #perl6, <https://github.com/drforr/> ## License Artistic License 2.0
## dist_zef-lizmat-P5lcfirst.md [![Actions Status](https://github.com/lizmat/P5lcfirst/workflows/test/badge.svg)](https://github.com/lizmat/P5lcfirst/actions) # NAME Raku port of Perl's lcfirst() / ucfirst() built-ins # SYNOPSIS ``` use P5lcfirst; say lcfirst "FOOBAR"; # fOOBAR with "ZIPPO" { say lcfirst; # zIPPO } say ucfirst "foobar"; # Foobar with "zippo" { say ucfirst; # Zippo } ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `lcfirst` and `ucfirst` built-ins as closely as possible in the Raku Programming Language. # ORIGINAL PERL 5 DOCUMENTATION ``` lcfirst EXPR lcfirst Returns the value of EXPR with the first character lowercased. This is the internal function implementing the "\l" escape in double-quoted strings. If EXPR is omitted, uses $_. This function behaves the same way under various pragmata, such as in a locale, as "lc" does. ucfirst EXPR ucfirst Returns the value of EXPR with the first character in uppercase (titlecase in Unicode). This is the internal function implementing the "\u" escape in double-quoted strings. If EXPR is omitted, uses $_. This function behaves the same way under various pragma, such as in a locale, as "lc" does. ``` # PORTING CAVEATS In future language versions of Raku, it will become impossible to access the `$_` variable of the caller's scope, because it will not have been marked as a dynamic variable. So please consider changing: ``` lcfirst; ``` to either: ``` lcfirst($_); ``` or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant: ``` .&lcfirst; ``` # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! Source can be located at: <https://github.com/lizmat/P5lcfirst> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen Re-imagined from Perl as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-HANENKAMP-DOM-Tiny.md # NAME DOM::Tiny - A lightweight, self-contained DOM parser/manipulator # SYNOPSIS ``` use DOM::Tiny; # Parse my $dom = DOM::Tiny.parse('<div><p id="a">Test</p><p id="b">123</p></div>'); # Find say $dom.at('#b').text; say $dom.find('p').map(*.text).join("\n"); say $dom.find('[id]').map(*.attr('id')).join("\n"); # Iterate $dom.find('p[id]').reverse.map({ .<id>.say }); # Loop for $dom.find('p[id]') -> $e { say $e<id>, ':', $e.text; } # Modify $dom.find('div p')[*-1].append('<p id="c">456</p>'); $dom.find(':not(p)').map(*.strip); # Render say "$dom"; ``` # DESCRIPTION DOM::Tiny is a smallish, relaxed pure-Perl HTML/XML DOM parser. It is relatively robust owing mostly to the enormous test suite inherited from its progenitor. The HTML/XML parsing is very forgiving and the CSS parser supports a reasonable subset of CSS3 for selecting elements in the DOM tree. This module started as a port of Mojo::DOM58 from Perl 5, but maintaining compatibility with that library is not a major aim of this project. In fact, features of Perl 6 render certain aspects of Mojo::DOM58 completely redundant. For example, the collection system that provides custom features such as `map`, `each`, `reduce`, etc. are completely unnecessary in Perl 6. The built-in syntax is as simple or simpler to use and safer in every case. # NODES AND ELEMENTS When we parse an HTML/XML fragment, it gets turned into a tree of nodes. ``` <!DOCTYPE html> <html> <head><title>Hello</title></head> <body>World!</body> </html> ``` There are currently the following different kinds of nodes: Root, Text, Tag, Raw, PI, Doctype, Comment, and CDATA. These can also be grouped into the following roles: DocumentNode (anything but Root), Node (all kinds), HasChildren (Root and Tag), and TextNode (includes Text, CDATA, and Raw). ``` Root |- Doctype (html) +- Tag (html) |- Tag (head) | +- Tag (title) | +- Text (Hello) +- Tag (body) +- Text (World!) ``` While all node types are represented as DOM::Tiny objects, some methods like `attr` and `namespace` only apply to elements. Under normal circumstances you will probably never need to use these objects directly, but they are available in case you have some special need. These objects are all defined in the DOM::Tiny::HTML namespace. If you want to import the short names, they are exported by default by that compilation unit: ``` { use DOM::Tiny; my $t = DOM::Tiny::HTML::Text.new(:text<Hello>); } { use DOM::Tiny; use DOM::Tiny::HTML; my $t = Text.new(:text<Hello>); } ``` # CASE SENSITIVITY DOM::Tiny defaults to HTML semantics. That means all tags and attribute names are automatically lowercased at parse time. Selectors will, therefore, need to be lowercase to match anything as matching is still case-sensitive. ``` # HTML semantics my $dom = DOM::Tiny.parse('<P ID="greeting">Hi!</P>'); say $dom.at('p[id]').text; ``` If an XML declaration is found at the start of the snippet to parse, the parser will automatically switch into XML mode and everything becomes case-sensitive. ``` # XML semantics my $dom = DOM::Tiny.parse('<?xml version="1.0"?><P ID="greeting">Hi!</P>'); say $dom.at('P[ID]').text; ``` XML detection can also be disabled or forced by explicitly setting the `:xml` flag as needed. ``` # Force XML semantics my $dom = DOM::Tiny.parse('<P ID="greeting">Hi!</P>', :xml); say $dom.at('P[ID]').text; # Force HTML semantics $dom = DOM::Tiny.parse('<P ID="greeting">Hi!</P>', :!xml); say $dom.at('p[id]').text; ``` # SELECTORS DOM::Tiny uses a CSS selector engine found in DOM::Tiny::CSS. We try to support all all CSS selectors that make sense for a standalone parser. Any element. ``` my $all = $dom.find('*'); ``` ## E An element of type E. ``` my $title = $dom.at('title'); ``` ## E[foo] An E element with a foo attribute. ``` my $links = $dom.find('a[href]'); ``` ## E[foo="bar"] An E element whose foo attribute value is exactly equal to bar. ``` my $case_sensitive = $dom.find('input[type="hidden"]'); my $case_sensitive = $dom.find('input[type=hidden]'); ``` ## E[foo="bar" i] An E element whose foo attribute value is exactly equal to any case-permutation of bar. ``` my $case_insensitive = $dom.find('input[type="hidden" i]'); my $case_insensitive = $dom.find('input[type=hidden i]'); my $case_insensitive = $dom.find('input[class~="foo" i]'); ``` This selector is part of Selectors Level 4. The "i" modifier may be added to any attribute selector to make what is normally an exact match to one that matches any case-permutation. ## E[foo~="bar"] An E element whose foo attribute value is a list of whitespace-separated values, one of which is exactly equal to bar. ``` my $foo = $dom.find('input[class~="foo"]'); my $foo = $dom.find('input[class~=foo]'); ``` ## E[foo^="bar"] An E element whose foo attribute value begins exactly with the string bar. ``` my $begins_with = $dom.find('input[name^="f"]'); my $begins_with = $dom.find('input[name^=f]'); ``` ## E[foo$="bar"] An E element whose foo attribute value ends exactly with the string bar. ``` my $ends_with = $dom.find('input[name$="o"]'); my $ends_with = $dom.find('input[name$=o]'); ``` ## E[foo\*="bar"] An E element whose foo attribute value contains the substring bar. ``` my $contains = $dom.find('input[name*="fo"]'); my $contains = $dom.find('input[name*=fo]'); ``` ## E:root An E element, root of the document. ``` my $root = $dom.at(':root'); ``` ## E:nth-child(n) An E element, the n-th child of its parent. ``` my $third = $dom.find('div:nth-child(3)'); my $odd = $dom.find('div:nth-child(odd)'); my $even = $dom.find('div:nth-child(even)'); my $top3 = $dom.find('div:nth-child(-n+3)'); ``` ## E:nth-last-child(n) An E element, the n-th child of its parent, but counting backwards from the end. ``` my $third = $dom.find('div:nth-last-child(3)'); my $odd = $dom.find('div:nth-last-child(odd)'); my $even = $dom.find('div:nth-last-child(even)'); my $bottom3 = $dom.find('div:nth-last-child(-n+3)'); ``` ## E:nth-of-type(n) An E element, the n-th sibling of its type. ``` my $third = $dom.find('div:nth-of-type(3)'); my $odd = $dom.find('div:nth-of-type(odd)'); my $even = $dom.find('div:nth-of-type(even)'); my $top3 = $dom.find('div:nth-of-type(-n+3)'); ``` ## E:nth-last-of-type(n) An E element, the n-th sibling of its type, counting backwards from the end. ``` my $third = $dom.find('div:nth-last-of-type(3)'); my $odd = $dom.find('div:nth-last-of-type(odd)'); my $even = $dom.find('div:nth-last-of-type(even)'); my $bottom3 = $dom.find('div:nth-last-of-type(-n+3)'); ``` ## E:first-child An E element, first child of its parent. ``` my $first = $dom.find('div p:first-child'); ``` ## E:last-child An E element, last child of its parent. ``` my $last = $dom.find('div p:last-child'); ``` ## E:first-of-type An E element, first sibling of its type. ``` my $first = $dom.find('div p:first-of-type'); ``` ## E:last-of-type An E element, last sibling of its type. ``` my $last = $dom.find('div p:last-of-type'); ``` ## E:only-child An E element, only child of its parent. ``` my $lonely = $dom.find('div p:only-child'); ``` ## E:only-of-type An E element, only sibling of its type. ``` my $lonely = $dom.find('div p:only-of-type'); ``` ## E:empty An E element that has no children (including text nodes, meaning the element does not even contain whitespace). ``` my $empty = $dom.find(':empty'); ``` ## E:checked A user interface element E which is checked (for instance a radio-button or checkbox). ``` my $input = $dom.find(':checked'); ``` ## E.warning An E element whose class is "warning". ``` my $warning = $dom.find('div.warning'); ``` ## E#myid An E element with an "id" attribute equal to "myid". Basically, a shorthand for `E[id=foo]`. ``` my $foo = $dom.at('div#foo'); ``` ## E:not(s) An E element that does not match simple selector s. ``` my $others = $dom.find('div p:not(:first-child)'); ``` ## E F An F element descendant of an E element. ``` my $headlines = $dom.find('div h1'); ``` ## E > F An F element child of an E element. ``` my $headlines = $dom.find('html > body > div > h1'); ``` ## E + F An F element immediately preceded by an E element. ``` my $second = $dom.find('h1 + h2'); ``` ## E ~ F An F element preceded by an E element. ``` my $second = $dom.find('h1 ~ h2'); ``` ## E, F, G Elements of type E, F and G. ``` my $headlines = $dom.find('h1, h2, h3'); ``` ## E[foo=bar][bar=baz] An E element whose attributes match all following attribute selectors. ``` my $links = $dom.find('a[foo^=b][foo$=ar]'); ``` # OPERATORS AND COERCIONS You can use array subscripts and hash subscripts with DOM::Tiny. Using this class as an array or hash, though, is not recommended as several of the standard methods for these do not work as expected. ## Array You may use array subscripts as a shortcut for calling `children`: ``` my $third-child = $dom[2]; ``` ## Hash You may use hash subscripts as a shortcut for calling `attr`: ``` my $id = $dom<id>; ``` ## Str If you convert the DOM::Tiny object to a string using `Str`, `~`, or putting it in a string, it will render the markup. ``` my $html = "$dom"; ``` # METHODS ## Construction, Parsing, and Rendering ### method new ``` method new(DOM::Tiny:U: Bool :$xml) returns DOM::Tiny:D ``` Constructs a DOM::Tiny object with an empty DOM tree. Setting the optional `$xml` flag guarantees XML mode. Setting it to a false guarantees HTML mode. If it is unset, DOM::Tiny will select a mode based upon the parsed text, defaulting to HTML. ### method deep-clone ``` method deep-clone(DOM::Tiny:D:) returns DOM::Tiny:D ``` Returns a deep-cloned copy of the current DOM::Tiny object and its children. Any change to the origin will not impact the copy and vice versa. ### method parse ``` method parse(DOM::Tiny:U: Str $ml, Bool :$xml) returns DOM::Tiny:D method parse(DOM::Tiny:D: Str $ml, Bool :$xml) returns DOM::Tiny:D ``` Parses the given string, `$ml`, as HTML or XML based upon the `$xml` flag or autodetection if the flag is not given. If called on an existing DOM::Tiny object, the newly parsed tree will replace the previous tree. ### method render ``` method render(DOM::Tiny:D:) returns Str:D ``` This renders the current node and all its content back to a string and returns it. The format of the markup is determined by the current `xml` setting. ### method Str ``` method Str(DOM::Tiny:D:) returns Str:D ``` This is a synonym for `render`. ### method xml ``` method xml(DOM::Tiny:D:) is rw returns Bool:D ``` This is the boolean flag determining how the node was parsed and how it will be rendered. ## Finding and Filtering Nodes ### method at ``` method at(DOM::Tiny:D: Str:D $selector) returns DOM::Tiny ``` Given a CSS selector, this will return the first node matching that selector or Nil. ### method find ``` method find(DOM::Tiny:D: Str:D $selector) ``` Returns all nodes matching the given CSS `$selector` within the current node. ### method matches ``` method matches(DOM::Tiny:D: Str:D $selector) returns Bool:D ``` Returns `True` if the current node matches the given `$selector` or `False` otherwise. ## Tag Details ### postcircumfix:<{}> ``` method postcircumfix:<{}>(DOM::Tiny:D: Str:D $k) is rw ``` You may use the `.{}` operator as a shortcut for calling the `attr` method and getting attributes on a tag. You may also use the `:exists` and `:delete` adverbs. ### method hash ``` method hash(DOM::Tiny:D:) returns Hash ``` This is a synonym for `attr`, when it is called with no arguments. ### method all-text ``` method all-text(DOM::Tiny:D: Bool :$trim = False) returns Str ``` Pulls the text from all nodes under the current item in the DOM tree and returns it as a string. This is identical to calling `text` with the `:recurse` flag set to `True`. The `:trim` flag may be set to true, which will cause all trimmable space to be clipped from the returned text (i.e., text not in an RCDATA tag like `title` or `textarea` and not in a `pre` tag). ### method attr ``` multi method attr(DOM::Tiny:D:) returns Hash:D multi method attr(DOM::Tiny:D: Str:D $name) returns Str multi method attr(DOM::Tiny:D: Str:D $name, Str() $value) returns DOM::Tiny:D multi method attr(DOM::Tiny:D: Str:D $name, Nil) returns DOM::Tiny:D multi method attr(DOM::Tiny:D: *%values) returns DOM::Tiny:D ``` The `attr` multi-method provides a getter/setter for attributes on the current tag. If the current node is not a tag, this is basically a no-op and will silently do nothing. With no arguments, the method returns the attributes of the tag as a <Hash>. With a single string argument, it returns the value of the named attribute or Nil. With two string arguments, it will set the value of the named attribute and return the current node. With a string argument and a `Nil`, it will delete the attribute and return the current node. Given one or more named arguments, the named values will be set to the given values and the current node will be returned. ### method content ``` multi method content(DOM::Tiny:D:) returns Str:D multi method content(DOM::Tiny:D: DOM::Tiny:D $tree) returns DOM::Tiny:D multi method content(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D ``` This multi-method works with the content of the node, something like `innerHTML` in the standard DOM. Given no arguments, it returns the markup within the element rendered to a string. If the node is empty or has no markup, it will return an empty string. Given a DOM::Tiny, the tree within that object will replace the content of the current node. If the current node cannot have children, then this is a no-op and will silently do nothing. This returns the current node. Given a string, the string will be parsed into HTML or XML (based upon the value of the `:xml` named argument, which defaults to the setting for the current node), and the generated node tree will be used to replace the content of the current node. The current node is returned. ### method namespace ``` method namespace(DOM::Tiny:D:) returns Str ``` Returns the namespace URI of the current tag or Str if it has no namespace. Returns Nil in all other cases (i.e., the current node is not a tag). ### method tag ``` multi method tag(DOM::Tiny:D:) returns Str multi method tag(DOM::Tiny:D: Str:D $tag) returns DOM::Tiny:D ``` If the current node is a tag, both versions of this multi-method are no-ops that silently do nothing. If no arguments are passed, the name of the tag is returned. If a single string is passed, the name of the tag is changed to the given string and the current node is returned. ### method text ``` method text(DOM::Tiny:D: Bool :$trim = False, Bool :$recurse = False) returns Str ``` This returns the text content of the current node. For a text node, this returns the text of the node itself. For a tag or the root, this will return the text of all of the immediate text node children of the current node concatenated together. If the argument named `:recurse` is passed, this method will return the text of all descendants rather than just the immediate children. This is the same as calling `all-text`. If the argument named `:trim` is passed, this method will compress all breaking space into single spaces while concatenating all the text together. ### method type ``` method type(DOM::Tiny:D:) returns Node:U ``` This method returns the type of node that is wrapped within the current DOM::Tiny object. This will be one of the following types: Root The root node of the tree. Tag Markup tag nodes within the tree. Text A regular text node. CDATA A CDATA text node. Comment A comment node. Doctype A DOCTYPE tag element. PI An XML processing instruction. This is also used to represent the XML declaration even though it is technically not a PI. Raw A special raw text node, used to represent the text inside of script and style tags. In addition to these types, you may also want to make use of the following roles, which help group the node types together: Node All nodes, including the root implement this role. DocumentNode All nodes that have a parent have this role, i.e., all but the root. HasChildren Only the nodes that have children have this role, so just Tag and Root. TextNode All nodes that contain text have this role. This includes Text, CDATA, and Raw. Each of these classes and roles are exported by `DOM::Tiny` by default. If you prevent these from being exported, you will need to use their full name, which are each prefixed with `DOM::Tiny::HTML::`. For example, `Tag` has the full name `DOM::Tiny::HTML::Tag` and `TextNode` as the full name `DOM::Tiny::HTML::TextNode`. ### method val ``` method val(DOM::Tiny:D) returns Str ``` Returns the value of the tag. Returns `Nil` if the current tag has no notion of value or if the current node is not a tag. Value is computed as follows, based on the tag name: * * **option**: If the option tag has a `value` attribute, that is the option's value. Otherwise, the option's text is used. * * **input**: The `value` attribute is used. * * **button**: The `value` attribute is used. * * **textarea**: The text content of the tag is used as the value. * * **select**: The value of the currently selected option is used. If no option is marked as selected, the select tag has no value. If the select tag has the `multiple` attribute set, then this returns all the selected values. * * Anything else will return `Nil` for the value. ## Tree Navigation ### method postcircumfix:<[]> ``` method postcircumfix:<[]>(DOM::Tiny:D: Int:D $i) is rw ``` The `.[]` can be used in place of `child-nodes` to retrieve children of the current root or tag from the DOM. The `:exists` and `:delete` adverbs also work. ### method list ``` method list(DOM::Tiny:D:) returns List ``` This is a synonym for `child-nodes`. ### method ancestors ``` method ancestors(DOM::Tiny:D: Str $selector?) returns Seq ``` Returns a sequence of ancestors to the current object as `DOM::Tiny` objects. This will return an empty sequence for the root or any node that no longer has a parent (such as may be the case for a recently removed node). ### method child-nodes ``` method child-nodes(DOM::Tiny:D: Bool :$tags-only = False) ``` If the current node has children (i.e., a tag or root), this method returns all of the children. If the `:tags-only` flag is set, it returns only the children that are tags. If the current node has no children or is not able to have children, an empty list will be returned. ### method children ``` method children(DOM::Tiny:D: Str $selector?) ``` If the current node has children, this method returns only the tags that are children of the current node. The `$selector` may be set to a CSS selector to filter the children returned. Only those matching the selector will be returned. If the current node has no children or is not able to have children, an empty list will be returned. ### method descendant-nodes ``` method descendant-nodes(DOM::Tiny:D:) ``` Returns all the descendants of the current node or an empty list if none or the node cannot have descendants. They are returned in depth-first order. ### method following ``` method following(DOM::Tiny:D: Str $selector?) ``` Returns all sibling tags of the current node that come after the current node. ### method following-nodes ``` method following-nodes(DOM::Tiny:D:) ``` Returns all sibling nodes of the current node that come after the current node. ### method next ``` method next(DOM::Tiny:D:) returns DOM::Tiny ``` Returns the next sibling tag of the current node. If there is no such sibling, it returns `Nil`. ### method next-node ``` method next-node(DOM::Tiny:D:) returns DOM::Tiny ``` Returns the next sibling node of the current node. If there is no such sibling, it returns `Nil`. ### method parent ``` method parent(DOM::Tiny:D:) returns DOM::Tiny ``` Returns the parent of the current node. If the current node is the root, this method returns `Nil` instead. ### method preceding ``` method preceding(DOM::Tiny:D: Str $selector?) ``` Retursn all siblings of the current node that are tags that come before the current node. A `$selector` may be given to filter the returned tags. ### method preceding-nodes ``` method preceding-nodes(DOM::Tiny:D:) ``` Returns all siblings nodes of the current node that precede the current node. ### method previous ``` method previous(DOM::Tiny:D:) returns DOM::Tiny ``` Returns the previous sibling tag of the current node. If there is no such sibling, it returns `Nil`. ### method previous-node ``` method previous-node(DOM::Tiny:D:) returns DOM::Tiny ``` Returns the previous sibling node of the current node. If there is no such sibling, it returns `Nil`. ### method root ``` method root(DOM::Tiny:D:) returns DOM::Tiny:D ``` Returns the root node of the tree. ## Tree Modification ### method append ``` method append(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D ``` Appends the given markup content immediately after the current node. The `:xml` flag may be set to determine whether the given markup should be parsed as XML or HTML (with the default being whatever the current document is being treated as). If the current node is the root (i.e., `$dom.type ~~ Root`), this operation is a no-op. It will silently do nothing. Returns the current node. ### method append-content ``` method append-content(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D ``` If this is the root or a tag (i.e., `$dom.type ~~ Root|Tag`), the given markup will be parsed and appended to the end of the root's or tag's children. If this is a text node (i.e., `$dom.type ~~ TextNode`), then the markup will be appended to the text node parent's children. Otherwise this is a no-op and will silently do nothing. The `:xml` flag may be used to specify the format for the markup being parsed, defaulting to the setting for the current document. Returns the node whose children have been modified. ### method prepend ``` method prepend(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D ``` Appends the given markup content immediately before the current node. The `:xml` flag may be set to tell the parser to parse in XML mode or not (with the default being whatever is set for the current node). If the current node is the root, this operation is a no-op and will silently do nothing. This method will return the current node. ### method prepend-content ``` method prepend-content(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D ``` Appends the given markup content at the beginning of the current node's children, if it is the root or a tag. (This is a no-op that silently does nothing unless the current node is the root or a tag.) The `:xml` flag sets whether to parse the `$ml` as XML or not, with the default being the xml mode flag set on the current node. This method returns the current node. ### method remove ``` method remove(DOM::Tiny:D:) returns DOM::Tiny:D ``` Removes the current node from the tree and returns the parent node. If this node is the root, then the tree is emptied and the current node (i.e., the root) is returned. ### method replace ``` method replace(DOM::Tiny:D: DOM::Tiny:D $tree) returns DOM::Tiny:D method replace(DOM::Tiny:D: Str() $ml) returns DOM::Tiny:D ``` The current node is replaced with the tree or markup given. If the current node is the root, the current node is returned. Otherwise, the original parent of this node, which has been replaced with the new tree, is returned. ### method strip ``` method strip(DOM::Tiny:D:) returns DOM::Tiny:D ``` If the current node is a tag, the tag is removed from the tree and its content moved up into the current node's original parent. This will then return the original node's parent. If the current node is anything else, this is a no-op that will silently do nothing and return the current node. ### method wrap ``` method wrap(DOM::Tiny:D: Str:D $ml, Bool :$xml = $!xml) returns DOM::Tiny:D ``` The given markup in `$ml` is parsed according to the format given by the `:xml` flag (defaulting to whatever the `xml` setting is for the current node). The current node is put within the innermost tag of the given markup. The current node is returned. This is a no-op and will silently do nothing if the current node is the root. ### method wrap-content ``` method wrap-content(DOM::Tiny:D: Str:D $ml, Bool :$xml = $!xml) returns DOM::Tiny:D ``` This is a no-op and will silently do nothing unless the current node is the root or a tag. The given markup in `$ml` is parsed. The parsing proceeds as XML if the `:xml` flag is set or HTML otherwise (with the default being whatever the `xml` flag is set to on the current node). The content of the current node is then placed within the innermost tag of the parsed markup and that parsed markup replaces the content of the current node. # CAVEATS This software is beta quality. It has been ported from a mature code base and survived many uses, but it has still only had a small number of bugs reported and fixed. It has a large test suite, but much of that has been ported from the Perl 5 module and is not necessarily specific to the kinds of bugs this port has. There has also been very little done to optimize the code or even to check to make sure it performs well in how it utilizes CPU and memory. As of the v0.5.0, this project is committed to the following signals regarding changes to this software in the future: * The major version number ("1" in "1.2.3") will be incremented whenever a documented feature changes in a way that is not backwards compatible. * The minor version number ("2" in "1.2.3") will be incremented whenever new features or added or any backwards compatible change is made to an undocumented feature or some other significant change is made to the project. * The patch number ("3" in "1.2.3") will be incremented whenever any other change is made (e.g., documentation, testing, minor bug fixes, etc.) Semantic versioning is not a perfect system as it is not always crystal clear what distinguishes "bug fix" from "new feature" or "backwards compatible change" until after the fact, but I will try to do my best. Any change thought to break backwards compatibility will be tagged with "BREAKING CHANGE" in `Changes`. # AUTHOR AND COPYRIGHT Copyright 2008-2016 Sebastian Riedel and others. Copyright 2016 Andrew Sterling Hanenkamp for the port to Perl 6. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible)
## parent.md parent Combined from primary sources listed below. # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_parent "direct link") See primary documentation [in context](/type/IO/Path#method_parent) for **method parent**. ```raku multi method parent(IO::Path:D:) multi method parent(IO::Path:D: UInt:D $level) ``` Returns the parent path of the invocant. Note that no actual filesystem access is made, so the returned parent is physical and not the logical parent of symlinked directories. ```raku '/etc/foo'.IO.parent.say; # OUTPUT: «"/etc".IO␤» '/etc/..' .IO.parent.say; # OUTPUT: «"/etc".IO␤» '/etc/../'.IO.parent.say; # OUTPUT: «"/etc".IO␤» './' .IO.parent.say; # OUTPUT: «"..".IO␤» 'foo' .IO.parent.say; # OUTPUT: «".".IO␤» '/' .IO.parent.say; # OUTPUT: «"/".IO␤» IO::Path::Win32.new('C:/').parent.say; # OUTPUT: «"C:/".IO␤» ``` If `$level` is specified, the call is equivalent to calling `.parent()` `$level` times: ```raku say "/etc/foo".IO.parent(2) eqv "/etc/foo".IO.parent.parent; # OUTPUT: «True␤» ``` # [In X::Inheritance::Unsupported](#___top "go to top of document")[§](#(X::Inheritance::Unsupported)_method_parent "direct link") See primary documentation [in context](/type/X/Inheritance/Unsupported#method_parent) for **method parent**. The type object that the child tried to inherit from.
## dist_github-retupmoca-Net-AMQP.md # Net::AMQP Net::AMQP - a AMQP 0.9.1 client library (built and tested against RabbitMQ) ## Synopsis First start a consumer that will print the received messages: ``` use v6; use Net::AMQP; my $n = Net::AMQP.new; my $connection = $n.connect.result; say 'connected'; my $channel = $n.open-channel(1).result; say 'channel'; my $q = $channel.declare-queue('echo').result; say 'queue'; $q.message-supply.tap({ say 'Got message!'; say $_.body.decode; if $_.body.decode eq 'exit' { $n.close("", ""); } }); say 'set up'; $q.consume; say 'consuming'; await $connection; ``` Then run the script that will send a message sent on the command line, ``` use v6; use Net::AMQP; sub MAIN($message) { my $n = Net::AMQP.new; await $n.connect; my $channel = $n.open-channel(1).result; $channel.exchange.result.publish(routing-key => "echo", body => $message.encode); await $n.close("", ""); } ``` ## Description This is an async network library. Any -supply method returns a supply, and every other method will return a promise (with the exception of the initial Net::AMQP.new call). ## Methods ### Net::AMQP * new * close * open-channel * connect ### Net::AMQP::Channel * close * declare-exchange * exchange * declare-queue * queue * qos * flow * recover ### Net::AMQP::Exchange * delete * publish * return-supply NYI * ack-supply NYI ### Net::AMQP::Queue * bind * unbind * purge * delete * consume * cancel NYI * message-supply * recover NYI ## Installation In order for this to work you will need to have access to an AMQP broker, the tests will, by default, use a broker on `localhost` with the default credentials. The tests will be skipped if no server is available, If you want to test against other than `localhost` or with different credentials then you can set the environment variables ``` * AMQP_HOST * AMQP_PORT * AMQP_LOGIN * AMQP_PASSWORD * AMQP_VHOST ``` as appropriate before running the tests. Assuming you have a working installation of Rakudo then you will be able to install this with *zef* : ``` zef install Net::AMQP # or if you have a local copy zef install . ```
## dist_zef-raku-community-modules-Data-StaticTable.md [![Actions Status](https://github.com/raku-community-modules/Data-StaticTable/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Data-StaticTable/actions) [![Actions Status](https://github.com/raku-community-modules/Data-StaticTable/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Data-StaticTable/actions) [![Actions Status](https://github.com/raku-community-modules/Data-StaticTable/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Data-StaticTable/actions) # NAME Data::StaticTable - a static memory structure in Raku # INTRODUCTION A StaticTable allows you to handle bidimensional data in a more natural way Some features: * Rows starts at 1 (`Data::StaticTable::Position` is the datatype used to reference row numbers) * Columns have header names * Any column can work as an index If the number of elements provided does not suffice to form a square or a rectangle, filler cells will be added as filler (you can define what goes in these filler cells as well). The module provides two classes: `StaticTable` and `StaticTable::Query`. A StaticTable can be populated, but it can not be modified later. To perform searchs and create/store indexes, a Query object is provided. You can add indexes per column, and perform searches (grep) later. If an index exists, it will be used. You can get data by rows, columns, and create subsets by taking some rows from an existing StaticTable. # TYPES ## Data::StaticTable::Position Basically, an integer greater than 0. Used to indicate a row position in the table. A StaticTable do not have rows on index 0. # OPERATORS ## eqv Compares the contents (header and data) of two StaticTable objects. Returns `False` as soon as any difference is detected, and `True` if it finds that everything is equal. ``` say '$t1 and $t2 are ' ~ ($t1 eqv $t2) ?? 'equal' !! 'different'; ``` # Data::StaticTable CLASS ## Positional features ### Brackets [] You can use [n] to get the full Nth row, in the way of a hash of **'Column name'** => data So, for example ``` $t[1] ``` Could return a hash like ``` {Column1 => 10, Column2 => 200.4, Column3 => 450} ``` And a call like ``` $t[10]<Column3> ``` would refer to the data in Row 10, with the heading Column3 ### The `ci` hash On construction, a public hash called `ci` (short for **c**olumn **i**ndex) is created. If for some reason, you need to refer the columns by number instead of name, this hash contains the column numbers as keys, and the heading name as values. if your column number **2** has the name "Weight", you can read the cell in the third row of that column like this: ``` my $val1 = $t.cell('Weight', 3); my $val2 = $t[3]<Weight>; ``` Or by using the `ci` hash ``` my $val1 = $t.cell($t.ci<2>, 3); my $val2 = $t[3]{$t.ci<2>}; ``` ## method new Depending on how your source data is organized, you can use the 2 **flat array** constructors or a **rowset** constructor. **Flat array** allows you to pass a long one dimensional array and order it in rows and columns, by specifiying a header. You can pass an array of string to specify the column names, or just a number of columns if you don't care about the column names. **Rowset** works when your data is already bidimensional, and it can include a first row as header. In the case that your rows contains a hash, you can tell the constructor, and it will take the hash keys to create a header with the appropiate column names. In this case, any row that does not contain a hash will be discarded (you have the option to recover the discarded data). ### The flat array constructor ``` my $t1 = StaticTable.new( 3 , (1 .. 15) ); my $t2 = StaticTable.new( <Column1 Column2 Column3> , ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12 13,14,15 ) ); ``` This will create a spreadsheet-like table, with numbered rows and labeled columns. In the case of `$t1`, since the first parameter is a number, it will have columns named automatically, as `A`, `B`, `C`... etc. `$t2` has an array as the first parameter. So it will have three columns labeled `Column1`, `Column2` and `Column3`. You just need to provide an array to fill the table. The rows and columns will be automatically cut and filled in a number of rows. If you do not provide enough data to fill the last row, empty cells will be appended. If you already have your data ordered in an array of arrays, use the rowset constructor described below. ### The rowset constructor You can also create a StaticTable from an array, with each element representing a row. The StaticTable will acommodate the values as best as possible, adding empty values or discarding values that go beyond the boundaries, or data that is not prepared appropiately This constructor can be called like this, using an Array of Arrays ``` my $t = StaticTable.new( (1,2,3), (4,5,6), (7,8,9) ); ``` For a Array of Hashes, you can call it like this ``` my $t = StaticTable.new( [ { name => 'Eggplant', color => 'aubergine', type => 'vegetal' }, { name => 'Egg', color => ('white', 'beige'), type => 'animal' }, { name => 'Banana', color => 'yellow', type => 'fruit' }, { name => 'Avocado', color => 'green', type => 'fruit', class => 'Hass' } ] ); ``` *(Note the use of brackets, we needed to explicitly pass an Array of Hashes)* There is a set of named parameters usable in this constructor ``` my $t = StaticTable.new(@ArrayOfArrays):data-has-header ``` This will use the first row as header. Any value that falls outside the column boundaries determined by the header will be discarded in each row. ``` my $t = StaticTable.new(@ArrayOfHashes):set-of-hashes ``` This will consider each row as a hash, and will create columns for each key found. The most populated will be the first columns. Any row that is not a hash will be discarded ### Recovering discarded data In some situations, some data can be rejected from your original array passed to the constructor. This will happen in two cases, using the rowset constructor: * You specified `:data-has-header` but there are rows longer that the length of the header. So, if your first row had 4 elements, any row with more that 4 elements will be cut and the extra elements will be rejected * You specified `:set-of-hashes` but there are rows that does not contain hashes. All these rows will be rejected too. For recovering discarded data from an Array of Arrays: ``` my %rejected; my $tAoA = StaticTable.new( @ArrayOfArrays, rejected-data => %rejected # <--- Note, rejected is a hash ):data-has-header ``` In this case, `%rejected` is a hash where the key is the row from where the data was discarded, pointing to an array of the elements discarded in that row. For recovering discarded data from an Array of Hashes: ``` my @rejected; my $tAoH = StaticTable.new( @ArrayOfHashes, rejected-data => @rejected # <--- rejected is an array ):set-of-hashes ``` In this case, `@rejected` will have a list of all the rejected rows. ### The `filler` value There is another named parameter, called `filler`. This is used to complete rows that need more cells, so the table has every row with the same number of elements. By default, it uses `Nil`. Example: ``` my $t = Data::StaticTable.new( <A B C>, (1,2,3, 4,5,6, 7), # 2 last cells will be fillers, so the 3rd row is complete filler => 'N/A' ); print $t[3]<C>; #This will print N/A ``` ## method raku Returns a representation of the StaticTable. Can be used for serialization. ## method clone Returns a newly created StaticTable with the same attributes. It does **not** copy attributes to clone. Instead, runs the constructor again. ## method display Shows a 'visual' representation of the contents of the StaticTable. Used for debugging, **not for serialization**. It would look like this: ``` A B C ⋯ ⋯ ⋯ [1] [2] [3] [4] [5] [6] [7] [8] [9] ``` However, you could save the output of this method to a tab-separated csv file. ## method cell(Str $column-heading, Position $row) Retrieves the content of a cell. ## method column(Str $column-heading) Retrieves the content of a column like a regular `List`. ## method row(Position $row) Retrieves the content of a row as a regular `List`. ## method shaped-array Retrieves the content of the table as a multiple dimension array. ## method elems Retrieves the number of cells in the table ## method generate-index(Str $heading) Generate a `Hash`, where the key is the value of the cell, and the value is a list of row numbers (of type `Data::StaticTable::Position`). ## method take(@rownums where .all ~~ Position) Generate a new `StaticTable`, using a list of row numbers (using the type `Data::StaticTable::Position`) The order of the rows will be kept, and you can consider repeated rows. You can use `.unique` and `.sort` on the row numbers list. A sorted, unique list will make the construction of the new table **faster**. Consider this is you want to use a lot of rownums. ``` #-- Order and repeated rows will be kept my $new-t1 = $t.take(@list); #-- Consider this if @list is big, not sorted and has repeated elements my $new-t2 = $t.take(@list.uniq.sort) =end raku You can combine this with C<generate-index> =begin code :lang<raku> my %i-Status = $t.generate-index("Status"); # We want a new table with rows where Status = "Open" my $t-open = $t.take(%i-Status<Open>); # We want another where Status = "Awaiting feedback" my $t-waiting = $t.take(%i-Status{'Awaiting feedback'}); ``` Also works with the `.grep` method from the `StaticTable::Query` object. This allows to you do more complex searches in the columns. An identical, but slurpy version of this method is also available for convenience. # Data::StaticTable::Query CLASS Since StaticTable is immutable, a helper class to perform searches is provided. It can contain generated indexes. If an index is provided, it will be used whenever a search is performed. ## Associative features You can use hash-like keys, to get a specific index for a column ``` $Q1<Column1> $Q1{'Column1'} ``` Both can get you the index (the same you could get by using `generate-index` in a `StaticTable`). ## method new(Data::StaticTable $T, \*@to-index) You need to specify an existing `StaticTable` to create this object. Optionally you can pass a list with all the column names you want to consider as indexes. Examples: ``` my $q1 = Data::StaticTable::Query.new($t); #-- No index at construction my $q2 = Data::StaticTable::Query.new($t, 'Address'); #-- Indexing column 'Address' my $q3 = Data::StaticTable::Query.new($t, $t.header); #-- Indexing all columns ``` If you don't pass any column names in the constructor, you can always use the method `add-index` later ## method raku Returns a representation of the StaticTable::Query object. Can be used for serialization. **Note:** This value will contain *the complete* StaticTable for this index. ## method keys Returns the name of the columns indexed. ## method values Returns the values indexed. ## method k Returns the hash of the same indexes in the `Query` object. ## method grep(Mu $matcher where { -> Regex {}($\_); True }, Str $heading, Bool :$h = True, Bool :$n = False, Bool :$r = False, Bool :$nr = False, Bool :$nh = False) Allows to use grep over a column. Depending on the flags used, returns the resulting row information for all that rows where there are matches. You can not only use a regxep, but a `Junction` of `Regex` elements. Examples of Regexp and Junctions: ``` # Get the rownumbers where the column 'A' contains '9' my Data::StaticTable::Position @rs1 = $q.grep(rx/9/, "A"):n; # Get the rownumbers where the column 'A' contains 'n' and 'e' my Data::StaticTable::Position @rs2 = $q.grep(all(rx/n/, rx/e/), "A"):n; ``` When you use the flag `:n`, you can use these results later with the method `take` ### Flags Similar to the default grep method, this contains flags that allows you to receive the information in various ways. Consider this StaticTable and its Query: ``` my $t = Data::StaticTable.new( <Countries Import Tons>, ( 'US PE CL', 'Copper', 100, # Row 1 'US RU', 'Alcohol', 50, # Row 2 'IL UK', 'Processor', 12, # Row 3 'UK', 'Tuxedo', 1, # Row 4 'JP CN', 'Tuna', 10, # Row 5 'US RU CN', 'Uranium', 0.01 # Row 6 ) ); my $q = Data::StaticTable::Query.new($t) ``` * :n Returns only the row numbers. This is very useful to combine with the `take` method. ``` my @a = $q.grep(all(rx/US/, rx/RU/), 'Countries'):n; # Result: The array (2, 6) ``` * :r Returns the rows, just data, no headers ``` my @a = $q.grep(all(rx/US/, rx/RU/), 'Countries'):r; # Result: The array # [ # ("US RU", "Alcohol", 50), # ("US RU CN", "Uranium", 0.01) # ] ``` * :h Returns the rows as a hash with header information This is the default mode. You don't need to use the `:h` flag to get this result ``` my @a1 = $q.grep(all(rx/US/, rx/RU/), 'Countries'):h; # :h is the default my @a2 = $q.grep(all(rx/US/, rx/RU/), 'Countries'); # @a1 and @a2 are identical # Result: The array # [ # {:Countries("US RU"), :Import("Alcohol"), :Tons(50)}, # {:Countries("US RU CN"), :Import("Uranium"), :Tons(0.01)} # ] ``` * :nr Like `:r` but in a hash, with the row number as the key ``` my %h = $q.grep(all(rx/US/, rx/RU/), 'Countries'):nr; # Result: The hash # { # "2" => $("US RU", "Alcohol", 50), # "6" => $("US RU CN", "Uranium", 0.01) # } ``` * :nh Like `:h` but in a hash, with the row number as the key ``` my %h = $q.grep(all(rx/US/, rx/RU/), 'Countries'):nh; # Result: The hash # { # "2" => ${:Countries("US RU"), :Import("Alcohol"), :Tons(50)}, # "6" => ${:Countries("US RU CN"), :Import("Uranium"), :Tons(0.01)} # } ``` ## method add-index($column-heading) Creates a new index, and it will return a score indicating the index quality. Values of 1, or very close to zero are the less ideals. Nevertheless, even an index with a score 1 will help. Example: ``` my $q1 = Data::StaticTable::Query.new($t); #-- Creates index and ... $q1.add-index('Address'); #-- indexes the column 'Address' ``` When an index is created, it is used automatically in any further `grep` calls. # AUTHOR shinobi # COPYRIGHT AND LICENSE Copyright 2018 - 2019 shinobi Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## printf.md printf Combined from primary sources listed below. # [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_printf "direct link") See primary documentation [in context](/type/IO/Handle#method_printf) for **method printf**. ```raku multi method printf(IO::Handle:D: Cool $format, *@args) ``` Formats a string based on the given format and arguments and `.print`s the result into the filehandle. See [sprintf](/routine/sprintf) for details on acceptable format directives. Attempting to call this method when the handle is [in binary mode](/type/IO/Handle#method_encoding) will result in [`X::IO::BinaryMode`](/type/X/IO/BinaryMode) exception being thrown. ```raku my $fh = open 'path/to/file', :w; $fh.printf: "The value is %d\n", 32; $fh.close; ``` # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_routine_printf "direct link") See primary documentation [in context](/type/independent-routines#routine_printf) for **routine printf**. ```raku multi printf(Cool:D $format, *@args) ``` Produces output according to a format. The format used is the invocant (if called in method form) or the first argument (if called as a routine). The rest of the arguments will be substituted in the format following the format conventions. See [sprintf](/routine/sprintf) for details on acceptable format directives. ```raku "%s is %s".printf("þor", "mighty"); # OUTPUT: «þor is mighty» printf( "%s is %s", "þor", "mighty"); # OUTPUT: «þor is mighty» ``` On [`Junction`](/type/Junction)s, it will also autothread, without a guaranteed order. ```raku printf( "%.2f ", ⅓ | ¼ | ¾ ); # OUTPUT: «0.33 0.25 0.75 » ``` # [In Cool](#___top "go to top of document")[§](#(Cool)_method_printf "direct link") See primary documentation [in context](/type/Cool#method_printf) for **method printf**. ```raku method printf(*@args) ``` Uses the object, as long as it is a [format string](/type/independent-routines#Directives), to format and print the arguments ```raku "%.8f".printf(now - now ); # OUTPUT: «-0.00004118» ```
## dist_zef-guifa-Intl-Regex-CharClass.md # Intl::Regex::CharClass This module aims to provide localized variants of built in character classes. It currently only supports the `<alpha>` class inside of grammars, but support for other classes and outside of grammars. The API is still experimental, so do not (yet) depend on it. ## Use It's as simple as importing the module and adding in the trait `is localized`. ``` use Intl::Regex::CharClass grammar Word is localized('en') { token TOP { <alpha>+ } } Word.parse('party'); # party Word.parse('piñata'); # [no match] grammar Palabra is localized('es') { token TOP { <alpha>+ } } Palabra.parse('piñata'); # piñata Palabra.parse('fête'); # [no match] ``` If you do not specify a language, it will by default localized to the system language as defined by `User::Language`. If for some reason that is not available or detectable, it will default to `en` (English). ### Version history * **v0.1.0** First release with support for `<alpha>`
## dist_zef-lizmat-P5reset.md [![Actions Status](https://github.com/lizmat/P5reset/workflows/test/badge.svg)](https://github.com/lizmat/P5reset/actions) # NAME Raku port of Perl's reset() built-in # SYNOPSIS ``` use P5reset; reset("a"); # reset all "our" variables starting with "a" reset("a-z"); # reset all "our" variables starting with lowercase letter reset; # does not reset any variables ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `reset` built-in as closely as possible in the Raku Programming Language. # ORIGINAL PERL DOCUMENTATION ``` reset EXPR reset Generally used in a "continue" block at the end of a loop to clear variables and reset "??" searches so that they work again. The expression is interpreted as a list of single characters (hyphens allowed for ranges). All variables and arrays beginning with one of those letters are reset to their pristine state. If the expression is omitted, one-match searches ("?pattern?") are reset to match again. Only resets variables or searches in the current package. Always returns 1. Examples: reset 'X'; # reset all X variables reset 'a-z'; # reset lower case variables reset; # just reset ?one-time? searches Resetting "A-Z" is not recommended because you'll wipe out your @ARGV and @INC arrays and your %ENV hash. Resets only package variables; lexical variables are unaffected, but they clean themselves up on scope exit anyway, so you'll probably want to use them instead. See "my". ``` # PORTING CAVEATS Since Raku doesn't have the concept of `?one time searches?`, the no-argument form of `reset` will not reset any variables at all. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! Source can be located at: <https://github.com/lizmat/P5reset> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen Re-imagined from Perl as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-path-utils.md [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) # NAME path-utils - low-level path introspection utility functions # SYNOPSIS ``` use path-utils; # export all subs use path-utils <path-exists>; # only export sub path-exists say path-exists($filename); 0 or 1 ``` # DESCRIPTION path-utils provides a number of low-level path introspection utility functions for those cases where you're interested in performance, rather than functionality. All subroutines take a (native) string as the only argument. Note that these functions only return native `int` and native `num` values, which can be used in conditions without any problems, just don't expect them to be upgraded to `Bool` values. Also note that all functions (except `path-exists`) expect the path to exist. An exception will be thrown if the path does not exist. The reason for this is that in situations where you are already sure a path exists, there is no point checking for its existence again if you e.g. would like to know its size. # SELECTIVE IMPORTING ``` use path-utils <path-exists>; # only export sub path-exists ``` By default all utility functions are exported. But you can limit this to the functions you actually need by specifying the names in the `use` statement. To prevent name collisions and/or import any subroutine with a more memorable name, one can use the "original-name:known-as" syntax. A semi-colon in a specified string indicates the name by which the subroutine is known in this distribution, followed by the name with which it will be known in the lexical context in which the `use` command is executed. ``` use path-utils <path-exists:alive>; # export "path-exists" as "alive" say alive "/etc/passwd"; # 1 if on Unixy, 0 on Windows ``` # EXPORTED SUBROUTINES In alphabetical order: ## path-accessed Returns number of seconds since epoch as a `num` when path was last accessed. ## path-blocks Returns the number of filesystem blocks allocated for this path. ## path-block-size Returns the preferred I/O size in bytes for interacting wuth the path. ## path-created Returns number of seconds since epoch as a `num` when path was created. ## path-device-number Returns the device number of the filesystem on which the path resides. ## path-exists Returns 1 if paths exists, 0 if not. ## path-filesize Returns the size of the path in bytes. ## path-gid Returns the numeric group id of the path. ## path-git-repo Returns the path of the Git repository associated with the **absolute** path given, or returns the empty string if the path is not part inside a Git repository. Note that this not mean that the file is actually part of that Git repository: it merely indicates that the returned path returned `True` with `path-is-git-repo`. ## path-hard-links Returns the number of hard links to the path. ## path-has-setgid The path has the SETGID bit set in its attributes. ## path-inode Returns the inode of the path. ## path-is-device Returns 1 if path is a device, 0 if not. ## path-is-directory Returns 1 if path is a directory, 0 if not. ## path-is-empty Returns 1 if the path has a filesize of 0. ## path-is-executable Returns a non-zero integer value if path is executable by the current user. ## path-is-github-repo Returns 1 if path appears to be the top directory in a GitHub repository (as recognized by having a `.github` directory in it). ## path-is-git-repo Returns 1 if path appears to be the top directory in a Git repository (as recognized by having a <.git> directory in it). ## path-is-group-executable Returns a non-zero integer value if path is executable by members of the group of the path. ## path-is-group-readable Returns a non-zero integer value if path is readable by members of the group of the path. ## path-is-group-writable Returns a non-zero integer value if path is writable by members of the group of the path. ## path-is-moarvm Returns 1 if path is a `MoarVM` bytecode file (either from core, or from a precompiled module file), 0 if not. ## path-is-owned-by-user Returns a non-zero integer value if path is owned by the current user. ## path-is-owned-by-group Returns a non-zero integer value if path is owned by the group of the current user. ## path-is-owner-executable Returns a non-zero integer value if path is executable by the owner of the path. ## path-is-owner-readable Returns a non-zero integer value if path is readable by the owner of the path. ## path-is-owner-writable Returns a non-zero integer value if path is writable by the owner of the path. ## path-is-pdf Returns 1 if path looks a `PDF` file, judging by its magic number, 0 if not. ## path-is-readable Returns a non-zero integer value if path is readable by the current user. ## path-is-regular-file Returns 1 if path is a regular file, 0 if not. ## path-is-sticky The path has the STICKY bit set in its attributes. ## path-is-symbolic-link Returns 1 if path is a symbolic link, 0 if not. ## path-is-text Returns 1 if path looks like it contains text, 0 if not. ## path-is-world-executable Returns a non-zero integer value if path is executable by anybody. ## path-is-world-readable Returns a non-zero integer value if path is readable by anybody. ## path-is-world-writable Returns a non-zero integer value if path is writable by any body. ## path-is-writable Returns a non-zero integer value if path is writable by the current user. ## path-meta-modified Returns number of seconds since epoch as a `num` when the meta information of the path was last modified. ## path-mode Returns the numeric unix-style mode. ## path-modified Returns number of seconds since epoch as a `num` when path was last modified. ## path-uid Returns the numeric user id of the path. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/path-utils> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2022, 2023, 2024, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.