txt
stringlengths
93
37.3k
## concreterolehow.md role Metamodel::ConcreteRoleHOW Provides an implementation of a concrete instance of a role ```raku class Metamodel::ConcreteRoleHOW does Metamodel::Naming does Metamodel::Versioning does Metamodel::PrivateMethodContainer does Metamodel::MethodContainer does Metamodel::MultiMethodContainer does Metamodel::AttributeContainer does Metamodel::RoleContainer does Metamodel::MultipleInheritance does Metamodel::ArrayType does Metamodel::Concretization {} ``` *Warning*: this class is part of the Rakudo implementation, and is not a part of the language specification. You can use this to build roles, in the same way that `ClassHOW` can be used to build classes: ```raku my $a = Metamodel::ConcreteRoleHOW.new_type(name => "Bar"); $a.^compose; say $a.^roles; # OUTPUT: «(Mu)␤» ``` The main difference with [`ClassHOW.new_type`](/type/Metamodel/ClassHOW#method_new_type) is that you can mix-in roles in this newly created one. This class is Rakudo specific, and provided only for completeness. Not really intended to be used by the final user.
## dist_zef-martimm-Gnome-Gtk4.md ![](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-raku.png) # Gnome::Gtk4 - Raku interface to the GTK toolkit ![L](http://martimm.github.io/label/License-label.svg) # Description This package holds the native object description as well as the interface description to connect to the Gnome libraries. This set of modules will never act on their own. They will be used by other packages such as `Gnome::Gtk4` and the like. ## Example An example of a window showing two buttons is shown below. Its origin comes from the package **GTK::Simple** of Richard Hainsworth. Some important things to note; * It is important to add the `:api<2>` part to the module in the *use* statement to be sure you get the proper module. This is neccesary to prevent clashes with the older **Gnome::Gtk3** series of modules when you have installed them or when your application gets installed on some other machine. However, this set of repos only holds **Gnome::Gtk4** but the repos it depends on have the same names as before like **Gnome::Glib**, **Gnome::Gio** and **Gnome::GObject**. Those classes are all redone with the :api<2> tag. And, dunno, maybe the gtk3 gets added in the future. * The instanciation of the classes in the `Gnome::*` `:api<2>` packages is changed compared to the `:api<1>` version. There is no `new()` (for most classes).   The decision is made to follow the interface of the gnome libraries more strictly. Because of that, it is easier to look into examples written in C and translate it into Raku.   The Raku new method only accepts named arguments, except when you tinker a bit with it, which I didn't want to do.   E.g. the GtkWindow class has a `gtk_window_new()`. So it became `new-window()` and returns an instanciated object. Other examples like this are `new-label()` and `new-grid()`, with or without parameters. Other new functions are longer, e.g. Label has also `gtk_label_new_with_mnemonic()` which becomes `new-with-mnemonic()`. * As with the :api<1> version, this version makes use of native types as used in the gnome libraries. An example of this is `gboolean` type which is mapped to some Raku native type in the **Gnome::N::GlibToRakuTypes** module. ### Initialization Loading the modules needed for the application. ``` use Gnome::Glib::N-MainLoop:api<2>; use Gnome::Gtk4::Button:api<2>; use Gnome::Gtk4::Window:api<2>; use Gnome::Gtk4::Grid:api<2>; use Gnome::N::GlibToRakuTypes:api<2>; use Gnome::N::N-Object:api<2>; # Convenience shortened class names constant Window = Gnome::Gtk4::Window; constant Button = Gnome::Gtk4::Button; constant Grid = Gnome::Gtk4::Grid; my Gnome::Glib::N-MainLoop $main-loop .= new-mainloop( N-Object, True); ``` ### Helper class to handle the events from the buttons The first method `stopit()` is used to stop the application, triggered by a button on the decoration of the application. The second method `b1-press()` is called when the top button is pressed. After showing a message it will make the second button responsive and the top button is made insensitive. The third method `b2-press()` will also stop the program. ``` class SH { method stopit ( --> gboolean ) { say 'close request'; $main-loop.quit; 0 } method b1-press ( Button() :_native-object($button1), Button :$button2 ) { say 'button1 pressed'; $button2.set-sensitive(True); $button1.set-sensitive(False); } method b2-press ( ) { say 'button2 pressed'; $main-loop.quit; } } # Instanciate the helper object my SH $sh .= new; ``` ### Building the GUI First the two buttons are created. Registration of the signal is using the methods in the **SH** class. The first three parameters are obliged and the named arguments are optional. ``` with my Button $button2 .= new-with-label('Goodbye') { .register-signal( $sh, 'b2-press', 'clicked'); .set-sensitive(False); } with my Button $button1 .= new-with-label('Hello World') { .register-signal( $sh, 'b1-press', 'clicked', :$button2); } ``` Next, the buttons are placed in a grid. The grid gets a wide empty area around the buttons. ``` with my Grid $grid .= new-grid { .set-margin-top(30); .set-margin-bottom(30); .set-margin-start(30); .set-margin-end(30); .attach( $button1, 0, 0, 1, 1); .attach( $button2, 0, 1, 1, 1); } ``` Finally the grid is placed in a window. It gets a title in the decoration of the window and the button action in the decoration to stop the application will be processed by `stopit()`. ``` with my Window $window .= new-window { .register-signal( $sh, 'stopit', 'close-request'); .set-title('Hello GTK!'); .set-child($grid); .show; } ``` ### Starting the application To get everything visible and responsive we need to start the event loop. The call to `$main-loop.quit();` in two of the methods in the **SH** class will cause the program to return from this call. ``` $main-loop.run; ``` # Documentation * [🔗 Website](https://martimm.github.io/) * [🔗 License document](http://www.perlfoundation.org/artistic_license_2_0) * [🔗 Release notes](https://github.com/MARTIMM/gnome-native/blob/master/CHANGES.md) * [🔗 Issues](https://github.com/MARTIMM/gnome-source-skim-tool/issues) # Installation Use the following command to install `Gnome::Gtk4:api<2>` and all its dependencies. ``` 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 root](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_zef-melezhik-Sparrow6.md # Sparrow ![SparkyCI](https://sparky.sparrowhub.io/badge/gh-melezhik-Sparrow6?foo=bar) [Discord chat](https://discord.gg/ZMXSMFTK) Sparrow is a Raku based automation framework. It's written on Raku and has Raku API. Who might want to use Sparrow? People dealing with daily tasks varying from servers software installations/configurations to cloud resources creation. Sparrow could be thought as an alternative to existing configuration management and provisioning tools like Ansible or Chef, however Sparrow is much broader and not limited to configuration management only. It could be seen as a generic automation framework enabling an end user quick and effective script development easing some typical challenges along the road - such as scripts configurations, code reuse and testing. # Sparrow Essential Features * Sparrow is a language friendly framework. A user write underlying code on a language of their choice (see supported languages), and Sparrow glues all the code using Raku API within high level Sparrow scenarios. * Sparrow has a command line API. A user can run scripts using command line API, at this point to *use* Sparrow one does not need to know any programming language at all. * Sparrow is a script oriented framework. Basic low level building blocks in Sparrow are old good scripts. That makes Sparrow extremely effective when working with existing codebase written on many well known languages. * Sparrow is a function oriented framework. Though users write underlying code as scripts, those scripts are called as Raku functions within high level scenarios. * Sparrow has a repository of ready to use scripts or Sparrow plugins as they called in Sparrow. No need to code at all, just find a proper plugin and start using it. Sparrow repository could be easily deployed as public or private instances using just an Nginx web server. # Install ``` zef install Sparrow6 ``` # Supported languages You can write underlying Sparrow tasks using following languages: * Raku * Perl5 * Ruby * Python * Bash * Powershell * [Golang](https://github.com/melezhik/sparrowgo) All the languages have a *unified* Sparrow API easing script development, see Sparrow development guide. # Documentation ## Sparrow Development Guide Check out [documentation/development](https://github.com/melezhik/Sparrow6/blob/master/documentation/development.md) guide on how to develop Sparrow tasks using Sparrow compatible languages. ## Raku API Sparrow Raku API allows to run Sparrow tasks as Raku functions. One can use `task-run` function to run arbitrary Sparrow plugins or tasks. Or choose Sparrow DSL to call a subset of Raku functions designed for most popular automation tasks. ### Task Run Sparrow provides Raku API to run Sparrow tasks as functions: ``` task-run "run my build", "vsts-build", %( definition => "JavaApp" ); ``` Read more about Sparrow task runner at [documentation/taskrunner](https://github.com/melezhik/Sparrow6/blob/master/documentation/taskrunner.md). ### Sparrow DSL Sparrow DSL allows one to run Sparrow tasks using even better Raku functions shortcuts. In comparison with `task-run` function, DSL provides input parameters validation and dedicated function names. DSL is limited to a certain subset of Sparrow plugins: ``` #!raku package-install "nginx"; service-restart "nginx"; bash "echo Hello World"; ``` See a full list of DSL functions here - [documentation/dsl](https://github.com/melezhik/Sparrow6/blob/master/documentation/dsl.md). ## Plugins Sparrow plugins are distributable scripts written on Sparrow compatible languages. One could run plugins as Raku functions using Raku API or as command line utilities. Check out [documentation/plugins](https://github.com/melezhik/Sparrow6/blob/master/documentation/plugins.md) for details. ## Repositories Sparrow repositories store distributable Sparrow tasks packaged as plugins. See [documentation/repository](https://github.com/melezhik/Sparrow6/blob/master/documentation/repository.md). ### Cli API Sparrow provides a handy command line interface to run Sparrow tasks as command line. Enter `s6` - Sparrow command line client and plugin manager. You use `s6` to install, configure and run tasks as well as uploading tasks to repositories. Check [documentation/s6](https://github.com/melezhik/Sparrow6/blob/master/documentation/s6.md) for details. ### Sparrow modules Sparrow modules allow to write portable Sparrow scenarios distributed as Raku modules, read more about it in [documentation/modules](https://github.com/melezhik/Sparrow6/blob/master/documentation/modules.md). ## Testing API Sparrow provides it's way to write tests for tasks, making it is easy not only create scripts, but write tests for your script codebase. ### Task checks Task checks is regexp based DSL to verify structured and unstructured text. It allows to write *embedded* tests for user scripts verifying scripts output. With task checks it's easy to develop scripts in TDD way or create black box testing test suites. See, for example, Tomty framework. Read more about task checks at [documentation/taskchecks](https://github.com/melezhik/Sparrow6/blob/master/documentation/taskchecks.md). ### M10 METEN - is a Minimalist Embedded Testing Engine. You can "embed" test into task source code and conditionally run them. The method is not of much use in favor of task checks approach. Check out [documentation/m10](https://github.com/melezhik/Sparrow6/blob/master/documentation/m10.md) for details. ## Environment variables Sparrow is configurable though some environment variables. Check out [documentation/envvars](https://github.com/melezhik/Sparrow6/blob/master/documentation/envvars.md) documentation. # Sparrow eco system Sparrow eco system encompasses various tools and subsystems. Choose the one you need. All the tools are powered by Sparrow engine. ## Sparrowdo Sparrow based configuration management tool. Visit [Sparrowdo](https://github.com/melezhik/sparrowdo) GH project for details. ## Tomtit Task runner and workflow management tool. Visit [Tomtit](https://github.com/melezhik/tomtit) GH project for details. ## Tomty Tomty is a Sparrow based test framework. Visit [Tomty](https://github.com/melezhik/tomty) GH project for details. ## Sparky Run Sparrow tasks in asynchronously and remotely. Visit [Sparky](https://github.com/melezhik/sparky) GH project for details. # Internal APIs This section contains links to some internal APIs, which are mostly of interest for Sparrow developers: * Sparrow6::Task::Repository API - [documentation/internal/repo-and-plugins-api](https://github.com/melezhik/Sparrow6/blob/master/documentation/internal/repo-and-plugins-api.md) # Roadmap Sparrow is not yet (fully) implemented, see [Roadmap](https://github.com/melezhik/Sparrow6/blob/master/Roadmap.md) to check a status. # Examples See `.tomty/` folder. # Author Alexey Melezhik # Thanks to God Who inspires me in my life!
## does.md does Combined from primary sources listed below. # [In Type system](#___top "go to top of document")[§](#(Type_system)_trait_does "direct link") See primary documentation [in context](/language/typesystem#trait_does) for **trait does**. The trait `does` can be applied to roles and classes providing compile time mixins. To refer to a role that is not defined yet, use a forward declaration. The type name of the class with mixed in roles does not reflect the mixin, a type check does. If methods are provided in more than one mixed in role, the method that is defined first takes precedence. A list of roles separated by comma can be provided. In this case conflicts will be reported at compile time. ```raku role R2 {...}; role R1 does R2 {}; role R2 {}; class C does R1 {}; say [C ~~ R1, C ~~ R2]; # OUTPUT: «[True True]␤» ``` For runtime mixins see [but](/language/operators#infix_but) and [does](/language/operators#infix_does). # [In Mu](#___top "go to top of document")[§](#(Mu)_routine_does "direct link") See primary documentation [in context](/type/Mu#routine_does) for **routine does**. ```raku method does(Mu $type --> Bool:D) ``` Returns `True` if and only if the invocant conforms to type `$type`. ```raku my $d = Date.new('2016-06-03'); say $d.does(Dateish); # OUTPUT: «True␤» (Date does role Dateish) say $d.does(Any); # OUTPUT: «True␤» (Date is a subclass of Any) say $d.does(DateTime); # OUTPUT: «False␤» (Date is not a subclass of DateTime) ``` Unlike [`isa`](/routine/isa#(Mu)_routine_isa), which returns `True` only for superclasses, `does` includes both superclasses and roles. ```raku say $d.isa(Dateish); # OUTPUT: «False␤» ``` Using the smartmatch operator [~~](/routine/~~) is a more idiomatic alternative. ```raku my $d = Date.new('2016-06-03'); say $d ~~ Dateish; # OUTPUT: «True␤» say $d ~~ Any; # OUTPUT: «True␤» say $d ~~ DateTime; # OUTPUT: «False␤» ``` # [In Operators](#___top "go to top of document")[§](#(Operators)_infix_does "direct link") See primary documentation [in context](/language/operators#infix_does) for **infix does**. ```raku sub infix:<does>(Mu $obj, Mu $role) is assoc<non> ``` Mixes `$role` into `$obj` at runtime. Requires `$obj` to be mutable. Similar to [but](/routine/but) operator, if `$role` supplies exactly one attribute, an initializer can be passed in parentheses. Similar to [but](/routine/but) operator, the `$role` can instead be an instantiated object, in which case, the operator will create a role for you automatically. The role will contain a single method named the same as `$obj.^name` and that returns `$obj`: ```raku my $o = class { method Str { "original" } }.new; put $o; # OUTPUT: «original␤» $o does "modded"; put $o; # OUTPUT: «modded␤» ``` If methods of the same name are present already, the last mixed in role takes precedence.
## dist_zef-coke-App-Zef-Deps.md # Overview `zef-deps` is a script to report on module dependencies for raku. Given a list of package names on the command line, generate a listing of all dependencies, direct and indirect. # Usage ``` % zef-deps App::Cal App::Cal Terminal::ANSIColor Test::Differences Data::Dump Text::Diff Algorithm::Diff Test Test Text::Tabs ``` The indent level shows the nesting of dependencies. So in this example, `App::Cal` depends on `Test::Differences`, which in turn depends on `Data::Dump`. Both `Algorithm::Diff` and `Text::Diff` depend on `Test`. Multiple packages can be specified on the command line. If a single name of `.` is specified, `zef-deps` will instead read the local `META6.json` and use the `depends` attribute as the list of packages. In the default textual output, repeated dependencies anywhere in the hierarchy are replaced with `...`. # Options `--json` generates JSON output for the dependencies. `--png` generates a `png` file showing dependencies using `dot`. To use this option, you must install the optional module `Uxmal`. When run with this option, a file is generated in a temp directory and the path to the file is printed as the only non-debug output. # Environment variables ## ZEF\_DEPS\_INDENT Indenting defaults to 4 spaces but can be overridden by setting this environment variable to the number of desired spaces.
## dist_zef-raku-community-modules-Math-Symbolic.md [![Actions Status](https://github.com/raku-community-modules/Math-Symbolic/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Math-Symbolic/actions) [![Actions Status](https://github.com/raku-community-modules/Math-Symbolic/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Math-Symbolic/actions) [![Actions Status](https://github.com/raku-community-modules/Math-Symbolic/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Math-Symbolic/actions) # NAME Math::Symbolic - Symbolic math for Raku # SYNOPSIS Either of ``` symbolic --m=1 --b=0 'y=m*x+b' x ``` on the command line, or ``` say Math::Symbolic.new("y=m*x+b").isolate("x").evaluate(:m(1), :b(0)); ``` in Raku code, will print ``` x=y ``` # DESCRIPTION This is a Raku symbolic math module. It parses, manipulates, evaluates, and outputs mathematical expressions and relations. This module is PRE-ALPHA quality. # USAGE ## Command line A basic command line program named 'symbolic' is provided. It takes at least one positional argument: the relation or expression to work with. If a second positional is passed, it is the name of the variable to isolate in the given relation (non-relation expressions are unsupported for isolation). If "0" is passed instead of a variable name, the relation is arranged with 0 on the right side and terms grouped by variable (when possible) on the left side. If any named args are passed, they are substituted into the expression for the variables they name. Each named argument's value is parsed as an expression itself, so it doesn't just have to be a numeric value to give the variable. The resulting expression will be printed after applying all requested transformations, and attempting to simplify. ## API At the time of this writing, most of the API is too unstable to document yet. To minimize exposure to the internal chaos and to provide a starting point for thinking about what functionality needs to exist in a more formal future API, a minimal temporary public interface is implemented as a small collection of simple methods in the main `Math::Symbolic` class. Note that where the actual signatures differ from what is documented here, the undocumented differences are considered "private", and may not do what is expected. # METHODS ## .new(Str:D $expression) Creates a new `Math::Symbolic` object, initialized with the tree resulting from a parse of $expression (which may also be a relation; currently only "=" equality is supported for relations). ## .clone() Returns a clone of the object with an independent copy of the tree structure. This is important because all manipulations (below) are done in place, and cloning avoids the parsing overhead of .new(). ## .isolate(Str:D $var) Arranges a relation with $var on the left and everything else on the right. Or attempts to. It supports simple operation inversion when only one instance of a variable exists, as well as attempting to combine instances via distributive property and/or factoring of polynomial expressions, if necessary. Calling `.isolate` on a non-relation expression is not supported. ## .evaluate(\*%values) Replaces all instances of variables named by the keys of the hash, with the expressions in the values of the hash, and simplifies the result as much as possible (see `.simplify`). If the resulting expression has no variables, this means it can be fully evaluated down to a single value. Note that fully evaluating an equation with valid values would result in something mostly unhelpful like "0=0" if the simplifier is smart enough. Though in the future, when such a relation can be evaluated for truth, that will become useful. ## .simplify() Makes a childish attempt to reduce the complexity of the expression by evaluating operations on constants, removing operations on identity values (and eventually other special cases like 0, inverse identity, etc). Also already does a very small number of rearrangements of combinations of operations, like transforming a+-b into a-b. `.simplify` is sometimes called after certain manipulations like `.isolate` and `.poly` which might otherwise leave messy expressions e.g. operations with identity values and awkward forms of negation and inversion. It is also called at the end of the command line tool for output of the final result. ## .poly(Str $var?) Attempts to arrange the equation/expression in polynomial form. If $var is given, terms are grouped for that specific variable. Otherwise terms are grouped separately according to the set of all variables in a term. For example "x²+x²\*y" will be unchanged by `.poly()`, but `.poly('x')` will rearrange it to something like "x²\*(1+y)". Unlike the formal definition of a polynomial, this function may accept and return any expression for coefficients, and allows for exponents of any constant value. If `.poly` is called on a relation, it is first arranged so that the right side is equal to zero, before grouping terms on the left. An attempt is made to guess which side should be subtracted from the other to avoid ending up with an excessive amount of negation. ## .expression(Str:D $var) Creates a new `Math::Symbolic` object from the expression on the right-hand side of a relation after isolating $var on the left. Note that unlike the above transformations, no changes are made to the original object. ## .compile($positional = False, $defaults?) Returns a Raku subroutine which is mathematically equivalent to the `Math::Symbolic` expression. Not all operations are currently supported. Compiling relations is also undefined behavior at this time. All arguments are named by default. If $positional is True, all arguments are positional instead, sorted in default Raku sort order. If $positional is itself a Positional class then only the listed variables will be taken positionally, in the specified order. All arguments are also required by default. If $defaults is an Associative object, it is taken as a map of variable names to default values, and the listed variables will be optional. If $defaults is any other defined value, that value is taken as the default for all arguments. ## .routine($positional = False, $defaults?) Identical to `.compile (above)`, but returns the code as a string without compiling via `EVAL`, for instance to embed the code into another module or script. ## .count() Returns the number of nodes in the expression's tree. This could be useful to determine if an expression has been fully evaluated, or used as a crude complexity metric. ## .dump\_tree() Prints out the tree structure of the expression. This really should return the string instead, and perhaps be renamed. ## .Str() Returns the expression re-assembled into a string by the same syntactic constructs which govern parsing. As with all Raku objects, this is also the method which gets called when the object is coerced to a string by other means, e.g. interpolation, context, or the ~ prefix. The `.gist` method is also handled by this routine, for easy printing of a readable result. Passing the result of `.Str` back in to `.new` should always yield a mathematically equivalent structure (exact representation may vary by some auto-simplification), giving the same type of round-trip characteristics to expressions that `.raku` and `EVAL()` provide for Raku objects. This allows a user to, for instance, isolate a variable in an equation, then plug the result in to `.evaluate` for that variable in a different equation, all with the simplicity of strings; no additional classes or APIs for the user to worry about (albeit at a steep performance penalty). ## .Numeric() Returns the expression coerced first to a string (see above), then to a number. This will fail if the expression hasn't already been evaluated or simplified (see further above) to a single constant value. As with all Raku objects, this is also the method which gets called when the object is coerced to a number by other means, e.g. context or the + prefix. # SYNTAX AND OPERATIONS All whitespace is optional. Implicit operations, e.g. multiplication by putting two variables in a row with no infix operator, are not supported, and likely never will be. It leads to far too many consequences, compromises, complexities and non-determinisms. The available operations and syntax in order of precedence are currently: ``` * Terms * Variables * valid characters for variable names are alphanumerics and underscore * first character must not be a number, mainly to avoid collisions with E notation (see below) * Values * optional sign (only "-" for now) * E notation supported * case insensitive * no restriction on value of exponent, with sign and decimal * subexpressions not supported (e is numeric syntax, not an op) * leading zeros before decimals not required * imaginary, complex, quaternion, etc NYI * vector, matrix, set, etc NYI * Circumfix * () Grouping Parens * || Absolute Value * cannot invert this op for solving/manipulating, ± NYI * Postfix * ! Factorial * syntax only, no functional implementation * ² Square (same as ^ 2) * Prefix * - Negate (same as * -1) * √ Square Root (same as ^ .5) * Infix Operation * Power * ^ Exponentiation, like raku's ** * mathematical convention dictates that this operation be chained right-to-left, which is NYI * √ Root, n√x is the same as x^(1/n) * evaluates to positive only (± NYI) * imaginary numbers NYI * ^/ is a Texan variant of √ with the operands reversed * x^/n is the same as x^(1/n) or n√x * Logarithms are NYI, so no solving for variables in exponents yet * Scale * * Multiplication * / Division * Shift * + Addition * - Subtraction * Infix Relation * = Equality is currently the only relation supported * this is really because proper relations are more-or-less NYI * note that relations are optional in the input string, it automatically detects whether it is working with an expression or a relation * really it just breaks if you call 'solve' on an expression ATM ``` ## BUGS Many, in all likelihood. Patches graciously accepted. # AUTHOR raydiak # COPYRIGHT AND LICENSE Copyright 2014 - 2021 raydiak Copyright 2025 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-tbrowder-Abbreviations.md [![Actions Status](https://github.com/tbrowder/Abbreviations/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/Abbreviations/actions) [![Actions Status](https://github.com/tbrowder/Abbreviations/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/Abbreviations/actions) [![Actions Status](https://github.com/tbrowder/Abbreviations/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/Abbreviations/actions) # NAME Abbreviations - Provides abbreviations for an input set of one or more words # SYNOPSIS ``` use Abbreviations; my $words = 'A ab Abcde'; # The main exported routine: my %abbrevs = abbreviations $words; say %abbrevs.gist; # OUTPUT: «{A => A, Abcde => Ab, ab => a}␤» ``` # DESCRIPTION **Abbreviations** is a module with one automatically exported subroutine, `abbreviations`, which takes as input a set of words and returns the original set with added unique abbreviations for the set. (Note the input words are also abbreviations in the context of this module.) Its signature: ``` sub abbreviations($word-set, #= Str, List, or Hash (Set) :$out-type = HA, #= the default, HashAbbrev :$lower-case, #= convert the word st to lowercase :$min-length, #= minimum abbreviation length ) is export {...} ``` A *word* satisfies the Raku regex `$word ~~ /\S+/` which is quite loose. Using programs can of course further restrict that if need be. For example, for use with module **Opt::Handler** words must satisfy this regex: `$word ~~ /<ident>/`. ## A regex alternation for single-word sets A natural consequence of generating all the abbreviations for a set of one word is this: the output provides a regex alternation which matches any partial length of the target word. For example, given a target word 'Args': ``` use Abbreviations; use Test; my $target = "Args"; my $regex = abbrev $target; # OUTPUT: «"A|Ar|Arg|Args"␤»; my $res = False; my @w = $regex.split('|'); for @w { when /<$regex>/ { $res = True } default { $res = False } } is $res, True; # OUTPUT: «ok 1␤» ``` As shown in the example above, limiting the input set to one word results in the output of a regex alternation string. The rest of this description applies to sets of two or more words. ## Abbrevians for multiple-word sets The input multiple-word set can be in one of three forms: (1) a list (recommended), (2) a string containing the words separated by spaces, or (3) as a hash (or set) with the words being keys of the hash (set members). Duplicate words will be automatically and quietly eliminated. Note the input word set will not be modified unless the `:lower-case` option is used. In that case, all characters will be transformed to lower-case and any new duplicate words deleted. If the user wishes, he or she can restrict the minimum length of the generated abbreviations by using the `:$min-length` parameter. One will normally get the result as a hash with the input words as keys with their shortest abbreviation as values (return type HA), but the return type can be specified via `enum Out-type` if desired by selecting one of the `:$output-type` options. For example: ``` my %abbrevs = abbrevs @words, :output-type(AH); ``` There are two shorter alias names for `sub abbreviations` one can use that are always exported: ``` abbrevs abbrev ``` In the sprit of the module, one can `use Abbreviations :ALL;` and have these additional shorter alias names available: ``` abbre abbr abb ab a ``` Each of those is individually available by adding its name as an adverb, for example: ``` use Abbreviations :abb; my %abb = abb $words; ``` ### `enum Out-type` ``` enum Out-type is export <HA H AH AL L S >; ``` The *enum* `Out-type` is exported automatically as it is required for using `sub abbreviations`. It has the following types: * `HA` (HashAbbrev) The default *HashAbbrev* (`HA`) returned will have input words as keys whose value will be the shortest valid abbreviation. * `H` (Hash) A variant of `HA`, the *Hash* (`H`) returned will have input words as keys whose value will be a sorted list of its valid abbreviations (sorted by length, shortest first, then by `Str` order). * `AH` (AbbrevHash) An *AbbrevHash* (`AH`) is keyed by all of the valid abbreviations for the input word list and whose values are the word from which that abbreviation is defined. * `AL` (AbbrevList) An *AbbrevList* (`AL`) is special in that the returned list is the one, shortest abbreviation for each of the input words in input order. For example, ``` my @w = <Monday Tuesday Wednesday Thursday Friday Saturday Sunday>; my @abb = abbrevs @w, :output-type(AL); say @abb; # OUTPUT: «M Tu W Th F Sa Su␤» ``` Note that a hash (or set) input type will not reliably provide this output as expected since the keys are not stored in order. Instead, the ouput will be based on a list of the hash's keys. In effect, entering `%out = abbreviations %in` is the same as: ``` my @inputlist = %in.keys.sort({.chars, .Str}'; my %out = abbreviations @inputlist; ``` * `L` (List) A *List* (`L`) contains all of the valid abbreviations for the input word list, including the words themselves, sorted by length, then character order. * `S` (String) A *String* (`S`) is the string formed by joining the *List* by a single space between words. ### Improved abbreviation search The abbreviation algorithm has been improved from the original (as found on <https://rosettacode.org>) in the following way: The input word set is formed into subgroups comprised of each input word. Abbreviations are created for each word, abbreviations shared by two or words are eliminated, then all those abbreviations are combined into one set. The result will be the largest possible set of unique abbreviations for a given input word set. For example, given an input set consisting of the words `A ab Abcde`, the default output hash of abbreviations (with the original words as keys) contains a total of seven abbreviations: ``` A => ['A'], ab => ['a', 'ab'], Abcde => ['Ab', 'Abc', 'Abcd', 'Abcde'], ``` If the `:lower-case` option is used, we get a slightly different result since we have fewer unique abbreviations from the lower-cased words. The new hash has only five abbreviations: ``` my $words = 'A ab Abcde': my %abbr = abbrevs $words, :lower-case; ``` The result is ``` a => ['a'], ab => ['ab], abcde => ['abc', 'abcd', 'abcde'], ``` Notice the input word **ab** now has only one abbreviation and **abcde** has only three. ## Other exported symbols ### `sub sort-list` ``` sub sort-list(@list, :$type = SL, :$reverse --> List) is export(:sort) {...} ``` By default, this routine sorts all lists by word length, then by Str order. The order by length is by the shortest abbreviation first unless the `:$reverse` option is used. This is the routine used for all the output types produced by this module *except* the *AbbrevList* (`AL`) which keeps the original word set order. The routine's output can be modified for other uses by entering the `:$type` parameter to choose another of the s. ### `enum Sort-type` ``` enum Sort-type is export(:sort) < SL LS SS LL N>; ``` The `Sort-type`s are: * SL - order by Str, then order by Length * LS - order by Length, then order by Str * SS - Str order only * LL - Length order only * N - Numerical order only (falls back to SS if any words are not numbers) # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # CREDITS * Leon Timmermans (aka @Leont) for inspiration from his Raku module `Getopt::Long`. * @thundergnat, the original author of the Raku `auto-abbreviate` algorithm on [Rosetta Code](http://rosettacode.org/wiki/Abbreviations,_automatic#Raku). * The Raku community for help with subroutine signatures. # COPYRIGHT and LICENSE Copyright © 2020-2023 Tom Browder This library is free software; you may redistribute or modify it under the Artistic License 2.0.
## vm.md class VM Raku Virtual Machine related information ```raku class VM does Systemic { } ``` Built-in class for providing information about the virtual machine in which Raku is running. Usually accessed through the [$\*VM](/language/variables#index-entry-%24*VM) dynamic variable. # [Methods](#class_VM "go to top of document")[§](#Methods "direct link") ## [method osname](#class_VM "go to top of document")[§](#method_osname "direct link") ```raku multi method osname(VM:U:) multi method osname(VM:D:) ``` Instance / Class method returning the name of the Operating System, as known by the configuration of the VM object / currently running virtual machine. ## [method precomp-ext](#class_VM "go to top of document")[§](#method_precomp-ext "direct link") Instance method returning a string of the extension that should be used for precompiled files of the VM object. ## [method precomp-target](#class_VM "go to top of document")[§](#method_precomp-target "direct link") Instance method returning a string of the value of the compilation target that should be used when precompiling source-files with the VM object. ## [method prefix](#class_VM "go to top of document")[§](#method_prefix "direct link") Instance method returning a string of the path in which the virtual machine of the VM object is installed. ## [method request-garbage-collection](#class_VM "go to top of document")[§](#method_request-garbage-collection "direct link") Available as of the 2020.05 release of the Rakudo compiler. Class method that tells the virtual machine on which Raku is running, to perform a garbage collect run when possible. Issues a warning if such a request is not supported by the virtual machine. Provides no guarantee that the process will actually use less memory after a garbage collect. In fact, calling this method repeatedly, may actually cause more memory to be used due to memory fragmentation. Mainly intended as a debugging aid for module / core developers. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `VM` raku-type-graph VM VM Any Any VM->Any Systemic Systemic VM->Systemic Mu Mu Any->Mu [Expand chart above](/assets/typegraphs/VM.svg)
## dist_zef-raku-community-modules-Benchmark.md [![Actions Status](https://github.com/raku-community-modules/Benchmark/workflows/test/badge.svg)](https://github.com/raku-community-modules/Benchmark/actions) # NAME Benchmark - Simple benchmarking # SYNOPSIS ``` use Benchmark; my ($start, $end, $diff, $avg) = timethis(1000, "code"); my @stats = timethis(1000, sub { #`( code ) }); say @stats; my %results = timethese 1000, { "foo" => sub { ... }, "bar" => sub { ... }, }; say ~%results; ``` # DESCRIPTION A simple benchmarking module with an interface similar to Perl's `Benchmark.pm`. However, rather than output results to `$*OUT`, the results are merely returned so that you can output them however you please. You can also have some basic statistics: ``` use Benchmark; %result = timethis(10, { sleep rand }, :statistics); say %result; say "$_ : %result{$_}" for <min median mean max sd>; my %results = timethese 5, { "foo" => { sleep rand }, "bar" => { sleep rand }, }, :statistics; say ~%results; ``` # AUTHOR Jonathan Scott Duff # COPYRIGHT AND LICENSE Copyright 2009 - 2016 Jonathan Scott Duff Copyright 2017 - 2023 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-JNTHN-Cro-WebSocket.md # Cro::WebSocket Build Status This is part of the Cro libraries for implementing services and distributed systems in Raku. See the [Cro website](http://cro.services/) for further information and documentation.
## dist_zef-l10n-L10N-IT.md # NAME L10N::IT - Italian localization of Raku # SYNOPSIS ``` use L10N::IT; dillo "Hello World"; ``` # DESCRIPTION L10N::IT contains the logic to provide a Italian localization of the Raku Programming Language. # AUTHORS JJ Merelo # 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.
## gather-take.md gather take Combined from primary sources listed below. # [In Control flow](#___top "go to top of document")[§](#(Control_flow)_gather_take_gather_take "direct link") See primary documentation [in context](/language/control#gather/take) for **gather/take**. `gather` is a statement or block prefix that returns a [sequence](/type/Seq) of values. The values come from calls to [take](/type/Mu#routine_take) in the dynamic scope of the `gather` code. In the following example, we implement a subroutine to compute the factors of an integer with `gather` (note that the factors are not generated in order): ```raku sub factors( Int:D \n ) { my $k = 1; gather { while $k**2 < n { if n %% $k { take $k; take n div $k; } $k++; } take $k if $k**2 == n; } } say factors(36); # OUTPUT: «1, 36, 2, 18, 3, 12, 4, 9, 6␤» ``` The `gather/take` combination can generate values lazily, depending on context. Binding to a scalar or sigilless container will force laziness. If you want to force lazy evaluation use the [lazy](/type/Iterable#method_lazy) subroutine or method. For example: ```raku my @vals = lazy gather { take 1; say "Produced a value"; take 2; } say @vals[0]; say 'between consumption of two values'; say @vals[1]; # OUTPUT: # 1 # between consumption of two values # Produced a value # 2 ``` `gather/take` is scoped dynamically, so you can call `take` from subs or methods that are called from within `gather`: ```raku sub weird(@elems, :$direction = 'forward') { my %direction = ( forward => sub { take $_ for @elems }, backward => sub { take $_ for @elems.reverse }, random => sub { take $_ for @elems.pick(*) }, ); return gather %direction{$direction}(); } say weird(<a b c>, :direction<backward> ); # OUTPUT: «(c b a)␤» ``` If values need to be mutable on the caller side, use [take-rw](/type/Mu#routine_take-rw). Note that the [`Seq`](/type/Seq) created by `gather/take` may be coerced to another type. An example with assignment to a hash: ```raku my %h = gather { take "foo" => 1; take "bar" => 2}; say %h; # OUTPUT: «{bar => 2, foo => 1}␤» ``` **Note**: `gather/take` must not be used to collect results from `react/whenever`. The `whenever` block is not run from the thread that runs the `gather/react`, but the thread that runs the `emit`. On this thread, there is no handler for the control exception thrown by `take`, causing it to error out.
## is.md is Combined from primary sources listed below. # [In module Test](#___top "go to top of document")[§](#(module_Test)_sub_is "direct link") See primary documentation [in context](/type/Test#sub_is) for **sub is**. ```raku multi is(Mu $got, Mu:U $expected, $desc = '') multi is(Mu $got, Mu:D $expected, $desc = '') ``` Marks a test as passed if `$got` and `$expected` compare positively with the [`eq` operator](/routine/eq), unless `$expected` is a type object, in which case [`===` operator](/routine/===) will be used instead; accepts an optional description of the test as the last argument. **NOTE:** the `eq` operator stringifies its operands, which means `is()` is not a good function for testing more complex things, such as lists: `is (1, (2, (3,))), [1, 2, 3]` passes the test, even though the operands are vastly different. For those cases, use [`is-deeply` routine](#sub_is-deeply) ```raku my $pdf-document; sub factorial($x) { ... }; ...; is $pdf-document.author, "Joe", 'Retrieving the author field'; is factorial(6), 720, 'Factorial - small integer'; my Int $a; is $a, Int, 'The variable $a is an unassigned Int'; ``` **Note:** if *only* whitespace differs between the values, `is()` will output failure message differently, to show the whitespace in each values. For example, in the output below, the second test shows the literal `\t` in the `got:` line: ```raku is "foo\tbar", "foo\tbaz"; # expected: 'foo baz'␤# got: 'foo bar' is "foo\tbar", "foo bar"; # expected: "foo bar"␤# got: "foo\tbar" ``` # [In Traits](#___top "go to top of document")[§](#(Traits)_trait_is "direct link") See primary documentation [in context](/language/traits#The_is_trait) for **The is trait**. ```raku proto trait_mod:<is>(Mu $, |) {*} ``` `is` applies to any kind of scalar object, and can take any number of named or positional arguments. It is the most commonly used trait, and takes the following forms, depending on the type of the first argument.
## dist_zef-Altai-man-Slang-Kazu.md [![Build Status](https://travis-ci.org/Altai-man/Slang-Kazu.svg?branch=master)](https://travis-ci.org/Altai-man/Slang-Kazu) # NAME Slang::Kazu - Japanese numerals in your Perl 6 # SYNOPSIS ``` use Slang::Kazu; say "3542" ~~ 三千五百四十二; # True say '一' ~~ /<single-kazu>/; # Will match any digit from 1 to 9 ``` # DESCRIPTION Slang::Kazu is a Perl 6 slang that allows you to use a subset of native Japanese numerals in your Perl 6 code because you can. You can use numbers from 1 to 99999. Counters are yet to be implemented. Mostly this is a clone of [drforr's](http://github.com/drforr) `Slang::Roman`, but for Japanese numerals - all thanks to him for the idea and the implementation. Currently, incorrect numbers like `二二` are evaluated to `Nil` and you will see some scary errors because of that, so don't lose your kanji! This project is just a joke and doesn't intented to be used in any serious codebases! You are warned. # AUTHOR Altai-man on Github, you can cast sena\_kun on freenode too. # COPYRIGHT AND LICENSE Copyright © License GPLv3: The GNU General Public License, Version 3, 29 June 2007 <https://www.gnu.org/licenses/gpl-3.0.txt> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.
## dist_github-grondilu-EC.md ![Sparky](https://sparky.sparrowhub.io/badge/grondilu-elliptic-curves-raku?foo=bar) # Elliptic Curves Cryptography in raku secp256k1 and ed25519 in [raku](http://raku.org) ## Synopsis ``` { use secp256k1; say G; say $_*G for 1..10; use Test; is 35*G + 5*G, 40*G; } { use ed25519; # create a key # - randomly : my ed25519::Key $key .= new; # - from a seed : my blob8 $secret-seed .= new: ^256 .roll: 32; my ed25519::Key $key .= new: $secret-seed; # use key to sign a message my $signature = $key.sign: "Hello world!"; # verify signature use Test; lives-ok { ed25519::verify "foo", $key.sign("foo"), $key.point }; dies-ok { ed25519::verify "foo", $key.sign("bar"), $key.point }; } ``` ## References * [RFC 8032](http://www.rfc-editor.org/info/rfc8032) * Jacobian coordinates: * [WikiBooks entry](https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates) * [hyperelliptic.org page](http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html) * Chalkias, Konstantinos, et. al. ["Taming the many EdDSAs."](https://eprint.iacr.org/2020/1244.pdf) *Security Standardisation Research Conference*, Dec. 2020
## dist_zef-jonathanstowe-Lumberjack-Dispatcher-Syslog.md # Lumberjack::Dispatcher::Syslog A Syslog dispatcher for the Lumberjack logger ![Build Status](https://github.com/jonathanstowe/Lumberjack-Dispatcher-Syslog/workflows/CI/badge.svg) ## Synopsis ``` use Lumberjack; use Lumberjack::Dispatcher::Syslog; # Add the syslog dispatcher Lumberjack.dispatchers.append: Lumberjack::Dispatcher::Syslog.new; class MyClass does Lumberjack::Logger { method start() { self.log-info("Starting ..."); ... } method do-stuff() { self.log-debug("Doing stuff ..."); ... if $something-went-wrong { self.log-error("Something went wrong"); } } method stop() { ... self.log-info("Stopped."); } } MyClass.log-level = Lumberjack::Debug; ``` ## Description This provides a dispatcher for [Lumberjack](https://github.com/jonathanstowe/Lumberjack) which allows you to log to your system's `syslog` facility, this may log to various log files in, for instance, `/var/log` depending on the configuration of the syslog daemon. Because the actual logging daemon being used may differ from system to system (there is syslog-ng, rsyslog, syslog "classic" etc,) you will need to refer to the local documentation or a system administrator to determine the actual logging behaviour. Some systems may for instance just drop "debug" or "trace" messages in the default configuration (or put them in separate files.) ## Installation Assuming you have got a working installation of Rakudo you should be able to install this with *zef*: ``` zef install Lumberjack::Dispatcher::Syslog ``` Or if you have a local clone of the code: ``` zef install . ``` ## Support This in itself is very simple, it is likely that the configuration of the syslog itself is more of a challenge and you should refer to the configuration or documentation of the local syslog installation in the first instance if things aren't being logged as you expect. You may also want to check the documentation for Lumberjack itself as well as Log::Syslog::Native which this uses to send the messages. If you have any problems or suggestions for the module itself then please feel free to post at <https://github.com/jonathanstowe/Lumberjack-Dispatcher-Syslog/issues> ## Licence and copyright This is free software. Please see the <LICENCE> file in the repository. © Jonathan Stowe, 2016 - 2021
## dist_zef-jonathanstowe-EventSource-Server.md # EventSource::Server A simple handler to provide Server Sent Events from Raku applications ![Build Status](https://github.com/jonathanstowe/EventSource-Server/workflows/CI/badge.svg) ## Synopsis This sends out an event with the DateTime string every second ``` use EventSource::Server; use HTTP::Server::Tiny; my $supply = Supply.interval(1).map( { EventSource::Server::Event.new(type => 'tick', data => DateTime.now.Str) } ); my &es = EventSource::Server.new(:$supply); HTTP::Server::Tiny.new(port => 7798).run(&es) ``` Or using Cro: ``` use EventSource::Server; use Cro::HTTP::Router; use Cro::HTTP::Server; my $supply = Supply.interval(1).map( { EventSource::Server::Event.new(type => 'tick', data => DateTime.now.Str) } ); my $es = EventSource::Server.new(:$supply); my $app = route { get -> { content 'text/event-stream', $es.out-supply; } }; my Cro::Service $tick = Cro::HTTP::Server.new(:host<localhost>, :port<7798>, application => $app); $tick.start; react whenever signal(SIGINT) { $tick.stop; exit; } ``` And in some Javascript program somewhere else: ``` var EventSource = require('eventsource'); var v = new EventSource(' http://127.0.0.1:7798'); v.addEventListener("tick", function(e) { console.info(e); }, false); ``` See also the [examples directory](examples) in this distribution. ## Description This provides a simple mechanism for creating a source of [Server Sent Events](https://www.w3.org/TR/eventsource/) in a web server application. The EventSource interface is implemented by most modern web browsers and provides a lightweight alternative to Websockets for those applications where only a uni-directional message is required (for example for notifications,) ## Installation Assuming you have a working installation of Rakudo with `zef` installed then you should be able to install this with: ``` zef install EventSource::Server ``` If you want to install this from a local copy substitute the distribution name for the path to the local copy. ## Support This is quite a simple module but is fairly difficult to test well without bringing in a vast array of large and otherwise un-needed modules, so I won't be surprised there are bugs, similarly whilst I have tested for interoperability with the Javascript hosts that I have available to me I haven't tested against every known host that provides the EventSource interface. So please feel free to report any problems (or make suggestions,) to <https://github.com/jonathanstowe/EventSource-Server/issues> ## Copyright and Licence This is free software, please see the <LICENCE> file in the distribution. © Jonathan Stowe 2017 - 2021
## dist_zef-lizmat-P5defined.md [![Actions Status](https://github.com/lizmat/P5defined/workflows/test/badge.svg)](https://github.com/lizmat/P5defined/actions) # NAME Raku port of Perl's defined() / undef() built-ins # SYNOPSIS ``` use P5defined; my $foo = 42; given $foo { say defined(); # True } say defined($foo); # True $foo = undef(); undef($foo); ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `defined` and `undef` built-ins as closely as possible in the Raku Programming Language. # ORIGINAL PERL 5 DOCUMENTATION ``` defined EXPR defined Returns a Boolean value telling whether EXPR has a value other than the undefined value "undef". If EXPR is not present, $_ is checked. Many operations return "undef" to indicate failure, end of file, system error, uninitialized variable, and other exceptional conditions. This function allows you to distinguish "undef" from other values. (A simple Boolean test will not distinguish among "undef", zero, the empty string, and "0", which are all equally false.) Note that since "undef" is a valid scalar, its presence doesn't necessarily indicate an exceptional condition: "pop" returns "undef" when its argument is an empty array, or when the element to return happens to be "undef". You may also use "defined(&func)" to check whether subroutine &func has ever been defined. The return value is unaffected by any forward declarations of &func. A subroutine that is not defined may still be callable: its package may have an "AUTOLOAD" method that makes it spring into existence the first time that it is called; see perlsub. Use of "defined" on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate had ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size: if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" } When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use "exists" for the latter purpose. Examples: print if defined $switch{D}; print "$val\n" while defined($val = pop(@ary)); die "Can't readlink $sym: $!" unless defined($value = readlink $sym); sub foo { defined &$bar ? &$bar(@_) : die "No bar"; } $debugging = 0 unless defined $debugging; Note: Many folks tend to overuse "defined" and are then surprised to discover that the number 0 and "" (the zero-length string) are, in fact, defined values. For example, if you say "ab" =~ /a(.*)b/; The pattern match succeeds and $1 is defined, although it matched "nothing". It didn't really fail to match anything. Rather, it matched something that happened to be zero characters long. This is all very above-board and honest. When a function returns an undefined value, it's an admission that it couldn't give you an honest answer. So you should use "defined" only when questioning the integrity of what you're trying to do. At other times, a simple comparison to 0 or "" is what you want. See also "undef", "exists", "ref". undef EXPR undef Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using "@"), a hash (using "%"), a subroutine (using "&"), or a typeglob (using "*"). Saying "undef $hash{$key}" will probably not do what you expect on most predefined variables or DBM list values, so don't do that; see "delete". Always returns the undefined value. You can omit the EXPR, in which case nothing is undefined, but you still get an undefined value that you could, for instance, return from a subroutine, assign to a variable, or pass as a parameter. Examples: undef $foo; undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; undef @ary; undef %hash; undef &mysub; undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; select undef, undef, undef, 0.25; ($a, $b, undef, $c) = &foo; # Ignore third value returned Note that this is a unary operator, not a list operator. ``` # PORTING CAVEATS ## Parentheses Because of some overzealous checks for Perl 5isms, it is necessary to put parentheses when using `undef` as a value. Since the 2018.09 Rakudo compiler release, it is possible to use the `isms` pragma: ``` use isms <Perl5>; say undef; # Nil ``` ## $\_ no longer accessible from caller's scope 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: ``` defined; ``` to either: ``` defined($_); ``` or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant: ``` .&defined; ``` # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) 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/P5defined> . 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-iynehz-Inline-Scheme-Gambit.md [![Actions Status](https://github.com/iynehz/perl6-Inline-Scheme-Gambit/actions/workflows/ci.yml/badge.svg)](https://github.com/iynehz/perl6-Inline-Scheme-Gambit/actions) # Inline::Scheme::Gambit This is a Raku module which allows execution of Gambit Scheme code from Raku code with inspiration from other Inline:: modules like Inline::Python, Inline::Lua, Inline::Scheme::Guile, etc. ## Synopsis ``` use Inline::Scheme::Gambit; my $gambit = Inline::Scheme::Gambit.new; my $code = q:to/END/; (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) END $gambit.run($code); say $gambit.call('fib', 8); say $gambit.call('map', $gambit.run(q{(lambda (n) (fib n))}), [0 .. 8]); ``` ## Status Testing has only been done under Rakudo MoarVM on x86-64 Linux. It requires Gambit-C 4, and Gambit-C 4.8.3 and 4.2.8 have been tested by the author. Values can be passed to and returned from Gambit-C. Simple types like boolean, integer, number, string, list, table, vector should work. Present mapping between Gambit-C and Raku types is as following table. ``` Gambit-C from Perl to Perl boolean Bool Bool integer(exact) Int Int rational(exact) Rat Rat rational(inexact) Num Num complex Complex Complex string Stringy Str list Positional Array table Associative Hash vector Array procedure OpaquePointer other objects OpaquePointer OpaquePointer ``` Note that at present both scheme list and vector converts to Array in Raku, but through the call() method (see below) Raku Array only converts to list. The API is incomplete and experimental. It may change in future if necessary. ### To Do * Think about wrapping OpaquePointer for scheme-object, so that it can do better on scheme list/vector/procedure/etc. * Support scheme record type. * Improve error handling. ## Install ``` zef install Inline::Scheme::Gambit ``` It by default tries to use 'gsc-script' or 'gsc' as the gsc command, and dynamically link to libgambc.so. It supports several environment variables to override the default behavior. For example to override gsc in case 'gsc-script' or 'gsc' is not in PATH, or 'gsc-script' is an incorrect symlink. ``` GSC=/usr/bin/gsc zef install Inline::Scheme::Gambit ``` And if on your system gambit dll is not named libgambc.so, you can override it like below, ``` LIBS="-l:libgambit.so.4" zef install Inline::Scheme::Gambit ``` Or if you would like to static link to some libgambit.a ``` LIBS=-lutil MYEXTLIB=/usr/lib/gambit-c/libgambit.a zef install Inline::Scheme::Gambit ``` You can refer to Makefile.in and Build.pm to know more details. ## Usage ### Inline::Scheme::Gambit Object of Inline::Scheme::Gambit represents a global Gambit-C instance. #### method new() Returns the global Inline::Scheme::Gambit singleton. The first call to new() initializes the singleton. #### method run(Str:D $code) Runs $code and returns any resulting value. #### method call(Str:D $name, \*\*@args) Calls the named function with @args, and returns any resulting value. ## Contact <https://github.com/iynehz/perl6-Inline-Scheme-Gambit>
## dist_cpan-ANTONOV-Data-Reshapers.md # Raku Data::Reshapers [![Build Status](https://app.travis-ci.com/antononcube/Raku-Data-Reshapers.svg?branch=main)](https://app.travis-ci.com/github/antononcube/Raku-Data-Reshapers) [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) This Raku package has data reshaping functions for different data structures that are coercible to full arrays. The supported data structures are: * Positional-of-hashes * Positional-of-arrays The five data reshaping provided by the package over those data structures are: * Cross tabulation, `cross-tabulate` * Long format conversion, `to-long-format` * Wide format conversion, `to-wide-format` * Join across (aka `SQL JOIN`), `join-across` * Transpose, `transpose` The first four operations are fundamental in data wrangling and data analysis; see [AA1, Wk1, Wk2, AAv1-AAv2]. (Transposing of tabular data is, of course, also fundamental, but it also can be seen as a basic functional programming operation.) --- ## Usage examples ### Cross tabulation Making contingency tables -- or cross tabulation -- is a fundamental statistics and data analysis operation, [Wk1, AA1]. Here is an example using the [Titanic](https://en.wikipedia.org/wiki/Titanic) dataset (that is provided by this package through the function `get-titanic-dataset`): ``` use Data::Reshapers; my @tbl = get-titanic-dataset(); my $res = cross-tabulate( @tbl, 'passengerSex', 'passengerClass'); say $res; # {female => {1st => 144, 2nd => 106, 3rd => 216}, male => {1st => 179, 2nd => 171, 3rd => 493}} say to-pretty-table($res); # +--------+-----+-----+-----+ # | | 1st | 2nd | 3rd | # +--------+-----+-----+-----+ # | female | 144 | 106 | 216 | # | male | 179 | 171 | 493 | # +--------+-----+-----+-----+ ``` ### Long format Conversion to long format allows column names to be treated as data. (More precisely, when converting to long format specified column names of a tabular dataset become values in a dedicated column, e.g. "Variable" in the long format.) ``` my @tbl1 = @tbl.roll(3); .say for @tbl1; .say for to-long-format( @tbl1 ); my @lfRes1 = to-long-format( @tbl1, 'id', [], variablesTo => "VAR", valuesTo => "VAL2" ); .say for @lfRes1; ``` ### Wide format Here we transform the long format result `@lfRes1` above into wide format -- the result has the same records as the `@tbl1`: ``` ‌‌say to-pretty-table( to-wide-format( @lfRes1, 'id', 'VAR', 'VAL2' ) ); # +-------------------+----------------+--------------+--------------+-----+ # | passengerSurvival | passengerClass | passengerAge | passengerSex | id | # +-------------------+----------------+--------------+--------------+-----+ # | died | 1st | 20 | male | 308 | # | died | 2nd | 40 | female | 412 | # | survived | 2nd | 50 | female | 441 | # | died | 3rd | 20 | male | 741 | # | died | 3rd | -1 | male | 932 | # +-------------------+----------------+--------------+--------------+-----+ ``` ### Transpose Using cross tabulation result above: ``` my $tres = transpose( $res ); say to-pretty-table($res, title => "Original"); # +--------------------------+ # | Original | # +--------+------+----------+ # | | died | survived | # +--------+------+----------+ # | female | 127 | 339 | # | male | 682 | 161 | # +--------+------+----------+ say to-pretty-table($tres, title => "Transposed"); # +--------------------------+ # | Transposed | # +----------+--------+------+ # | | female | male | # +----------+--------+------+ # | died | 127 | 682 | # | survived | 339 | 161 | # +----------+--------+------+ ``` --- ## TODO 1. Simpler more convenient interface. * ~~Currently, a user have to specify four different namespaces in order to be able to use all package functions.~~ 2. More extensive long format tests. 3. More extensive wide format tests. 4. Implement verifications for * Positional-of-hashes * Positional-of-arrays * Positional-of-key-to-array-pairs * Positional-of-hashes, each record of which has: * Same keys * Same type of values of corresponding keys * Positional-of-arrays, each record of which has: * Same length * Same type of values of corresponding elements 5. Implement "nice tabular visualization" using [Pretty::Table](https://gitlab.com/uzluisf/raku-pretty-table) and/or [Text::Table::Simple](https://github.com/ugexe/Perl6-Text--Table--Simple). 6. Document examples using pretty tables. 7. Implement transposing operation for: * hash of hashes * hash of arrays * array of hashes * array of arrays * array of key-to-array pairs 8. Implement to-pretty-table for: * hash of hashes * hash of arrays * array of hashes * array of arrays * array of key-to-array pairs 9. Implemented join-across: * inner, left, right, outer * single key-to-key pair * multiple key-to-key pairs * optional fill-in of missing values * handling collisions 10. Implement to long format conversion for: * hash of hashes * hash of arrays 11. Speed/performance profiling. * Come up with profiling tests * Comparison with R * Comparison with Python --- ## References ### Articles [AA1] Anton Antonov, ["Contingency tables creation examples"](https://mathematicaforprediction.wordpress.com/2016/10/04/contingency-tables-creation-examples/), (2016), [MathematicaForPrediction at WordPress](https://mathematicaforprediction.wordpress.com). [Wk1] Wikipedia entry, [Contingency table](https://en.wikipedia.org/wiki/Contingency_table). [Wk2] Wikipedia entry, [Wide and narrow data](https://en.wikipedia.org/wiki/Wide_and_narrow_data). ### Functions, repositories [AAf1] Anton Antonov, [CrossTabulate](https://resources.wolframcloud.com/FunctionRepository/resources/CrossTabulate), (2019), [Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository). [AAf2] Anton Antonov, [LongFormDataset](https://resources.wolframcloud.com/FunctionRepository/resources/LongFormDataset), (2020), [Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository). [AAf3] Anton Antonov, [WideFormDataset](https://resources.wolframcloud.com/FunctionRepository/resources/WideFormDataset), (2021), [Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository). [AAf4] Anton Antonov, [RecordsSummary](https://resources.wolframcloud.com/FunctionRepository/resources/RecordsSummary), (2019), [Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository). ### Videos [AAv1] Anton Antonov, ["Multi-language Data-Wrangling Conversational Agent"](https://www.youtube.com/watch?v=pQk5jwoMSxs), (2020), [YouTube channel of Wolfram Research, Inc.](https://www.youtube.com/channel/UCJekgf6k62CQHdENWf2NgAQ). (Wolfram Technology Conference 2020 presentation.) [AAv2] Anton Antonov, ["Data Transformation Workflows with Anton Antonov, Session #1"](https://www.youtube.com/watch?v=iXrXMQdXOsM), (2020), [YouTube channel of Wolfram Research, Inc.](https://www.youtube.com/channel/UCJekgf6k62CQHdENWf2NgAQ). [AAv3] Anton Antonov, ["Data Transformation Workflows with Anton Antonov, Session #2"](https://www.youtube.com/watch?v=DWGgFsaEOsU), (2020), [YouTube channel of Wolfram Research, Inc.](https://www.youtube.com/channel/UCJekgf6k62CQHdENWf2NgAQ).
## dist_github-ugexe-Distribution-Common.md ## Distribution::Common Create an installable Distribution from common sources. But really this serves to provide examples on how to create your own `Distribution` classes that don't rely on a specific file system directory layout before being installed. ## Synopsis ``` use Distribution::Common::Git; use Distribution::Common::Tar; use Distribution::Common::Directory; # a local path with a .git folder my $git-dist = Distribution::Common::Git.new($path.IO, :$force); # a file ending in .tar.gz my $tar-dist = Distribution::Common::Tar.new($path.IO, :$force); # a plain directory like Distribution::Path for brevity my $dir-dist = Distribution::Common::Directory.new($path.IO, :$force); ``` ## Classes ### Distribution::Common::Tar Installable `Distribution` from a `.tar.gz` archive ### Distribution::Common::Git Installable `Distribution` from a local git repo. Because this is a directory it inclusion is meant to serve as an example as `Distribution::Common::Directory` will handle this similarly. In the future however it could support changing branches ### Distribution::Common::Directory Essentially the built-in `Distribution::Path` but built around the `Distribution::Common` interface ## Roles ### Distribution::Common The base for the various common distribution classes. Fulfills rakudo's `Distribution` role by providing its own IO interface requirements (`Distribution::IO`) which do most of the actual work. It's main purpose is to fake `IO::Handle` methods such as `open` and `close` for `IO`-like access to objects that don't need to be `.open` before being read. ### Distribution::IO Like rakudo's own `Distribution`, but with an additional requirement, `ls-files`, to automatically handle the setting of `$!meta{files}` for `Distribution::Common` ### Distribution::IO::Proc::Tar ### Distribution::IO::Proc::Git Extract a single file from a distribution to memory. When `CompUnitRepository::Installation::Install.install` accesses such files they are written directly to their install location instead of first using an intermediate temporary location ### Distribution::IO::Directory Basically provides a recursive file listing and little else
## dist_cpan-VRURG-OO-Plugin.md # NAME OO::Plugin – framework for working with OO plugins. # SYNOPSIS ``` use OO::Plugin; use OO::Plugin::Manager; class Foo is pluggable { has $.attr; method bar is pluggable { return 42; } } plugin Fubar { method a-bar ( $msg ) is plug-around( Foo => 'bar' ) { $msg.set-rc( pi ); # Will override &Foo::bar return value and prevent its execution. } } my $manager = OO::Plugin::Manager.new.initialize; my $instance = $manager.create( Foo, attr => 'some value' ); say $instance.bar; # 3.141592653589793 ``` # DESCRIPTION With this framework any application can have highly flexible and extensible plugin subsystem with which plugins would be capable of: * method overriding * class overriding (inheriting) * callbacks * asynchronous event handling The framework also supports: * automatic loading of plugins with a predefined namespace * managing plugin ordering and dependencies Not yet supported but planned for the future is plugin compatibility management. Read more in [OO::Plugin::Manual](https://github.com/vrurg/Perl6-OO-Plugin/blob/v0.0.4/docs/md/OO/Plugin/Manual.md). # SEE ALSO [OO::Plugin::Manual](https://github.com/vrurg/Perl6-OO-Plugin/blob/v0.0.4/docs/md/OO/Plugin/Manual.md), [OO::Plugin](https://github.com/vrurg/Perl6-OO-Plugin/blob/v0.0.4/docs/md/OO/Plugin.md), [OO::Plugin::Manager](https://github.com/vrurg/Perl6-OO-Plugin/blob/v0.0.4/docs/md/OO/Plugin/Manager.md), [OO::Plugin::Class](https://github.com/vrurg/Perl6-OO-Plugin/blob/v0.0.4/docs/md/OO/Plugin/Class.md) # AUTHOR Vadim Belman [[email protected]](mailto:[email protected])
## dist_zef-jmaslak-Net-BGP.md # NAME Net::BGP - BGP Server Support # SYNOPSIS ``` use Net::BGP my $bgp = Net::BGP.new( port => 179 ); # Create a server object ``` # DESCRIPTION This provides framework to support the BGP protocol within a Raku application. This is a pre-release of the final version, and as such the interface may change. The best way of seeing how this module works is to look at `bin/bgpmon.pl6` and examining it. If you are interested in using this module, and have any suggestions at all, please let me know! # ATTRIBUTES ## port The port attribute defaults to 179 (the IETF assigned port default), but can be set to any value between 0 and 65535. It can also be set to Nil, meaning that it will be an ephimeral port that will be set once the listener is started. ## listen-host The host to listen on (defaults to the IPv4 any-host IP, 0.0.0.0). ## server-channel Returns the channel communicate to command the BGP server process. This will not be defined until `listen()` is executed. It is intended that user code will send messages to the BGP server. ## user-channel Returns the channel communicate for the BGP server process to communicate to user code. ## add-unknown-peers If this is `True` (default is `False`), connections from unknown peers are allowed. When they first connect, a new peer is added to the peer list using the remote address and the ASN sent in the peer's OPEN message. # METHODS ## listen ``` $bgp.listen(); ``` Starts BGP listener, on the port provided in the port attribute. For a given instance of the BGP class, only one listener can be active at any point in time. ## peer-add ``` $bgp.peer-add( :peer-asn(65001), :peer-ip("192.0.2.1"), :peer-port(179), :passive(False), :ipv4(True), :ipv6(False), :md5($key), ); ``` Add a new peer to the BGP server. Providing `peer-asn` and `peer-ip` is required. However, if the `peer-port` is not provided, `179` will be used. If `passive` is not used, the connection will not be configured as a passive connection. If `ipv4` is not provided, it defaults to `True` (enabling the IPv4 address family), while `ipv6` defaults to `False` (disabling the IPv6 address family). If an `md5` parameter is provided, this is used to set up MD5 associations (on OSes that support this via the `TCP::LowLevel` module). # PATRONS Mythic Beasts, a managed and unmanaged VPS, dedicated server, web and email hosting company (among many other services) generously donated the use of a VPS host with IPv4 and IPv6 BGP feeds for the development of this module. Check them out at <https://www.mythic-beasts.com/>. # AUTHOR Joelle Maslak [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright © 2018-2020 Joelle Maslak This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-martimm-Gnome-GObject.md ![](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-perl6.png) # Gnome GObject - The base type system and object class ![Artistic License 2.0](https://martimm.github.io/label/License-label.svg) ## 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.
## naming.md role Metamodel::Naming Metaobject that supports named types ```raku role Metamodel::Naming { } ``` *Warning*: this role is part of the Rakudo implementation, and is not a part of the language specification. [Metamodel](/language/mop) role for (optionally) named things, like classes, roles and enums. # [Methods](#role_Metamodel::Naming "go to top of document")[§](#Methods "direct link") ## [method name](#role_Metamodel::Naming "go to top of document")[§](#method_name "direct link") ```raku method name($type) ``` Returns the name of the metaobject, if any. ```raku say 42.^name; # OUTPUT: «Int␤» ``` ## [method set\_name](#role_Metamodel::Naming "go to top of document")[§](#method_set_name "direct link") ```raku method set_name($type, $new_name) ``` Sets the new name of the metaobject.
## dist_zef-jjmerelo-Grammar-Message.md # Grammar::Message, a Raku module to make grammar and regex messages prettier [Test-install distro](https://github.com/JJ/raku-grammar-message/actions/workflows/test.yaml) inspired by [Grammar::PrettyErrors](https://github.com/bduggan/p6-grammar-prettyerrors), and ripping off the code used there for printing messages, prints error messages highlighting the line and, if possible, the position where it last worked. ## Installing Do the usual ``` zef install Grammar::Message ``` ## Running You will need to insert a variable assignment behind the match you are going to check ``` my $str = (('a'..'z').rotor(3).map: *.join("")).join("\n"); my $saved-match; # Saves in situ $str ~~ / m { $saved-match = $/} /; # Code right behind match you need printed say pretty-message( "Found", $saved-match); ``` Will print ``` Found 3 │ ghi 4 │ jkl 5 │▶ mno ^ 6 │ pqr 7 │ stu 8 │ vwx ``` with highlights for the matching line. ``` grammar G { token TOP { <letters>+ % \v} token letters { { $saved-match = $/} \w ** 3 } } $str .= subst( "m", "mm" ); G.parse( $str ); say pretty-message( "Some failure around here", $saved-match); ``` will print ``` Some failure around here 4 │ jkl 5 │ mmno 6 │▶ pqr ^ 7 │ stu 8 │ vwx ``` Take into account that the marked point will always be the best bet, and in any case it will reflect the state of the `pos` attribute of the Match at the point you saved it. ## See also Code by Brian Duggan in [`Grammar::PrettyErrors`](https://github.com/bduggan/p6-grammar-prettyerrors) is the origin of this code. ## License (c) Brian Duggan, JJ Merelo Respecting the original code license, this is also licensed under the Artistic license (included).
## ipc.md Inter-process communication Programs running other programs and communicating with them # [Running programs](#Inter-process_communication "go to top of document")[§](#Running_programs "direct link") Many programs need to be able to run other programs, and we need to pass information to them and receive their output and exit status. Running a program in Raku is as easy as: ```raku run 'git', 'status'; ``` This line runs the program named "git" and passes "git" and "status" to its command-line. It will find the program using the `%*ENV<PATH>` setting. If you would like to run a program by sending a command-line to the shell, there's a tool for that as well. All shell metacharacters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on. ```raku shell 'ls -lR | gzip -9 > ls-lR.gz'; ``` Caution should be taken when using `shell` with user input. # [The](#Inter-process_communication "go to top of document") [`Proc`](/type/Proc) object[§](#The_Proc_object "direct link") Both `run` and `shell` return a [`Proc`](/type/Proc) object, which can be used to communicate with the process in more detail. Please note that unless you close all output pipes, the program will usually not terminate. ```raku my $git = run 'git', 'log', '--oneline', :out; for $git.out.lines -> $line { my ($sha, $subject) = $line.split: ' ', 2; say "$subject [$sha]"; } $git.out.close(); ``` If the program fails (exits with a non-zero exit code), it will throw an exception when the returned [`Proc`](/type/Proc) object is sunk. You can save it into a variable, even anonymous one, to prevent the sinking: ```raku $ = run '/bin/false'; # does not sink the Proc and so does not throw ``` You can tell the [`Proc`](/type/Proc) object to capture output as a filehandle by passing the `:out` and `:err` flags. You may also pass input via the `:in` flag. ```raku my $echo = run 'echo', 'Hello, world', :out; my $cat = run 'cat', '-n', :in($echo.out), :out; say $cat.out.get; $cat.out.close(); ``` You may also use [`Proc`](/type/Proc) to capture the PID, send signals to the application, and check the exitcode. ```raku my $crontab = run 'crontab', '-l'; if $crontab.exitcode == 0 { say 'crontab -l ran ok'; } else { say 'something went wrong'; } ``` ## [Example with shell](#Inter-process_communication "go to top of document")[§](#Example_with_shell "direct link") Suppose there is a utility that will takes input from STDIN and outputs to STDOUT, but there isn't yet a Raku wrapper. For this example, lets use [sass](https://sass-lang.com/documentation/cli/dart-sass/), which preprocesses a more convenient form of CSS called SCSS into standard CSS. In a terminal the utility would be used as sass --stdin We want to convert multiple strings of SCSS into CSS. The code below only converts one string and captures the output into a variable, but it should be obvious how to adapt this into a loop. ```raku #| process with utility, first check it exists in the environment my $proc = shell( <<sass --version>>, :out, :merge); exit note 'Cannot run sass' unless $proc.out.slurp(:close) ~~ / \d \. \d+ /; # start loop here for multiple SCSS strings # set up the process for stdin. $proc = shell( <<sass --stdin --style=compressed>>, :in, :err, :out ); my $scss = q:to/SCSS/; div.rendered-formula { display: flex; justify-content: space-around; align-items: center; img.logo { align-self: center; } } SCSS # now pipe the SCSS string into the process as STDIN (remembering to close the pipe) $proc.in.spurt($scss,:close); # extract the output or the error my $error = $_ with $proc.err.slurp(:close); my $output = $_ with $proc.out.slurp(:close); # end loop here ``` # [The](#Inter-process_communication "go to top of document") [`Proc::Async`](/type/Proc/Async) object[§](#The_Proc::Async_object "direct link") When you need more control over the communication with and from another process, you will want to make use of [`Proc::Async`](/type/Proc/Async). This class provides support for asynchronous communication with a program, as well as the ability to send signals to that program. ```raku # Get ready to run the program my $log = Proc::Async.new('tail', '-f', '/var/log/system.log'); $log.stdout.tap(-> $buf { print $buf }); $log.stderr.tap(-> $buf { $*ERR.print($buf) }); # Start the program my $done = $log.start; sleep 10; # Tell the program to stop $log.kill('QUIT'); # Wait for the program to finish await $done; ``` The small program above uses the "tail" program to print out the contents of the log named `system.log` for 10 seconds and then tells the program to stop with a QUIT signal. Whereas [`Proc`](/type/Proc) provides access to output using [`IO::Handle`](/type/IO/Handle)s, [`Proc::Async`](/type/Proc/Async) provides access using asynchronous supplies (see [`Supply`](/type/Supply)). If you want to run a program and do some work while you wait for the original program to finish, the `start` routine returns a [`Promise`](/type/Promise), which is kept when the program quits. Use the `write` method to pass data into the program.
## dist_github-ufobat-StrictClass.md [![Build Status](https://travis-ci.org/ufobat/p6-StrictClass.svg?branch=master)](https://travis-ci.org/ufobat/p6-StrictClass) # NAME StrictClass - Make your object constructors blow up on unknown attributes # SYNOPSIS ``` use StrictClass; class MyClass does StrictClass { has $.foo; has $.bar; } MyClass.new( :foo(1), :bar(2), :baz('makes you explode')); ``` # DESCRIPTION Simply using this role for your class makes your `new` "strict". This is a great way to catch small typos. # AUTHOR Martin Barth [[email protected]](mailto:[email protected]) # head THANKS TO ``` * FCO aka SmokeMaschine from #perl6 IRC channel for this code. * Dave Rolsky for his perl5 module `MooseX::StrictContructor`. ``` # COPYRIGHT AND LICENSE Copyright 2018 Martin Barth This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-FCO-DateTime-Extended.md [![Build Status](https://travis-ci.org/FCO/DateTime-Extended.svg?branch=master)](https://travis-ci.org/FCO/DateTime-Extended) # DateTime-Extended
## dist_zef-lizmat-Ecosystem-Archive.md [![Actions Status](https://github.com/lizmat/Ecosystem-Archive/workflows/test/badge.svg)](https://github.com/lizmat/Ecosystem-Archive/actions) # NAME Ecosystem::Archive - Interface to the Raku Ecosystem Archive # SYNOPSIS ``` use Ecosystem::Archive; my $ea = Ecosystem::Archive.new( shelves => 'archive', jsons => 'meta', http-client => default-http-client ); say "Archive has $ea.meta.elems() identities:"; .say for $ea.meta.keys.sort; ``` # DESCRIPTION Ecosystem::Archive provides the basic logic to the Raku Programming Language Ecosystem Archive, a place where (almost) every distribution ever available in the Raku Ecosystem, can be obtained even after it has been removed (specifically in the case of the old ecosystem master list and the distributions kept on CPAN). ## ARGUMENTS * shelves The name (or an `IO` object) of a directory in which to place distributions. This is usually a symlink to the "archive" directory of the actual [Raku Ecosystem Archive repository](https://github.com/lizmat/REA). The default is 'archive', aka the 'archive' subdirectory from the current directory. * jsons The name (or an `IO` object) of a directory in which to store `META6.json` files as downloaded. This is usually a symlink to the "meta" directory of the actual [Raku Ecosystem Archive repository](https://github.com/lizmat/REA). The default is 'meta', aka the 'meta' subdirectory from the current directory. * http-client The `Cro::HTTP::Client` object to do downloads with. Defaults to a `Cro::HTTP::Client` object that advertises this module as its User-Agent. * degree The number of CPU cores that may be used for parallel processing. Defaults to the **half** number of `Kernel.cpu-cores`. * batch The number of objects to be processed in parallel per batch. Defaults to **64**. # METHODS ## batch ``` say "Processing with batches of $ea.batch() objects in parallel"; ``` The number of objects per batch that will be used in parallel processing. ## clear-notes ``` my @cleared = $ea.clear-notes; say "All notes have been cleared"; ``` Returns the `notes` of the object as a `List`, and removes them from the object. ## degree ``` say "Using $ea.degree() CPUs"; ``` The number of CPU cores that will be used in parallel processing. ## distro-io ``` my $identity = $ea.find-identities('eigenstates').head; say $ea.distro-io($identity); ``` Returns an `IO` object for the given identity, or `Nil` if it can not be found. ## distros ``` say "Archive has $ea.distros.elems() different distributions, they are:"; .say for $ea.distros.keys.sort; ``` Returns a `Map` keyed by distribution name, with a list of identities that are available of this distribution, as value. ## find-identities ``` my @identities = $ea.find-identities('eigenstates', :ver<0.0.3*>); say "@identities[0] is the most recent"; ``` Find the identities that supply the given module name (as a positional parameter) and possible refinement with named parameters for `:ver`, `:auth` and `:api`. Note that the `:ver` specification can contain `+` or `*` to indicate a range rather than a single version. The identities will be returned sorted by highest version first. So if you're interested in only the most recent version, then just select the first element returned. ## http-client ``` say "Information fetched as '$ea.http-client.user-agent()'"; ``` The `Cro::HTTP::Client` object that is used for downloading information from the Internet. ## investigate-repo ``` my @found = $ea.investigate-repo($url, "lizmat"); ``` Performs a `git clone` on the given URL, scans the repo for changes in the `META6.json` file that would change the version, and downloads and saves a tar-file of the repository (and the associated META information in `git-meta`) at that state of the repository. The second positional parameter indicates the default `auth` value to be applied to any JSON information, if no `auth` value is found or it is invalid. Only `Github` and `Gitlab` URLs are currently supported. Returns a list of `Pair`s of the distributions that were added, with the identity as the key, and the META information hash as the value. Updates the `.meta` and `.modules` meta-information in a thread-safe manner. ## jsons ``` indir $ea.jsons, { my $jsons = (shell 'ls */*', :out).out.lines.elems; say "$jsons different distributions"; } ``` The `IO` object of the directory in which the JSON meta files are being stored. For instance the `IRC::Client` distribution: ``` meta |- ... |- I |- ... |- IRC::Client |- IRC::Client:ver<1.001001>:auth<github:zoffixznet>.json |- IRC::Client:ver<1.002001>:auth<github:zoffixznet>.json |- ... |- IRC::Client:ver<3.007010>:auth<github:zoffixznet>.json |- IRC::Client:ver<3.007011>:auth<cpan:ELIZABETH>.json |- IRC::Client:ver<3.009990>:auth<cpan:ELIZABETH>.json |- ... |- ... ``` ## meta ``` say "Archive has $ea.meta.elems() identities, they are:"; .say for $ea.meta.keys.sort; ``` Returns a hash of all of the META information of all distributions, keyed by identity (for example "Module::Name:ver<0.1>:authfoo:bar:api<1>"). The value is a hash obtained from the distribution's meta data. ## meta-as-json ``` say $ea.meta-as-json; # at least 3MB of text ``` Returns the JSON of all the currently known meta-information. The JSON is ordered by identity in the top level array. ## modules ``` say "Archive has $ea.modules.elems() different modules, they are:"; .say for $ea.modules.keys.sort; ``` Returns a `Map` keyed by module name, with a list of identities that provide that module name, as value. ## note ``` $ea.note("something's wrong"); ``` Add a note to the `notes` of the object. ## notes ``` say "Found $ea.notes.elems() notes:"; .say for $ea.notes; ``` Returns the `notes` of the object as a `List`. ## shelves ``` indir $ea.shelves, { my $distros = (shell 'ls */*', :out).out.lines.elems; say "$distros different distributions in archive"; } ``` The `IO` object of the directory where distributions are being stored in a subdirectory by the name of the module in the distribution. For instance the `silently` distribution: ``` archive |- ... |- S |- ... |- silently |- silently:ver<0.0.1>:auth<cpan:ELIZABETH>.tar.gz |- silently:ver<0.0.2>:auth<cpan:ELIZABETH>.tar.gz |- silently:ver<0.0.3>:auth<cpan:ELIZABETH>.tar.gz |- silently:ver<0.0.4>:auth<zef:lizmat>.tar.gz |- ... |- ... ``` Note that a subdirectory will contain **all** distributions of the name, regardless of version, authority or API value. ## update ``` my %updated = $ea.update; ``` Updates all the meta-information and downloads any new distributions. Returns a hash with the identities and the meta info of any distributions that were not seen before. Also updates the `.meta` and `.modules` information in a thread-safe manner. # EXPORTED SUBROUTINES ## identity2module ``` say identity2module("zef:ver<0.1.1>:auth<zef:ugexe>"); # zef ``` Returns the module of a given identity. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Ecosystem-Archive>. Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2021 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-ugexe-PathTools.md ## PathTools General purpose file system utility routines ## Exports #### FLAGS Definitions of the argument flags that can be passed to `PathTools` routines: ``` :f - list files :d - list directories :r - recursively visit directories :!f - exclude files :!d - exclude directories :!r - only in the immediate path ``` #### `ls($path, Bool :$f = True, Bool :$d = True, Bool :$r --> Str @paths)` ``` use PathTools; # all paths using directory recursion my @all = ls($path, :r, :d, :f); # only *file* paths, found using directory recursion my @files = ls($path, :r, :!d, :f); # only directories in the current level (no directory recursion) my @dirs = ls($path, :d, :!r); ``` Like the built-in `dir` but with optional recursion. Any undocumented additional named arguments passed in will be passed along to the internal `mkdir` and `dir` calls used. For instance, one may wish to pass `:$test` which internally defaults to `none('.','..')` and is documented further here: [dir](https://docs.raku.org/routine/dir) ``` > .say for ls('t'); /home/user/Raku-PathTools/t/01-basic.rakumod /home/user/Raku-PathTools/t/00-sanity.rakumod ``` To search for files, just grep the results of `ls`: ``` > my @files = ls($path, :r, :!d, :f); > my @p6modules = @files.grep(*.IO.extension ~~ 'pm6') ``` #### `rm(*@paths, :Bool $f = True, Bool :$d = True, Bool :$r --> Str @deleted-paths)` ``` # rm -rf tmp/foo my @deleted-files = rm("tmp/foo"), :r, :f, :d); ``` Passes its arguments to `ls` and subsequently unlinks the files and/or deletes folders, possibly recursively. ``` > .say for rm('t'); /home/user/Raku-PathTools/t/01-basic.rakumod /home/user/Raku-PathTools/t/00-sanity.rakumod ``` #### `mkdirs($paths --> Str $created-path)` ``` # generate a multi level temporary path name my $created-path = mkdirs(".work/{$new-month}/{$new-day}") ``` VM/OS independent folder creation. Identical to the built-in `mkdir` except the path parts are created folder by folder. This usually isn't needed, but in some edge cases the built-in `mkdir` fails when creating a multi level folder. ``` > say mkdirs('newDir/newSubdir'); /home/user/newDir/newSubdir ``` #### `mktemp($path?, Bool :$f = False --> Str $tmppath)` ``` # create a temporary folder and clean it up after program exit my $cleanup-path = mkdirs("/tmp/.worker{$id}/{time}") ``` If argument C<:$f> is `True` it will create a new file to be deleted at `END { }`. Otherwise, by default, creates a new folder, `$path`, and will attempt to recursively cleanup its contents at `END { }`. If `$path` is not supplied, a path name will be generated automatically with `tmppath` ``` # a random directory > say mktemp(); /tmp/tmppath/1444251805_1 # a random file > say mktemp(:f); /tmp/tmppath/1444251805_1 # a file (or directory) name of your choosing > say mktemp(".cache", :f); /home/user/Raku-PathTools/.cache ``` #### `tmppath($base? = $*TMPDIR --> Str $pathname)` ``` my $pathname = tmppath(".work") ``` Generate a (hopefully) unique timestamp based path name that is prefixed by C<$base>. This does not actually create the path; Use `mkdirs` or [mkdir](https://docs.raku.org/routine/mkdir) on the result. ``` > say tmppath(); /tmp/tmppath/1444251805_1 > say tmppath(".work"); .work/tmppath/1444255482_1 > say tmppath("/con/con")' /con/con/tmppath/1444268295_1 > say tmppath.IO.e; False > say mkdirs(tmppath).IO.e True ```
## dist_cpan-YGUILLEMO-Qt-QtWidgets.md # Qt::QtWidgets A Raku module and native wrapper providing an interface to the Qt5 GUI. ## CONTENT * 1. DESCRIPTION * 2. LIMITATIONS * 3. IMPLEMENTED FUNCTIONALITIES * 4. DOCUMENTATION * 4.1 Classes and methods * 4.2 Instantiation * 4.3 Calling a method * 4.4 Enums * 4.5 Signals and slots * 4.6 Connect * 4.7 Disconnect * 4.8 Emit a QtSignal * 4.9 Subclassing a Qt object * 5. EXAMPLES * 5.1 clock\_fixedSize.raku * 5.2 clock\_resizable.raku * 5.3 2deg\_eqn\_solver.raku * 5.4 sketch\_board.raku * 5.5 editor.raku * 5.6 sliders.raku * 6. TOOL * 7. PREREQUISITES * 8. INSTALLATION * 9. SOURCE CODE * 10. AUTHOR * 11. COPYRIGHT AND LICENSE ## 1. DESCRIPTION This module defines Raku classes trying to mimic the Qt GUI C++ classes. Qt objects are created and used through the Raku classes with native calls. This is a work in progress and, currently, only a few classes and methods are defined. Nevertheless, this module is already usable (see paragraph 5 *EXAMPLES* below). ## 2. LIMITATIONS Currently, this module is only working with Linux. Although already usable, this interface is still limited to a few of the most basic objects of the Qt GUI. ## 3. IMPLEMENTED FUNCTIONALITIES The list of Qt classes and methods already ported is given in the file doc/Qt/QtWidgets/Classes.html included in the distribution. ## 4. DOCUMENTATION ### 4.1 Classes and methods The Raku API aims to be as close as possible to the C++ one. Classes defined by the Raku API implement the Qt C++ classes and the Raku methods have the same arguments as their related C++ methods. Therefore the Qt C++ documentation should apply to its Raku interface. This documentation is available here: <https://doc.qt.io/qt-5>. The Raku API hides the C++ passing mode of the parameters. Each class resides in its own compunit. So, before using a class, an **use** instruction have to be provided for the related module. For example, the following line: ``` use Qt::QtWidgets::QPushButton; ``` has to be issued before using any instruction related to a QPushButton. The script **guessuse** is provided to help writing the needed **use** instructions. See the paragraph 6 *TOOL* below. ### 4.2 Instantiation To instantiate a Qt class object from Raku, just use new with the same arguments than the C++ constructor. For example the C++ call of a QPushButton constructor is : `QPushButton * button = new QPushButton("some text");` the raku equivalent is: `my $button = QPushButton.new("some text");` ### 4.3 Calling a method Raku methods are called exactly as the original C++ method. The C++ code : `button->setDisable(true);` is translated to Raku as : `$button.setDisable(True);` ### 4.4 Enums Similarly the C++ enums have their Raku equivalent : the C++ code : `QPen * pen = new QPen(Qt::DashLine);` is translated to Raku as : `my $pen = QPen.new(Qt::DashLine);` ### 4.5 Signals and slots The signals and slots mechanism used by Qt allows unrelated objects to communicate. A C++ Qt object can have **slots** and/or **signals** if it inherits from the C++ class **QObject**. Similarly, a Raku object can have **QtSlots** and/or **QtSignals** if it inherits from the Raku class **QtObject**. The class **QtObject** and the related subroutines **connect** and **disconnect** are exported from the compunit **Qt::QtWidgets** and have to be imported with: `use Qt::QtWidgets;` A Raku Qt::QtWidgets **Qtslot** is an ordinary method defined with the trait **is QtSlot**. ``` class MyClass is Qt::QtWidgetsObject { ... # Some code method mySlot(...) is QtSlot { ... # Some code } ... # Some code } ``` As well, a Raku Qt::QtWidgets **Qtsignal** is a method defined with the trait **is QtSignal**. Its associated code will never be executed. So a stub should be used when defining the method. ``` class MyClass2 is Qt::QtWidgetsObject { ... # Some code method mySignal(...) is QtSignal { ... } ... # Some code } ``` ### 4.6 Connect The subroutine **connect** connects a QtSignal to a QtSlot (or to another QtSignal). `sub connect(QtObject $src, Str $signal, QtObject $dst, Str $slot)` The names of signal and slot are passed to connect in strings. The signal and slot must have compatible signatures. > TODO: explanations needed Example: ``` my $src = MyClass2.new; my $dst = MyClass.new; connect $src, "mySignal", $dst, "mySlot"; ``` ### 4.7 Disconnect The subroutine **disconnect** does the opposite of **connect**. `sub disconnect(QtObject $src, Str $signal, QtObject $dst, Str $slot)` Example: `disconnect $src, "mySignal", $dst, "mySlot";` ### 4.8 Emit a QtSignal In C++ Qt, the keyword **emit** is used to emit a signal. `emit mySignal(some_arg);` In Raku Qt::QtWidgets, you only have to execute the method to emit the associated **QtSignal**. `self.mySignal(some_arg);` ### 4.9 Subclassing a Qt object When programming with Qt and C++, some features can only be accessed by overriding a Qt C++ virtual method. A parallel mechanism is implemented in the Qt::QtWidgets module. Subclassing a Qt object needs three steps: * Define a Raku class inheriting the Qt class * Call the **subClass** method of the parent class from the BUILD or TWEAK submethod of the new class. * Override the virtual methods. The overriding method must have the same name and signature that the overrided method and doesn't need any specific syntax. The first and third steps are obvious. The second one is used to instantiate the C++ counterpart of the Raku class and to pass it the parameters its constructor needs. In this second step, the parent class whose the subClass method is called must be explicitely specified: `self.ParentClass::subClass($param, ...);` The following example shows how to subclass a QLabel and override its QMousePressEvent method. **Pure C++ version:** ``` #include <QtWidgets> class MyLabel : public QLabel { public : MyLabel(const QString txt) : QLabel(txt) { } void mousePressEvent(QMouseEvent* event) { // Do something when the mouse is pressed on the label } }; ... // Instantiation of the label in the main function : MyLabel * label = new MyLabel("text on the label"); ``` **Raku version:** ``` use Qt::QtWidgets; use Qt::QtWidgets::QLabel; use Qt::QtWidgets::QMouseEvent; class MyLabel is QLabel { has Str $.txt; submethod TWEAK { self.QLabel::subClass($!txt); } method mousePressEvent(QMouseEvent $event) { # Do something when the mouse is pressed on the label } } ... # Instantiation of the label in the main program : my $label = MyLabel.new(txt => "text on the label"); ``` ## 5. EXAMPLES ### 5.1 clock\_fixedSize.raku A very simple clock displaying the current time. `raku examples/clock_fixedSize.raku` ### 5.2 clock\_resizable.raku The same clock with a resizable window. `raku examples/clock_resizable.raku` ### 5.3 2deg\_eqn\_solver.raku A graphical interface to solve quadratic equations. `raku examples/2deg_eqn_solver.raku` ### 5.4 sketch\_board.raku A small example showing how to draw with the mouse and how to get file names using QFileDialog methods. `raku examples/sketch_board.raku` ### 5.5 editor.raku A tiny text editor build with QTextEdit `raku examples/editor.raku` ### 5.6 sliders.raku A demonstration of QSlider, QDial, QCheckBox and QRadioButton widgets. `raku examples/sliders.raku` ## 6. TOOL Ideally, inserting "use Qt::QtWidgets;" at the beginning of a script should be sufficient to import all the elements of the Qt::QtWidgets module. Unfortunately it's not the case and seems not to be possible with the current version of Raku (except by gathering all the classes of this API inside a single huge source file). Currently a specific **use** instruction is needed for each Qt class used in a script. That's why a tool named **guessuse** is provided to help the user to find what **use** instructions a given script needs. When called with the name of a raku file as argument, it writes out the list of **use** instructions related to **Qt::QtWidgets** needed by this script. For example, the command: ``` guessUse examples/sketch_board.raku ``` prints out the following lines: ``` use Qt::QtWidgets; use Qt::QtWidgets::QAction; use Qt::QtWidgets::QApplication; use Qt::QtWidgets::QBrush; use Qt::QtWidgets::QColor; use Qt::QtWidgets::QFileDialog; use Qt::QtWidgets::QHBoxLayout; use Qt::QtWidgets::QMenu; use Qt::QtWidgets::QMouseEvent; use Qt::QtWidgets::QPaintEvent; use Qt::QtWidgets::QPainter; use Qt::QtWidgets::QPen; use Qt::QtWidgets::QPushButton; use Qt::QtWidgets::QVBoxLayout; use Qt::QtWidgets::QWidget; use Qt::QtWidgets::Qt; ``` Beware that this tool, when scanning a source file, doesn't make any difference between code, comments and character strings and may very well print out "use" instruction for some unneeded compunit. **guessuse** resides in the the bin directory of the distribution and is installed by **zef** along with the **Qt::QtWidgets** module. ## 7. PREREQUISITES * Linux OS * Qt5 development package * C++ compiler This module has been tested with **Qt 5.9.4** and **gcc 5.5.0** and with **Qt 5.15.2** and **gcc 10.3.0**. Many other versions should be usable as well. ## 8. INSTALLATION `zef install Qt::QtWidgets` ## 9. SOURCE CODE The source code is available here: <https://github.com/yguillemot/Raku-Qt-QtWidgets.git> Given the large number of Qt Classes and methods, manually writing such a code is very tedious and error prone. That's why this source and its associated documentation have been automatically generated from the Qt C++ headers files coming with the Qt development package. The building tools are available here: <https://github.com/yguillemot/RaQt_maker.git> ## 10. AUTHOR Yves Guillemot <[[email protected]](mailto:[email protected])> ## 11. COPYRIGHT AND LICENSE Copyright (C) 2021 Yves Guillemot This software is free: you can redistribute and/or modify it under the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This software 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
## dist_zef-lizmat-Game-Covid19.md # NAME Game::Covid19 - Play the COVID-19 game # SYNOPSIS ``` use Game::Covid19; play(age => 64); # must specify age play(age => 34, :mask, :distancing); death-rate(age => 64); ``` # DESCRIPTION Game::Covid19 is an implementation of a DND-type game that is based on CDC data and was posted by Stephen Richard Watson at: ``` https://www.facebook.com/photo.php?fbid=10163856786525537&set=gm.1155683021483491&type=3&theater ``` It exports two subroutines: `play` and `death-rate`. # SUBROUTINES ## play ``` play(age => 64); ``` The `play` subroutine will play the game. You need to at least specify the `age` named parameter. It will return your final constitution, with `0` indicating death. The following named parameters are optional: ### constitution ``` constitution => 80, ``` A value of 1..100 indicating the state of your constitution, with `100` indicating fully healthy. Defaults to `100`. ### mask ``` :mask ``` A Boolean indicating whether or not you're wearing a mask. Defaults to `False`. ### distancing ``` :distancing ``` A Boolean indicating whether or not you're socially distancing. Defaults to `False`. ### verbose ``` :!verbose ``` A Boolean indicating whether verbose play output is wanted. Defaults to `True`. ## death-rate ``` death-rate(age => 64); ``` The `death-rate` sub will run the game many times and record how many times the game resulted in death, and use that to calculate a death-rate as a percentage. It takes the same named parameters as the `play` subroutine. Additional named parameters are: ### times ``` times => 10000 ``` The number of times the game should be played. Defaults to 10000. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Game-Covid19> . 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_github-JuneKelly-HTTP-Router-Blind.md # HTTP::Router::Blind A simple, framework-agnostic HTTP Router for Perl6 [![Build Status](https://travis-ci.org/ShaneKilkelly/perl6-http-router-blind.svg?branch=master)](https://travis-ci.org/ShaneKilkelly/perl6-http-router-blind) ## Example With the HTTP::Easy server: ``` use v6; use HTTP::Easy::PSGI; use HTTP::Router::Blind; my $http = HTTP::Easy::PSGI.new(:port(8080)); my $router = HTTP::Router::Blind.new(); # simple string-match route $router.get("/", sub (%env) { [200, ['Content-Type' => 'text/plain'], ["Home is where the heart is"]] }); $router.get("/about", sub (%env) { [200, ['Content-Type' => 'text/plain'], ["About this site"]] }); # string match with keyword params, # the second parameter to the handler function is a hash of params # extracted from the URL $router.get("/user/:id", sub (%env, %params) { my $user-id = %params<id>; [200, ['Content-Type' => 'text/plain'], ["It's user $user-id"]] }); # regex match, with named capture-group, # will match a request like '/items/42253', # the second parameter to the handler is the Regex match object; $router.get(/\/items\/$<id>=(.*)/, sub (%env, $params) { my $id = $params<id>; [200, ['Content-Type' => 'text/plain'], ["got request for item $id"]] }); # you can pass multiple handler functions # which will be chained together in order sub do-something-special (%env) { ...; return %env; } $router.get('/secret', &do-something-special, sub (%env) { [200, ['Content-Type' => 'text/plain'], ["it's a secret"]] }); # in our app function, we just call $router.dispatch my $app = sub (%env) { $router.dispatch(%env<REQUEST_METHOD>, %env<REQUEST_URI>, %env); }; $http.handle($app); ``` # CHANGELOG * 2.0.0 : for keyword and regex matches, pass the matched `params` as a second parameter to the handler function, instead of setting `%env<params>`.
## semaphore.md class Semaphore Control access to shared resources by multiple threads ```raku class Semaphore { } ``` Protect your shared code, data or device access using semaphores. An example is a printer manager managing a pool of printers without the need of storing print jobs when all printers are occupied. The next job is just blocked until a printer becomes available. ```raku class print-manager { has Array $!printers; has Semaphore $!print-control; method BUILD( Int:D :$nbr-printers ) { for ^$nbr-printers -> $pc { $!printers[$pc] = { :name{"printer-$pc"} }; } $!print-control .= new($nbr-printers); } method find-available-printer-and-print-it($job) { say "Is printed!"; } method print( $print-job ) { $!print-control.acquire; self.find-available-printer-and-print-it($print-job); $!print-control.release; } } ``` Another example is a protection around code updating sensitive data. In such a case the semaphore is typically initialized to 1. It is important to have a release on every exit of your program! While this is obvious, it is easy to fall in traps such as throwing an exception caused by some event. When the program dies there is no problem. When the exception is caught your program might eventually come back to the acquire method and will hang indefinitely. # [Methods](#class_Semaphore "go to top of document")[§](#Methods "direct link") ## [method new](#class_Semaphore "go to top of document")[§](#method_new "direct link") ```raku method new( int $permits ) ``` Initialize the semaphore with the number of permitted accesses. E.g. when set to 2, program threads can pass the acquire method twice until it blocks on the third time acquire is called. ## [method acquire](#class_Semaphore "go to top of document")[§](#method_acquire "direct link") ```raku method acquire() ``` Acquire access. When other threads have called the method before and the number of permits are used up, the process blocks until threads passed before releases the semaphore. ## [method try\_acquire](#class_Semaphore "go to top of document")[§](#method_try_acquire "direct link") ```raku method try_acquire(--> Bool) ``` Same as acquire but will not block. Instead it returns `True` if access is permitted or `False` otherwise. ## [method release](#class_Semaphore "go to top of document")[§](#method_release "direct link") ```raku method release() ``` Release the semaphore raising the number of permissions. Any blocked thread will get access after that. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Semaphore` raku-type-graph Semaphore Semaphore Any Any Semaphore->Any Mu Mu Any->Mu [Expand chart above](/assets/typegraphs/Semaphore.svg)
## dist_zef-jjmerelo-Test-Script.md # Test::Script [Test-install distro](https://github.com/JJ/raku-test-script/actions/workflows/test.yaml) Test a script in Raku, checking its output ## Installing Use `zef instal --deps-only .` to install only dependencies. There are no non-Raku dependencies. ## Running ``` use Test::Script; output-is "script.p6", "hello: goodbye\n", "Two args ", args => ["--msg=goodbye", "hello"]; output-like "script.p6, /"hello → goodbye"/, "Prints environment ", env => { "hello" => "goodbye" }; variable-ok "script.p6", '$foo', "Variable exists and is set"; variable-is "script.p6", '$foo', <bar baz>, "Variable exists and has value"; error-like "Totally-messed-up-program.p6", /messy/, "Messy program fails"; ``` ## See also See documentation [as a POD](lib/Test/Script.pm6). ## License This module is licensed under the Artistic 2.0 License (the same as Raku itself).
## dist_zef-Kaiepi-Kind-Subset-Parametric.md [![Build Status](https://github.com/Kaiepi/ra-Kind-Subset-Parametric/actions/workflows/test.yml/badge.svg)](https://github.com/Kaiepi/ra-Kind-Subset-Parametric/actions/workflows/test.yml) # NAME Kind::Subset::Parametric - Support for generic subsets # SYNOPSIS ``` use Kind::Subset::Parametric; # Arrays don't type their elements by default: my @untyped = 1, 2, 3; say @untyped.^name; # OUTPUT: Array # You can make it so they do by parameterizing Array: my Int:D @typed = 1, 2, 3; say @typed.^name; # OUTPUT: Array[Int:D] # But you can't typecheck untyped arrays using these parameterizations: say @typed ~~ Array[Int:D]; # OUTPUT: True say @untyped ~~ Array[Int:D]; # OUTPUT: False # So let's make our own array type that handles this using a parametric subset: subset TypedArray of Array will parameterize -> ::T { proto sub check(Array) {*} multi sub check(Array[T] --> True) { } multi sub check(Array:U --> False) { } multi sub check(Array:D $topic) { so $topic.all ~~ T } &check } where { !!! }; # Now they can both be typechecked: given TypedArray[Int:D] -> \IntArray { say @typed ~~ IntArray; # OUTPUT: True say @untyped ~~ IntArray; # OUTPUT: True say <foo bar baz> ~~ IntArray; # OUTPUT: False } ``` # DESCRIPTION `Kind::Subset::Parametric` enhances subsets with support for parameterization. This allows you to write subsets with generic `where` clauses. `Kind::Subset::Parametric` is documented. You can refer to the documentation for its trait and `MetamodelX::ParametricSubset` at any time using `WHY`. # TRAITS ## will parameterize ``` multi sub trait_mod:<will>(Mu \T where Subset, &body_block, :parameterize($)!) ``` This trait mixes the `MetamodelX::ParametricSubset` metarole into the HOW of the type it is applied to, which may only be a subset of some sort. Afterwards, the subset will be instantiated with its `&body_block`, which is what makes it possible to parameterize the subset. The main metamethod of interest this metarole provides is `parameterize`, which accepts arbitrary type argumentss. This is created using a name (generated similarly to how the name of a parametric role is generated), the refinee of the parametric subset (the value of `of`), and the return value of the body block when invoked with the arguments as its refinement (the value of `where`). For example, given an identity type: ``` subset Identity will parameterize { $_ } where { !!! }; ``` `Identity[Any]` may be written to produce: ``` subset ::('Identity[Any]') where Any; ``` Note the stubbed `where` clause. Parametric subsets can still be given a refinement when this trait is applied, which handles typechecking against the subset when it has not been parameterized. If it's not desirable for a parametric subset to typecheck without being parameterized, the `!!!` stub will throw. Historically, `...` was used, but failures don't necessarily sink when the typechecker's nqp is involved. The body block may be introspected with the `body_block` metamethod, which returns the body block it was parameterized with given a subset type. `set_body_block` must be called after being instantiated either by mixin on a HOW or by `&trait_mod:<does>` in order to replace this. Refer to `t/02-will.t` for more examples of how to use this trait. # AUTHOR Ben Davies (Kaiepi) # COPYRIGHT AND LICENSE Copyright 2022 Ben Davies This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## primitives.md class Metamodel::Primitives Metaobject that supports low-level type operations ```raku class Metamodel::Primitives {} ``` `Metamodel::Primitives` provides low-level operations for working with types, which are otherwise only available as implementation-dependent directives. These primitives are available as class methods. Here is an example that steals the metamodel instance from the [`Int`](/type/Int) class to create a custom type (usually you would create your own metaclass if you mess with something as low-level), which allows calling of just one method called `why`: ```raku my Mu $type := Metamodel::Primitives.create_type(Int.HOW, 'P6opaque'); $type.^set_name('why oh why?'); my %methods = why => sub ($) { say 42 }; Metamodel::Primitives.install_method_cache($type, %methods, :authoritative); $type.why; # 42 $type.list; CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::Method::NotFound: Method 'list' not found for invocant of class 'why oh why?'␤» ``` Every metaobject has the capacity to hold a parameterization cache. This is distinct from the `parameterize` metamethod backing parameterization syntax. For example, a package can be parametric in this low-level sense: ```raku package Cache { our sub parameterize(+args) is raw { Metamodel::Primitives.parameterize_type: $?PACKAGE, args } sub noop(Mu, Mu \args) is raw { args } BEGIN Metamodel::Primitives.set_parameterizer: $?PACKAGE, &noop; } ``` # [Methods](#class_Metamodel::Primitives "go to top of document")[§](#Methods "direct link") ## [method create\_type](#class_Metamodel::Primitives "go to top of document")[§](#method_create_type "direct link") ```raku method create_type(Mu $how, $repr = 'P6opaque') ``` Creates and returns a new type from a metaobject `$how` and a representation name. ## [method set\_package](#class_Metamodel::Primitives "go to top of document")[§](#method_set_package "direct link") ```raku method set_package(Mu $type, $package) ``` Sets the package associated with the type. ## [method install\_method\_cache](#class_Metamodel::Primitives "go to top of document")[§](#method_install_method_cache "direct link") ```raku method install_method_cache( Mu $type, %cache, :$authoritative = True) ``` Installs a method cache, that is, a mapping from method names to code objects. If `:authoritative` is missing, or set to `True`, then calls of methods that do not exist in the cache will throw an exception of type [`X::Method::NotFound`](/type/X/Method/NotFound). If `:authoritative` is set to `False`, the usual fallback mechanism are tried. ## [method configure\_type\_checking](#class_Metamodel::Primitives "go to top of document")[§](#method_configure_type_checking "direct link") ```raku method configure_type_checking( Mu $type, @cache, :$authoritative = True, :$call_accepts = False ) ``` Configures the type checking for `$type`. `@cache` is a list of known types against which `$type` checks positively (so in a classical class-based system, the type itself and all recursive superclasses). If `:authoritative` is missing or `True`, this type will fail checks against all types not in `@cache`. If `:call_accepts` is True, the method [ACCEPTS](/routine/ACCEPTS) will be called for type checks against this type. ## [method configure\_destroy](#class_Metamodel::Primitives "go to top of document")[§](#method_configure_destroy "direct link") ```raku method configure_destroy(Mu $type, $destroy) ``` Configures whether `DESTROY` methods are called (if present) when the garbage collector collects an object of this type (if `$destroy` is set to a true value). This comes with a performance overhead, so should only be set to a true value if necessary. ## [method compose\_type](#class_Metamodel::Primitives "go to top of document")[§](#method_compose_type "direct link") ```raku method compose_type(Mu $type, $configuration) ``` Composes `$type` (that is, finalizes it to be ready for instantiation). See <https://github.com/Raku/nqp/blob/master/docs/6model/repr-compose-protocol.markdown> for what `$configuration` can contain (until we have better docs, sorry). ## [method rebless](#class_Metamodel::Primitives "go to top of document")[§](#method_rebless "direct link") ```raku method rebless(Mu $object, Mu $type) ``` Changes `$object` to be of type `$type`. This only works if `$type` type-checks against the current type of `$object`, and if the storage of `$object` is a subset of that of `$type`. [[1]](#fn1) ## [method is\_type](#class_Metamodel::Primitives "go to top of document")[§](#method_is_type "direct link") ```raku method is_type(Mu \obj, Mu \type --> Bool:D) ``` Type-checks `obj` against `type` ## [method set\_parameterizer](#class_Metamodel::Primitives "go to top of document")[§](#method_set_parameterizer "direct link") ```raku method set_parameterizer(Mu \obj, &parameterizer --> Nil) ``` Initializes the parameterization cache for a metaobject. This incorporates the `&parameterize` routine to produce parameterizations to be cached. This is assumed to carry a signature compatible with `:(Mu $root, List:D $args)`, `$root` being the base metaobject for the parameterization, `$args` being the type arguments' object buffer. ## [method parameterize\_type](#class_Metamodel::Primitives "go to top of document")[§](#method_parameterize_type "direct link") ```raku method parameterize_type(Mu \obj, +parameters --> Mu) ``` Parameterizes a metaobject prepared by `set_parameterizer` with `parameters`. The resulting metaobject is cached by literal object comparisons with `=:=` for each element of `parameters`. *Containers tend to invalidate any match*. ## [method type\_parameterized](#class_Metamodel::Primitives "go to top of document")[§](#method_type_parameterized "direct link") ```raku method type_parameterized(Mu \obj --> Mu) ``` Returns the base metaobject from a parameterization given its resulting `obj`. Returns [`Mu`](/type/Mu) if none was ever performed. ## [method type\_parameters](#class_Metamodel::Primitives "go to top of document")[§](#method_type_parameters "direct link") ```raku method type_parameters(Mu \obj --> List:D) ``` Returns the type arguments' object buffer from a parameterization given its resulting `obj`. Dies if none was ever performed. ## [method type\_parameter\_at](#class_Metamodel::Primitives "go to top of document")[§](#method_type_parameter_at "direct link") ```raku method type_parameter_at(Mu \obj, Int:D \idx --> Mu) is raw ``` Returns a particular object from a parameterization given its resulting `obj` and an index, skipping the [`List`](/type/List)-building step of `type_parameters`. Dies if none was ever performed. 1 [[↑]](#fnret1) As of Raku 2019.11, this method requires [special arrangements](https://github.com/rakudo/rakudo/issues/3414#issuecomment-573251877).
## dist_cpan-SHLOMIF-CI-Gen.md # NAME CI-Gen - A Don't Repeat Yourself (DRY) framework for generating continuous integration scripts # SYNOPSIS ``` $ git clone ... $ zef install --force-install . $ ci-generate ``` # DESCRIPTION CI::Gen aims to be a continuous integration scriptology generation framework. Currently it is far from being generic enough. I don't know about you, but I find it tiresome to maintain all the .travis.yml / .appveyor.yml / etc. configurations for my repositories which are full of copy+paste and duplicate code. CI-Gen eventually aims to generate them based on the <https://en.wikipedia.org/wiki/Don%27t_repeat_yourself> principle . # Philosophy Bottom-up design and avoiding <https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it> . See <https://www.joelonsoftware.com/2002/01/23/rub-a-dub-dub/> : "This stuff went into classes which were not really designed — I simply added methods lazily as I discovered a need for them. (Somewhere, someone with a big stack of 4×6 cards is sharpening their pencil to poke my eyes out. What do you mean you didn’t design your classes?) " # AUTHOR Shlomi Fish [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018 Shlomi Fish This library is free software; you can redistribute it and/or modify it under the MIT/Expat license.
## registry.md class Encoding::Registry Management of available encodings ```raku class Encoding::Registry {} ``` `Encoding::Registry` is initialized with a list of encoding that is available for any Raku application, namely: * `utf8` * `utf8-c8` * `utf16` * `utf16le` * `utf16be` * `utf32`, `utf-32` * `ascii` * `iso-8859-1`, `iso_8859-1:1987`, `iso_8859-1`, `iso-ir-100`, `latin1`, `latin-1`, `csisolatin1`, `l1`, `ibm819`, `cp819` * `windows-1251` * `windows-1252` * `windows-932` # [Methods](#class_Encoding::Registry "go to top of document")[§](#Methods "direct link") ## [method name](#class_Encoding::Registry "go to top of document")[§](#method_name "direct link") ```raku method register(Encoding $enc --> Nil) ``` Register a new [`Encoding`](/type/Encoding). ## [method find](#class_Encoding::Registry "go to top of document")[§](#method_find "direct link") ```raku method find(Str() $name) ``` Finds an encoding by its name. Returns an `Encoding::Encoder` or `Encoding::Decoder`, depending on what had been registered.
## module-packages.md Module packages Creating module packages for code reuse *N.B.* "Module" is an overloaded term in Raku; this document focuses on use of the `module` declarator. # [What are modules?](#Module_packages "go to top of document")[§](#What_are_modules? "direct link") Modules, like classes and grammars, are a kind of [package](/language/packages). Module objects are instances of the `ModuleHOW` metaclass; this provides certain capabilities useful for creating namespaces, versioning, delegation and data encapsulation (see also [class](/syntax/class) and [role](/syntax/role)). To create a module, use the `module` declarator: ```raku module M {} say M.HOW; # OUTPUT: «Perl6::Metamodel::ModuleHOW.new␤» ``` Here we define a new module named `M`; introspection with `HOW` confirms that the metaclass underlying `M` is `Perl6::Metamodel::ModuleHOW`. ## [When to use modules](#Module_packages "go to top of document")[§](#When_to_use_modules "direct link") Modules are primarily useful for encapsulating code and data that do not belong inside a class or role definition. Module contents (classes, subroutines, variables, etc.) can be exported from a module with the `is export` trait; these are available in the caller's namespace once the module has been imported with `import` or `use`. A module can also selectively expose symbols within its namespace for qualified reference via `our`. ## [Working with modules](#Module_packages "go to top of document")[§](#Working_with_modules "direct link") To illustrate module scoping and export rules, let's begin by defining a simple module `M`: ```raku module M { sub greeting ($name = 'Camelia') { "Greetings, $name!" } our sub loud-greeting (--> Str) { greeting().uc } sub friendly-greeting is export { greeting('friend') } } ``` Recall that subroutines are lexically scoped unless otherwise specified (declarator [`sub`](/syntax/sub) is equivalent to `my sub`), so `greeting` in the above example is lexically scoped to the module and inaccessible outside of it. We've also defined `loud-greeting` with the `our` declarator, which means that in addition to being lexically scoped it is aliased in the module's symbol table. Finally, `friendly-greeting` is marked for export; it will be registered in the *caller's* symbol table when the module is imported: ```raku import M; # import the module say M::loud-greeting; # OUTPUT: «GREETINGS, CAMELIA!␤» say friendly-greeting; # OUTPUT: «Greetings, friend!␤» ``` # [Modules on disk](#Module_packages "go to top of document")[§](#Modules_on_disk "direct link") While `.raku` and `.rakumod` files are sometimes referred to as "modules", they are really just normal files that are loaded and compiled when you write `need`, `use` or `require`. For a `.rakumod` file to provide a module in the sense that we've been using, it needs to declare one with `module` as documented above. For example, by placing module `M` inside `Foo.rakumod`, we can load and use the module as follows: ```raku use Foo; # find Foo.rakumod, run need followed by import say M::loud-greeting; # OUTPUT: «GREETINGS, CAMELIA!␤» say friendly-greeting; # OUTPUT: «Greetings, friend!␤» ``` Note the decoupling between file and module names—a `.rakumod` file can declare zero or more modules with arbitrary identifiers. ## [File and module naming](#Module_packages "go to top of document")[§](#File_and_module_naming "direct link") Often we want a `.rakumod` file to provide a *single* module and nothing more. Here a common convention is for the file basename to match the module name. Returning to `Foo.rakumod`, it is apparent that it only provides a single module, `M`; in this case, we might want to rename `M` to `Foo`. The amended file would then read: ```raku module Foo { sub greeting ($name = 'Camelia') { "Greetings, $name!" } our sub loud-greeting (--> Str) { greeting().uc } sub friendly-greeting is export { greeting('friend') } } ``` which can be used more consistently by the caller (note the relationship between the `use Foo` and `Foo::`): ```raku use Foo; say Foo::loud-greeting; # OUTPUT: «GREETINGS, CAMELIA!␤» say friendly-greeting; # OUTPUT: «Greetings, friend!␤» ``` If `Foo.rakumod` is placed deeper within the source tree, e.g. at `lib/Utils/Foo.rakumod`, we can elect to name the module `Utils::Foo` to maintain consistency. ### [The `unit` keyword](#Module_packages "go to top of document")[§](#The_unit_keyword "direct link") Files that only provide a single module can be written more concisely with the `unit` keyword; `unit module` specifies that the rest of the compilation unit is part of the declared module. Here's `Foo.rakumod` rewritten with `unit`: ```raku unit module Foo; sub greeting ($name = 'Camelia') { "Greetings, $name!" } our sub loud-greeting (--> Str) { greeting().uc } sub friendly-greeting is export { greeting('friend') } ``` Everything following the unit declaration is part of the `Foo` module specification. (Note that `unit` can also be used with `class`, `grammar` and `role`.) ## [What happens if I omit `module`?](#Module_packages "go to top of document")[§](#What_happens_if_I_omit_module? "direct link") To better understand what the `module` declarator is doing in `Foo.rakumod`, let's contrast it with a variant file, `Bar.rakumod`, that omits the declaration. The subroutine definitions below are almost identical (the only difference is in the body of `greeting`, modified for clarity): ```raku sub greeting ($name = 'Camelia') { "Greetings from Bar, $name!" } our sub loud-greeting (--> Str) { greeting().uc } sub friendly-greeting is export { greeting('friend') } ``` As a reminder, here's how we used `Foo.rakumod` before, ```raku use Foo; say Foo::loud-greeting; # OUTPUT: «GREETINGS, CAMELIA!␤» say friendly-greeting; # OUTPUT: «Greetings, friend!␤» ``` and here's how we use `Bar.rakumod`, ```raku use Bar; say loud-greeting; # OUTPUT: «GREETINGS FROM BAR, CAMELIA!␤» say friendly-greeting; # OUTPUT: «Greetings from Bar, friend!␤» ``` Note the use of `loud-greeting` rather than `Bar::loud-greeting` as `Bar` is not a known symbol (we didn't create a `module` of that name in `Bar.rakumod`). But why is `loud-greeting` callable even though we didn't mark it for export? The answer is simply that `Bar.rakumod` doesn't create a new package namespace—`$?PACKAGE` is still set to `GLOBAL`—so when we declare `loud-greeting` as `our`, it is registered in the `GLOBAL` symbol table. ### [Lexical aliasing and safety](#Module_packages "go to top of document")[§](#Lexical_aliasing_and_safety "direct link") Thankfully, Raku protects us from accidentally clobbering call site definitions (e.g. builtins). Consider the following addition to `Bar.rakumod`: ```raku our sub say ($ignored) { print "oh dear\n" } ``` This creates a lexical alias, hiding the `say` builtin *inside* `Bar.rakumod` but leaving the caller's `say` unchanged. Consequently, the following call to `say` still works as expected: ```raku use Bar; say 'Carry on, carry on...'; # OUTPUT: «Carry on, carry on...␤» ```
## dist_zef-raku-community-modules-ASCII-To-Uni.md [![Actions Status](https://github.com/raku-community-modules/ASCII-To-Uni/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/ASCII-To-Uni/actions) [![Actions Status](https://github.com/raku-community-modules/ASCII-To-Uni/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/ASCII-To-Uni/actions) [![Actions Status](https://github.com/raku-community-modules/ASCII-To-Uni/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/ASCII-To-Uni/actions) # NAME ASCII::To::Uni - convert operators in Raku source files from ASCII to Unicode # SYNOPSIS ``` use ASCII::To::Uni; convert-file($filename); ``` # DESCRIPTION The `ASCII::To::Uni` distribution provides a basic (and incomplete) way to convert operators in your Raku-related source files from an ASCII version to Unicode symbol version. It doesn't support some operators and has some limitations. # SUBROUTINES This distribution has two basic subroutines: ## convert-file The `convert-file` subroutine takes a file name and by default point s output to a new file with extension like `file-name.uni.xtension`. A different path can be set with the `:new-path` named argument. It can rewrite file if the named argument `:rewrite` was specified with a `True` value. However, rewriting is not recommended, since this distribution way still be buggy and can mess up your work. ## convert-string The `convert-string` subroutine takes read-write string and converts it accordingly to operator table. ## HISTORY This distribution started as `Texas::To::Uni`, but since the use of the term "Texas" has been deprecated in favor of "ASCII", it felt like a good opportunity to change the name when reviving it as a Raku Community module. Note that the old name `Texas::To::Uni` is still available as a use target. # AUTHOR Alexander Kiryuhin # COPYRIGHT AND LICENSE Copyright 2016 - 2017 Alexander Kiryuhin Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dateish.md role Dateish Object that can be treated as a date ```raku role Dateish { ... } ``` Both [`Date`](/type/Date) and [`DateTime`](/type/DateTime) support accessing of the year, month and day-of-month represented in the object, as well as related functionality such as calculating the day of the week. # [Methods](#role_Dateish "go to top of document")[§](#Methods "direct link") ## [method year](#role_Dateish "go to top of document")[§](#method_year "direct link") ```raku method year(Date:D: --> Int:D) ``` Returns the year of the date. ```raku say Date.new('2015-12-31').year; # OUTPUT: «2015␤» say DateTime.new(date => Date.new('2015-12-24'), hour => 1).year; # OUTPUT: «2015␤» ``` ## [method month](#role_Dateish "go to top of document")[§](#method_month "direct link") ```raku method month(Date:D: --> Int:D) ``` Returns the month of the date (1..12). ```raku say Date.new('2015-12-31').month; # OUTPUT: «12␤» say DateTime.new(date => Date.new('2015-12-24'), hour => 1).month; # OUTPUT: «12␤» ``` ## [method day](#role_Dateish "go to top of document")[§](#method_day "direct link") ```raku method day(Date:D: --> Int:D) ``` Returns the day of the month of the date (1..31). ```raku say Date.new('2015-12-31').day; # OUTPUT: «31␤» say DateTime.new(date => Date.new('2015-12-24'), hour => 1).day; # OUTPUT: «24␤» ``` ## [method formatter](#role_Dateish "go to top of document")[§](#method_formatter "direct link") ```raku method formatter(Dateish:D:) ``` Returns the formatting function which is used for conversion to [`Str`](/type/Str). If none was provided at object construction, a default formatter is used. In that case the method will return a Callable type object. The formatting function is called by [DateTime method Str](/type/DateTime#method_Str) with the invocant as its only argument. ```raku my $dt = Date.new('2015-12-31'); # (no formatter specified) say $dt.formatter.^name; # OUTPUT: «Callable␤» my $us-format = sub ($self) { sprintf "%02d/%02d/%04d", .month, .day, .year given $self; }; $dt = Date.new('2015-12-31', formatter => $us-format); say $dt.formatter.^name; # OUTPUT: «Sub␤» say $dt; # OUTPUT: «12/31/2015␤» ``` ## [method is-leap-year](#role_Dateish "go to top of document")[§](#method_is-leap-year "direct link") ```raku method is-leap-year(Dateish:D: --> Bool:D) ``` Returns `True` if the year of the Dateish object is a leap year. ```raku say DateTime.new(:year<2016>).is-leap-year; # OUTPUT: «True␤» say Date.new("1900-01-01").is-leap-year; # OUTPUT: «False␤» ``` ## [method day-of-month](#role_Dateish "go to top of document")[§](#method_day-of-month "direct link") ```raku method day-of-month(Date:D: --> Int:D) ``` Returns the day of the month of the date (1..31). Synonymous to the `day` method. ```raku say Date.new('2015-12-31').day-of-month; # OUTPUT: «31␤» say DateTime.new(date => Date.new('2015-12-24'), hour => 1).day-of-month; # OUTPUT: «24␤» ``` ## [method day-of-week](#role_Dateish "go to top of document")[§](#method_day-of-week "direct link") ```raku method day-of-week(Date:D: --> Int:D) ``` Returns the day of the week, where 1 is Monday, 2 is Tuesday and Sunday is 7. ```raku say Date.new('2015-12-31').day-of-week; # OUTPUT: «4␤» say DateTime.new(date => Date.new('2015-12-24'), hour => 1).day-of-week; # OUTPUT: «4␤» ``` ## [method day-of-year](#role_Dateish "go to top of document")[§](#method_day-of-year "direct link") ```raku method day-of-year(Date:D: --> Int:D) ``` Returns the day of the year (1..366). ```raku say Date.new('2015-12-31').day-of-year; # OUTPUT: «365␤» say DateTime.new(date => Date.new('2015-03-24'), hour => 1).day-of-year; # OUTPUT: «83␤» ``` ## [method days-in-year](#role_Dateish "go to top of document")[§](#method_days-in-year "direct link") ```raku method days-in-year(Dateish:D: --> Int:D) ``` Returns the number of days in the year represented by the Dateish object: ```raku say Date.new("2016-01-02").days-in-year; # OUTPUT: «366␤» say DateTime.new(:year<2100>, :month<2>).days-in-year; # OUTPUT: «365␤» ``` Available as of the 2022.12 release of the Rakudo compiler. ## [method days-in-month](#role_Dateish "go to top of document")[§](#method_days-in-month "direct link") ```raku method days-in-month(Dateish:D: --> Int:D) ``` Returns the number of days in the month represented by the Dateish object: ```raku say Date.new("2016-01-02").days-in-month; # OUTPUT: «31␤» say DateTime.new(:year<10000>, :month<2>).days-in-month; # OUTPUT: «29␤» ``` ## [method week](#role_Dateish "go to top of document")[§](#method_week "direct link") ```raku method week() ``` Returns a list of two integers: the year, and the week number. This is because at the start or end of a year, the week may actually belong to the other year. ```raku my ($year, $week) = Date.new("2014-12-31").week; say $year; # OUTPUT: «2015␤» say $week; # OUTPUT: «1␤» say Date.new('2015-01-31').week; # OUTPUT: «(2015 5)␤» ``` ## [method week-number](#role_Dateish "go to top of document")[§](#method_week-number "direct link") ```raku method week-number(Date:D: --> Int:D) ``` Returns the week number (1..53) of the date specified by the invocant. The first week of the year is defined by ISO as the one which contains the fourth day of January. Thus, dates early in January often end up in the last week of the prior year, and similarly, the final few days of December may be placed in the first week of the next year. ```raku say Date.new("2014-12-31").week-number; # OUTPUT: «1␤» (first week of 2015) say Date.new("2016-01-02").week-number; # OUTPUT: «53␤» (last week of 2015) ``` ## [method week-year](#role_Dateish "go to top of document")[§](#method_week-year "direct link") ```raku method week-year(Date:D: --> Int:D) ``` Returns the week year of the date specified by the invocant. Normally `week-year` is equal to `Date.year`. Note however that dates early in January often end up in the last week of the prior year, and similarly, the final few days of December may be placed in the first week of the next year. ```raku say Date.new("2015-11-15").week-year; # OUTPUT: «2015␤» say Date.new("2014-12-31").week-year; # OUTPUT: «2015␤» (date belongs to the first week of 2015) say Date.new("2016-01-02").week-year; # OUTPUT: «2015␤» (date belongs to the last week of 2015) ``` ## [method weekday-of-month](#role_Dateish "go to top of document")[§](#method_weekday-of-month "direct link") ```raku method weekday-of-month(Date:D: --> Int:D) ``` Returns a number (1..5) indicating the number of times a particular day-of-week has occurred so far during that month, the day itself included. ```raku say Date.new("2003-06-09").weekday-of-month; # OUTPUT: «2␤» (second Monday of the month) ``` ## [method yyyy-mm-dd](#role_Dateish "go to top of document")[§](#method_yyyy-mm-dd "direct link") ```raku method yyyy-mm-dd(str $sep = "-" --> Str:D) ``` Returns the date in `YYYY-MM-DD` format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)). The optional positional argument `$sep`, which defaults to `-`, is a one-character separator placed between the different parts of the date. ```raku say Date.new("2015-11-15").yyyy-mm-dd; # OUTPUT: «2015-11-15␤» say DateTime.new(1470853583).yyyy-mm-dd; # OUTPUT: «2016-08-10␤» say Date.today.yyyy-mm-dd("/"); # OUTPUT: «2020/03/14␤» ``` ## [method mm-dd-yyyy](#role_Dateish "go to top of document")[§](#method_mm-dd-yyyy "direct link") ```raku method mm-dd-yyyy(str $sep = "-" --> Str:D) ``` Returns the date in `MM-DD-YYYY` format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)). The optional positional argument `$sep`, which defaults to `-`, is a one-character separator placed between the different parts of the date. ```raku say Date.new("2015-11-15").mm-dd-yyyy; # OUTPUT: «11-15-2015␤» say DateTime.new(1470853583).mm-dd-yyyy; # OUTPUT: «08-10-2016␤» say Date.today.mm-dd-yyyy("/"); # OUTPUT: «03/14/2020␤» ``` ## [method dd-mm-yyyy](#role_Dateish "go to top of document")[§](#method_dd-mm-yyyy "direct link") ```raku method dd-mm-yyyy(str $sep = "-" --> Str:D) ``` Returns the date in `DD-MM-YYYY` format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)). The optional positional argument `$sep`, which defaults to `-`, is a one-character separator placed between the different parts of the date. ```raku say Date.new("2015-11-15").dd-mm-yyyy; # OUTPUT: «15-11-2015␤» say DateTime.new(1470853583).dd-mm-yyyy; # OUTPUT: «10-08-2016␤» say Date.today.dd-mm-yyyy("/"); # OUTPUT: «14/03/2020␤» ``` ## [method daycount](#role_Dateish "go to top of document")[§](#method_daycount "direct link") ```raku method daycount(Dateish:D: --> Int:D) ``` Returns the number of days from the epoch Nov. 17, 1858, to the day of the invocant. The daycount returned by this method is the integral part of the [Modified Julian Day](https://en.wikipedia.org/wiki/Julian_day) (MJD) which is used routinely by astronomers, geodesists, scientists, and others. The MJD convention is designed to facilitate simplified chronological calculations. The fractional part of the MJD consists of the hours, minutes, and seconds of the using DateTime object converted to the equivalent fraction of 24 hours. Those two values added define the MJD of that instant. ```raku say Date.new('1995-09-27').daycount; # OUTPUT: «49987␤» ``` ## [method IO](#role_Dateish "go to top of document")[§](#method_IO "direct link") ```raku method IO(Dateish:D: --> IO::Path:D) ``` Returns an [`IO::Path`](/type/IO/Path) object representing the stringified value of the Dateish object: ```raku Date.today.IO.say; # OUTPUT: «"2016-10-03".IO␤» DateTime.now.IO.say; # OUTPUT: «"2016-10-03T11:14:47.977994-04:00".IO␤» ``` **PORTABILITY NOTE:** some operating systems (e.g. Windows) do not permit colons (`:`) in filenames, which would be present in [`IO::Path`](/type/IO/Path) created from a [`DateTime`](/type/DateTime) object. ## [method earlier](#role_Dateish "go to top of document")[§](#method_earlier "direct link") ```raku multi method earlier(Dateish:D: *%unit) multi method earlier(Dateish:D: @pairs) ``` Returns an object based on the current one, but with a date delta towards the past applied. Unless the given unit is `second` or `seconds`, the given value will be converted to an [`Int`](/type/Int). See [`.later`](/type/Dateish#method_later) for usage. It will generally be used through classes that implement this role, [`Date`](/type/Date) or [`DateTime`](/type/DateTime) ```raku my $d = Date.new('2015-02-27'); say $d.earlier(month => 5).earlier(:2days); # OUTPUT: «2014-09-25␤» my $d = DateTime.new(date => Date.new('2015-02-27')); say $d.earlier(month => 1).earlier(:2days); # OUTPUT: «2015-01-25T00:00:00Z␤» ``` If the resultant time has value `60` for seconds, yet no leap second actually exists for that time, seconds will be set to `59`: ```raku say DateTime.new('2008-12-31T23:59:60Z').earlier: :1day; # OUTPUT: «2008-12-30T23:59:59Z␤» ``` Negative offsets are allowed, though [later](/routine/later) is more idiomatic for that. If you need to use more than one unit, you will need to build them into a [`List`](/type/List) of [`Pair`](/type/Pair)s to use the second form of the method: ```raku say Date.new('2021-03-31').earlier( ( year => 3, month => 2, day => 8 ) ); # OUTPUT: «2018-01-23␤» ``` This feature was introduced in release 2021.02 of the Rakudo compiler. ## [method later](#role_Dateish "go to top of document")[§](#method_later "direct link") ```raku multi method later(DateTime:D: *%unit) ``` Returns an object based on the current one (belonging to any class that mixes this role in), but with a time delta applied. The time delta can be passed as a named argument where the argument name is the unit. Unless the given unit is `second` or `seconds`, the given value will be converted to an [`Int`](/type/Int). Allowed units are `second`, `seconds`, `minute`, `minutes`, `hour`, `hours`, `day`, `days`, `week`, `weeks`, `month`, `months`, `year`, `years`. Please note that the plural forms can only be used with the `later` and `earlier` methods. The `:2nd` form of colonpairs can be used as a compact and self-documenting way of specifying the delta: ```raku say DateTime.new('2015-12-24T12:23:00Z').later(:2years); # OUTPUT: «2017-12-24T12:23:00Z␤» ``` Since addition of several different time units is not commutative, only one unit may be passed (and the first multi will be used). ```raku my $d = DateTime.new(date => Date.new('2015-02-27')); say $d.later(month => 1).later(:2days); # OUTPUT: «2015-03-29T00:00:00Z␤» say $d.later(days => 2).later(:1month); # OUTPUT: «2015-04-01T00:00:00Z␤» say $d.later(days => 2).later(:month); # same, as +True === 1 ``` You can also (since release 2021.02 of the Rakudo compiler) pass several units at the same time, but you will have to join them in a [`List`](/type/List) to activate the second form: ```raku say DateTime.new(date => Date.new('2015-02-27')).later( (:1month, :2days) ) # OUTPUT: «2015-03-29T00:00:00Z␤» ``` If the resultant time has value `60` for seconds, yet no leap second actually exists for that time, seconds will be set to `59`: ```raku say DateTime.new('2008-12-31T23:59:60Z').later: :1day; # OUTPUT: «2009-01-01T23:59:59Z␤» ``` Negative offsets are allowed, though [earlier](/routine/earlier) is more idiomatic for that. Objects of type [`Date`](/type/Date) will behave in the same way: ```raku my $d = Date.new('2015-02-27'); say $d.later(month => 1).later(:2days); # OUTPUT: «2015-03-29␤» say $d.later(days => 2).later(:1month); # OUTPUT: «2015-04-01␤» say $d.later(days => 2).later(:month); # same, as +True === 1 ``` # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Dateish` raku-type-graph Dateish Dateish Mu Mu Any Any Any->Mu DateTime DateTime DateTime->Dateish DateTime->Any Date Date Date->Dateish Date->Any [Expand chart above](/assets/typegraphs/Dateish.svg)
## dist_github-CurtTilmes-GraphQL.md # Perl 6 GraphQL [![Build Status](https://travis-ci.org/CurtTilmes/Perl6-GraphQL.svg)](https://travis-ci.org/CurtTilmes/Perl6-GraphQL) A [Perl 6](https://perl6.org/) implementation of the [GraphQL](http://graphql.org/) standard. GraphQL is a query language for APIs originally created by Facebook. ## Intro Before we get into all the details, here's the Perl 6 GraphQL "Hello World" [hello.pl](https://github.com/CurtTilmes/Perl6-GraphQL/blob/master/eg/hello.pl) ``` use GraphQL; use GraphQL::Server; class Query { method hello(--> Str) { 'Hello World' } } my $schema = GraphQL::Schema.new(Query); GraphQL-Server($schema); ``` You can run this with a GraphQL query on the command line: ``` $ perl6 hello.pl --help Usage: hello.pl <query> hello.pl [--filename=<Str>] hello.pl [--port=<Int>] $ perl6 hello.pl '{hello}' { "data": { "hello": "Hello World" } } ``` You can even ask for information about the schema and types: ``` $ perl6 hello.pl '{ __schema { queryType { name } } }' { "data": { "__schema": { "queryType": { "name": "Query" } } } } $ perl6 hello.pl '{ __type(name: "Query") { fields { name type { name }}}}' { "data": { "__type": { "fields": [ { "name": "hello", "type": { "name": "String" } } ] } } } ``` ## Running as a server That's fine for the command line, but you can also easily wrap GraphQL into a web server to expose that API to external clients. GraphQL::Server uses the Perl 6 web framework [Bailador](https://github.com/ufobat/Bailador) to do that: ``` $ ./hello.pl Entering the development dance floor: http://0.0.0.0:3000 [2016-12-21T13:02:38Z] Started HTTP server. ``` The server takes any GraphQL query sent with HTTP POST to /graphql, executes it against the GraphQL Schema, and returns the result in JSON. There is one additional feature. If it receives a GET request to "/graphql", it sends back the [GraphiQL](https://github.com/graphql/graphiql) graphical interactive in-browser GraphQL IDE. ![](eg/hello-graphiql.png) You can use that to explore the schema (though the Hello World schema is very simple, that won't take long), and interactively construct and execute GraphQL queries. ## Embedding in a Cro server As an alternative to Bailador, you can use `Cro::HTTP::Router::GraphQL` to embed GraphQL into [Cro](http://mi.cro.services/) HTTP routes: ``` use GraphQL; use Cro::HTTP::Router::GraphQL; use Cro::HTTP::Router; use Cro::HTTP::Server; class Query { method hello(--> Str) { 'Hello World' } } my $schema = GraphQL::Schema.new(Query); my Cro::Service $hello = Cro::HTTP::Server.new: :host<localhost>, :port<10000>, application => route { get -> { redirect '/graphql' } get -> 'graphql' { graphiql } post -> 'graphql' { graphql($schema) } } $hello.start; react whenever signal(SIGINT) { $hello.stop; exit; } ``` You can mix/match with other routes you want your server to handle. There is also a `CroX::HTTP::Transform::GraphQL` you can easily delegate to from Cro routes: ``` route { delegate graphql => CroX::HTTP::Transform::GraphQL.new(:$schema, :graphiql); } ``` Pass in your GraphQL schema, and optional `:graphiql` to enable GraphiQL support on an http GET. `CroX::HTTP::Transform::GraphQL` is a `Cro::HTTP::Transform` that consumes `Cro::HTTP::Request`s and produces `Cro::HTTP::Response`s. It is still pretty basic. A planned enhancement is caching parsed GraphQL query documents. (Patches or advice welcome!) ## More documentation See [eg/usersexample.md](/eg/usersexample.md) for a more complicated example. See [slides](https://curttilmes.github.com/2017-GraphQL-PHLPM) from a presentation about Perl 6 GraphQL at the Philadelphia Perl Mongers. [GraphQL Documentation](/doc/GraphQL.md) 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.
## dist_cpan-TITSUKI-Terminal-Getpass.md [![Actions Status](https://github.com/titsuki/raku-Terminal-Getpass/workflows/test/badge.svg)](https://github.com/titsuki/raku-Terminal-Getpass/actions) # NAME Terminal::Getpass - A getpass implementation for Raku # SYNOPSIS ``` use Terminal::Getpass; my $password = getpass; say $password; ``` # DESCRIPTION Terminal::Getpass is a getpass implementation for Raku. ## METHODS ### getpass Defined as: ``` sub getpass(Str $prompt = "Password: ", IO::Handle $stream = $*ERR --> Str) is export ``` Reads password from a command line secretly and returns the text. # AUTHOR Itsuki Toyota [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018 Itsuki Toyota This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-TITSUKI-Math-Roman.md [![Actions Status](https://github.com/titsuki/raku-Math-Roman/workflows/test/badge.svg)](https://github.com/titsuki/raku-Math-Roman/actions) # NAME Math::Roman - A roman numerals converter # SYNOPSIS ``` use Math::Roman; 10R.say; # X 1996R.say; # MCMXCVI (1000R + 996R)R.say; # MCMXCVI (Math::Roman.new: "MCMXCVI").as-arabic.say; # 1996 ``` # DESCRIPTION Math::Roman is a roman numerals converter ## CONSTRUCTOR Defined as: ``` multi method new(Str $roman) { self.bless(value => to-arabic($roman)) } multi method new(Int $arabic) { self.bless(value => $arabic) } method Bridge { $!value } sub postfix:<R> is export { Math::Roman.new: $^value }; ``` Creates a `Math::Roman` instance internally and returns it as an integer or a str corresponding with the context. Postfix `R` provides a syntactic sugar for converting arabic numerals into roman numerals (e.g., `10R` returns `X`). ## METHODS ### as-arabic Defined as: ``` method as-arabic(--> Int) ``` Returns the instance as an arabic numeral. ## SUBS ### to-roman Defined as: ``` sub to-roman(Int $n where $n >= 0 --> Str) ix export ``` Returns the roman numeral form of the integer `$n`. ### to-arabic Defined as: ``` sub to-arabic(Str $r, $pos = 0 --> Int) is export ``` Returns the arabic numeral form of the roman numeral `$r`. # AUTHOR Itsuki Toyota [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Itsuki Toyota This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-azawawi-File-Zip.md ## File::Zip [Build Status](https://travis-ci.org/azawawi/perl6-file-zip) [Build status](https://ci.appveyor.com/project/azawawi/perl6-file-zip/branch/master) This module provides a [Perl 6](http://perl6.org) API to the [ZIP file format](https://en.wikipedia.org/wiki/Zip_(file_format)). ***Note:*** This module is a work in progress. Please see its project status [here](https://github.com/azawawi/perl6-file-zip/blob/master/README.md#project-status). ## Example ``` use File::Zip; my $zip-file = File::Zip.new(file-name => 'test.zip'); # List the files in the archive say $_.perl for $zip-file.files; # Unzip the archive into given directory $zip-file.unzip(directory => 'output'); ``` For more examples, please see the <examples> folder. ## Project Status * Improve documentation * More examples * Get all file members API * Extract a zip file using deflate * Write tests ## Installation To install it using zef (a module management tool bundled with Rakudo Star): ``` $ zef install File::Zip ``` ## Testing To run tests: ``` $ prove -e perl6 ``` ## Author Ahmad M. Zawawi, [azawawi](https://github.com/azawawi/) on #perl6 ## License MIT License
## die.md die Combined from primary sources listed below. # [In Exception](#___top "go to top of document")[§](#(Exception)_routine_die "direct link") See primary documentation [in context](/type/Exception#routine_die) for **routine die**. ```raku multi die() multi die(*@message) multi die(Exception:D $e) method die(Exception:D:) ``` Throws a fatal `Exception`. The default exception handler prints each element of the list to [`$*ERR`](/language/variables#index-entry-%24%2AERR) (STDERR). ```raku die "Important reason"; ``` If the subroutine form is called without arguments, the value of [`$!` variable](/syntax/$!) is checked. If it is set to a [`.DEFINITE`](/language/mop#DEFINITE) value, its value will be used as the `Exception` to throw if it's of type `Exception`, otherwise, it will be used as payload of [`X::AdHoc`](/type/X/AdHoc) exception. If `$!` is not `.DEFINITE`, [`X::AdHoc`](/type/X/AdHoc) with string `"Died"` as payload will be thrown. `die` will print by default the line number where it happens ```raku die "Dead"; # OUTPUT: «(exit code 1) Dead␤ # in block <unit> at /tmp/dead.raku line 1␤␤» ``` However, that default behavior is governed at the `Exception` level and thus can be changed to anything we want by capturing the exception using `CATCH`. This can be used, for instance, to suppress line numbers. ```raku CATCH { default { .payload.say } }; die "Dead" # OUTPUT: «Dead␤» ```
## dist_cpan-HANENKAMP-Smack.md # NAME Smack - Reference implementation of the Web API for Raku # DESCRIPTION This aims to be the reference implementation of the P6W standard. The aims of this project include: * Providing an example implementation of P6W to aid the development of other servers. * Provide a set of tools and utilities to aid in the building of applications and middleware. * Provide a testing ground for future extensions and modifications to P6W. * Provide a testing ground for determining how difficult P6W is to implement at all layers of development. # STATUS The current status of this code is VERY ALPHA. The P6W specification is still wet on the paper and this implementation is not really even complete yet. The standalone server works and is generally compatible with the 0.9.Draft of RakuWAPI. There is practically no documentation at this point. At this point, I am in the process of porting the features of Plack to Smack as a way of testing whether or not the P6W specification is feasible. The goal is to make sure that the easy things are easy and the hard things are possible. # FAQ ## How does this differ from Crust? (This information may be dated. I haven't checked up on it recently.) The Raku [Crust](https://github.com/tokuhirom/p6-Crust) project is a port of the older [PSGI specification](https://metacpan.org/pod/release/MIYAGAWA/PSGI-1.102/PSGI.pod) for Perl 5. The PSGI specification is a basically serial specification implemented around HTTP/1.0 and parts of HTTP/1.1. This has several weaknesses when it comes to supporting modern protocols, dealing with high-performance applications, and application portability. RakuWAPI aims to be a forward looking specification that incorporates built-in support for HTTP/2, WebSockets, and other concurrent and/or asynchronous web-related protocols. It also aims to better support high-performance applications and address the portability weaknesses in PSGI. Smack aims to be the reference implementation for [RakuWAPI](https://github.com/zostay/RakuWAPI) instead. ## How does this differ from Cro? Cro provides a very different API for writing asynchronous web applications. It aims to produce applications, for the web or otherwise, that are built around the concept of pipelines that transform input into output. These are built according to the specific API provided by Cro. Smack (through the specification in RakuWAPI) provides something similar, but instead of thinking of an application as a pipeline that transforms inputs into outputs, it treats the application as an asynchronous subroutine. Pipelining is performed by wrapping that subroutine in another subroutine rather than creating another transformer class as is done in Cro. RakuWAPI could be implemented as a transformer in Cro or Cro could be made to run within a Smack web server, but they are fundamentally different ways of thinking about a similar problem each with their own trade-offs. ## Can I participate? PATCHES WELCOME!! Please help! If you have any interest in participating in the development of this project, please have a look. There is precious little documentation as things are still changing a little too quickly in RakuWAPI as yet. If you need help please shoot me an email, file an issue, or ping me on IRC. Please note that I am lurking as zostay on irc.perl.org and Freenode, but it is unusual that I am actually looking at my chat window, so email is your best bet (see below for my email). ## How do I get started? * Install raku (For example, on Mac OSX, `brew install rakudo-star` (rakudo is a compiler for Raku. That command will put the `perl6` executable in your path. See <http://raku.org/> for more details or how to install on other platforms). * Clone this repository (e.g. `git clone https://github.com/zostay/Smack.git`) * Go into the Smack directory and run `zef install . --deps-only` * Run `perl6 t/env.t` to run a few tests and see if things are working at a basic level * If that looks good, a simple `Hello World` example is provided in `examples/hello-world.wapi`: #!smackup # vim: set ft=perl6 : use v6; sub app(%env) { start { 200, [ Content-Type => 'text/plain' ], 'Hello, World!'; } } * until you have everything in your path, you can start the application with `perl6 -I lib/ bin/smackup --app=examples/hello-world.wapi` * that command should show you some debugging output, like this: Starting on http://0.0.0.0:5000/... * You should now be able to open a browser and put `http://0.0.0.0:5000/` in the location bar, and see a message familiar to programmers world wide. * There are other examples in the t/apps directory that you can look at to start to get an idea of how it works. # CONTRIBUTORS Sterling Hanenkamp `<[email protected]>` # LICENSE AND COPYRIGHT Copyright 2019 Andrew Sterling Hanenkamp. This is free software made available under the Artistic 2.0 license.
## classtut.md ## Chunk 1 of 2 Classes and objects A tutorial about creating and using classes in Raku Raku provides a rich built-in syntax for defining and using classes. It makes writing classes expressive and short for most cases, but also provides mechanisms to cover the rare corner cases. # [A quick overview](#Classes_and_objects "go to top of document")[§](#A_quick_overview "direct link") Let's start with an example to give an overview: ```raku class Rectangle { has Int $.length = 1; has Int $.width = 1; method area(--> Int) { return $!length * $!width; } } my $r1 = Rectangle.new(length => 2, width => 3); say $r1.area(); # OUTPUT: «6␤» ``` We define a new *Rectangle* class using the [class](/language/objects#Classes) keyword. It has two [attributes](#Attributes), `$!length` and `$!width` introduced with the [has](/syntax/has) keyword. Both default to `1`. Read only accessor methods are automatically generated. (Note the `.` instead of `!` in the declaration, which triggers the generation. Mnemonic: `!` resembles a closed door, `.` an open one.) The [method](/language/objects#Methods) named `area` will return the area of the rectangle. It is rarely necessary to explicitly write a constructor. An automatically inherited default constructor called [new](/language/objects#Object_construction) will automatically initialize attributes from named parameters passed to the constructor. # [The Task example](#Classes_and_objects "go to top of document")[§](#The_Task_example "direct link") As a more elaborate example the following piece of code implements a dependency handler. It showcases custom constructors, private and public attributes, methods, and various aspects of signatures. It's not a lot of code, and yet the result is interesting and useful. It will be used as an example throughout the following sections. ```raku class Task { has &!callback is built; has Task @!dependencies is built; has Bool $.done; method new(&callback, *@dependencies) { return self.bless(:&callback, :@dependencies); } method add-dependency(Task $dependency) { push @!dependencies, $dependency; } method perform() { unless $!done { .perform() for @!dependencies; &!callback(); $!done = True; } } } my $eat = Task.new({ say 'eating dinner. NOM!' }, Task.new({ say 'making dinner' }, Task.new({ say 'buying food' }, Task.new({ say 'making some money' }), Task.new({ say 'going to the store' }) ), Task.new({ say 'cleaning kitchen' }) ) ); $eat.perform(); ``` # [Class](#Classes_and_objects "go to top of document")[§](#Class "direct link") Raku, like many other languages, uses the `class` keyword to define a class. The block that follows may contain arbitrary code, just as with any other block, but classes commonly contain state and behavior declarations. The example code includes attributes (state), introduced through the `has` keyword, and behaviors, introduced through the `method` keyword. # [Attributes](#Classes_and_objects "go to top of document")[§](#Attributes "direct link") In the `Task` class, the first three lines inside the block all declare attributes (called *fields* or *instance storage* in other languages) using the `has` declarator. Just as a `my` variable cannot be accessed from outside its declared scope, attributes are never directly accessible from outside of the class (this is in contrast to many other languages). This *encapsulation* is one of the key principles of object oriented design. ## [Twigil `$!`](#Classes_and_objects "go to top of document")[§](#Twigil_$! "direct link") The first declaration specifies instance storage for a callback (i.e. a bit of code to invoke in order to perform the task that an object represents): ```raku has &!callback is built; ``` The `&` sigil indicates that this attribute represents something invocable. The `!` character is a *twigil*, or secondary sigil. A twigil forms part of the name of the variable. In this case, the `!` twigil emphasizes that this attribute is private to the class. The attribute is *encapsulated*. Private attributes will not be set by the default constructor by default, which is why we add the `is built` trait to allow just that. Mnemonic: `!` looks like a closed door. The second declaration also uses the private twigil: ```raku has Task @!dependencies is built; ``` However, this attribute represents an array of items, so it requires the `@` sigil. These items each specify a task that must be completed before the present one is completed. Furthermore, the type declaration on this attribute indicates that the array may only hold instances of the `Task` class (or some subclass of it). ## [Twigil `$.`](#Classes_and_objects "go to top of document")[§](#Twigil_$. "direct link") The third attribute represents the state of completion of a task: ```raku has Bool $.done; ``` This scalar attribute (with the `$` sigil) has a type of [`Bool`](/type/Bool). Instead of the `!` twigil, the `.` twigil is used. While Raku does enforce encapsulation on attributes, it also saves you from writing accessor methods. Replacing the `!` with a `.` both declares a private attribute and an accessor method named after the attribute. In this case, both the attribute `$!done` and the accessor method `done` are declared. It's as if you had written: ```raku has Bool $!done; method done() { return $!done } ``` Note that this is not like declaring a public attribute, as some languages allow; you really get *both* a private attribute and a method, without having to write the method by hand. You are free instead to write your own accessor method, if at some future point you need to do something more complex than returning the value. ## [`is rw` trait](#Classes_and_objects "go to top of document")[§](#is_rw_trait "direct link") Note that using the `.` twigil has created a method that will provide read-only access to the attribute. If instead the users of this object should be able to reset a task's completion state (perhaps to perform it again), you can change the attribute declaration: ```raku has Bool $.done is rw; ``` The `is rw` trait causes the generated accessor method to return a container so external code can modify the value of the attribute. ## [`is built` trait](#Classes_and_objects "go to top of document")[§](#is_built_trait "direct link") ```raku has &!callback is built; ``` By default private attributes are not automatically set by the default constructor. (They are private after all.) In the above example we want to allow the user to provide the initial value but keep the attribute otherwise private. The `is built` trait allows to do just that. One can also use it to do the opposite for public attributes, i.e. prevent them to be automatically initialized with a user provided value, but still generate the accessor method: ```raku has $.done is built(False); ``` Above declaration makes sure one can't construct finished tasks, but still allow users to look if a task is done. The `is built` trait was introduced in Rakudo version 2020.01. ## [`is required` trait](#Classes_and_objects "go to top of document")[§](#is_required_trait "direct link") Providing a value for an attribute during initialization is optional by default. Which in the task example makes sense for all three, the `&!callback`, the `@!dependencies` and the `$.done` attribute. But lets say we want to add another attribute, `$.name`, that holds a tasks name and we want to force the user to provide a value on initialization. We can do that as follows: ```raku has $.name is required; ``` ## [Default values](#Classes_and_objects "go to top of document")[§](#Default_values "direct link") You can also supply default values to attributes (which works equally for those with and without accessors): ```raku has Bool $.done = False; ``` The assignment is carried out at object build time. The right-hand side is evaluated at that time, and can even reference earlier attributes: ```raku has Task @!dependencies; has $.ready = not @!dependencies; ``` Writable attributes are accessible through writable containers: ```raku class a-class { has $.an-attribute is rw; } say (a-class.new.an-attribute = "hey"); # OUTPUT: «hey␤» ``` This attribute can also be accessed using the `.an-attribute` or `.an-attribute()` syntax. See also [the `is rw` trait on classes](/language/typesystem#trait_is_rw) for examples on how this works on the whole class. # [Class variables](#Classes_and_objects "go to top of document")[§](#Class_variables "direct link") A class declaration can also include *class variables*, declared with `my` or `our`, which are variables whose value is shared by all instances, and can be used for things like counting the number of instantiations or any other shared state. So *class variables* act similarly to *static* variables known from other programming languages. They look the same as normal (non class) lexical variables (and in fact they are the same): ```raku class Str-with-ID is Str { my $counter = 0; our $our-counter = 0; has Str $.string; has Int $.ID is built(False); submethod TWEAK() { $counter++; $our-counter++; $!ID = $counter; } } class Str-with-ID-and-tag is Str-with-ID { has Str $.tag; } say Str-with-ID.new(string => 'First').ID; # OUTPUT: «1␤» say Str-with-ID.new(string => 'Second').ID; # OUTPUT: «2␤» say Str-with-ID-and-tag.new( string => 'Third', tag => 'Ordinal' ).ID; # OUTPUT: «3␤» say $Str-with-ID::our-counter; # OUTPUT: «3␤» ``` *Class variables* are shared by all subclasses, in this case `Str-with-ID-and-tag`. Additionally, when the package scope `our` declarator is used, the variable is visible via their fully qualified name (FQN), while lexically scoped `my` variables are "private". This is the exact behavior that `my` and `our` also show in non class context. *Class variables* act similarly to *static* variables in many other programming languages. ```raku class Singleton { my Singleton $instance; method new {!!!} submethod instance { $instance = Singleton.bless unless $instance; $instance; } } ``` In this implementation of the *Singleton* pattern a *class variable* is used to save the instance. ```raku class HaveStaticAttr { my Int $.foo = 5; } ``` Class attributes may also be declared with a secondary sigil – in a similar manner to instance attributes – that will generate read-only accessors if the attribute is to be public. Default values behave as expected and are assigned only once. # [Methods](#Classes_and_objects "go to top of document")[§](#Methods "direct link") While attributes give objects state, methods give objects behaviors. Back to our `Task` example. Let's ignore the `new` method temporarily; it's a special type of method. Consider the second method, `add-dependency`, which adds a new task to a task's dependency list: ```raku method add-dependency(Task $dependency) { push @!dependencies, $dependency; } ``` In many ways, this looks a lot like a `sub` declaration. However, there are two important differences. First, declaring this routine as a method adds it to the list of methods for the current class, thus any instance of the `Task` class can call it with the `.` method call operator. Second, a method places its invocant into the special variable `self`. The method itself takes the passed parameter – which must be an instance of the `Task` class – and `push`es it onto the invocant's `@!dependencies` attribute. The `perform` method contains the main logic of the dependency handler: ```raku method perform() { unless $!done { .perform() for @!dependencies; &!callback(); $!done = True; } } ``` It takes no parameters, working instead with the object's attributes. First, it checks if the task has already completed by checking the `$!done` attribute. If so, there's nothing to do. Otherwise, the method performs all of the task's dependencies, using the `for` construct to iterate over all of the items in the `@!dependencies` attribute. This iteration places each item – each a `Task` object – into the topic variable, `$_`. Using the `.` method call operator without specifying an explicit invocant uses the current topic as the invocant. Thus the iteration construct calls the `.perform()` method on every `Task` object in the `@!dependencies` attribute of the current invocant. After all of the dependencies have completed, it's time to perform the current `Task`'s task by invoking the `&!callback` attribute directly; this is the purpose of the parentheses. Finally, the method sets the `$!done` attribute to `True`, so that subsequent invocations of `perform` on this object (if this `Task` is a dependency of another `Task`, for example) will not repeat the task. ## [Private methods](#Classes_and_objects "go to top of document")[§](#Private_methods "direct link") Just like attributes, methods can also be private. Private methods are declared with a prefixed exclamation mark. They are called with `self!` followed by the method's name. In the following implementation of a `MP3TagData` class to extract [ID3v1](https://en.wikipedia.org/wiki/ID3) metadata from an mp3 file, methods `parse-data`, `can-read-format`, and `trim-nulls` are private methods while the remaining ones are public methods: ```raku class MP3TagData { has $.filename where { .IO ~~ :e }; has Str $.title is built(False); has Str $.artist is built(False); has Str $.album is built(False); has Str $.year is built(False); has Str $.comment is built(False); has Int $.genre is built(False); has Int $.track is built(False); has Str $.version is built(False); has Str $.type is built(False) = 'ID3'; submethod TWEAK { with $!filename.IO.open(:r, :bin) -> $fh { $fh.seek(-128, SeekFromEnd); my $tagdata = $fh.read(128); self!parse-data: $tagdata; $fh.close; } else { warn "Failed to open file." } } method !parse-data($data) { if self!can-read-format($data) { my $offset = $data.bytes - 128; $!title = self!trim-nulls: $data.subbuf($offset + 3, 30); $!artist = self!trim-nulls: $data.subbuf($offset + 33, 30); $!album = self!trim-nulls: $data.subbuf($offset + 63, 30); $!year = self!trim-nulls: $data.subbuf($offset + 93, 4); my Int $track-flag = $data.subbuf($offset + 97 + 28, 1).Int; $!track = $data.subbuf($offset + 97 + 29, 1).Int; ($!version, $!comment) = $track-flag == 0 && $!track != 0 ?? ('1.1', self!trim-nulls: $data.subbuf($offset + 97, 28)) !! ('1.0', self!trim-nulls: $data.subbuf($offset + 97, 30)); $!genre = $data.subbuf($offset + 97 + 30, 1).Int; } } method !can-read-format(Buf $data --> Bool) { self!trim-nulls($data.subbuf(0..2)) eq 'TAG' } method !trim-nulls(Buf $data --> Str) { $data.decode('utf-8').subst(/\x[0000]+/, '') } } ``` To call a private method of another class, the caller has to be trusted by the callee. A trust relationship is declared with [`trusts`](/language/typesystem#trait_trusts) and the class to be trusted must already be declared. Calling a private method of another class requires an instance of that class and the fully qualified name (FQN) of the method. A trust relationship also allows access to private attributes. ```raku class B {...} class C { trusts B; has $!hidden = 'invisible'; method !not-yours () { say 'hidden' } method yours-to-use () { say $!hidden; self!not-yours(); } } class B { method i-am-trusted () { my C $c.=new; $c!C::not-yours(); } } C.new.yours-to-use(); # the context of this call is GLOBAL, and not trusted by C B.new.i-am-trusted(); ``` Trust relationships are not subject to inheritance. To trust the global namespace, the pseudo package `GLOBAL` can be used. # [Construction](#Classes_and_objects "go to top of document")[§](#Construction "direct link") The object construction mechanisms described up to now suffice for most use cases. But if one actually needs to tweak object construction more than said mechanisms allow, it's good to understand how object construction works in more detail. Raku is rather more liberal than many languages in the area of constructors. A constructor is anything that returns an instance of the class. Furthermore, constructors are ordinary methods. You inherit a default constructor named `new` from the base class [`Mu`](/type/Mu), but you are free to override `new`, as the Task example does: ```raku method new(&callback, *@dependencies) { return self.bless(:&callback, :@dependencies); } ``` ## [bless](#Classes_and_objects "go to top of document")[§](#bless "direct link") The biggest difference between constructors in Raku and constructors in languages such as C# and Java is that rather than setting up state on a somehow already magically created object, Raku constructors create the object themselves. They do this by calling the [bless](/routine/bless) method, also inherited from [`Mu`](/type/Mu). The `bless` method expects a set of named parameters to provide the initial values for each attribute. The example's constructor turns positional arguments into named arguments, so that the class can provide a nicer constructor for its users. The first parameter is the callback (the thing which will execute the task). The rest of the parameters are dependent `Task` instances. The constructor captures these into the `@dependencies` slurpy array and passes them as named parameters to `bless` (note that `:&callback` uses the name of the variable – minus the sigil – as the name of the parameter). One should refrain from putting logic other than reformulating the parameters in the constructor, because constructor methods are not recursively called for parent classes. This is different from e.g. Java. Declaring `new` as a `method` and not as a `multi method` prevents access to the default constructor. +So if you intend to keep the default constructor available, use `multi method new`. ## [`TWEAK`](#Classes_and_objects "go to top of document")[§](#TWEAK "direct link") After `bless` has initialized the classes attributes from the passed values, it will in turn call `TWEAK` for each class in the inheritance hierarchy. `TWEAK` gets passed all the arguments passed to bless. This is where custom initialization logic should go. Remember to always make `TWEAK` a [submethod](/type/Submethod) and not a normal `method`. If in a class hierarchy a class contains a `TWEAK` method (declared as a `method` instead of a `submethod`) that method is inherited to its subclass and will thus be called twice during construction of the subclass! ## [`BUILD`](#Classes_and_objects "go to top of document")[§](#BUILD "direct link") It is possible to disable the automatic attribute initialization and perform the initialization of attributes oneself. To do so one needs to write a custom `BUILD` submethod. There are several edge cases one needs to be aware of and take into account though. This is detailed in the [Object Construction Reference](/language/objects#Object_construction). Because of the difficulty of using `BUILD`, it is recommended to only make use of it when none of the other approaches described above suffices. # [Destruction](#Classes_and_objects "go to top of document")[§](#Destruction "direct link") Raku is a garbage collecting language. This means that one usually doesn't need to care about cleaning up objects, because Raku does so automatically. Raku does not give any guarantees as to when it will clean up a given object though. It usually does a cleanup run only if the runtime needs the memory, so we can't rely on when it's going to happen. To run custom code when an object is cleaned up one can use the `DESTROY` submethod. It can for example be used to close handles or supplies or delete temporary files that are no longer going to be used. As garbage collection can happen at arbitrary points during the runtime of our program, even in the middle of some totally unrelated piece of code in a different thread, we must make sure to not assume any context in our `DESTROY` submethod. ```raku my $in_destructor = 0; class Foo { submethod DESTROY { $in_destructor++ } } my $foo; for 1 .. 6000 { $foo = Foo.new(); } say "DESTROY called $in_destructor times"; ``` This might print something like `DESTROY called 5701 times` and possibly only kicks in after we have stomped over former instances of `Foo` a few thousand times. We also can't rely, on the order of destruction. Same as `TWEAK`: Make sure to always declare `DESTROY` as a `submethod`. # [Consuming our class](#Classes_and_objects "go to top of document")[§](#Consuming_our_class "direct link") After creating a class, you can create instances of the class. Declaring a custom constructor provides a simple way of declaring tasks along with their dependencies. To create a single task with no dependencies, write: ```raku my $eat = Task.new({ say 'eating dinner. NOM!' }); ``` An earlier section explained that declaring the class `Task` installed a type object in the namespace. This type object is a kind of "empty instance" of the class, specifically an instance without any state. You can call methods on that instance, as long as they do not try to access any state; `new` is an example, as it creates a new object rather than modifying or accessing an existing object. Unfortunately, dinner never magically happens. It has dependent tasks: ```raku my $eat = Task.new({ say 'eating dinner. NOM!' }, Task.new({ say 'making dinner' }, Task.new({ say 'buying food' }, Task.new({ say 'making some money' }), Task.new({ say 'going to the store' }) ), Task.new({ say 'cleaning kitchen' }) ) ); ``` Notice how the custom constructor and the sensible use of whitespace makes task dependencies clear. Finally, the `perform` method call recursively calls the `perform` method on the various other dependencies in order, giving the output: 「output」 without highlighting ``` ``` making some money going to the store buying food cleaning kitchen making dinner eating dinner. NOM! ``` ``` ## [A word on types](#Classes_and_objects "go to top of document")[§](#A_word_on_types "direct link") Declaring a class creates a new *type object* which, by default, is installed into the current package (just like a variable declared with `our` scope). This type object is an "empty instance" of the class. For example, types such as [`Int`](/type/Int) and [`Str`](/type/Str) refer to the type object of one of the Raku built-in classes. One can call methods on these type objects. So there is nothing special with calling the `new` method on a type object. You can use the `.DEFINITE` method to find out if what you have is an instance or a type object: ```raku say Int.DEFINITE; # OUTPUT: «False␤» (type object) say 426.DEFINITE; # OUTPUT: «True␤» (instance) class Foo {}; say Foo.DEFINITE; # OUTPUT: «False␤» (type object) say Foo.new.DEFINITE; # OUTPUT: «True␤» (instance) ``` In function signatures one can use so called type "smileys" to only accept instances or type objects: ```raku multi foo (Int:U) { "It's a type object!" } multi foo (Int:D) { "It's an instance!" } say foo Int; # OUTPUT: «It's a type object!␤» say foo 42; # OUTPUT: «It's an instance!␤» ``` # [Inheritance](#Classes_and_objects "go to top of document")[§](#Inheritance "direct link") Object Oriented Programming provides the concept of inheritance as one of the mechanisms for code reuse. Raku supports the ability for one class to inherit from one or more classes. When a class inherits from another class it informs the method dispatcher to follow the inheritance chain to look for a method to dispatch. This happens both for standard methods defined via the `method` keyword and for methods generated through other means, such as attribute accessors. ```raku class Employee { has $.salary; } class Programmer is Employee { has @.known_languages is rw; has $.favorite_editor; method code_to_solve( $problem ) { return "Solving $problem using $.favorite_editor in " ~ $.known_languages[0]; } } ``` Now, any object of type Programmer can make use of the methods and accessors defined in the Employee class as though they were from the Programmer class. ```raku my $programmer = Programmer.new( salary => 100_000, known_languages => <Raku Perl Erlang C++>, favorite_editor => 'vim' ); say $programmer.code_to_solve('halting problem'), " will get \$ {$programmer.salary()}"; # OUTPUT: «Solving halting problem using vim in Raku will get $100000␤» ``` ## [Overriding inherited methods](#Classes_and_objects "go to top of document")[§](#Overriding_inherited_methods "direct link") Classes can override methods and attributes defined by parent classes by defining their own. The example below demonstrates the `Baker` class overriding the `Cook`'s `cook` method. ```raku class Cook is Employee { has @.utensils is rw; has @.cookbooks is rw; method cook( $food ) { say "Cooking $food"; } method clean_utensils { say "Cleaning $_" for @.utensils; } } class Baker is Cook { method cook( $confection ) { say "Baking a tasty $confection"; } } my $cook = Cook.new( utensils => <spoon ladle knife pan>, cookbooks => 'The Joy of Cooking', salary => 40000 ); $cook.cook( 'pizza' ); # OUTPUT: «Cooking pizza␤» say $cook.utensils.raku; # OUTPUT: «["spoon", "ladle", "knife", "pan"]␤» say $cook.cookbooks.raku; # OUTPUT: «["The Joy of Cooking"]␤» say $cook.salary; # OUTPUT: «40000␤» my $baker = Baker.new( utensils => 'self cleaning oven', cookbooks => "The Baker's Apprentice", salary => 50000 ); $baker.cook('brioche'); # OUTPUT: «Baking a tasty brioche␤» say $baker.utensils.raku; # OUTPUT: «["self cleaning oven"]␤» say $baker.cookbooks.raku; # OUTPUT: «["The Baker's Apprentice"]␤» say $baker.salary; # OUTPUT: «50000␤» ``` Because the dispatcher will see the `cook` method on `Baker` before it moves up to the parent class the `Baker`'s `cook` method will be called. To access methods in the inheritance chain, use [re-dispatch](/language/functions#Re-dispatching) or the [MOP](/type/Metamodel/ClassHOW#method_can). ## [Multiple inheritance](#Classes_and_objects "go to top of document")[§](#Multiple_inheritance "direct link") As mentioned before, a class can inherit from multiple classes. When a class inherits from multiple classes the dispatcher knows to look at both classes when looking up a method to search for. Raku uses the [C3 algorithm](https://en.wikipedia.org/wiki/C3_linearization) to linearize multiple inheritance hierarchies, which is better than depth-first search for handling multiple inheritance. ```raku class GeekCook is Programmer is Cook { method new( *%params ) { push( %params<cookbooks>, "Cooking for Geeks" ); return self.bless(|%params); } } my $geek = GeekCook.new( books => 'Learning Raku', utensils => ('stainless steel pot', 'knife', 'calibrated oven'), favorite_editor => 'MacVim', known_languages => <Raku> ); $geek.cook('pizza'); $geek.code_to_solve('P =? NP'); ``` Now all the methods made available to the Programmer and the Cook classes are available from the GeekCook class. While multiple inheritance is a useful concept to know and occasionally use, it is important to understand that there are more useful OOP concepts. When reaching for multiple inheritance it is good practice to consider whether the design wouldn't be better realized by using roles, which are generally safer because they force the class author to explicitly resolve conflicting method names. For more information on roles, see [Roles](/language/objects#Roles). ## [`also`](#Classes_and_objects "go to top of document")[§](#The_also_declarator "direct link") Classes to be inherited from can be listed in the class declaration body by prefixing the `is` trait with `also`. This also works for the role composition trait `does`. ```raku class GeekCook { also is Programmer; also is Cook; # ... } role A {}; role B {}; class C { also does A; also does B; # ... } ``` # [Introspection](#Classes_and_objects "go to top of document")[§](#Introspection "direct link") Introspection is the process of gathering information about some objects in your program, not by reading the source code, but by querying the object (or a controlling object) for some properties, such as its type. Given an object `$o` and the class definitions from the previous sections, we can ask it a few questions: ```raku my Programmer $o .= new; if $o ~~ Employee { say "It's an employee" }; say $o ~~ GeekCook ?? "It's a geeky cook" !! "Not a geeky cook"; say $o.^name; say $o.raku; say $o.^methods(:local)».name.join(', '); ``` The output might look like this: 「output」 without highlighting ``` ``` It's an employee Not a geeky cook Programmer Programmer.new(known_languages => ["Perl", "Python", "Pascal"], favorite_editor => "gvim", salary => "too small") code_to_solve, known_languages, favorite_editor ``` ``` The first two tests each smartmatch against a class name. If the object is of that class, or of an inheriting class, it returns `True`. So the object in question is of class `Employee` or one that inherits from it, but not `GeekCook`. The call `$o.^name` tells us the type of `$o`; in this case `Programmer`. `$o.raku` returns a string that can be executed as Raku code, and reproduces the original object `$o`. While this does not work perfectly in all cases, it is very useful for debugging simple objects. [[1]](#fn1) The syntax of calling a method with `.^` instead of a single dot means that it is actually a method call on its *metaclass*, which is a class managing the properties of the `Programmer` class – or any other class you are interested in. This metaclass enables other ways of introspection too: ```raku say $o.^attributes.join(', '); say $o.^parents.map({ $_.^name }).join(', '); ``` Finally `$o.^name` calls the `name` method on the metaobject, which unsurprisingly returns the class name. Given an object `$mp3` and the `MP3TagData` class definition from the section [Private methods](/language/classtut#Private_methods), we can inquire about its public methods with `.^methods`: ```raku my $mp3 = MP3TagData.new(filename => 'football-head.mp3'); say $mp3.^methods(:local); # OUTPUT: (TWEAK filename title artist album year comment genre track version # type Submethod+{is-hidden-from-backtrace}.new) ``` `$mp3.^methods(:local)` produces a list of [`Method`](/type/Method)s that can be called on `$mp3`. The `:local` named argument limits the returned methods to those defined in the `MP3TagData` class and excludes the inherited methods; `MP3TagData` inherits from no class, so providing `:local` makes no difference. To check if a type object (or an instance object) implements a certain public method, use the [`.^find-method`](/routine/find_method) metamethod, which returns the method object if it exists. Otherwise, it returns [`Mu`](/type/Mu). ```raku say $mp3.^find_method('name'); # OUTPUT: «(Mu)␤» say $mp3.^find_method('artist'); # OUTPUT: «artist␤» ``` Type objects can also be introspected for its private methods. However, public and private methods don't use the same APIs, and thus different metamethods must be used: [`.^private_methods`](/routine/private_methods) and [`.^find_private_method`](/routine/find_private_method). ```raku say $mp3.^private_methods; # OUTPUT: «(parse-data can-read-format trim-nulls)␤» say $mp3.^find_private_method('parse-data'); # OUTPUT: «parse-data␤» say $mp3.^find_private_method('remove-nulls'); # OUTPUT: «(Mu)␤» ``` Introspection is very useful for debugging and for learning the language and new libraries. When a function or method returns an object you don't know about, by finding its type with `.^name`, seeing a construction recipe for it with `.raku`, and so on, you'll get a good idea of what its return value is. With `.^methods`, you can learn what you can do with the class. But there are other applications too. For instance, a routine that serializes objects to a bunch of bytes needs to know the attributes of that object, which it can find out via introspection. ## [Overriding default gist method](#Classes_and_objects "go to top of document")[§](#Overriding_default_gist_method "direct link") Some classes might need their own version of `gist`, which overrides the terse way they are printed when called to provide a default representation of the class. For instance, [exceptions](/language/exceptions#Uncaught_exceptions) might want to write just the `payload` and not the full object so that it is clearer what to see what's happened. However, this isn't limited to exceptions; you can do that with every class: ```raku class Cook
## classtut.md ## Chunk 2 of 2 { has @.utensils is rw; has @.cookbooks is rw; method cook( $food ) { return "Cooking $food"; } method clean_utensils { return "Cleaning $_" for @.utensils; } multi method gist(Cook:U:) { '⚗' ~ self.^name ~ '⚗' } multi method gist(Cook:D:) { '⚗ Cooks with ' ~ @.utensils.join( " ‣ ") ~ ' using ' ~ @.cookbooks.map( "«" ~ * ~ "»").join( " and ") } } my $cook = Cook.new( utensils => <spoon ladle knife pan>, cookbooks => ['Cooking for geeks','The French Chef Cookbook']); say Cook.gist; # OUTPUT: «⚗Cook⚗» say $cook.gist; # OUTPUT: «⚗ Cooks with spoon ‣ ladle ‣ knife ‣ pan using «Cooking for geeks» and «The French Chef Cookbook»␤» ``` Usually you will want to define two methods, one for the class and another for class instances; in this case, the class method uses the alembic symbol, and the instance method, defined below it, aggregates the data we have on the cook to show it in a narrative way. ## [A practical introspection example](#Classes_and_objects "go to top of document")[§](#A_practical_introspection_example "direct link") When one creates a new class, it is sometimes useful to have informative (and safe) introspection accessible more easily as a public method. For example, the following class is used to hold attributes for a record row in a CSV spreadsheet with a header row defining its field (attribute) names. ```raku unit class CSV-Record; #| Field names and values for a CSV row has $last; has $first; #...more fields (attributes)... method fields(--> List) { #| Return a list of the the attribute names (fields) #| of the class instance my @attributes = self.^attributes; my @names; for @attributes -> $a { my $name = $a.name; # The name is prefixed by its sigil and twigil # which we don't want $name ~~ s/\S\S//; @names.push: $name; } @names } method values(--> List) { #| Return a list of the values for the attributes #| of the class instance my @attributes = self.^attributes; my @values; for @attributes -> $a { # Syntax is not obvious my $value = $a.get_value: self; @values.push: $value; } @values } ``` We use it with a simple CSV file with contents: 「csv」 without highlighting ``` ``` last, first #...more fields... Wall, Larry Conway, Damian ``` ``` Load the first record and show its contents: ```raku my $record = CSV-Record.new: :$last, :$first; say $record.fields.raku; # OUTPUT: «["last", "first"]␤» say $record.values.raku; # OUTPUT: «["Wall", "Larry"]␤» ``` Note that practically we would have designed the class so that it has the `fields` list as a constant since its values are the same for all class objects: ```raku constant @fields = <last first>; method fields(--> List) { @fields } ``` Downsides of using the introspective method for attribute names include slightly more processing time and power and the probable need to remove the sigil and twigil for public presentation. 1 [[↑]](#fnret1) For example, closures cannot easily be reproduced this way; if you don't know what a closure is don't worry. Also current implementations have problems with dumping cyclic data structures this way, but they are expected to be handled correctly by `.raku` at some point.
## dist_zef-raku-community-modules-Number-Bytes-Human.md [![Actions Status](https://github.com/raku-community-modules/Number-Bytes-Human/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Number-Bytes-Human/actions) [![Actions Status](https://github.com/raku-community-modules/Number-Bytes-Human/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Number-Bytes-Human/actions) [![Actions Status](https://github.com/raku-community-modules/Number-Bytes-Human/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Number-Bytes-Human/actions) # NAME Number::Bytes::Human - Convert byte count into an easy to read format # SYNOPSIS ``` # Functional interface use Number::Bytes::Human :functions; my $size = format-bytes 1024; # '1K' my $bytes = parse-bytes '1.0K'; # 1024 # OO Interface my Number::Bytes::Human; my $human = Number::Bytes::Human.new; my $size = $human.format(1024); # '1K' my $bytes = $human.parse('1.0K'); # 1024 ``` # DESCRIPTION This is the Raku re-write of CPAN's `Number::Bytes::Human` module. Special thanks to the original author: Adriano R. Ferreira. The `Number::Bytes::Humani` module converts large numbers of bytes into a more human friendly format, e.g. '15G'. The functionality of this module will be similar to the `-h` switch on Unix commands like `ls`, `du`, and `df`. Currently the module rounds to the nearest whole unit. From the FreeBSD man page of df: <http://www.freebsd.org/cgi/man.cgi?query=df> ``` "Human-readable" output. Use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to four or fewer using base 2 for sizes. byte B kilobyte K = 2**10 B = 1024 B megabyte M = 2**20 B = 1024 * 1024 B gigabyte G = 2**30 B = 1024 * 1024 * 1024 B terabyte T = 2**40 B = 1024 * 1024 * 1024 * 1024 B petabyte P = 2**50 B = 1024 * 1024 * 1024 * 1024 * 1024 B exabyte E = 2**60 B = 1024 * 1024 * 1024 * 1024 * 1024 * 1024 B zettabyte Z = 2**70 B = 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 B yottabyte Y = 2**80 B = 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 B ``` # AUTHOR Douglas L. Jenkins # COPYRIGHT AND LICENSE Copyright 2016 - 2017 Douglas L. Jenkins Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-jaffa4-Dependency-Sort.md # Dependency-Sort This is a Perl6 module. It serialises a list of dependencies or it performs a topological sort on directed graph. Example: ``` my %h; # this represents one node my %g; %h<itemid> = 1; # itemid should be unique for each rach %g<itemid> = 2; %h<name> = '1'; %g<name> = '2'; my %j = ( "itemid", 3, "name", 3 ); my %j4 = ( "itemid", 4, "name", 4 ); my $s = Dependency::Sort.new(); $s.add_dependency( %h, %g ); # this means %h depends on %g $s.add_dependency( %h, %j ); $s.add_dependency( %j, %j4 ); $s.add_dependency( %j, %g ); $s.add_dependency( %g, %j ); if !$s.serialise # returns false if there is an error { die $s.error_message; # the error message, meaning circular reference } else { # list of nodes in result... starting with independent ones.. then less dependent ones say $s.result.perl; # prints independent ones first } ```
## dist_zef-jnthn-HTTP-HPACK.md # HTTP::HPACK [![Build Status](https://travis-ci.org/jnthn/p6-http-hpack.svg?branch=master)](https://travis-ci.org/jnthn/p6-http-hpack) ## Synopsis Decoding: ``` my $decoder = HTTP::HPACK::Decoder.new; my @headers = $decoder.decode-headers($buf); say "{.name}: {.value} ({.indexing})" for @headers; ``` Encoding: ``` my @headers = HTTP::HPACK::Header.new( name => ':method', value => 'GET' ), HTTP::HPACK::Header.new( name => 'password', value => 'correcthorsebatterystaple', indexing => HTTP::HPACK::Indexing::NeverIndexed ); my $encoder = HTTP::HPACK::Encoder.new; my $buf = $encoder.encode-headers(@headers); ``` ## Description HPACK is the HTTP/2 header compression algorithm. This module implements encoding (compression) and decoding (decompression) of the HPACK format, as specified in RFC 7541. A HTTP/2 connection will typically have an instance of the decoder (to decompress incoming headers) and an instance of the encoder (to compress outgoing headers). ## Notes on specific features ### Huffman compression Decoding of headers compressed using the Huffman codes (set out in the RFC) takes place automatically. By default, the encoder will not apply Huffman compression. To enable this, construct it with the `huffman` option set to `True`: ``` my $encoder = HTTP::HPACK::Encoder.new(:huffman); ``` ### Dynamic table management The dynamic table size can be limited by passing the `dynamic-table-limit` option when constructing either the encoder or decoder: ``` my $decoder = HTTP::HPACK::Decoder.new(dynamic-table-limit => 256); ``` It is also possible to introspect the current dynamic table size: ``` say $decoder.dynamic-table-size; ``` The size is computed according to the algorithm in RFC 7541 Section 4.1. ## Thread safety Instances of HTTP::HPACK::Header are immutable and so safe to share and access concurrently. Instances of HTTP::HPACK::Decoder and HTTP::HPACK::Encoder are stateful (as a result of the dynamic table), and so a given instance may not be used concurrently. This is not a practical problem, since headers may only be processed in the order they are being received or transmitted anyway. ## Known issues * The Huffman code termination handling has not been validated to be completely up to specification, and so may fail to signal errors in some cases where the Huffman code is terminated in a bogus way.
## dist_zef-witawayar-Asserter.md ## Asserter Be assertive in the form `assert EXPR, MESSAGE?` ``` use Asserter; # Without a custom message, expression itself and its value are reported my $val = Empty; assert $val; #= Assertion failed: `$val` is not true; it evaluates to `Empty` # You can say what you like assert $val.&prime-factors.pick.is-prime, "mathematics gone wrong"; #= Assertion failed: mathematics gone wrong # If condition is truthful, short-circuits, i.e., MESSAGE is not evaluated assert True, destroy-the-universe(); #= Universe is still fine at this point # The error is CATCHable as: { CATCH { when X::Assertion { ... } } assert ...; } # If more than 2 things are supplied, it errs in compile time assert $val, "message", "and some more"; #`[ ===SORRY!=== Error while compiling some/file.raku That's too assertive; expected 1 or 2 things, got 3 at some/file.raku:5 ------> assert $val, "message", "and some more"⏏; ] ``` ### .WHAT, .WHY, .HOW Sometimes you want to make sure something is something in the program flow; `assert` does that for you, like in C, Java, Python and others. It compiles to something like `die MESSAGE unless EXPR`, which a programmer could be lazy enough not to write in full. So this module refines the main slang to do that with the word `assert`. #### Installation Using [pakku](https://github.com/hythm7/Pakku): ``` pakku add Asserter ```
## dist_cpan-VRURG-Async-Workers.md # NAME `Async::Workers` - Asynchronous threaded workers # SYNOPSIS ``` use Async::Workers; my $wm = Async::Workers.new( :max-workers(5) ); for 1..10 -> $n { $wm.do-async: { sleep 1.rand; say "Worker #$n"; } } await $wm; ``` # DESCRIPTION This module provides an easy way to execute a number of jobs in parallel while allowing to keep the resources consumed by your code under control. Both OO and procedural interfaces are provided. ## Reliability This module has been tested by running 20k repetitions of it's test suite using 56 parallel processes. This doesn't prove there're no bugs, but what can be told for certain is that within the tested scenarios the robustness is high enough. ## Terminology * *job* is what gets executed. Depending on context, a *job* could be an instance of `Async::Workers::Job` class, or a user provided code object. * *worker* is an instance of `Async::Workers::Worker` class. It is controlling a dedicated thread in which the job code is ran. * *worker manager* or just *manager* is an instance of `Async::Workers` class which controls the execution flow and manages workers. ## How it works. The goal is achieved by combining a *queue of jobs* and a number of pre-spawned threads controlled by *workers*. A job is picked from the queue by a currently unoccupied worker and the code object associated with it is invoked. Since the number of workers is limited it is easier to predict and plan CPU usage. Yet, it is still possible to over-use memory and cause heavy swapping or even overflows in cases when there is too many jobs are produced and an average one takes longer to complete than it is needed to generate a new one. To provide some control over this situation one can define *hi* and *lo* thresholds on the queue size. When the queue contains as many jobs, as defined by the *hi* threshold, `do-async` method blocks upon receiving a new job request and unblocks only when the queue shortens down to its *lo* threshold. The worker manager doesn't start workers until the first job is sent to the queue. It is also possible to shutdown all workers if they're no longer needed. Some internal events are reported with messages from `Async::Workers::Msg`. See the `on_msg` method below. # ATTRIBUTES ## `max-workers` Maximum number of workers. Defaults to `$*KERNEL.cpu-cores`. ## `max-jobs` Set the maximum number of jobs a worker should process before stopping and letting the manager to spawn a new one. The functionality is not activated if the attribute is left undefined. ## `lo-threshold`, `hi-threshold` Low and high thresholds of the queue size. ## `queued` Current queue size. If the queue has been blocked due to reaching `hi-threshold` then jobs awaiting for unblock are not counted toward this value. ## `running` The number of currently occupied workers. ## `completed` A `Promise` which is kept when manager completes all jobs after transitioning into *shutdown* state. When this happens the job queue is closed and all workers are requested to stop. Submission of a new job with `do-async` at this point will re-vivify the queue and return the manager into working state. In case of an internal failure the promise will be broken with an exception. ## `empty` A `Promise` which is kept each time the queue gets emptied. Note that the initially empty queue is not reflected with this attribute. Only when the queue contained at least one element and then went down to zero length this promise is kept. In other words, it happens when `Async::Workers::Msg::Queue::Empty` is emitted. Immediately after being kept the attribute gets replaced with a fresh `Promise`. So that the following example will finish only if the queue has been emptied twice: ``` await $wm.empty; await $wm.empty; ``` ## `quiet` If set to *True* then no exceptions thrown by jobs are reported. In this case it is recommended to monitor messages for `Async::Workers::Msg::Job::Died`. # METHODS ## `do-async( &code, |params --> Async::Workers::Job )` Takes a `&code` object and wraps it into a job object. `params` are passed to `&code` when it gets executed. This method blocks if `hi-threshold` is defined and the queue size has reached the limit. If no error happens then the method returns an `Async::Workers::Job` instance. Otherwise it may throw either `X::Manager::Down` if the manager is in `shutdown` or `completed` status; or it may throw `X::Manager::NoQueue` if somehow the job queue has not been initialized properly. ## `shutdown` Switches the manager into *shutdown* state and closes the job queue. Since the queue might still contain some incomplete jobs it is likely to take some time until the `completed` promise gets kept. Normally it'd be helpful to `await` for the manager: ``` my $wm = Async::Workers.new(...); ... $wm.shutdown; await $wm; ``` In this case the execution blocks until the job queue is emptied. Note that at this point `completed` might still not been fulfilled because workers are being shutting down in the meanwhile. ## `workers` Returns the number of started workers. ## `workers( UInt $num )` Sets the maximum number of workers (`max-workers` attribute). Can be used at any time without shutting down the manager: ``` $wm = Async::Worker.new: :max-workers(20); $wm.do-async: &job1 for ^$repetitions; $wm.workers($wm.workers - 5); $wm.do-async: &job2 for ^$repetitions; ``` If user increases the number of workers then as many additional ones are started as necessary. On the contrary, if the number of workers is reduced then as many of them are requested to stop as needed to meet user's demand. **Note** that this is done by injecting special jobs. It means that for a really long queue it may take quite a time before the extra workers receive the stop command. This behaviour may change in the future. ## `set-threshold( UInt :$lo, Num :$hi )` Dynamically sets high and low queue thresholds. The high might be set to `Inf` to define unlimited queue size. Note that this would translate into undefined value of `hi-threshold` attribute. ## `on_msg( &callback )` Submits a `Async::Workers::Msg` message object to user code passed in `&callback`. Internally this method does tapping on a message and returns a resulting `Tap` object (see documentation on `Supply`). The following messages can currently be emitted by the manager (names are shortened to not include `Async::Workers::Msg::` prefix): * `Shutdown` - when the manager is switched into shutdown state * `Complete` - when manager completed all jobs and shut down all workers * `Exception` - when an internal failure is intercepted; the related exception object is stored in attribute `exception` * `Worker` - not emitted, a base class for other `Worker` messages. Defines attribute `worker` which contains the worker object * `Worker::Started` - when a new worker thread has started * `Worker::Complete` - when a worker finishes * `Worker::Died` - when a worker throws. `exception` attribute will then contain the exception thrown. This message normally should not be seen as it signals about an internal error. * `Queue` – not emitted, a base class for other `Queue` messages. Defines attribute `size` which contains queue size at the moment when message was emitted. * `Queue::Inc` - queue size inceased; i.e. a new job submitted. Note that if the queue has reached the *hi* threshold then a job passed to `do-async` doesn't make it into the queue and thus no message is emitted until the queue is unblocked. * `Queue::Dec` – a job has finished and the queue size is reduced * `Queue::Full` - *hi* threshold is reached * `Queue::Low` - queue size reduced down to *lo* threshold * `Queue::Empty` – the queue was emtied * `Job` – not emitted, a parent class of job-related messages. Defines `job` attribute which holds a `Async::Workers::Job` object. * `Job::Enter` - emitted right before a worker is about to invoke a job * `Job::Complete` – emitted right after a job finishes * `Job::Died` – when a job throws. `exception` attribute contains the exception object. # HELPER SUBS ## `stop-worker($rc?, :$soft = False)` Bypasses to the current worker `stop` method. If called from within a job code it would cause the worker controlling the job to stop. If this would reduce the number of workers to less than `max-workers` then the manager will spawn as many new ones as needed: ``` $wm.do-async: { if $something-went-wrong { stop-worker } } ``` Note that the job would be stopped too, unless `:soft` parameter is used. In this case both the job and its worker will be allowed to complete. The worker will stop after the job is done. # PROCEDURAL Procedural interface hides a singleton object behind it. The following subs are exported by the module: ## `async-workers( |params --> Async::Workers:D )` Returns the singleton object. Creates it if necessary. If supplied with parameters they're passed to the constructor. If singleton is already created then the parameters are ignored. ## `do-async` Bypasses to the corresponding method on the singleton. ``` do-async { say "My task"; } ``` ## `shutdown-workers` Bypasses to `shutdown` on the singleton. # AUTHOR Vadim Belman [[email protected]](mailto:[email protected]) # LICENSE Artistic License 2.0 See the *LICENSE* file in this distribution.
## dist_zef-antononcube-Math-DistanceFunctions-Native.md # Math::DistanceFunctions::Native [![Actions Status](https://github.com/antononcube/Raku-LibAccelerate-DistanceFunctions/actions/workflows/linux.yml/badge.svg)](https://github.com/antononcube/Raku-LibAccelerate-DistanceFunctions/actions) [![Actions Status](https://github.com/antononcube/Raku-LibAccelerate-DistanceFunctions/actions/workflows/macos.yml/badge.svg)](https://github.com/antononcube/Raku-LibAccelerate-DistanceFunctions/actions) [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) Raku package with distance functions implemented in C. Apple's Accelerate library is used if available. The primary motivation for making this library is to have fast sorting and nearest neighbors computations over collections of LLM-embedding vectors. --- ## Usage examples ### Regular vectors Make a large (largish) collection of large vectors and find Euclidean distances over them: ``` use Math::DistanceFunctions::Native; my @vecs = (^1000).map({ (^1000).map({1.rand}).cache.Array }).Array; my @searchVector = (^1000).map({1.rand}); my $start = now; my @dists = @vecs.map({ euclidean-distance($_, @searchVector)}); my $tend = now; say "Total time of computing {@vecs.elems} distances: {round($tend - $start, 10 ** -6)} s"; say "Average time of a single distance computation: {($tend - $start) / @vecs.elems} s"; ``` ``` # Total time of computing 1000 distances: 0.63326 s # Average time of a single distance computation: 0.0006332598499999999 s ``` ### `CArray` vectors Use `CArray` vectors instead: ``` use NativeCall; my @cvecs = @vecs.map({ CArray[num64].new($_) }); my $cSearchVector = CArray[num64].new(@searchVector); $start = now; my @cdists = @cvecs.map({ euclidean-distance($_, $cSearchVector)}); $tend = now; say "Total time of computing {@cvecs.elems} distances: {round($tend - $start, 10 ** -6)} s"; say "Average time of a single distance computation: {($tend - $start) / @cvecs.elems} s"; ``` ``` # Total time of computing 1000 distances: 0.002994 s # Average time of a single distance computation: 2.994124e-06 s ``` I.e., we get ≈ 200 times speed-up using `CArray` vectors and the functions of this package. ### Edit distance The loading of this package automatically loads the (C-implemented) function `edit-distance` of ["Math::DistanceFunctions::Edit"](https://github.com/antononcube/Raku-Math-DistanceFunctions-Edit). Here is an example usage: ``` edit-distance('racoon', 'raccoon') ``` ``` # 1 ```
## dist_github-alabamenhu-Test-Inline.md # Test::Inline An lightweight Raku module allowing tests anywhere in modules (thus potentially enabling access to implementation details). This module was inspired by an [r/rakulang post](https://www.reddit.com/r/rakulang/comments/ih8tc9) by **codesections**, who expressed a desire to have test files be more closely connected with their associated modules. While this technique doesn't remove the code from distribution versions, it *does* allow for testing *inside of* modules/classes/etc. To use, simply add the trait `is test` to a `Sub` anywhere in your code. There is really only a single restriction * *The `Sub` must take no arguments* (Use dynamic variables to pass data if you need to) Here is a somewhat contrived example that should show nicely how it can be integrated. ``` unit module Rectangle; use Test::Inline; has Point $.a; # bottom left has Point $.b; # top right sub calculate-area($x, $y) { $x * $y } sub distance( $a, $b) { abs $a - $b } method area { calculate-area distance($!a.x, $!b.x), distance($!a.y, $!b.y) } method overlap(Rectangle $other) { ... } sub t-distance is test { use Test; is distance( 2,4), 2; is distance(-2,4), 6; ... } sub t-area is test { use Test; is calculate-area(1,3), 3; is calculate-area(8,3), 24; ... } ``` This marks `t-area` and `t-distance` as special subs that contains tests. Because they are inside of `Rectangle`, they can access its lexically scoped subs or variables, which a normal test file cannot. Each test sub can contain or do whatever it wants but it's *strongly* recommended to `use Test` and take advantage of its routines, like in the example. Each test sub is treated as a subtest (ha!) of the package it's included in. To actually run the tests, just add the option `:testing` to import in the special sub `inline-testing` in a test file. When this is called, it will cycle through all subs tagged as tests, grouping them by packages: ``` use Test; use Test::Inline :testing; # The first step is to 'use' each module that contains # testable subs. Nothing else needs to be done here. use Rectangle; # load any modules with use Circle; # subs that have the use Trapezoid; # 'is test' trait # Then, initiate the inline testing # (counts as a single test with subtests) inline-testing; # Conclude testing in the .t file done-testing(); ``` ## Version history * **v0.1** * Initial release * All features should work * If no issues are found, I'll bump version to 1.0 at the end of 2020. ## License and Copyright Licensed under the Artist License 2.0. © 2020 Matthew Stephen Stuckwisch
## dist_cpan-UFOBAT-I18N-LangTags.md [![Build Status](https://travis-ci.org/ufobat/p6-I18N-LangTags.svg?branch=master)](https://travis-ci.org/ufobat/p6-I18N-LangTags) # NAME I18N::LangTags - ported from Perl5 # SYNOPSIS ``` use I18N::LangTags; ``` # DESCRIPTION Language tags are a formalism, described in RFC 3066 (obsoleting 1766), for declaring what language form (language and possibly dialect) a given chunk of information is in. This library provides functions for common tasks involving language tags as they are needed in a variety of protocols and applications. Please see the "See Also" references for a thorough explanation of how to correctly use language tags. # FUNCTIONS * `is_language_tag(Str:D $lang1 --> Bool)` Returns `True` if `$lang1` is a formally valid language tag. ``` is_language_tag("fr") # is True is_language_tag("x-jicarilla") # is False # Subtags can be 8 chars long at most -- 'jicarilla' is 9 is_language_tag("sgn-US") # is True # That's American Sign Language is_language_tag("i-Klikitat") # is True # True without regard to the fact noone has actually # registered Klikitat -- it's a formally valid tag is_language_tag("fr-patois") # is True # Formally valid -- altho descriptively weak! is_language_tag("Spanish") # is False is_language_tag("french-patois") # is False # No good -- first subtag has to be 2 or 3 chars long -- see RFC3066 is_language_tag("x-borg-prot2532") # is True # Yes, subtags can contain digits, as of RFC3066 ``` * `extract_language_tags(Str:D $text --> Seq)` Returns a list of whatever looks like formally valid language tags in `$text`. Not very smart, so don't get too creative with what you want to feed it. ``` extract_language_tags("fr, fr-ca, i-mingo") # returns: ('fr', 'fr-ca', 'i-mingo') extract_language_tags("It's like this: I'm in fr -- French!") # returns: ('It', 'in', 'fr') # (So don't just feed it any old thing.) ``` * `same_language_tag(Str:D $lang1, Str:D $lang2 --> Bool)` Returns `True` if `$lang1` and `$lang2` are acceptable variant tags representing the same language-form. ``` same_language_tag('x-kadara', 'i-kadara') # is True # (The x/i- alternation doesn't matter) same_language_tag('X-KADARA', 'i-kadara') # is True # (...and neither does case) same_language_tag('en', 'en-US') # is False # (all-English is not the SAME as US English) same_language_tag('x-kadara', 'x-kadar') # is False # (these are totally unrelated tags) same_language_tag('no-bok', 'nb') # is True # (no-bok is a legacy tag for nb (Norwegian Bokmal)) ``` `same_language_tag` works by just seeing whether `encode_language_tag($lang1)` is the same as `encode_language_tag($lang2)`. (Yes, I know this function is named a bit oddly. Call it historic reasons.) * `similarity_language_tag($lang1, $lang2 --> Int)` Returns an integer representing the degree of similarity between tags `$lang1` and `$lang2` (the order of which does not matter), where similarity is the number of common elements on the left, without regard to case and to x/i- alternation. ``` similarity_language_tag('fr', 'fr-ca') # is 1 # (one element in common) similarity_language_tag('fr-ca', 'fr-FR') # is 1 # (one element in common) similarity_language_tag('fr-CA-joual', 'fr-CA-PEI') # is 2 similarity_language_tag('fr-CA-joual', 'fr-CA') # is 2 # (two elements in common) similarity_language_tag('x-kadara', 'i-kadara') # is 1 # (x/i- doesn't matter) similarity_language_tag('en', 'x-kadar') # is 0 similarity_language_tag('x-kadara', 'x-kadar') # is 0 # (unrelated tags -- no similarity) similarity_language_tag('i-cree-syllabic', 'i-cherokee-syllabic') # is 0 # (no B<leftmost> elements in common!) ``` * `is_dialect_of(Str:D $lang1, Str:D $lang2 -->Bool)` Returns `True` if language tag `$lang1` represents a subform of language tag `$lang2`. **Get the order right! It doesn't work the other way around!** ``` is_dialect_of('en-US', 'en') # is True # (American English IS a dialect of all-English) is_dialect_of('fr-CA-joual', 'fr-CA') # is True is_dialect_of('fr-CA-joual', 'fr') # is True # (Joual is a dialect of (a dialect of) French) is_dialect_of('en', 'en-US') # is False # (all-English is a NOT dialect of American English) is_dialect_of('fr', 'en-CA') # is False is_dialect_of('en', 'en' ) # is True is_dialect_of('en-US', 'en-US') # is True # (these are degenerate cases) is_dialect_of('i-mingo-tom', 'x-Mingo') # is True # (the x/i thing doesn't matter, nor does case) is_dialect_of('nn', 'no') # is True # (because 'nn' (New Norse) is aliased to 'no-nyn', # as a special legacy case, and 'no-nyn' is a # subform of 'no' (Norwegian)) ``` * `super_languages(Str:D $lang1 --> Seq)` Returns a sequence of language tags that are superordinate tags to `$lang1` -- it gets this by removing subtags from the end of `$lang1` until nothing (or just "i" or "x") is left. ``` super_languages("fr-CA-joual") # is ("fr-CA", "fr") super_languages("en-AU") # is ("en") super_languages("en") # is empty-list, () super_languages("i-cherokee") # is empty-list, () # ...not ("i"), which would be illegal as well as pointless. ``` If `$lang1` is not a valid language tag, returns empty-list. A notable and rather unavoidable problem with this method: "x-mingo-tom" has an "x" because the whole tag isn't an IANA-registered tag -- but super\_languages('x-mingo-tom') is ('x-mingo') -- which isn't really right, since 'i-mingo' is registered. But this module has no way of knowing that. (But note that same\_language\_tag('x-mingo', 'i-mingo') is `True`.) More importantly, you assume *at your peril* that superordinates of `$lang1` are mutually intelligible with `$lang1`. Consider this carefully. * `locale2language_tag(Str:D $locale_identifier --> Str)` This takes a locale name (like "en", "en\_US", or "en\_US.ISO8859-1") and maps it to a language tag. If it's not mappable (as with, notably, "C" and "POSIX"), this returns empty-list in a list context, or undef in a scalar context. ``` locale2language_tag("en") is "en" locale2language_tag("en_US") is "en-US" locale2language_tag("en_US.ISO8859-1") is "en-US" locale2language_tag("C") is undef or () locale2language_tag("POSIX") is undef or () locale2language_tag("POSIX") is undef or () ``` I'm not totally sure that locale names map satisfactorily to language tags. Think REAL hard about how you use this. YOU HAVE BEEN WARNED. The output is untainted. If you don't know what tainting is, don't worry about it. * `encode_language_tag(Str:D $lang1 -> Str)` This function, if given a language tag, returns an encoding of it such that: * tags representing different languages never get the same encoding. * tags representing the same language always get the same encoding. * an encoding of a formally valid language tag always is a string value that is defined, has length, and is true if considered as a boolean. Note that the encoding itself is **not** a formally valid language tag. Note also that you cannot, currently, go from an encoding back to a language tag that it's an encoding of. Note also that you **must** consider the encoded value as atomic; i.e., you should not consider it as anything but an opaque, unanalysable string value. (The internals of the encoding method may change in future versions, as the language tagging standard changes over time.) `encode_language_tag` returns `Str` if given anything other than a formally valid language tag. The reason `encode_language_tag` exists is because different language tags may represent the same language; this is normally treatable with `same_language_tag`, but consider this situation: You have a data file that expresses greetings in different languages. Its format is "[language tag]=[how to say 'Hello']", like: ``` en-US=Hiho fr=Bonjour i-mingo=Hau' ``` And suppose you write a program that reads that file and then runs as a daemon, answering client requests that specify a language tag and then expect the string that says how to greet in that language. So an interaction looks like: ``` greeting-client asks: fr greeting-server answers: Bonjour ``` So far so good. But suppose the way you're implementing this is: **This is Perl 5 Code** ``` my %greetings; die unless open(IN, "<", "in.dat"); while(<IN>) { chomp; next unless /^([^=]+)=(.+)/s; my($lang, $expr) = ($1, $2); $greetings{$lang} = $expr; } close(IN); ``` at which point %greetings has the contents: ``` "en-US" => "Hiho" "fr" => "Bonjour" "i-mingo" => "Hau'" ``` And suppose then that you answer client requests for language $wanted by just looking up $greetings{$wanted}. If the client asks for "fr", that will look up successfully in %greetings, to the value "Bonjour". And if the client asks for "i-mingo", that will look up successfully in %greetings, to the value "Hau'". But if the client asks for "i-Mingo" or "x-mingo", or "Fr", then the lookup in %greetings fails. That's the Wrong Thing. You could instead do lookups on $wanted with: **This is Perl 5 Code** ``` use I18N::LangTags qw(same_language_tag); my $response = ''; foreach my $l2 (keys %greetings) { if(same_language_tag($wanted, $l2)) { $response = $greetings{$l2}; last; } } ``` But that's rather inefficient. A better way to do it is to start your program with: **This is Perl 5 Code** ``` use I18N::LangTags qw(encode_language_tag); my %greetings; die unless open(IN, "<", "in.dat"); while(<IN>) { chomp; next unless /^([^=]+)=(.+)/s; my($lang, $expr) = ($1, $2); $greetings{ encode_language_tag($lang) } = $expr; } close(IN); ``` and then just answer client requests for language $wanted by just looking up **This is Perl 5 Code** ``` $greetings{encode_language_tag($wanted)} ``` And that does the Right Thing. * `alternate_language_tags(Str:D $lang1 --> List)` This function, if given a language tag, returns all language tags that are alternate forms of this language tag. (I.e., tags which refer to the same language.) This is meant to handle legacy tags caused by the minor changes in language tag standards over the years; and the x-/i- alternation is also dealt with. Note that this function does *not* try to equate new (and never-used, and unusable) ISO639-2 three-letter tags to old (and still in use) ISO639-1 two-letter equivalents -- like "ara" -> "ar" -- because "ara" has *never* been in use as an Internet language tag, and RFC 3066 stipulates that it never should be, since a shorter tag ("ar") exists. Examples: ``` alternate_language_tags('no-bok') # is ('nb') alternate_language_tags('nb') # is ('no-bok') alternate_language_tags('he') # is ('iw') alternate_language_tags('iw') # is ('he') alternate_language_tags('i-hakka') # is ('zh-hakka', 'x-hakka') alternate_language_tags('zh-hakka') # is ('i-hakka', 'x-hakka') alternate_language_tags('en') # is () alternate_language_tags('x-mingo-tom') # is ('i-mingo-tom') alternate_language_tags('x-klikitat') # is ('i-klikitat') alternate_language_tags('i-klikitat') # is ('x-klikitat') ``` This function returns empty-list if given anything other than a formally valid language tag. * `panic_languages(@accept_languages -> Seq)` This function takes a list of 0 or more language tags that constitute a given user's Accept-Language list, and returns a list of tags for *other* (non-super) languages that are probably acceptable to the user, to be used *if all else fails*. For example, if a user accepts only 'ca' (Catalan) and 'es' (Spanish), and the documents/interfaces you have available are just in German, Italian, and Chinese, then the user will most likely want the Italian one (and not the Chinese or German one!), instead of getting nothing. So `panic_languages('ca', 'es')` returns a list containing 'it' (Italian). English ('en') is *always* in the return list, but whether it's at the very end or not depends on the input languages. This function works by consulting an internal table that stipulates what common languages are "close" to each other. A useful construct you might consider using is: ``` @fallbacks = super_languages(@accept_languages); @fallbacks.append: panic_languages( |@accept_languages, |@fallbacks, ); ``` * `implicate_supers(@languages --> Seq)` This takes a list of strings (which are presumed to be language-tags; strings that aren't, are ignored); and after each one, this function inserts super-ordinate forms that don't already appear in the list. The original list, plus these insertions, is returned. In other words, it takes this: ``` pt-br de-DE en-US fr pt-br-janeiro ``` and returns this: ``` pt-br pt de-DE de en-US en fr pt-br-janeiro ``` This function is most useful in the idiom. **But detect() is not jet implemented**. ``` implicate_supers( I18N::LangTags::Detect::detect() ); ``` * `implicate_supers_strictly(@languages --> Seq)` This works like `implicate_supers` except that the implicated forms are added to the end of the return list. In other words, implicate\_supers\_strictly takes a list of strings (which are presumed to be language-tags; strings that aren't, are ignored) and after the whole given list, it inserts the super-ordinate forms of all given tags, minus any tags that already appear in the input list. In other words, it takes this: ``` pt-br de-DE en-US fr pt-br-janeiro ``` and returns this: ``` pt-br de-DE en-US fr pt-br-janeiro pt de en ``` The reason this function has "\_strictly" in its name is that when you're processing an Accept-Language list according to the RFCs, if you interpret the RFCs quite strictly, then you would use implicate\_supers\_strictly, but for normal use (i.e., common-sense use, as far as I'm concerned) you'd use implicate\_supers. # SEE ALSO * <https://metacpan.org/pod/I18N::LangTags> * I18N::LangTags::List * RFC 3066, `http://www.ietf.org/rfc/rfc3066.txt`, "Tags for the Identification of Languages". (Obsoletes RFC 1766) * RFC 2277, `http://www.ietf.org/rfc/rfc2277.txt`, "IETF Policy on Character Sets and Languages". * RFC 2231, `http://www.ietf.org/rfc/rfc2231.txt`, "MIME Parameter Value and Encoded Word Extensions: Character Sets, Languages, and Continuations". * RFC 2482, `http://www.ietf.org/rfc/rfc2482.txt`, "Language Tagging in Unicode Plain Text". * Locale::Codes, in `http://www.perl.com/CPAN/modules/by-module/Locale/` * ISO 639-2, "Codes for the representation of names of languages", including two-letter and three-letter codes, `http://www.loc.gov/standards/iso639-2/php/code_list.php` * The IANA list of registered languages (hopefully up-to-date), `http://www.iana.org/assignments/language-tags` # AUTHOR Martin Barth [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018 Martin Barth This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-MELEZHIK-Sparky.md # SYNOPSIS Sparky is a flexible and minimalist continuous integration server written in Raku. ![Nice web UI](https://raw.githubusercontent.com/melezhik/sparky/master/images/sparky-web-ui5.png) The essential features of Sparky: * Defining builds times in crontab style * Triggering builds using external APIs and custom logic * Build scenarios defined as [Sparrow6](https://github.com/melezhik/Sparrow6) scripts * [Nice set](https://github.com/melezhik/Sparrow6/blob/master/documentation/dsl.md) of predefined tasks is available * Everything is kept in SCM repository - easy to port, maintain and track changes * Builds gets run in one of 3 flavors - 1) on localhost 2) on remote machines via **ssh** 3) on **docker** instances * Nice web UI to read build reports Interested? Let's go ahead! (: # Build status [![Build Status](https://travis-ci.org/melezhik/sparky.svg?branch=master)](https://travis-ci.org/melezhik/sparky) # Sparky workflow in 4 lines: ``` $ sparkyd # run Sparky daemon to build your projects $ raku bin/sparky-web.raku # run Sparky web UI to see build statuses and reports $ nano ~/.sparky/projects/my-project/sparrowfile # write a build scenario $ firefox 127.0.0.1:3000 # see what's happening ``` # Installation ``` $ sudo apt-get install sqlite3 $ git clone https://github.com/melezhik/sparky.git $ cd sparky && zef install . ``` # Setup First you should run database initialization script to populate database schema: ``` $ raku db-init.raku ``` # Running daemon Then you need to run (\*) the sparky daemon ``` $ sparkyd ``` * Sparky daemon traverses sub directories found at the project root directory. * For every directory found initiate build process invoking sparky worker ( `sparky-runner.raku` ). * Sparky root directory default location is `~/.sparky/projects`. * Once all the sub directories gets passed, sparky daemon sleeps for $timeout seconds. * A `timeout` option allows to balance a load on your system. * You can change a timeout by applying `--timeout` parameter when running sparky daemon: ``` $ sparkyd --timeout=600 # sleep 10 minutes ``` * You can also set a timeout by using `SPARKY_TIMEOUT` environment variable: ``` $ SPARKY_TIMEOUT=30 sparkyd ... ``` Running sparky in demonized mode. At the moment sparky can't demonize itself, as temporary workaround use linux `nohup` command: ``` $ nohup sparkyd & ``` Or you can use Sparrowdo installer, which install service as systemd unit: ``` $ nano utils/install-sparky-web-systemd.raku # change working directory and user $ sparrowdo --sparrowfile=utils/install-sparkyd-systemd.raku --no_sudo --localhost ``` \* `sparkyd` should be in your PATH, if not, fix it before going further. You should have installed with `zef install .` listed above. It could live for instance in `$HOME/.raku/bin` along with other scripts required (like `sparrowdo`) # Running Web UI And finally sparky has simple web UI to show builds statuses and reports. To run Sparky web UI launch `sparky-web.raku` script from the `bin/` directory: ``` $ raku bin/sparky-web.raku ``` This is [Bailador](https://github.com/Bailador/Bailador) application, so you can set any Bailador related options here. For example: ``` $ BAILADOR=host:0.0.0.0,port:5000 raku bin/sparky-web.raku ``` You can use Sparrowdo installer as well, which installs service as systemd unit: ``` $ nano utils/install-sparky-web-.raku # change working directory, user and root directory $ sparrowdo --sparrowfile=utils/install-sparky-web-systemd.raku --no_sudo --localhost ``` # Creating first sparky project Sparky project is just a directory located at the sparky root directory: ``` $ mkdir ~/.sparky/projects/bailador-app ``` # Build scenario Sparky is built on Sparrowdo, read [Sparrowdo](https://github.com/melezhik/sparrowdo) *to know how to write Sparky scenarios*. Here is a short example. Say, we want to check out a Raku project from from Git, install dependencies and then run unit tests: ``` $ nano ~/.sparky/projects/bailador-app/sparrowfile ``` And add content like this: ``` directory "project"; git-scm 'https://github.com/melezhik/rakudist-teddy-bear.git', %( to => "project", ); zef "{%*ENV<PWD>}/project", %( depsonly => True ); zef 'TAP::Harness App::Prove6'; bash 'prove6 -l', %( debug => True, cwd => "{%*ENV<PWD>}/project/" ); ``` # Configure Sparky workers By default the build scenario gets executed *on the same machine you run Sparky at*, but you can change this to *any remote host* setting Sparrowdo related parameters in the `sparky.yaml` file: ``` $ nano ~/.sparky/projects/bailador-app/sparky.yaml ``` And define worker configuration: ``` sparrowdo: host: '192.168.0.1' ssh_private_key: /path/to/ssh_private/key.pem ssh_user: sparky no_index_update: true sync: /tmp/repo ``` You can read about the all [available parameters](https://github.com/melezhik/sparrowdo#sparrowdo-cli) in Sparrowdo documentation. # Skip bootstrap Sparrowdo bootstrap takes a while, if you don't need bootstrap ( sparrow client is already installed at a target host ) use `bootstrap: false` option: ``` sparrowdo: bootstrap: false ``` # Purging old builds To remove old build set `keep_builds` parameter in `sparky.yaml`: ``` $ nano ~/.sparky/projects/bailador-app/sparky.yaml ``` Put number of past builds to keep: ``` keep_builds: 10 ``` That makes Sparky remove old build and only keep last `keep_builds` builds. # Run by cron It's possible to setup scheduler for Sparky builds, you should define `crontab` entry in sparky yaml file. for example to run a build every hour at 30,50 or 55 minute say this: ``` $ nano ~/.sparky/projects/bailador-app/sparky.yaml ``` With this schedule: ``` crontab: "30,50,55 * * * *" ``` Follow [Time::Crontab](https://github.com/ufobat/p6-time-crontab) documentation on crontab entries format. # Manual run If you want to build a project from web UI, use `allow_manual_run`: ``` $ nano ~/.sparky/projects/bailador-app/sparky.yaml ``` And activate manual run: ``` allow_manual_run: true ``` # Trigger build by SCM changes \*\* warning \*\* - the feature is not properly tested, feel free to post issues or suggestions To trigger Sparky builds on SCM changes, define `scm` section in `sparky.yaml` file: ``` scm: url: $SCM_URL branch: $SCM_BRANCH ``` Where: * `url` - git URL * `branch` - git branch, optional, default value is `master` For example: ``` scm: url: https://github.com/melezhik/rakudist-teddy-bear.git branch: master ``` Once a build is triggered one needs to handle build environment leveraging `tags()<SCM_*>` objects: ``` directory "scm"; say "current commit is: {tags()<SCM_SHA>}"; git-scm tags()<SCM_URL>, %( to => "scm", branch => tags<SCM_BRANCH> ); bash "ls -l {%*ENV<PWD>}/scm"; ``` # Disable project You can disable project builds by setting `disable` option to true: ``` $ nano ~/.sparky/projects/bailador-app/sparky.yaml disabled: true ``` It's handy when you start a new project and don't want to add it into build pipeline. # Downstream projects You can run downstream projects by setting `downstream` field at the upstream project `sparky.yaml` file: ``` $ nano ~/.sparky/projects/main/sparky.yaml downstream: downstream-project ``` # File triggering protocol (FTP) Sparky FTP allows to *trigger* builds automatically by just creating files with build *parameters* in special format: ``` $ nano $project/.triggers/foo-bar-baz.pl6 ``` File should have a `*.pl6` extension and be located in project `.trigger` directory. A content of the file should Raku code returning a Hash: ``` { description => "Build app", cwd => "/path/to/working/directory", sparrowdo => %( localhost => True, no_sudo => True, conf => "/path/to/file.conf" ) } ``` Sparky daemon parses files in `.triggers` and launch build per every file, removing file afterwards, this process is called file triggering. To separate different builds just create trigger files with unique names inside `$project/.trigger` directory. FTP allows to create *supplemental* APIs to implement more complex and custom build logic, while keeping Sparky itself simple. ## Trigger attributes Those keys could be used in trigger Hash. All they are optional. * `cwd` Directory where sparrowfile is located, when a build gets run, the process will change to this directory. * `description` Arbitrary text description of build * `sparrowdo` Options for sparrowdo run, for example: ``` %( host => "foo.bar", ssh_user => "admin", tags => "prod,backend" ) ``` Should follow the format of sparky.yaml, `sparrowdo` section * `key` A unique key # Sparky plugins Sparky plugins are extensions points to add extra functionality to Sparky builds. These are Raku modules get run *after* a Sparky project finishes or in other words when a build is completed. To use Sparky plugins you should: * Install plugins as Raku modules * Configure plugins in project's `sparky.yaml` file ## Install Sparky plugins You should install a module on the same server where you run Sparky at. For instance: ``` $ zef install Sparky::Plugin::Email # Sparky plugin to send email notifications ``` ## Configure Sparky In project's `sparky.yaml` file define plugins section, it should be list of Plugins and its configurations. For instance: ``` $ cat sparky.yaml ``` That contains: ``` plugins: - Sparky::Plugin::Email: parameters: subject: "I finished" to: "[email protected]" text: "here will be log" - Sparky::Plugin::Hello: parameters: name: Sparrow ``` ## Creating Sparky plugins Technically speaking Sparky plugins should be just Raku modules. For instance, for mentioned module Sparky::Plugin::Email we might have this header lines: ``` use v6; unit module Sparky::Plugin::Hello; ``` That is it. The module should have `run` routine which is invoked when Sparky processes a plugin: ``` our sub run ( %config, %parameters ) { } ``` As we can see the `run` routine consumes its parameters as Raku Hash, these parameters are defined at mentioned `sparky.yaml` file, at plugin `parameters:` section, so this is how you might handle them: ``` sub run ( %config, %parameters ) { say "Hello " ~ %parameters<name>; } ``` You can use `%config` Hash to access Sparky guts: * `%config<project>` - the project name * `%config<build-id>` - the build number of current project build * `%cofig<build-state>` - the state of the current build For example: ``` sub run ( %config, %parameters ) { say "build id is: " ~ %parameters<build-id>; } ``` Alternatively you may pass *some* predefined parameters plugins: * %PROJECT% - equivalent of `%config<project>` * %BUILD-STATE% - equivalent of `%config<build-state>` * %BUILD-ID% - equivalent of `%config<build-id>` For example: ``` $ cat sparky.yaml ``` That contains: ``` plugins: - Sparky::Plugin::Hello: parameters: name: Sparrow from project %PROJECT% ``` ## Limit plugin run scope You can defined *when* to run plugin, here are 3 run scopes: * `anytime` - run plugin irrespective of a build state. This is default value * `success` - run plugin only if build has succeeded * `fail` - run plugin only if build has failed Scopes are defined at `run_scope:` parameter: ``` - Sparky::Plugin::Hello: run_scope: fail parameters: name: Sparrow ``` ## An example of Sparky plugins An example Sparky plugins are: * [Sparky::Plugin::Hello](https://github.com/melezhik/sparky-plugin-hello) * [Sparky::Plugin::Notify::Email](https://github.com/melezhik/sparky-plugin-notify-email) # Command line client You can build the certain project using sparky command client called `sparky-runner.raku`: ``` $ sparky-runner.raku --dir=/home/user/.sparky/projects/bailador-app ``` Or just: ``` $ cd ~/.sparky/projects/bailador-app && sparky-runner.raku ``` # Sparky runtime parameters All this parameters could be overridden by command line ( `--root`, `--work-root` ) ## Root directory This is sparky root directory, or directory where Sparky looks for the projects to get built: ``` ~/.sparky/projects/ ``` ## Work directory This is working directory where sparky might place some stuff, useless at the moment: ``` ~/.sparky/work ``` # Environment variables ## SPARKY\_SKIP\_CRON You can disable cron check to run project forcefully, by setting `SPARKY_SKIP_CRON` environment variable: ``` $ export SPARKY_SKIP_CRON=1 && sparkyd ``` ## SPARKY\_ROOT Sets the sparky root directory ## SPARKY\_HTTP\_ROOT Set Sparky web application http root. Useful when proxy application through Nginx. ## SPARKY\_TIMEOUT Sets timeout for sparky workers, see [Running daemon](#running-daemon) section. # Running under other databases engines (MySQL, PostgreSQL) By default Sparky uses sqlite as database engine, which makes it easy to use when developing. However sqlite has limitation on transactions locking whole database when doing inserts/updates (Database Is Locked errors). if you prefer other databases here is guideline. ## Create sparky configuration file You should defined database engine and connection parameters, say we want to use MySQL: ``` $ nano ~/sparky.yaml ``` With content: ``` database: engine: mysql host: $dbhost port: $dbport name: $dbname user: $dbuser pass: $dbpassword ``` For example: ``` database: engine: mysql host: "127.0.0.1" port: 3306 name: sparky user: sparky pass: "123" ``` ## Installs dependencies Depending on platform it should be client needed for your database API, for example for Debian we have to: ``` $ sudo yum install mysql-client ``` ## Creating database user, password and schema DB init script will generate database schema, provided that user defined and sparky configuration file has access to the database: ``` $ raku db-init.raku ``` That is it, now sparky runs under MySQL! # Change UI theme Sparky uses [Bulma](https://bulma.io/) as a CSS framework, you can easily change the theme through sparky configuration file: ``` $ nano ~/sparky.yaml ``` And choose your theme: ``` ui: theme: cosmo ``` The list of available themes is on <https://jenil.github.io/bulmaswatch/> # Trigger jobs from HTTP API ``` POST /build/project/$project ``` # Examples You can see examples of sparky scenarios in `examples/` folder. # See also [Bailador](https://github.com/Bailador/Bailador) - A light-weight route-based web application framework for Perl 6. [Sparky-docker](https://github.com/melezhik/sparky-docker) - Run Sparky as Docker container. # Author Alexey Melezhik
## dist_github-jaffa4-Rakudo-Perl6-Parsing.md # Rakudo::Perl6::Parsing It is a wrapper around nqp Perl6 parsing methods. Known problem: if it is compiled into pir. (Panda does that), use Perl6::Parsing fails. It seems to be a Rakudo bug. Workaround: delete Parsing.pir. Usage: ``` use Rakudo::Perl6::Parsing; my $p= Rakudo::Perl6::Parsing.new(); # create a new object $p.parse("my \$p=3;"); # let us parse this text <br> say $p.parser.dump; # dumps parse tree $p.printree(); #prints the parse tree using a different format my @tokens = $p.tokenise(); # extract tokens , requires $p.parse... Instead of tokens, it would be more accurate to say parsed texts. It may be useful for all kind of Perl 6 analysis. @tokens is a array of [hash (keys are tokentypes or parsing events, values are charpos where the token may ends), startpos in text, endpos in text ]. There are overlapping tokens but no overlaps are returned. Look at the values of the hash to determine overlaps. <br> E.g. values in the previous line is not equal to endpos in text. say $p.text.substr(@tokens[0][1],@tokens[0][2]-@tokens[0][1]); # prints first token Tokens are derived from parse tree. It means the token boundaries may not be where you expect them to be. <br> For example, two consecutive comments may be returned as one token. Token boundaries are derived from what the parser considered to be important: code mainly. say @tokens.perl; # look at the structure say $p.dumptokens(); # shows better view ```
## dist_zef-dwarring-FDF.md [[Raku PDF Project]](https://pdf-raku.github.io) / [[FDF Module]](https://pdf-raku.github.io/FDF-raku) # FDF-raku A Raku module for the creation and manipulation of FDF (Form Data Format) files, including PDF export and import. ## Classes/Roles in this Distribution * [FDF](https://pdf-raku.github.io/FDF-raku/FDF) - FDF file * [FDF::Annot](https://pdf-raku.github.io/FDF-raku/FDF/Annot) - FDF Annotations * [FDF::Catalog](https://pdf-raku.github.io/FDF-raku/FDF/Catalog) - FDF Catalog * [FDF::Dict](https://pdf-raku.github.io/FDF-raku/FDF/Dict) - FDF Main Dictionary * [FDF::Field](https://pdf-raku.github.io/FDF-raku/FDF/Field) - FDF Fields * [FDF::Field::AdditionalActions](https://pdf-raku.github.io/FDF-raku/FDF/Field/AdditionalActions) - FDF Field Additional Actions * [FDF::IconFit](https://pdf-raku.github.io/FDF-raku/FDF/IconFit) - FDF IconFits * [FDF::JavaScript](https://pdf-raku.github.io/FDF-raku/FDF/JavaScript) - FDF JavaScripts * [FDF::NamedPageRef](https://pdf-raku.github.io/FDF-raku/FDF/NamedPageRef) - FDF Named Page References * [FDF::Page](https://pdf-raku.github.io/FDF-raku/FDF/Page) - FDF Pages to be added * [FDF::Template](https://pdf-raku.github.io/FDF-raku/FDF/Template) - FDF Page Templates ## Synopsis ### Export fields from a PDF to an FDF ``` use PDF::Class; use FDF; my PDF::Class $from .= open: "MyDoc.pdf"; my FDF $fdf .= new; # fill the email field, overriding PDF value my %fill = :email<[email protected]>; # Combined import and filling $fdf.import: :$from, :%fill; # -OR- import then fill $fdf.import: :$from; $fdf.import: :%fill; note "saving fields :-" for $fdf.field-hash.sort { note " - {.key}: {.value.perl}"; } $fdf.save-as: "MyDoc.fdf"; ``` ### List field values in an FDF file ``` use FDF; use FDF::Field; my FDF $fdf .= open: "MyDoc.fdf"; my FDF::Fields @fields = $fdf.fields; for @fields { say .key ~ ': ' ~ .value.raku; } ``` ### Export field data from an FDF to a PDF ``` use PDF::Class; use FDF; my PDF::Class $to .= open: "MyDoc.pdf"; my FDF $fdf .= open: "MyDoc.fdf"; # populate form data from the PDF $fdf.export: :$to; # save updated fields $to.update; ``` ## Description FDF (Form Data Format) is a format for storing form data and formatting or annotations seperately from PDF files. ## Bugs and Limitations Not yet handled: * Form signing and signature manipulation * Import/export of annotations and pages * Custom encodings (`/Encoding` entry in the FDF dictionary)
## dist_cpan-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 <[email protected]> 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-lizmat-P5times.md [![Actions Status](https://github.com/lizmat/P5times/workflows/test/badge.svg)](https://github.com/lizmat/P5times/actions) # NAME Raku port of Perl's times() built-in # SYNOPSIS ``` use P5times; # exports times() ($user,$system,$cuser,$csystem) = times; $user = times(Scalar); ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `times` built-in as closely as possible in the Raku Programming Language. # ORIGINAL PERL DOCUMENTATION ``` times Returns a four-element list giving the user and system times in seconds for this process and any exited children of this process. ($user,$system,$cuser,$csystem) = times; In scalar context, "times" returns $user. Children's times are only included for terminated children. Portability issues: "times" in perlport. ``` # PORTING CAVEATS ## Microseconds vs Seconds Due to a misunderstanding, it was found that the the `times` function returns **microseconds** versus seconds (as the original Perl version does). This was only found after two years of this module's existence, and deemed much more useful in the Raku context. Therefore it was decided to keep this behaviour in December 2020. ## Child process information There is currently no way to obtain the usage information of child processes. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/P5times> . 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.
## timezoneclash.md class X::DateTime::TimezoneClash Error due to using both time zone offset and :timezone ```raku class X::DateTime::TimezoneClash does X::Temporal is Exception { } ``` This exception is thrown when code tries to create a [`DateTime`](/type/DateTime) object specifying both a time zone offset and the named argument `:timezone`. ```raku say DateTime.new('2015-12-24T12:23:00+0200'); # works say DateTime.new('2015-12-24T12:23:00', timezone => 7200); # works say DateTime.new('2015-12-24T12:23:00+0200', timezone => 7200); # exception ``` # [Methods](#class_X::DateTime::TimezoneClash "go to top of document")[§](#Methods "direct link") ## [method message](#class_X::DateTime::TimezoneClash "go to top of document")[§](#method_message "direct link") ```raku method message() ``` Returns 'DateTime.new(Str): :timezone argument not allowed with a timestamp offset'
## dist_github-melezhik-Sparrowdo-Rakudo.md # Sparrowdo::Rakudo [![Build Status](https://travis-ci.org/melezhik/perl6-sparrowdo-rakudo.svg?branch=master)](https://travis-ci.org/melezhik/perl6-sparrowdo-rakudo) ## SYNOPSIS ## Via sparrowfile ``` $ cat sparrowfile # install default version module_run 'Rakudo'; # install specific version module_run 'Rakudo', %( version => 'https://github.com/nxadm/rakudo-pkg/releases/download/2017.02/perl6-rakudo-moarvm-ubuntu16.04_20170200-01_i386.deb' ) ``` ## Via sparrowdo command line: ``` # install default version $ sparrowdo --host=192.168.0.1 --module_run=Rakudo # install specific version $ sparrowdo --host=192.168.0.1 --module_run=Rakudo@version=https://github.com/nxadm/rakudo-pkg/releases/download/2017.02/perl6-rakudo-moarvm-ubuntu16.04_20170200-01_i386.deb ``` # Description This is simple installer of Rakudo Perl6. # Platforms supported: ``` CentOS Ubuntu ``` ## LICENSE All files (unless noted otherwise) can be used, modified and redistributed under the terms of the Artistic License Version 2. Examples (in the documentation, in tests or distributed as separate files) can be considered public domain. ⓒ2017 'Alexey Melezhik'
## dist_github-gfldex-Operator-DynvarOr.md # Operator::DynvarOr [![Build Status](https://travis-ci.org/gfldex/raku-operator-dynvaror.svg?branch=master)](https://travis-ci.org/gfldex/raku-operator-dynvaror) ## SYNOPSIS ``` use Operator::DynvarOr; sub s { my $*dynvar //* 42; } s; ``` This module supplies the infix operator `//*` that expects its LHS to be a dynvar and its RHS a value. It scans the call stack for a dynvar of the same name and sets the LHS to its value. If the dynvar is not declared in any caller it will assign the RHS to the LHS. This allows optional dynvars to contain undefined values which is otherwise difficult to achieve. ## LICENSE All files (unless noted otherwise) can be used, modified and redistributed under the terms of the Artistic License Version 2. Examples (in the documentation, in tests or distributed as separate files) can be considered public domain. ⓒ2020 Wenzel P. P. Peppmeyer
## notcomposable.md class X::Mixin::NotComposable Error due to using an ineligible type as a mixin ```raku class X::Mixin::NotComposable is Exception { } ``` Thrown when a mixin with infix `does` or `but` is done with a composer that cannot be used for mixin. For example ```raku class B { }; 1 but B; CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::Mixin::NotComposable: Cannot mix in non-composable type B into object of type Int␤» ``` The compile-time equivalent of this error is [`X::Composition::NotComposable`](/type/X/Composition/NotComposable). # [Methods](#class_X::Mixin::NotComposable "go to top of document")[§](#Methods "direct link") ## [method target](#class_X::Mixin::NotComposable "go to top of document")[§](#method_target "direct link") ```raku method target() ``` Returns the target of the failed mixin operation. ## [method rolish](#class_X::Mixin::NotComposable "go to top of document")[§](#method_rolish "direct link") ```raku method rolish() ``` Returns the thing that could not act as a role for mixing it in
## order.md enum Order Human readable form for comparison operators. ```raku enum Order (:Less(-1), :Same(0), :More(1)); ``` # [Operators](#enum_Order "go to top of document")[§](#Operators "direct link") ## [infix cmp](#enum_Order "go to top of document")[§](#infix_cmp "direct link") ```raku multi infix:<cmp>(\a, \b --> Order:D) ``` `cmp` will first try to compare operands as strings (via coercion to [`Stringy`](/type/Stringy)), and, failing that, will try to compare numerically via the `<=>` operator or any other type-appropriate comparison operator. See also [the documentation for the `cmp` operator](/routine/cmp#(Operators)_infix_cmp). ## [infix `<=>`](#enum_Order "go to top of document")[§](#infix_<=> "direct link") ```raku multi infix:«<=>»(Int:D \a, Int:D \b --> Order:D) ``` Specialized form for Int. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Order` raku-type-graph Order Order Int Int Order->Int Mu Mu Any Any Any->Mu Cool Cool Cool->Any Numeric Numeric Real Real Real->Numeric Int->Cool Int->Real [Expand chart above](/assets/typegraphs/Order.svg)
## dist_github-sergot-Encode.md # Encode [test](https://github.com/sergot/perl6-encode/actions/workflows/test.yml) Character encodings in Perl 6
## dist_zef-raku-community-modules-Format-Lisp.md [![Actions Status](https://github.com/raku-community-modules/Format-Lisp/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Format-Lisp/actions) [![Actions Status](https://github.com/raku-community-modules/Format-Lisp/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Format-Lisp/actions) [![Actions Status](https://github.com/raku-community-modules/Format-Lisp/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Format-Lisp/actions) # NAME Format::Lisp - Common Lisp formatter # SYNOPSIS ``` my $fl = Format::Lisp.new; say $fl.format( "~~,,'~c:~c", ',', 'X' ); my $func = $fl.formatter( "x~ax" ); ``` # DESCRIPTION Implements the Common Lisp (format) function. # SPEC\_DIFFERENCES In Lisp, `~&` only adds a newline if there wasn't a newline on STDOUT previously. # METHODS ## format( Str $format-string, \*@args ) Given a format string and the appropriate (if any) args, return the formatted output # AUTHOR Jeffrey Goff # COPYRIGHT AND LICENSE Copyright 2017 Jeffrey Goff Copyright 2020 - 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-krunen-Term-termios.md # Term::termios termios routines for Raku ``` use Term::termios; # Save the previous attrs my $saved_termios := Term::termios.new(fd => 1).getattr; # Get the existing attrs in order to modify them my $termios := Term::termios.new(fd => 1).getattr; # Set the tty to raw mode $termios.makeraw; # You could also do the same in the old-fashioned way $termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>); $termios.set_oflags(<ONLCR>); $termios.set_cflags(<CS8>); $termios.unset_lflags(<ECHO ICANON IEXTEN ISIG>); # Set the modified atributes, delayed until the buffer is emptied $termios.setattr(:DRAIN); # Loop on characters from STDIN loop { # Read single bytes until the buffer can be decoded as UTF-8. my $buf = Buf.new; repeat { $buf.push($*IN.read(1)); } until try my $c = $buf.decode; print "got: " ~ $c.ord ~ "\r\n"; last if $c eq 'q'; } # Restore the saved, previous attributes before exit $saved_termios.setattr(:DRAIN); ``` See the manpage termios(3) for information about the flags.
## lookup.md lookup Combined from primary sources listed below. # [In Metamodel::ClassHOW](#___top "go to top of document")[§](#(Metamodel::ClassHOW)_method_lookup "direct link") See primary documentation [in context](/type/Metamodel/ClassHOW#method_lookup) for **method lookup**. ```raku method lookup($obj, $method-name --> Method:D) ``` Returns the first matching [`Method`](/type/Method) with the provided name. If no method was found, returns a VM-specific sentinel value (typically a low-level NULL value) that can be tested for with a test for [definedness](/routine/defined). It is potentially faster than `.^can` but does not provide a full list of all candidates. ```raku say Str.^lookup('Int').raku; # OUTPUT: «method Int (Str:D $: *%_) { #`(Method|39910024) ... }␤» for <uppercase uc> { Str.^lookup: $^meth andthen .("foo").say orelse "method `$meth` not found".say } # OUTPUT: # method `uppercase` not found # FOO ``` # [In role Metamodel::MethodContainer](#___top "go to top of document")[§](#(role_Metamodel::MethodContainer)_method_lookup "direct link") See primary documentation [in context](/type/Metamodel/MethodContainer#method_lookup) for **method lookup**. ```raku method lookup($obj, $name --> Method) ``` Returns the first matching [`Method`](/type/Method) object of the provided `$name` or `(Mu)` if no method object was found. The search for a matching method object is done by following the [mro](/type/Metamodel/C3MRO) of `$obj`. Note that `lookup` is supposed to be used for introspection, if you're after something which can be invoked you probably want to use [find\_method](/routine/find_method) instead. ```raku say 2.5.^lookup("sqrt").raku; # OUTPUT: «method sqrt (Rat $: *%_) ...␤» say Str.^lookup("BUILD").raku; # OUTPUT: «submethod BUILD (Str $: :$value = "", *%_ --> Nil) ...␤» say Int.^lookup("does-not-exist"); # OUTPUT: «(Mu)␤» ``` The difference between `find_method` and `lookup` are that `find_method` will use a default candidate for parametric roles, whereas `lookup` throws an exception in this case, and that `find_method` honors `FALLBACK` methods, which `lookup` does not.
## dist_zef-FRITH-Math-Libgsl-Combination.md [![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-Combination/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-Combination/actions) # NAME Math::Libgsl::Combination - An interface to libgsl, the Gnu Scientific Library - Combinations. # SYNOPSIS ``` use Math::Libgsl::Combination; ``` # DESCRIPTION Math::Libgsl::Combination is an interface to the combination functions of libgsl, the Gnu Scientific Library. This package provides both the low-level interface to the C library (Raw) and a more comfortable interface layer for the Raku programmer. ### new(:$n!, :$k!) ### new($n!, $k!) The constructor accepts two parameters: the total number of elements in the set and the number of elements chosen from the set; the parameters can be passed as Pair-s or as single values. The combination object is already initialized in lexicographically first combination, i.e. (0, 1, 2, …, $k − 1). All the following methods *throw* on error if they return **self**, otherwise they *fail* on error. ### init(:$start? = TOP) This method initialize the combination object and returns **self**. The default is to initialize the object in lexicographically first combination, but by specifying the optional parameter **$start** as **BOTTOM** the initialization is performed in the lexicographically last combination, i.e. ($n − $k, $n − $k + 1, …, $n − 1). TOP and BOTTOM are declared as values of the Starting-point enum. ### copy($src! where \* ~~ Math::Libgsl::Combination) This method copies the combination **$src** into the current combination object and returns **self**. ### get(Int $elem! --> Int) This method returns the combination value at position **$elem**. ### all(--> Seq) This method returns a Seq of all the elements of the current combination. ### size(--> List) This method returns the (n, k) parameters of the current combination object. ### is-valid(--> Bool) This method checks whether the current combination is valid: the k elements should lie in the range 0 to $n − 1, with each value occurring once at most and in increasing order. ### next() ### prev() These functions advance or step backwards the combination and return **self**, useful for method chaining. ### bnext(--> Bool) ### bprev(--> Bool) These functions advance or step backwards the combination and return a Bool: **True** if successful or **False** if there's no more combination to produce. ### write(Str $filename! --> Int) This method writes the combination data to a file. ### read(Str $filename! --> Int) This method reads the combination data from a file. The combination must be of the same size of the one to be read. ### fprintf(Str $filename!, Str $format! --> Int) This method writes the combination data to a file, using the format specifier. ### fscanf(Str $filename!) This method reads the combination data from a file. The combination must be of the same size of the one to be read. # 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::Combination ``` # AUTHOR Fernando Santagata [[email protected]](mailto:[email protected]) # 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-melezhik-Sparrowdo-Sparrow-Update.md # SYNOPSIS Sparrowdo module to install/update Sparrow toolchain on target host. # Install ``` $ panda install Sparrowdo::Sparrow::Update ``` # Usage ``` $ cat sparrowfile module_run 'Sparrow::Update'; ``` # Author [Alexey Melezhik](mailto:[email protected]) # See also [SparrowDo](https://github.com/melezhik/sparrowdo)
## duration.md class Duration Length of time ```raku class Duration is Cool does Real { } ``` A `Duration` represents a length of time in atomic seconds, with fractions. Like an [`Instant`](/type/Instant), it is epoch-agnostic. `Duration`s can be subtracted from or added to [`Instant`](/type/Instant)s to yield another, new [`Instant`](/type/Instant). Subtracting one [`Instant`](/type/Instant) from another yields a `Duration`. A `Duration` can also result from mathematical operations between two `Duration`s when it makes sense (namely, the addition, subtraction, or modulus of two `Duration`s). It can also be added, subtracted or divided modulo [`Real`](/type/Real) numbers. The type of object returned for other numeric operations is currently unspecified. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Duration` raku-type-graph Duration Duration Cool Cool Duration->Cool Real Real Duration->Real Mu Mu Any Any Any->Mu Cool->Any Numeric Numeric Real->Numeric [Expand chart above](/assets/typegraphs/Duration.svg)
## dist_zef-antononcube-WWW-OpenAI.md ## Chunk 1 of 2 # WWW::OpenAI Raku package ## In brief This Raku package provides access to the machine learning service [OpenAI](https://platform.openai.com), [OAI1]. For more details of the OpenAI's API usage see [the documentation](https://platform.openai.com/docs/api-reference/making-requests), [OAI2]. **Remark:** To use the OpenAI API one has to register and obtain authorization key. **Remark:** This Raku package is much "less ambitious" than the official Python package, [OAIp1], developed by OpenAI's team. Gradually, over time, I expect to add features to the Raku package that correspond to features of [OAIp1]. The original design and implementation of "WWW::OpenAI" were very similar to those of ["Lingua::Translation::DeepL"](https://raku.land/zef:antononcube/Lingua::Translation::DeepL), [AAp1]. Major refactoring of the original code was done -- now each OpenAI functionality targeted by "WWW::OpenAI" has its code placed in a separate file. --- ## Installation Package installations from both sources use [zef installer](https://github.com/ugexe/zef) (which should be bundled with the "standard" Rakudo installation file.) To install the package from [Zef ecosystem](https://raku.land/) use the shell command: ``` zef install WWW::OpenAI ``` To install the package from the GitHub repository use the shell command: ``` zef install https://github.com/antononcube/Raku-WWW-OpenAI.git ``` --- ## Usage examples **Remark:** When the authorization key, `auth-key`, is specified to be `Whatever` then the functions `openai-*` attempt to use the env variable `OPENAI_API_KEY`. ### Universal "front-end" The package has an universal "front-end" function `openai-playground` for the [different functionalities provided by OpenAI](https://platform.openai.com/docs/api-reference/introduction). Here is a simple call for a "chat completion": ``` use WWW::OpenAI; openai-playground('Where is Roger Rabbit?', max-tokens => 64); ``` ``` # [{finish_reason => stop, index => 0, logprobs => (Any), text => # # Roger Rabbit is a fictional character from the movie "Who Framed Roger Rabbit" and he does not exist in real life. He can only be found in the movie and its related merchandise.}] ``` Another one using Bulgarian: ``` openai-playground('Колко групи могат да се намерят в този облак от точки.', max-tokens => 64); ``` ``` # [{finish_reason => length, index => 0, logprobs => (Any), text => # # Не може да се даде точен отговор на този въпрос без да се предостави допълнителна информация за облака от точки. Броят на групите може да зав}] ``` **Remark:** The function `openai-completion` can be used instead in the examples above. See the section ["Create chat completion"](https://platform.openai.com/docs/api-reference/chat/create) of [OAI2] for more details. ### Models The current OpenAI models can be found with the function `openai-models`: ``` openai-models ``` ``` # (babbage-002 dall-e-2 dall-e-3 davinci-002 gpt-3.5-turbo gpt-3.5-turbo-0125 gpt-3.5-turbo-0301 gpt-3.5-turbo-0613 gpt-3.5-turbo-1106 gpt-3.5-turbo-16k gpt-3.5-turbo-16k-0613 gpt-3.5-turbo-instruct gpt-3.5-turbo-instruct-0914 gpt-4 gpt-4-0125-preview gpt-4-0613 gpt-4-1106-preview gpt-4-turbo-preview gpt-4-vision-preview text-embedding-3-large text-embedding-3-small text-embedding-ada-002 tts-1 tts-1-1106 tts-1-hd tts-1-hd-1106 whisper-1) ``` ### Code generation There are two types of completions : text and chat. Let us illustrate the differences of their usage by Raku code generation. Here is a text completion: ``` openai-completion( 'generate Raku code for making a loop over a list', type => 'text', max-tokens => 120, format => 'values'); ``` ``` # my @list = (1, 2, 3, 4, 5, 6); # example list # # for @list -> $item { # loop over the list using the for loop # say $item; # print each item in the list # } # # # Output: # # 1 # # 2 # # 3 # # 4 # # 5 # # 6 ``` Here is a chat completion: ``` openai-completion( 'generate Raku code for making a loop over a list', type => 'chat', max-tokens => 120, format => 'values'); ``` ``` # Here is an example of Raku code that loops over a list and prints each element: # # ```raku # my @list = 1, 2, 3, 4, 5; # # for @list -> $element { # say $element; # } # ``` # # This code will output: # ``` # 1 # 2 # 3 # 4 # 5 # ``` ``` **Remark:** The argument "type" and the argument "model" have to "agree." (I.e. be found agreeable by OpenAI.) For example: * `model => 'text-davinci-003'` implies `type => 'text'` * `model => 'gpt-3.5-turbo'` implies `type => 'chat'` ### Image generation **Remark:** See the files ["Image-generation\*"](./docs/Image-generation.md) for more details. Images can be generated with the function `openai-create-image` -- see the section ["Images"](https://platform.openai.com/docs/api-reference/images) of [OAI2]. Here is an example: ``` my $imgB64 = openai-create-image( "racoon with a sliced onion in the style of Raphael", response-format => 'b64_json', model = 'dalle-e-3', n => 1, size => '1024x1024', format => 'values', method => 'tiny'); ``` Here are the options descriptions: * `response-format` takes the values "url" and "b64\_json" * `n` takes a positive integer, for the number of images to be generated * `size` takes the values '1024x1024', '512x512', '256x256', 'large', 'medium', 'small'. Here we generate an image, get its URL, and place (embed) a link to it via the output of the code cell: ``` my @imgRes = |openai-create-image( "racoon and onion in the style of Roy Lichtenstein", response-format => 'url', n => 1, size => 'small', method => 'tiny'); '![](' ~ @imgRes.head<url> ~ ')'; ``` **Remark:** The argument "model" can be `Whatever` of one of "dall-e-2" or "dall-e-3". Not all parameters that are valid for one of the models are valid or respected by the other -- see the subsection ["Create image"](https://platform.openai.com/docs/api-reference/images/create) of [OpenAI's documentation](https://platform.openai.com/docs/api-reference). ### Image variation **Remark:** See the files ["Image-variation\*"](./docs/Image-variation-and-edition.md) for more details. Images variations over image files can be generated with the function `openai-variate-image` -- see the section ["Images"](https://platform.openai.com/docs/api-reference/images) of [OAI2]. Here is an example: ``` my $imgB64 = openai-variate-image( $*CWD ~ '/resources/RandomMandala.png', response-format => 'b64_json', n => 1, size => 'small', format => 'values', method => 'tiny'); ``` Here are the options descriptions: * `response-format` takes the values "url" and "b64\_json" * `n` takes a positive integer, for the number of images to be generated * `size` takes the values '1024x1024', '512x512', '256x256', 'large', 'medium', 'small'. **Remark:** Same arguments are used by `openai-generate-image`. See the previous sub-section. Here we generate an image, get its URL, and place (embed) a link to it via the output of the code cell: ``` my @imgRes = |openai-variate-image( $*CWD ~ '/resources/RandomMandala.png', response-format => 'url', n => 1, size => 'small', method => 'tiny'); '![](' ~ @imgRes.head<url> ~ ')'; ``` ### Image edition **Remark:** See the files ["Image-variation\*"](./docs/Image-variation-and-edition.md) for more details. Editions of images can be generated with the function `openai-edit-image` -- see the section ["Images"](https://platform.openai.com/docs/api-reference/images) of [OAI2]. Here are the descriptions of positional arguments: * `file` is a file name string (a PNG image with [RGBA color space](https://en.wikipedia.org/wiki/RGBA_color_model)) * `prompt` is a prompt tha describes the image edition Here are the descriptions of the named arguments (options): * `mask-file` a file name of a mask image (can be an empty string or `Whatever`) * `n` takes a positive integer, for the number of images to be generated * `size` takes the values '1024x1024', '512x512', '256x256', 'large', 'medium', 'small'. * `response-format` takes the values "url" and "b64\_json" * `method` takes the values "tiny" and "curl" Here is a random mandala color (RGBA) image: ![](../resources/RandomMandala2.png) Here we generate a few editions of the colored mandala image above, get their URLs, and place (embed) the image links using a table: ``` my @imgRes = |openai-edit-image( $*CWD ~ '/../resources/RandomMandala2.png', 'add cosmic background', response-format => 'url', n => 2, size => 'small', format => 'values', method => 'tiny'); @imgRes.map({ '![](' ~ $_ ~ ')' }).join("\n\n") ``` ### Vision In the fall of 2023 OpenAI introduced image vision model ["gpt-4-vision-preview"](https://openai.com/blog/new-models-and-developer-products-announced-at-devday), [OAIb1]. If the function `openai-completion` is given a list of images, textual results corresponding to those images is returned. The argument "images" is a list of image URLs, image file names, or image Base64 representations. (Any combination of those element types.) Here is an example with three images: ``` my $url1 = 'https://i.imgur.com/LEGfCeq.jpg'; my $url2 = 'https://i.imgur.com/UcRYl9Y.jpg'; my $fname3 = $*CWD ~ '/resources/ThreeHunters.jpg'; my @images = [$url1, $url2, $fname3]; say openai-completion("Give concise descriptions of the images.", :@images, max-tokens => 900, format => 'values'); ``` ``` # 1. The first image is a vibrant illustration of a raccoon perched on a tree branch surrounded by a flurry of colorful butterflies. # # 2. The second image depicts two raccoons running along a path next to a large tree with a sign, surrounded by butterflies, in a colorful autumn landscape. # # 3. The third image shows a trio of raccoons sitting in a tree hollow, with a warm, luminous backdrop and butterflies fluttering around, set in an autumnal forest scene. ``` The function `encode-image` from the namespace `WWW::OpenAI::ChatCompletions` can be used to get Base64 image strings corresponding to image files. For example: ``` my $img3 = WWW::OpenAI::ChatCompletions::encode-image($fname3); say "![]($img3)" ``` When a file name is given to the argument "images" of `openai-completion` then the function `encode-image` is applied to it. ### Moderation Here is an example of using [OpenAI's moderation](https://platform.openai.com/docs/api-reference/moderations): ``` my @modRes = |openai-moderation( "I want to kill them!", format => "values", method => 'tiny'); for @modRes -> $m { .say for $m.pairs.sort(*.value).reverse; } ``` ``` # violence => 0.998648464679718 # harassment/threatening => 0.5217957496643066 # harassment => 0.49981600046157837 # hate => 0.1619441658258438 # hate/threatening => 0.04833448305726051 # violence/graphic => 0.000130274318507872528 # sexual => 0.0000252172667387640096 # self-harm => 4.838872882828582e-06 # self-harm/intent => 2.9584793992398772e-06 # sexual/minors => 1.4673852888336114e-07 # self-harm/instructions => 1.7596822887711028e-09 ``` ### Audio transcription and translation Here is an example of using [OpenAI's audio transcription](https://platform.openai.com/docs/api-reference/audio): ``` my $fileName = $*CWD ~ '/resources/HelloRaccoonsEN.mp3'; say openai-audio( $fileName, format => 'json', method => 'tiny'); ``` ``` # { # "text": "Raku practitioners around the world, eat more onions!" # } ``` To do translations use the named argument `type`: ``` my $fileName = $*CWD ~ '/resources/HowAreYouRU.mp3'; say openai-audio( $fileName, type => 'translations', format => 'json', method => 'tiny'); ``` ``` # { # "text": "How are you, bandits, hooligans? I have long gone mad from you. I have been working as a guard all my life." # } ``` ### Audio speech generation Here is an example of text-to-speech generation - `type`, `prompt`, have to be specified: ``` my $fileName = $*CWD ~ '/resources/EveryDay.mp3'; my $res = openai-audio( $fileName, prompt => 'Every day is a summer day!', type => 'speech', format => 'mp3', voice => 'alloy', speed => 1, method => 'tiny'); ``` ``` # Buf[uint8]:0x<FF F3 E4 C4 00 5F 94 39 D8 17 5A C0 00 06 53 52 1C 77 E6 BC B9 73 8C C2 A3 68 E0 DB 30 35 48 0C D1 43 20 20 C8 89 30 E0 C0 40 CB 36 5A 72 CB 98 10 26 0C 29 85 02 62 03 18 60 C6 18 21 84 08 61 02 18 20 46 08 00 08 01 6B 0B 46 5B 32 CB 96 4C B2 65 A7 2E 59 6C CB 36 66 11 88 05 98 2E 42 0E 24 42 62 28 ...> ``` ### Embeddings [Embeddings](https://platform.openai.com/docs/api-reference/embeddings) can be obtained with the function `openai-embeddings`. Here is an example of finding the embedding vectors for each of the elements of an array of strings: ``` my @queries = [ 'make a classifier with the method RandomForeset over the data dfTitanic', 'show precision and accuracy', 'plot True Positive Rate vs Positive Predictive Value', 'what is a good meat and potatoes recipe' ]; my $embs = openai-embeddings(@queries, format => 'values', method => 'tiny'); $embs.elems; ``` ``` # 4 ``` Here we show: * That the result is an array of four vectors each with length 1536 * The distributions of the values of each vector ``` use Data::Reshapers; use Data::Summarizers; say "\$embs.elems : { $embs.elems }"; say "\$embs>>.elems : { $embs>>.elems }"; records-summary($embs.kv.Hash.&transpose); ``` ``` # $embs.elems : 4 # $embs>>.elems : 1536 1536 1536 1536 # +--------------------------------+-------------------------------+--------------------------------+-------------------------------+ # | 3 | 1 | 2 | 0 | # +--------------------------------+-------------------------------+--------------------------------+-------------------------------+ # | Min => -0.6047187 | Min => -0.6678709 | Min => -0.6308942 | Min => -0.590719 | # | 1st-Qu => -0.012928714 | 1st-Qu => -0.012335346 | 1st-Qu => -0.012563366 | 1st-Qu => -0.01316472075 | # | Mean => -0.00075381957348203 | Mean => -0.0007606080686471 | Mean => -0.00072762704473066 | Mean => -0.0007624376152279 | # | Median => -0.00081807276 | Median => -0.000239203835 | Median => -0.00061062546 | Median => -0.00098278925 | # | 3rd-Qu => 0.01215142175 | 3rd-Qu => 0.0114232735 | 3rd-Qu => 0.011824543 | 3rd-Qu => 0.012312613 | # | Max => 0.22180624 | Max => 0.2273228 | Max => 0.21278104 | Max => 0.21206765 | # +--------------------------------+-------------------------------+--------------------------------+-------------------------------+ ``` Here we find the corresponding dot products and (cross-)tabulate them: ``` use Data::Reshapers; use Data::Summarizers; my @ct = (^$embs.elems X ^$embs.elems).map({ %( i => $_[0], j => $_[1], dot => sum($embs[$_[0]] >>*<< $embs[$_[1]])) }).Array; say to-pretty-table(cross-tabulate(@ct, 'i', 'j', 'dot'), field-names => (^$embs.elems)>>.Str); ``` ``` # +---+----------+----------+----------+----------+ # | | 0 | 1 | 2 | 3 | # +---+----------+----------+----------+----------+ # | 0 | 1.000000 | 0.724379 | 0.756525 | 0.665386 | # | 1 | 0.724379 | 1.000000 | 0.808996 | 0.716001 | # | 2 | 0.756525 | 0.808996 | 1.000000 | 0.698533 | # | 3 | 0.665386 | 0.716001 | 0.698533 | 1.000000 | # +---+----------+----------+----------+----------+ ``` **Remark:** Note that the fourth element (the cooking recipe request) is an outlier. (Judging by the table with dot products.) ### Chat completions with engineered prompts Here is a prompt for "emojification" (see the [Wolfram Prompt Repository](https://resources.wolframcloud.com/PromptRepository/) entry ["Emojify"](https://resources.wolframcloud.com/PromptRepository/resources/Emojify/)): ``` my $preEmojify = q:to/END/; Rewrite the following text and convert some of it into emojis. The emojis are all related to whatever is in the text. Keep a lot of the text, but convert key words into emojis. Do not modify the text except to add emoji. Respond only with the modified text, do not include any summary or explanation. Do not respond with only emoji, most of the text should remain as normal words. END ``` ``` # Rewrite the following text and convert some of it into emojis. # The emojis are all related to whatever is in the text. # Keep a lot of the text, but convert key words into emojis. # Do not modify the text except to add emoji. # Respond only with the modified text, do not include any summary or explanation. # Do not respond with only emoji, most of the text should remain as normal words. ``` Here is an example of chat completion with emojification: ``` openai-chat-completion([ system => $preEmojify, user => 'Python sucks, Raku rocks, and Perl is annoying'], max-tokens => 200, format => 'values') ``` ``` # 🐍 Python sucks, 🦝 Raku rocks, and Perl is 😒 annoying ``` For more examples see the document ["Chat-completion-examples"](./docs/Chat-completion-examples_woven.md). ### Finding textual answers The models of OpenAI can be used to find sub-strings in texts that appear to be answers to given questions. This is done via the package ["ML::FindTextualAnswer"](https://raku.land/zef:antononcube/ML::FindTextualAnswer), [AAp3], using the parameter specs `llm => 'chatgpt'` or `llm => 'openai'`. Here is an example of finding textual answers: ``` use ML::FindTextualAnswer; my $text = "Lake Titicaca is a large, deep lake in the Andes on the border of Bolivia and Peru. By volume of water and by surface area, it is the largest lake in South America"; find-textual-answer($text, "Where is Titicaca?", llm => 'openai') ``` ``` # Andes ``` By default `find-textual-answer` tries to give short answers. If the option "request" is `Whatever` then depending on the number of questions the request is one those phrases: * "give the shortest answer of the question:" * "list the shortest answers of the questions:" In the example above the full query given to OpenAI's models is: > Given the text "Lake Titicaca is a large, deep lake in the Andes > on the border of Bolivia and Peru. By volume of water and by surface > area, it is the largest lake in South America" > give the shortest answer of the question: > Where is Titicaca? Here we get a longer answer by changing the value of "request": ``` find-textual-answer($text, "Where is Titicaca?", llm => 'chatgpt', request => "answer the question:") ``` ``` # Lake Titicaca is located in the Andes on the border of Bolivia and Peru in South America. ``` **Remark:** The function `find-textual-answer` is inspired by the Mathematica function [`FindTextualAnswer`](https://reference.wolfram.com/language/ref/FindTextualAnswer.html); see [JL1]. #### Multiple questions If several questions are given to the function `find-textual-answer` then all questions are spliced with the given text into one query (that is sent to OpenAI.) For example, consider the following text and questions: ``` my $query = 'Make a classifier with the method RandomForest over the data dfTitanic; show precision and accuracy.'; my @questions = ['What is the dataset?', 'What is the method?', 'Which metrics to show?' ]; ``` ``` # [What is the dataset? What is the method? Which metrics to show?] ``` Then the query send to OpenAI is: > Given the text: "Make a classifier with the method RandomForest over the data dfTitanic; show precision and accuracy." > list the shortest answers of the questions: > > 1. What is the dataset? > 2. What is the method? > 3. Which metrics to show? The answers are assumed to be given in the same order as the questions, each answer in a separated line. Hence, by splitting the OpenAI result into lines we get the answers corresponding to the questions. If the questions are missing question marks, it is likely that the result may have a completion as a first line followed by the answers. In that situation the answers are not parsed and a warning message is given. --- ## Command Line Interface ### Playground access The package provides a Command Line Interface (CLI) script: ``` openai-playground --help ``` ``` # Usage: # openai-playground [<words> ...] [--path=<Str>] [-n[=UInt]] [--mt|--max-tokens[=UInt]] [-m|--model=<Str>] [-r|--role=<Str>] [-t|--temperature[=Real]] [-i|--images=<Str>] [-l|--language=<Str>] [--response-format=<Str>] [-a|--auth-key=<Str>] [--timeout[=UInt]] [-f|--format=<Str>] [--method=<Str>] [--base-url=<Str>] -- Command given as a sequence of words. # # --path=<Str> Path, one of 'chat/completions', 'images/generations', 'images/edits', 'images/variations', 'moderations', 'audio/transcriptions', 'audio/translations', 'embeddings', or 'models'. [default: 'chat/completions'] # -n[=UInt] Number of completions or generations. [default: 1] # --mt|--max-tokens[=UInt] The maximum number of tokens to generate in the completion. [default: 100] # -m|--model=<Str> Model. [default: 'Whatever'] # -r|--role=<Str> Role. [default: 'user'] # -t|--temperature[=Real] Temperature. [default: 0.7] # -i|--images=<Str> Image URLs or file names separated with comma (','). [default: ''] # -l|--language=<Str> Language. [default: ''] # --response-format=<Str> The format in which the generated images are returned; one of 'url' or 'b64_json'. [default: 'url'] # -a|--auth-key=<Str> Authorization key (to use OpenAI API.) [default: 'Whatever'] # --timeout[=UInt] Timeout. [default: 10] # -f|--format=<Str> Format of the result; one of "json", "hash", "values", or "Whatever". [default: 'Whatever'] # --method=<Str> Method for the HTTP POST query; one of "tiny" or "curl". [default: 'tiny'] # --base-url=<Str> URL of the Web API service. [default: 'Whatever'] ``` **Remark:** When the authorization key argument "auth-key" is specified set to "Whatever" then `openai-playground` attempts to use the env variable `OPENAI_API_KEY`. --- ## Mermaid diagram The following flowchart corresponds to the steps in the package function `openai-playground`: ``` graph TD UI[/Some natural language text/] TO[/"OpenAI<br/>Processed output"/] WR[[Web request]] OpenAI{{https://platform.openai.com}} PJ[Parse JSON] Q{Return<br>hash?} MSTC[Compose query] MURL[[Make URL]] TTC[Process] QAK{Auth key<br>supplied?} EAK[["Try to find<br>OPENAI_API_KEY<br>in %*ENV"]] QEAF{Auth key<br>found?} NAK[/Cannot find auth key/] UI --> QAK QAK --> |yes|MSTC QAK --> |no|EAK EAK --> QEAF MSTC --> TTC QEAF --> |no|NAK QEAF --> |yes|TTC TTC -.-> MURL -.-> WR -.-> TTC WR -.-> |URL|OpenAI OpenAI -.-> |JSON|WR TTC --> Q Q --> |yes|PJ Q --> |no|TO PJ --> TO ``` --- ## Potential problems ### Tested on macOS only Currently this package is tested on macOS only. ### Not all models work Not all models listed and proclaimed by [OpenAI's documents](https://platform.openai.com/docs/models) work with the corresponding endpoints. Certain models are not available for text- or chat completions, although the documentation says they are. See and run the file ["Models-run-verification.raku"](./experiments/Models-run-verification.raku) to test the available models per endpoint. Related is a (current) deficiency of the package "WWW::OpenAI" -- the known models are hardcoded. (Although, there the function `openai-models` uses an endpoint provided by OpenAI.) ### SSL certificate problems (original package version) *(This subsection is for the original version of the package, not for the most recent one.)* * On macOS I get the errors: > Cannot locate symbol 'SSL\_get1\_peer\_certificate' in native library * See longer discussions about this problem [here](https://stackoverflow.com/questions/72792280/macos-how-to-avoid-ssl-hell-on-intel-mac-with-raku) and [here](https://github.com/jnthn/p6-io-socket-async-ssl/issues/66) * Interestingly: * I did not get these messages while implementing the changes of ver<1.1> of this package * I do not get these messages when using Raku in Markdown or Mathematica notebooks, [AA1], via the package ["Text::CodeProcessing"](https://raku.land/zef:antononcube/Text::CodeProcessing) * Because of those SSL problems I implemented the method option that takes the values 'cro' and 'curl'. * The method "curl": * Requires [`curl`](https://curl.se) to be installed * Invokes the procedure [`shell`](https://docs.raku.org/routine/shell) * Again, this is tested on macOS only. * After "discovering" "HTTP::Tiny" and given the problems with "Cro::HTTP::Client", I removed the 'cro' method. (I.e. the methods are 'tiny' and 'curl' in ver<0.2.0+>.) --- ## TODO * DONE Comprehensive unit tests * Note that this requires OpenAI auth token and costs money. (Ideally, not much.) * DONE Basic usage * DONE Completions - chat * DONE Completions - text * DONE Moderation * DONE Audio transcription * DONE Audio translation * DONE Image generation * DONE Image variation * DONE Image edition * DONE Embeddings * DONE Finding of textual answers * DONE Audio speech generation * DONE HTTP(S) retrieval methods * DONE `curl` * DONE "Cro" * Not used in ver<0.2.0+>. * DONE "HTTP::Tiny" * DONE Models implementation * DONE Embeddings implementation * DONE Refactor the code, so each functionality (audio, completion, moderation, etc) has a separate file. * DONE Refactor HTTP(S) retrieval functions to be simpler and more "uniform." * DONE De-Cro the request code. * Given the problems of using "Cro::HTTP::Client" and the implementations with `curl` and ["HTTP::Tiny"](https://gitlab.com/jjatria/http-tiny/-/blob/master/examples/cookbook.md), it seems it is better to make the implementation of "WWW::OpenAI" more lightweight. * DONE Implement finding of textual answers * DONE Factor out finding of textual answers into a separate package * So, other LLMs can be used. * See ["ML::FindTextualAnswer"](https://github.com/antononcube/Raku-ML-FindTextualAnswer). * DONE Implement vision (over images) * DONE Implement handling of tools --- ## References ### Articles [AA1] Anton Antonov, ["Connecting Mathematica and Raku"](https://rakuforprediction.wordpress.com/2021/12/30/connecting-mathematica-and-raku/), (2021), [RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com). [JL1] Jérôme Louradour, ["New in the Wolfram Language: FindTextualAnswer"](https://blog.wolfram.com/2018/02/15/new-in-the-wolfram-language-findtextualanswer), (2018), [blog.wolfram.com](https://blog.w
## dist_zef-antononcube-WWW-OpenAI.md ## Chunk 2 of 2 olfram.com/). [OAIb1] OpenAI team, ["New models and developer products announced at DevDay"](https://openai.com/blog/new-models-and-developer-products-announced-at-devday), (2023), [OpenAI/blog](https://openai.com/blog). ### Packages [AAp1] Anton Antonov, [Lingua::Translation::DeepL Raku package](https://github.com/antononcube/Raku-Lingua-Translation-DeepL), (2022), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [Text::CodeProcessing](https://github.com/antononcube/Raku-Text-CodeProcessing), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [ML::FindTextualAnswer](https://github.com/antononcube/Raku-ML-FindTextualAnswer), (2023), [GitHub/antononcube](https://github.com/antononcube). [OAI1] OpenAI Platform, [OpenAI platform](https://platform.openai.com/). [OAI2] OpenAI Platform, [OpenAI documentation](https://platform.openai.com/docs). [OAIp1] OpenAI, [OpenAI Python Library](https://github.com/openai/openai-python), (2020), [GitHub/openai](https://github.com/openai/). ### Videos
## dist_zef-antononcube-Data-ExampleDatasets.md # Data::ExampleDatasets Raku package [![SparrowCI](https://ci.sparrowhub.io/project/gh-antononcube-Raku-Data-ExampleDatasets/badge)](https://ci.sparrowhub.io) Raku package for (obtaining) example datasets. Currently, this repository contains only [datasets metadata](./resources/dfRdatasets.csv). The datasets are downloaded from the repository [Rdatasets](https://github.com/vincentarelbundock/Rdatasets/), [VAB1]. --- ## Usage examples ### Setup Here we load the Raku modules [`Data::Generators`](https://modules.raku.org/dist/Data::Generators:cpan:ANTONOV), [`Data::Summarizers`](https://github.com/antononcube/Raku-Data-Summarizers), and this module, [`Data::ExampleDatasets`](https://github.com/antononcube/Raku-Data-ExampleDatasets): ``` use Data::Reshapers; use Data::Summarizers; use Data::ExampleDatasets; ``` ``` # (Any) ``` ### Get a dataset by using an identifier Here we get a dataset by using an identifier and display part of the obtained dataset: ``` my @tbl = example-dataset('Baumann', :headers); say to-pretty-table(@tbl[^6]); ``` ``` # +-----------+-------------+----------+-------------+-------------+-----------+-------+ # | pretest.2 | post.test.3 | rownames | post.test.2 | post.test.1 | pretest.1 | group | # +-----------+-------------+----------+-------------+-------------+-----------+-------+ # | 3 | 41 | 1 | 4 | 5 | 4 | Basal | # | 5 | 41 | 2 | 5 | 9 | 6 | Basal | # | 4 | 43 | 3 | 3 | 5 | 9 | Basal | # | 6 | 46 | 4 | 5 | 8 | 12 | Basal | # | 5 | 46 | 5 | 9 | 10 | 16 | Basal | # | 13 | 45 | 6 | 8 | 9 | 15 | Basal | # +-----------+-------------+----------+-------------+-------------+-----------+-------+ ``` Here we summarize the dataset obtained above: ``` records-summary(@tbl) ``` ``` # +----------------+--------------------+-------------+--------------------+--------------------+---------------------+--------------------+ # | rownames | pretest.1 | group | post.test.1 | pretest.2 | post.test.3 | post.test.2 | # +----------------+--------------------+-------------+--------------------+--------------------+---------------------+--------------------+ # | Min => 1 | Min => 4 | Strat => 22 | Min => 1 | Min => 1 | Min => 30 | Min => 0 | # | 1st-Qu => 17 | 1st-Qu => 8 | DRTA => 22 | 1st-Qu => 5 | 1st-Qu => 3 | 1st-Qu => 40 | 1st-Qu => 5 | # | Mean => 33.5 | Mean => 9.787879 | Basal => 22 | Mean => 8.075758 | Mean => 5.106061 | Mean => 44.015152 | Mean => 6.712121 | # | Median => 33.5 | Median => 9 | | Median => 8 | Median => 5 | Median => 45 | Median => 6 | # | 3rd-Qu => 50 | 3rd-Qu => 12 | | 3rd-Qu => 11 | 3rd-Qu => 6 | 3rd-Qu => 49 | 3rd-Qu => 8 | # | Max => 66 | Max => 16 | | Max => 15 | Max => 13 | Max => 57 | Max => 13 | # +----------------+--------------------+-------------+--------------------+--------------------+---------------------+--------------------+ ``` **Remark**: The values for the first argument of `example-dataset` correspond to the values of the columns "Item" and "Package", respectively, in theA [metadata dataset](https://vincentarelbundock.github.io/Rdatasets/articles/data.html) from the GitHub repository "Rdatasets", [VAB1]. See the datasets metadata sub-section below. The first argument of `example-dataset` can take as values: * Strings that correspond to the column "Items" of the metadata dataset * E.g. `example-dataset("mtcars")` * Strings that correspond to the columns "Package" and "Items" of the metadata dataset * E.g. `example-dataset("COUNT::titanic")` * Regexes * E.g. `example-dataset(/ .* mann $ /)` * `Whatever` or `WhateverCode` ### Get a dataset by using an URL Here we get a dataset by using an URL and display a summary of the obtained dataset: ``` my $url = 'https://raw.githubusercontent.com/antononcube/Raku-Data-Reshapers/main/resources/dfTitanic.csv'; my @tbl2 = example-dataset($url, :headers); records-summary(@tbl2); ``` ``` # +----------------+---------------------+---------------+-----------------+-------------------+ # | passengerClass | passengerAge | passengerSex | id | passengerSurvival | # +----------------+---------------------+---------------+-----------------+-------------------+ # | 3rd => 709 | Min => -1 | male => 843 | Min => 1 | died => 809 | # | 1st => 323 | 1st-Qu => 10 | female => 466 | 1st-Qu => 327.5 | survived => 500 | # | 2nd => 277 | Mean => 23.550038 | | Mean => 655 | | # | | Median => 20 | | Median => 655 | | # | | 3rd-Qu => 40 | | 3rd-Qu => 982.5 | | # | | Max => 80 | | Max => 1309 | | # +----------------+---------------------+---------------+-----------------+-------------------+ ``` ### Datasets metadata Here we: 1. Get the dataset of the datasets metadata 2. Filter it to have only datasets with 13 rows 3. Keep only the columns "Item", "Title", "Rows", and "Cols" 4. Display it in "pretty table" format ``` my @tblMeta = get-datasets-metadata(); @tblMeta = @tblMeta.grep({ $_<Rows> == 13}).map({ $_.grep({ $_.key (elem) <Item Title Rows Cols>}).Hash }); say to-pretty-table(@tblMeta) ``` ``` # +------+------+------------+--------------------------------------------------------------------+ # | Rows | Cols | Item | Title | # +------+------+------------+--------------------------------------------------------------------+ # | 13 | 4 | Snow.pumps | John Snow's Map and Data on the 1854 London Cholera Outbreak | # | 13 | 7 | BCG | BCG Vaccine Data | # | 13 | 5 | cement | Heat Evolved by Setting Cements | # | 13 | 2 | kootenay | Waterflow Measurements of Kootenay River in Libby and Newgate | # | 13 | 5 | Newhouse77 | Medical-Care Expenditure: A Cross-National Survey (Newhouse, 1977) | # | 13 | 2 | Saxony | Families in Saxony | # +------+------+------------+--------------------------------------------------------------------+ ``` ### Keeping downloaded data By default the data is obtained over the web from [Rdatasets](https://github.com/vincentarelbundock/Rdatasets/), but `example-dataset` has an option to keep the data "locally." (The data is saved in `XDG_DATA_HOME`, see [[JS1](https://modules.raku.org/dist/XDG::BaseDirectory:cpan:JSTOWE)].) This can be demonstrated with the following timings of a dataset with ~1300 rows: ``` my $startTime = now; my $data = example-dataset( / 'COUNT::titanic' $ / ):keep; my $endTime = now; say "Geting the data first time took { $endTime - $startTime } seconds"; ``` ``` # Geting the data first time took 0.693845313 seconds ``` ``` $startTime = now; $data = example-dataset( / 'COUNT::titanic' $/ ):keep; $endTime = now; say "Geting the data second time took { $endTime - $startTime } seconds"; ``` ``` # Geting the data second time took 0.711934937 seconds ``` --- ## References ### Functions, packages, repositories [AAf1] Anton Antonov, [`ExampleDataset`](https://resources.wolframcloud.com/FunctionRepository/resources/ExampleDataset), (2020), [Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository). [VAB1] Vincent Arel-Bundock, [Rdatasets](https://github.com/vincentarelbundock/Rdatasets/), (2020), [GitHub/vincentarelbundock](https://github.com/vincentarelbundock). [JS1] Jonathan Stowe, [`XDG::BaseDirectory`](https://modules.raku.org/dist/XDG::BaseDirectory:cpan:JSTOWE), (last updated on 2021-03-31), [Raku Modules](https://modules.raku.org/). ### Interactive interfaces [AAi1] Anton Antonov, [Example datasets recommender interface](https://antononcube.shinyapps.io/ExampleDatasetsRecommenderInterface/), (2021), [Shinyapps.io](https://antononcube.shinyapps.io/).
## dist_cpan-JGOFF-Perl6-Parser.md [![Build Status](https://travis-ci.org/drforr/perl6-Perl6-Parser.svg?branch=master)](https://travis-ci.org/drforr/perl6-Perl6-Parser) # NAME Perl6::Parser - Extract a Perl 6 AST from the NQP Perl 6 Parser # SYNOPSIS ``` my $pt = Perl6::Parser.new; my $source = Q:to[_END_]; code-goes-here(); that you( $want-to, $parse ); _END_ # Get a fully-parsed data tree # my $tree = $pt.to-tree( $source ); say $pt.dump-tree( $tree ); # Return only the displayed tokens (including whitespace) in the document # my @token = $pt.to-tokens-only( $source ); # Return all tokens and structures in the document # my @everything = $pt.to-list( $source ); # This used to fire BEGIN and CHECK phasers, it no longer does so. # Use 'my $*PURE-PERL = True;' before parsing to enable an experimental # pure-Perl6 parser which will not execute phasers, but also won't install # custom operators in your code or any slangs that you may have in place. # As of 2017-09-28 it just bypasses NQP matches for the terminals such as # numbers, operators and keywords, but this will change. ``` # DESCRIPTION Uses the built-in Perl 6 parser exposed by the internal nqp module, so that you can parse Perl 6 using Perl 6 itself. If it scares you... well, it probably should. Assuming everything works out, you'll get back a Perl 6 object tree that exactly mirrors your source file's layout, with every bit of whitespace, POD, and code given one or more tokens. Redisplaying it becomes a matter of calling the `to-string()` method on the tree, which passes an optional formatting hashref down the tree. You can use the format methods as they are, or add a role or subclass the objects created as you see fit to create new objects. This process **will** be simplified and encapsulated in the near future, as reformatting Perl 6 code was what this rather extensive module was designed to do. I've added fairly extensive debugging documentation to the <README.md> of this module, along with an internal <DEBUGGING.pod> file talking about what you're seeing here, and why on **earth** didn't I do it **this** way? I have my reasons, but can be talked out of it with a good argument. Please note that this does compile your code, but it takes the precaution of munging `BEGIN` and `CHECK` phasers into `ENTER` instead so that it won't run at compile time. As it stands, the `.parse` method returns a deeply-nested object representation of the Perl 6 code it's given. It handles the regex language, but not the other braided languages such as embedded blocks in strings. It will do so eventually, but for the moment I'm busy getting the grammar rules covered. While classes like <EClass> won't go away, their parent classes like <DecInteger> will remove them from the tree once their validation job has been done. For example, while the internals need to know that [$/]($/%3Ceclass%3E) (the exponent for a scientific-notation number) hasn't been renamed or moved elsewhere in the tree, you as a consumer of the <DecInteger> class don't need to know that. The `DecInteger.perl6` method will delete the child classes so that we don't end up with a **horribly** cluttered tree. Classes representing Perl 6 object code are currently in the same file as the main Perl6::Parser class, as moving them to separate files caused a severe performance penalty. When the time is right I'll look at moving these to another location, but as shuffling out 20 classes increased my runtime on my little ol' VM from 6 to 20 seconds, it's not worth my time to break them out. And besides, having them all in one file makes editing en masse easier. # DEBUGGING Some notes on how I go about debugging various issues follow. Let's take the case of the following glitch: The terms `$_` and `0` don't show up in the fragment `[$_, 0 .. 100]`, for various reasons, mostly because there's a branch that's either not being traversed, or simply a term has gone missing. The first thing is to break the offending bit of code out so it's easier to debug. The test file I make to do this (usually an existing test file I've got lying around) looks partially like this, with boilerplate stripped out: ``` my $source = Q:to[_END_]; my @a; @a[$_, 0 .. 100]; _END_ my $p = $pt.parse( $source ); say $p.dump; my $tree = $pt.build-tree( $p ); say $pt.dump-tree($tree); is $pt.to-string( $tree ), $source, Q{formatted}; ``` Already a few things might stand out. First, the code inside the here-doc doesn't actually do anything, it'll never print anything to the screen or do anything interesting. That's not the point at this stage in the game. At this point all I need is a syntactically valid bit of Perl 6 that has the constructs that reproduce the bug. I don't care what the code actually does in the real world. Second, I'm not doing anything that you as a user of the class would do. As a user of a the class, all you have to do is run the to-string() method, and it does what you want. I'm breaking things down into their component steps. (side note - This will probably have changed in detail since I wrote this text - Consult your nearest test file for examples of current usage.) Internally, the library takes sevaral steps to get to the nicely objectified tree that you see on your output. The two important steps in our case are the `.parse( 'text goes here' )` method call, and `.build-tree( $parse-tree )`. The `.parse()` call returns a very raw <NQPMatch> object, which is the Perl 6 internal we're trying to reparse into a more useful form. Most of the time you can call `.dump()` on this object and get back a semi-useful object tree. On occasion this **will** lock up, most often because you're trying to `.dump()` a <list> accessor, and that hasn't been implemented for NQPMatch. The actual `list` accessor works, but the `.dump()` call will not. A simple workaround is to call `$p.list.[0].dump` on one of the list elements inside, and hope there is one. Again, these are NQP internals, and aren't quite as stable as the Perl 6 main support layer. Once you've got a dump of the offending area, it'll look something like this: ``` - postcircumfix: [0, $_ ... 100] - semilist: 0, $_ ... 100 - statement: 1 matches - EXPR: ... - 0: , - 0: 0 - value: 0 # ... - 1: $_ - variable: $_ - sigil: $ # ... - infix: , - sym: , - O: <object> - OPER: , ``` The full thing will probably go on for a few hundred lines. Hope you've got scrollback, or just use tmux as I do. With this you can almost immediately jump to what appears to be the offending expression, albeit with a bit of interpretation. You'll see `- 0: 0` and `- 1: $_`, and these are exactly the two bits of syntax that have gone missing in our example. Down below you'll see `- infix: ,` which is where the comma separator goes. We can combine these facts and reason that we have to search for the bit of code where we find an `infix` operator and two list elements. The `- 0` and `- 1` bits tell us that we're dealing with two list elements, and the `- infix` and `- OPER` bits tell us that we've also got two hash keys to find. Look down in this file for a `assert-hash-keys()` call attempting to assert the existence of exactly a `infix` and `OPER` tag. There may actually be other hash keys in this data structure, as `.dump()` doesn't report unused hash keys; this caused me a deal of confusion. Eventually you'll find in the `_EXPR()` method this bit of code: (due to change, obviously) ``` when self.assert-hash-keys( $_, [< infix OPER >] ) { @child.append( self._infix( $_.hash.<infix> ) ) } ``` You're most welcome to use the Perl 6 debugger, but what I just do is add a `say 1;` statement just above the `@child.append()` method call (and anywhere else I find a `infix` and `OPER` hash key hiding, because there are multiple places in the code that match an `infix` and `OPER` hash key) and rerun the test. Now that we've confirmed where the element `should` be getting generated, but somehow isn't, we need to look at the actual text to verify that this is actually where the `$_` and `0` bits are being matched, and we can use another internal debugging tool to help out with that. Add these lines: ``` key-bounds $_.list.[0]; key-bounds $_.hash.<infix>; key-bounds $_.list.[1]; key-bounds $_.hash.<OPER>; key-bounds $_; ``` And rerun your code. Or make the appropriate calls in the debugger, it's your funeral :) What this function does is return something that looks like this: ``` 45 60 [[0, $_ ... 100]] ``` The two numbers are the glyphs where the matched text starts and stops, respectively. The bit in between [..] (in this case seemingly doubled, but that's because the text is itself bracketed) is the actual text that's been matched. So, by now you know what the text you're matching actually looks like, where it is in the string, and maybe eve have a rough idea of why what you're seeing isn't being displayedk With any luck you'll see that the code simply isn't adding the variables to the list that is being glommed onto the `@child` array, and can add it. By convention, when you're dumping a `- semilist:` match, you can always call `self._semilist( $p.hash.<semilist> )` in order to get back the list of tokens generated by matching on the `$p.hash.semilist` object. You might be wondering why I don't just subclass NQPMatch and add this as a generic multimethod or dispatch it in some other way. Well, the reason it's called `NQP` is because it's Not Quite Perl 6, and like poor Rudolph, Perl 6 won't let NQP objects join in any subclasing or dispatching games, because it's Not Quite Perl. And yes, this leads to quite a bit of frustruation. Let's assume that you've found the `$_.list.[0]` and `$_.hash.<infix>` handlers, and now need to add whitespace between the `$_` and `0` elements in your generated code. Now we turn to the rather bewildering array of methods on the `Perl6::WS` class. This profusion of methods is because of two things: ``` * Whitespace can be inside a token, before or after a token, or even simply not be there because it's actually inside the L<NQPMatch> object one or more levels up, so you're never B<quite> sure where your whitespace will be hiding. * If each of the ~50 classes handled whitespace on its own, I'd have to track down each of the ~50 whitespace-generating methods in order to see which of the whitespace calls is being made. This way I can just look for L<Perl6::WS> and know that those are the only B<possible> places where a whitespace token could be being generated. ``` # METHODS * \_roundtrip( Str $perl-code ) returns Perl6::Parser::Root Given a string containing valid Perl 6 code ... well, return that code. This is mostly a shortcut for testing purposes, and wil probably be moved out of the main file. * to-tree( Str $source ) This is normally what you want, it returns the Perl 6 parsed tree corresponding to your source code. * parse( Str $source ) Returns the underlying NQPMatch object. This is what gets passed on to `build-tree()` and every other important method in this module. It does some minor wizardry to call the Perl 6 reentrant compiler to compile the string you pass it, and return a match object. Please note that it **has** to compile the string in order to validate things like custom operators, so this step is **not** optional. * build-tree( Mu $parsed ) Build the Perl6::Element tree from the NQPMatch object. This is the core, and runs the factory which silly-walks the match tree and returns one or more tokens for every single match entry it finds, and **more**. * consistency-check( Perl6::Element $root ) Check the integrity of the data structure. The Factory at its core puts together the structure very sloppily, to give the tree every possible chance to create actual quasi-valid text. This method makes sure that the factory returned valid tokens, which often doesn't happen. But since you really want to see the data round-tripped, most users don't care what the tree loos like internally. * to-string( Perl6::Element $tree ) returns Str Call .perl6 on each element of the tree. You can subclass or override this method in any class as you see fit to properly pretty-print the methods. Right now it's awkward to use, and will probably be removed in favor of an upcoming Perl6::Tidy module. That's why I wrote this yak.. er, module in the first place. * dump-tree( Perl6::Element $root ) returns Str Given a Perl6::Document (or other) object, return a full nested tree of text detailing every single token, for debugging purposes. * ruler( Str $source ) Purely a debugging aid, it puts an ASCII ruler above your source so that you don't have to go blind counting whitespace to figure out which ' ' a given token belongs to. As a courtesy it also makes newlines visible so you don't have to count those separately. I might use the visible space character later to make it easier to read, if I happen to like it. # Further-Information For further information, there's a <DEBUGGING.pod> file detailing how to go about tracing down a bug in this module, and an extensive test suite in <t/README.pod> with some ideas of how I'm structuring the test suite.
## dist_zef-raku-community-modules-Brazilian-FederalDocuments.md [![Actions Status](https://github.com/raku-community-modules/Brazilian-FederalDocuments/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Brazilian-FederalDocuments/actions) [![Actions Status](https://github.com/raku-community-modules/Brazilian-FederalDocuments/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Brazilian-FederalDocuments/actions) [![Actions Status](https://github.com/raku-community-modules/Brazilian-FederalDocuments/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Brazilian-FederalDocuments/actions) # NAME Brazilian::FederalDocuments - Brazilian federal documents validations # SYNOPSIS ``` use Brazilian::FederalDocuments; if FederalDocuments::CPF(number => 6931987887).is-valid { say "Valid CPF!!!" } else { say "Invalid CPF..." } if FederalDocuments::CNPJ(number => 394411000109).is-valid { say "Valid CNPF!!!" } else { say "Invalid CNPF..." } ``` # DESCRIPTION n Brazil, there are two numbers of documents used especially for financial transactions. For individuals, the CPF (Individual Persons Registry), and for companies, the CNPJ (National Registry of Legal Entities). This module verifies that the numbers are valid. # AUTHOR Paulo Henrique Rodrigues Pinheiro # COPYRIGHT AND LICENSE Copyright 2017 - 2020 Paulo Henrique Rodrigues Pinheiro Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-Hash-Util.md [![Actions Status](https://github.com/lizmat/Hash-Util/workflows/test/badge.svg)](https://github.com/lizmat/Hash-Util/actions) # NAME Raku port of Perl's Hash::Util module 0.23 # SYNOPSIS ``` use Hash::Util < lock_hash unlock_hash lock_hash_recurse unlock_hash_recurse lock_keys lock_keys_plus unlock_keys lock_value unlock_value hash_locked hash_unlocked hidden_keys legal_keys all_keys >; my %hash = foo => 42, bar => 23; # Ways to restrict a hash lock_keys(%hash); lock_keys(%hash, @keyset); lock_keys_plus(%hash, @additional_keys); # Ways to inspect the properties of a restricted hash my @legal = legal_keys(%hash); my @hidden = hidden_keys(%hash); all_keys(%hash,@keys,@hidden); my $is_locked = hash_locked(%hash); # Remove restrictions on the hash unlock_keys(%hash); # Lock individual values in a hash lock_value( %hash, 'foo'); unlock_value(%hash, 'foo'); # Ways to change the restrictions on both keys and values lock_hash (%hash); unlock_hash(%hash); ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `Hash::Util` module as closely as possible in the Raku Programming Language. Hash::Util contains a set of functions that support restricted hashes. It introduces the ability to restrict a hash to a certain set of keys. No keys outside of this set can be added. It also introduces the ability to lock an individual key so it cannot be deleted and the ability to ensure that an individual value cannot be changed. By default Hash::Util does not export anything. # MAYBE MAP IS ALL YOU NEED If you want to use this module for the sole purpose of only once locking a hash into an immutable state (calling only `lock_hash` once on a hash), then it is much better to turn your hash into a `Map` upon initialization by adding the `is Map` trait: ``` my %hash is Map = foo => 42, bar => 23; ``` This will have exactly the same effect as: ``` my %hash = foo => 42, bar => 23; lock_hash(%hash); ``` but won't need to load the `Hash::Util` module and will be much better performant because it won't need any additional run-time checks, because `Map` is the immutable version of `Hash` in Raku. # PORTING CAVEATS Functions that pertain to the unique implementation of Perl hashes, have **not** been ported. These include: ``` hash_seed hash_value hv_store bucket_stats bucket_info bucket_array hash_traversal_mask ``` Also field hashes (the tools to create inside-out objects) have not been ported is these were deemed rather useless in the Raku environment where everything is a true object. This pertains to the functions: ``` fieldhash fieldhashes ``` Since the concept of references does not exist as such in Raku, it didn't make sense to separately port the "\_ref" versions of the subroutines. They are however available as aliases to the non "\_ref" versions:: ``` lock_hashref unlock_hashref lock_hashref_recurse unlock_hashref_recurse lock_ref_keys lock_ref_keys_plus unlock_ref_keys lock_ref_value unlock_ref_value hashref_locked hashref_unlocked ``` # FUNCTIONS ## lock\_keys HASH, [KEYS] ``` lock_keys(%hash); lock_keys(%hash, @keys); ``` Restricts the given %hash's set of keys to @keys. If @keys is not given it restricts it to its current keyset. No more keys can be added. `:delete` and `:exists` will still work, but will not alter the set of allowed keys. Returns the hash it worked on. ## unlock\_keys HASH ``` unlock_keys(%hash); ``` Removes the restriction on the %hash's keyset. **Note** that if any of the values of the hash have been locked they will not be unlocked after this sub executes. Returns the hash it worked on. ## lock\_keys\_plus HASH, KEYS ``` lock_keys_plus(%hash,@additional_keys) ``` Similar to `lock_keys`, with the difference being that the optional key list specifies keys that may or may not be already in the hash. Essentially this is an easier way to say ``` lock_keys(%hash,@additional_keys,%hash.keys); ``` ## lock\_value HASH, KEY ``` lock_value(%hash, $key); ``` Locks the value for an individual key of a hash. The value of a locked key cannot be changed. Unless %hash has already been locked the key/value could be deleted regardless of this setting. Returns the hash on which it operated. ## unlock\_value HASH, KEY ``` unlock_value(%hash, $key); ``` Unlocks the value for an individual key of a hash. Returns the hash on which it operated. ## lock\_hash HASH ``` lock_hash(%hash); ``` Locks an entire hash, making all keys and values read-only. No value can be changed, no keys can be added or deleted. Returns the hash it operated on. If you only want to lock a hash only once after it has been initialized, it's better to make it a `Map`: ``` my %hash is Map = foo => 42, bar => 23; ``` This will have the same effect as `lock_hash`, but will be much more performant as no extra overhead is needed for checking access at runtime. ## unlock\_hash HASH ``` unlock_hash(%hash); ``` Does the opposite of `lock_hash`. All keys and values are made writable. All values can be changed and keys can be added and deleted. Returns the hash it operated on. ## lock\_hash\_recurse HASH ``` lock_hash_recurse(%hash); ``` Locks an entire hash and any hashes it references recursively, making all keys and values read-only. No value can be changed, no keys can be added or deleted. Returns the hash it originally operated on. This method **only** recurses into hashes that are referenced by another hash. Thus a Hash of Hashes (HoH) will all be restricted, but a Hash of Arrays of Hashes (HoAoH) will only have the top hash restricted. ## unlock\_hash\_recurse HASH ``` unlock_hash_recurse(%hash); ``` Does the opposite of lock\_hash\_recurse(). All keys and values are made writable. All values can be changed and keys can be added and deleted. Returns the hash it originally operated on. Identical recursion restrictions apply as to `lock_hash_recurse`. ## hash\_locked HASH ``` say "Hash is locked!" if hash_locked(%hash); ``` Returns true if the hash and/or its keys are locked. ## hash\_unlocked HASH ``` say "Hash is unlocked!" if hash_unlocked(%hash); ``` Returns true if the hash and/or its keys are **not** locked. ## legal\_keys HASH ``` my @legal = legal_keys(%hash); ``` Returns the list of the keys that are legal in a restricted hash. In the case of an unrestricted hash this is identical to calling `%hash.keys`. ## hidden\_keys HASH ``` my @hidden = hidden_keys(%hash); ``` Returns the list of the keys that are legal in a restricted hash but do not have a value associated to them. Thus if 'foo' is a "hidden" key of the %hash it will return False for both `defined` and `:exists` tests. In the case of an unrestricted hash this will return an empty list. ## all\_keys HASH, VISIBLE, HIDDEN ``` all_keys(%hash,@visible,@hidden); ``` Populates the arrays @visible with the all the keys that would pass an `exists` tests, and populates @hidden with the remaining legal keys that have not been utilized. Returns the hash it operated on. # SEE ALSO Scalar::Util, List::Util # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Hash-Util> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version originally developed by the Perl 5 Porters, subsequently maintained by Steve Hay.
## nameclash.md class X::Signature::NameClash Compilation error due to two named parameters with the same name ```raku my class X::Signature::NameClash does X::Comp { } ``` Compile time error thrown when two named parameters have the same name, potentially through aliases. For example ```raku sub f(:$a, :a(:@b)) { } ``` dies with 「text」 without highlighting ``` ``` ===SORRY!=== Name a used for more than one named parameter ``` ``` # [Methods](#class_X::Signature::NameClash "go to top of document")[§](#Methods "direct link") ## [method name](#class_X::Signature::NameClash "go to top of document")[§](#method_name "direct link") ```raku method name(--> Str:D) ``` Returns the name that was used for more than one parameter.
## dist_github-ramiroencinas-Win32-DrivesAndTypes.md Raku module - Provides a list of Win32 drives and drive types. ## OS Supported: Only Win32 by Native calls. ## Installing the module ``` zef update zef install Win32::DrivesAndTypes ``` ## Example Usage: ``` use v6; use Win32::DrivesAndTypes; say "Drive Type"; for Win32_Drives() { say $_ ~ " " ~ Win32_DriveType($_) } ``` ## Win32\_Drives() function Returns a @list of Strings with detected drives (A..Z). ## Win32\_DriveType(Str) function Accepts one string parameter with a letter drive (A..Z) and returns a string with the drive type that can be: * DRIVE\_UNKNOWN: The type cannot be determined. * DRIVE\_NO\_ROOT\_DIR: Invalid drive. * DRIVE\_REMOVABLE: USB sticks, external HD, etc. * DRIVE\_FIXED: HardDisk. * DRIVE\_REMOTE: Remote network drive like a shared folder. * DRIVE\_CDROM: CD-ROM drive. * DRIVE\_RAMDISK: RAM disk. * or ERROR.
## dist_zef-librasteve-Dan-Pandas.md [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) [![](https://github.com/librasteve/raku-Dan-Pandas/actions/workflows/pandas-weekly.yaml/badge.svg)](https://github.com/librasteve/raku-Dan-Pandas/actions/workflows/pandas-weekly.yaml) *THIS MODULE IS EXPERIMENTAL AND SUBJECT TO CHANGE WITHOUT NOTICE* # raku Dan::Pandas Dan::Pandas is the first specializer for the raku [Dan](https://github.com/librasteve/raku-Dan) **D**ata **AN**alysis Module. Dan::Pandas uses raku [Inline::Python](https://raku.land/cpan:NINE/Inline::Python) to construct shadow Python objects and to wrap them to maintain the Dan API. * Dan::Pandas::Series is a specialized Dan::Series * Dan::Pandas::DataFrame is a specialized Dan::DataFrame It adapts Dan maintaining **the base set of raku-style** datatype roles, accessors & methods - with a few exceptions as noted below, a Dan::Pandas object can be a drop in replacement for it's Dan equivalent. A Dockerfile is provided based on the Python [jupyter/scipy-notebook](https://jupyter-docker-stacks.readthedocs.io/en/latest/using/selecting.html#jupyter-scipy-notebook) - ideal for example Dan Jupyter notebooks! *Contributions via PR are very welcome - please see the backlog Issue, or just email [[email protected]](mailto:[email protected]) to share ideas!* # Installation * docker run -it librasteve/raku-dan:pandas-2022.02-amd64 -or- :pandas-2022.02-arm64 (see Dockerfile) [transitioning to docker run -it librasteve/raku-dan:pandas-amd64] * zef install <https://github.com/librasteve/raku-Dan-Pandas.git> * cd /usr/share/perl6/site/bin && ./synopsis-dan-pandas.raku # SYNOPSIS The raku Dan [README.md](https://github.com/librasteve/raku-Dan/blob/main/README.md) is a good outline of the Dan API. This synopsis emphasizes the differences, more examples in [bin/synopsis-dan-pandas.raku](https://github.com/librasteve/raku-Dan/blob/main/bin/synopsis-dan-pandas.raku). ``` #!/usr/bin/env raku use lib '../lib'; use Dan; #<== unlike a standalone Dan script, do NOT use the :ALL selector here use Dan::Pandas; ### Series ### ## Dan Similarities... my \s = Series.new( [rand xx 5], index => <a b c d e>); say ~s; #`[ a 0.297975 b 0.881274 c 0.868242 d 0.593949 e 0.141334 Name: anon, dtype: float64 #<== Dan::Pandas::Series has a Python numpy dtype #] # Methods s.dtype; s.ix; s.index; s.elems; s.map(*+2); s.splice(1,2,(j=>3)); my \t = Series.new( [f=>1, e=>0, d=>2] ); s.concat: t; # Operators & Accessors [+] s; s >>+>> 2; s >>+<< s; s[2]; s<c>; say "---------------------------------------------"; ## Dan Differences... say ~s.reindex(['d','e','f','g','h','i']); #<== reindex Pandas style, padding NaN #`[ d 0.593949 e 0.141334 f NaN g NaN h NaN i NaN #] Name: anon, dtype: float64 s.pull; #explicit pull operation synchronizes raku object attributes to shadow Python values (@.data, %.index, %.columns) #The Dan::Pandas .pd method takes a Python method call string and handles it from raku: s.pd: '.shape'; s.pd: '.flags'; s.pd: '.T'; s.pd: '.to_json("test.json")'; s.pd: '.to_csv("test.csv")'; s.pd: '.iloc[2] = 23'; s.pd: '.iloc[2]'; # 2-arity .pd methods are done like this: say ~my \quants = Series.new([100, 15, 50, 15, 25]); say ~my \prices = Series.new([1.1, 4.3, 2.2, 7.41, 2.89]); my \costs = quants; costs.pd: '.mul', prices; # round-trip to/from Dan::Series: my \u = s.Dan-Series; #Dan::Series [coerce from Dan::Pandas::Series] my \v = Series.new( u ); #Dan::Pandas::Series [construct from Dan::Series] say "---------------------------------------------"; ### DataFrames ### ## Dan Similarities... my \dates = (Date.new("2022-01-01"), *+1 ... *)[^6]; my \df = DataFrame.new( [[rand xx 4] xx 6], index => dates, columns => <A B C D> ); say ~df; # Accessors df[0;0]; # Data Accessors [row;col] df[0;0] = 3; # NOPE! <== unlike Dan, must use .pd method to set values, then optionally .pull df[0]<A>; # Cascading Accessors (mix Positional and Associative) df[0]; # 1d Row 0 (DataSlice) df[*]<A>; # 1d Col A (Series) # Operations [+] df[*;1]; # 2d Map/Reduce df >>+>> 2; # Hyper df.T; # Transpose df.shape; # Shape df.describe; # Describe df.sort: {.[1]}; # Sort by 2nd col (ascending) df.grep( {.[1] < 0.5} ); # Grep (binary filter) by 2nd column # Splice df2.splice( 1, 2, [j => $ds] ); # row-wise splice: df2.splice( :ax, 1, 2, [K => $se] ); # column-wise splice: axis => 1 # Concat my \dfa = DataFrame.new( [['a', 1], ['b', 2]], columns => <letter number> ); my \dfc = DataFrame.new( [['c', 3, 'cat'], ['d', 4, 'dog']], columns => <animal letter number> ); dfa.concat(dfc); say ~dfa; #`[ letter number animal 0 a 1 NaN 1 b 2 NaN 0⋅1 cat c 3.0 1⋅1 dog d 4.0 #] say "---------------------------------------------"; ## Dan Differences... df.pull; #explicit pull operation synchronizes raku object attributes to shadow Python values (@.data, %.index, %.columns) ### .pd Methods ### #The Dan::Pandas .pd method takes a Python method call string and handles it from raku: df.pd: '.flags'; df.pd: '.to_json("test.json")'; df.pd: '.to_csv("test.csv")'; df.pd: '.iloc[2] = 23'; df.pd: '.iloc[2]'; say ~df; #`[ A B C D 2022-01-01 0.744346 0.963167 0.548315 0.667035 2022-01-02 0.109722 0.007992 0.999305 0.613870 2022-01-03 23.000000 23.000000 23.000000 23.000000 2022-01-04 0.403802 0.762486 0.220328 0.152730 2022-01-05 0.245156 0.864305 0.577664 0.365762 2022-01-06 0.414237 0.981379 0.571082 0.926982 #] # 2-arity .pd methods and round trip follow the Series model ``` copyright(c) 2022 Henley Cloud Consulting Ltd.
## concurrency.md Concurrency Concurrency and asynchronous programming In common with most modern programming languages, Raku is designed to support parallelism, asynchronicity and [concurrency](https://en.wikipedia.org/wiki/Concurrent_computing). Parallelism is about doing multiple things at once. *Asynchronous programming*, which is sometimes called event driven or reactive programming, is about supporting changes in the program flow caused by events triggered elsewhere in the program. Finally, concurrency is about the coordination of access and modification of some shared resources. The aim of the Raku concurrency design is to provide a high-level, composable and consistent interface, regardless of how a virtual machine may implement it for a particular operating system, through layers of facilities as described below. Additionally, certain Raku features may implicitly operate in an asynchronous fashion, so in order to ensure predictable interoperation with these features, user code should, where possible, avoid the lower level concurrency APIs (e.g., [`Thread`](/type/Thread) and [`Scheduler`](/type/Scheduler)) and use the higher-level interfaces. # [High-level APIs](#Concurrency "go to top of document")[§](#High-level_APIs "direct link") ## [Promises](#Concurrency "go to top of document")[§](#Promises "direct link") A [`Promise`](/type/Promise) (also called *future* in other programming environments) encapsulates the result of a computation that may not have completed or even started at the time the promise is obtained. A [`Promise`](/type/Promise) starts from a `Planned` status and can result in either a `Kept` status, meaning the promise has been successfully completed, or a `Broken` status meaning that the promise has failed. Usually this is much of the functionality that user code needs to operate in a concurrent or asynchronous manner. ```raku my $p1 = Promise.new; say $p1.status; # OUTPUT: «Planned␤» $p1.keep('Result'); say $p1.status; # OUTPUT: «Kept␤» say $p1.result; # OUTPUT: «Result␤» # (since it has been kept, a result is available!) my $p2 = Promise.new; $p2.break('oh no'); say $p2.status; # OUTPUT: «Broken␤» say $p2.result; # dies, because the promise has been broken CATCH { default { say .^name, ': ', .Str } }; # OUTPUT: «X::AdHoc+{X::Promise::Broken}: oh no␤» ``` Promises gain much of their power by being composable, for example by chaining, usually by the [then](/type/Promise#method_then) method: ```raku my $promise1 = Promise.new(); my $promise2 = $promise1.then( -> $v { say $v.result; "Second Result" } ); $promise1.keep("First Result"); say $promise2.result; # OUTPUT: «First Result␤Second Result␤» ``` Here the [then](/type/Promise#method_then) method schedules code to be executed when the first [`Promise`](/type/Promise) is kept or broken, itself returning a new [`Promise`](/type/Promise) which will be kept with the result of the code when it is executed (or broken if the code fails). `keep` changes the status of the promise to `Kept` setting the result to the positional argument. `result` blocks the current thread of execution until the promise is kept or broken, if it was kept then it will return the result (that is the value passed to `keep`), otherwise it will throw an exception based on the value passed to `break`. The latter behavior is illustrated with: ```raku my $promise1 = Promise.new(); my $promise2 = $promise1.then(-> $v { say "Handled but : "; say $v.result}); $promise1.break("First Result"); try $promise2.result; say $promise2.cause; # OUTPUT: «Handled but : ␤First Result␤» ``` Here the `break` will cause the code block of the `then` to throw an exception when it calls the `result` method on the original promise that was passed as an argument, which will subsequently cause the second promise to be broken, raising an exception in turn when its result is taken. The actual [`Exception`](/type/Exception) object will then be available from `cause`. If the promise had not been broken `cause` would raise an [`X::Promise::CauseOnlyValidOnBroken`](/type/X/Promise/CauseOnlyValidOnBroken) exception. A [`Promise`](/type/Promise) can also be scheduled to be automatically kept at a future time: ```raku my $promise1 = Promise.in(5); my $promise2 = $promise1.then(-> $v { say $v.status; 'Second Result' }); say $promise2.result; ``` The [method in](/type/Promise#method_in) creates a new promise and schedules a new task to call `keep` on it no earlier than the supplied number of seconds, returning the new [`Promise`](/type/Promise) object. A very frequent use of promises is to run a piece of code, and keep the promise once it returns successfully, or break it when the code dies. The [start method](/type/Promise#method_start) provides a shortcut for that: ```raku my $promise = Promise.start( { my $i = 0; for 1 .. 10 { $i += $_ }; $i} ); say $promise.result; # OUTPUT: «55␤» ``` Here the `result` of the promise returned is the value returned from the code. Similarly if the code fails (and the promise is thus broken), then `cause` will be the [`Exception`](/type/Exception) object that was thrown: ```raku my $promise = Promise.start({ die "Broken Promise" }); try $promise.result; say $promise.cause; ``` This is considered to be such a commonly required pattern that it is also provided as a keyword: ```raku my $promise = start { my $i = 0; for 1 .. 10 { $i += $_ } $i } my $result = await $promise; say $result; ``` The subroutine [await](/type/Promise#sub_await) is almost equivalent to calling `result` on the promise object returned by `start` but it will also take a list of promises and return the result of each: ```raku my $p1 = start { my $i = 0; for 1 .. 10 { $i += $_ } $i }; my $p2 = start { my $i = 0; for 1 .. 10 { $i -= $_ } $i }; my @result = await $p1, $p2; say @result; # OUTPUT: «[55 -55]␤» ``` In addition to `await`, two class methods combine several [`Promise`](/type/Promise) objects into a new promise: `allof` returns a promise that is kept when all the original promises are kept or broken: ```raku my $promise = Promise.allof( Promise.in(2), Promise.in(3) ); await $promise; say "All done"; # Should be not much more than three seconds later ``` And `anyof` returns a new promise that will be kept when any of the original promises is kept or broken: ```raku my $promise = Promise.anyof( Promise.in(3), Promise.in(8600) ); await $promise; say "All done"; # Should be about 3 seconds later ``` Unlike `await` however the results of the original kept promises are not available without referring to the original, so these are more useful when the completion or otherwise of the tasks is more important to the consumer than the actual results, or when the results have been collected by other means. You may, for example, want to create a dependent Promise that will examine each of the original promises: ```raku my @promises; for 1..5 -> $t { push @promises, start { sleep $t; Bool.pick; }; } say await Promise.allof(@promises).then({ so all(@promises>>.result) }); ``` Which will give True if all of the promises were kept with True, False otherwise. If you are creating a promise that you intend to keep or break yourself then you probably don't want any code that might receive the promise to inadvertently (or otherwise) keep or break the promise before you do. For this purpose there is the [method vow](/type/Promise#method_vow), which returns a Vow object which becomes the only mechanism by which the promise can be kept or broken. If an attempt to keep or break the Promise is made directly then the exception [`X::Promise::Vowed`](/type/X/Promise/Vowed) will be thrown, as long as the vow object is kept private, the status of the promise is safe: ```raku sub get_promise { my $promise = Promise.new; my $vow = $promise.vow; Promise.in(10).then({$vow.keep}); $promise; } my $promise = get_promise(); # Will throw an exception # "Access denied to keep/break this Promise; already vowed" $promise.keep; CATCH { default { say .^name, ': ', .Str } }; # OUTPUT: «X::Promise::Vowed: Access denied to keep/break this Promise; already vowed␤» ``` The methods that return a promise that will be kept or broken automatically such as `in` or `start` will do this, so it is not necessary to do it for these. ## [Supplies](#Concurrency "go to top of document")[§](#Supplies "direct link") A [`Supply`](/type/Supply) is an asynchronous data streaming mechanism that can be consumed by one or more consumers simultaneously in a manner similar to "events" in other programming languages and can be seen as enabling *event driven* or reactive designs. At its simplest, a [`Supply`](/type/Supply) is a message stream that can have multiple subscribers created with the method `tap` on to which data items can be placed with `emit`. The [`Supply`](/type/Supply) can either be `live` or `on-demand`. A `live` supply is like a TV broadcast: those who tune in don't get previously emitted values. An `on-demand` broadcast is like Netflix: everyone who starts streaming a movie (taps a supply), always starts it from the beginning (gets all the values), regardless of how many people are watching it right now. Note that no history is kept for `on-demand` supplies, instead, the `supply` block is run for each tap of the supply. A `live` [`Supply`](/type/Supply) is created by the [`Supplier`](/type/Supplier) factory, each emitted value is passed to all the active tappers as they are added: ```raku my $supplier = Supplier.new; my $supply = $supplier.Supply; $supply.tap( -> $v { say $v }); for 1 .. 10 { $supplier.emit($_); } ``` Note that the `tap` is called on a [`Supply`](/type/Supply) object created by the [`Supplier`](/type/Supplier) and new values are emitted on the [`Supplier`](/type/Supplier). An `on-demand` [`Supply`](/type/Supply) is created by the `supply` keyword: ```raku my $supply = supply { for 1 .. 10 { emit($_); } } $supply.tap( -> $v { say $v }); ``` In this case the code in the supply block is executed every time the [`Supply`](/type/Supply) returned by `supply` is tapped, as demonstrated by: ```raku my $supply = supply { for 1 .. 10 { emit($_); } } $supply.tap( -> $v { say "First : $v" }); $supply.tap( -> $v { say "Second : $v" }); ``` The `tap` method returns a [`Tap`](/type/Tap) object which can be used to obtain information about the tap and also to turn it off when we are no longer interested in the events: ```raku my $supplier = Supplier.new; my $supply = $supplier.Supply; my $tap = $supply.tap( -> $v { say $v }); $supplier.emit("OK"); $tap.close; $supplier.emit("Won't trigger the tap"); ``` Calling `done` on the supply object calls the `done` callback that may be specified for any taps, but does not prevent any further events being emitted to the stream, or taps receiving them. The method `interval` returns a new `on-demand` supply which periodically emits a new event at the specified interval. The data that is emitted is an integer starting at 0 that is incremented for each event. The following code outputs 0 .. 5 : ```raku my $supply = Supply.interval(2); $supply.tap(-> $v { say $v }); sleep 10; ``` A second argument can be supplied to `interval` which specifies a delay in seconds before the first event is fired. Each tap of a supply created by `interval` has its own sequence starting from 0, as illustrated by the following: ```raku my $supply = Supply.interval(2); $supply.tap(-> $v { say "First $v" }); sleep 6; $supply.tap(-> $v { say "Second $v"}); sleep 10; ``` A live [`Supply`](/type/Supply) that keeps values until first tapped can be created with [`Supplier::Preserving`](/type/Supplier/Preserving). ### [`whenever`](#Concurrency "go to top of document")[§](#whenever "direct link") The `whenever` keyword can be used in supply blocks or in react blocks. From the 6.d version, it needs to be used within the lexical scope of them. It introduces a block of code that will be run when prompted by an asynchronous event that it specifies - that could be a [`Supply`](/type/Supply), a [`Channel`](/type/Channel), a [`Promise`](/type/Promise) or an [`Iterable`](/type/Iterable). Please note that one should keep the code inside the `whenever` as small as possible, as only one `whenever` block will be executed at any time. One can use a `start` block inside the `whenever` block to run longer running code. In this example we are watching two supplies. ```raku my $bread-supplier = Supplier.new; my $vegetable-supplier = Supplier.new; my $supply = supply { whenever $bread-supplier.Supply { emit("We've got bread: " ~ $_); }; whenever $vegetable-supplier.Supply { emit("We've got a vegetable: " ~ $_); }; } $supply.tap( -> $v { say "$v" }); $vegetable-supplier.emit("Radish"); # OUTPUT: «We've got a vegetable: Radish␤» $bread-supplier.emit("Thick sliced"); # OUTPUT: «We've got bread: Thick sliced␤» $vegetable-supplier.emit("Lettuce"); # OUTPUT: «We've got a vegetable: Lettuce␤» ``` ### [`react`](#Concurrency "go to top of document")[§](#react "direct link") The `react` keyword introduces a block of code containing one or more `whenever` keywords to watch asynchronous events. The main difference between a supply block and a react block is that the code in a react block runs where it appears in the code flow, whereas a supply block has to be tapped before it does anything. Another difference is that a supply block can be used without the `whenever` keyword, but a react block requires at least one `whenever` to be of any real use. ```raku react { whenever Supply.interval(2) -> $v { say $v; done() if $v == 4; } } ``` Here the `whenever` keyword uses [`.act`](/type/Supply#method_act) to create a tap on the [`Supply`](/type/Supply) from the provided block. The `react` block is exited when `done()` is called in one of the taps. Using `last` to exit the block would produce an error indicating that it's not really a loop construct. An `on-demand` [`Supply`](/type/Supply) can also be created from a list of values that will be emitted in turn, thus the first `on-demand` example could be written as: ```raku react { whenever Supply.from-list(1..10) -> $v { say $v; } } ``` ### [Transforming supplies](#Concurrency "go to top of document")[§](#Transforming_supplies "direct link") An existing supply object can be filtered or transformed, using the methods `grep` and `map` respectively, to create a new supply in a manner like the similarly named list methods: `grep` returns a supply such that only those events emitted on the source stream for which the `grep` condition is true is emitted on the second supply: ```raku my $supplier = Supplier.new; my $supply = $supplier.Supply; $supply.tap(-> $v { say "Original : $v" }); my $odd_supply = $supply.grep({ $_ % 2 }); $odd_supply.tap(-> $v { say "Odd : $v" }); my $even_supply = $supply.grep({ not $_ % 2 }); $even_supply.tap(-> $v { say "Even : $v" }); for 0 .. 10 { $supplier.emit($_); } ``` `map` returns a new supply such that for each item emitted to the original supply a new item which is the result of the expression passed to the `map` is emitted: ```raku my $supplier = Supplier.new; my $supply = $supplier.Supply; $supply.tap(-> $v { say "Original : $v" }); my $half_supply = $supply.map({ $_ / 2 }); $half_supply.tap(-> $v { say "Half : $v" }); for 0 .. 10 { $supplier.emit($_); } ``` ### [Ending a supply](#Concurrency "go to top of document")[§](#Ending_a_supply "direct link") If you need to have an action that runs when the supply finishes, you can do so by setting the `done` and `quit` options in the call to `tap`: ```raku $supply.tap: { ... }, done => { say 'Job is done.' }, quit => { when X::MyApp::Error { say "App Error: ", $_.message } }; ``` The `quit` block works very similar to a `CATCH`. If the exception is marked as seen by a `when` or `default` block, the exception is caught and handled. Otherwise, the exception continues to up the call tree (i.e., the same behavior as when `quit` is not set). ### [Phasers in a supply or react block](#Concurrency "go to top of document")[§](#Phasers_in_a_supply_or_react_block "direct link") If you are using the `react` or `supply` block syntax with `whenever`, you can add phasers within your `whenever` blocks to handle the `done` and `quit` messages from the tapped supply: ```raku react { whenever $supply { ...; # your usual supply tap code here LAST { say 'Job is done.' } QUIT { when X::MyApp::Error { say "App Error: ", $_.message } } } } ``` The behavior here is the same as setting `done` and `quit` on `tap`. ## [Channels](#Concurrency "go to top of document")[§](#Channels "direct link") A [`Channel`](/type/Channel) is a thread-safe queue that can have multiple readers and writers that could be considered to be similar in operation to a "fifo" or named pipe except it does not enable inter-process communication. It should be noted that, being a true queue, each value sent to the [`Channel`](/type/Channel) will only be available to a single reader on a first read, first served basis: if you want multiple readers to be able to receive every item sent you probably want to consider a [`Supply`](/type/Supply). An item is queued onto the [`Channel`](/type/Channel) with the [method send](/type/Channel#method_send), and the [method receive](/type/Channel#method_receive) removes an item from the queue and returns it, blocking until a new item is sent if the queue is empty: ```raku my $channel = Channel.new; $channel.send('Channel One'); say $channel.receive; # OUTPUT: «Channel One␤» ``` If the channel has been closed with the [method close](/type/Channel#method_close) then any `send` will cause the exception [`X::Channel::SendOnClosed`](/type/X/Channel/SendOnClosed) to be thrown, and a `receive` will throw an [`X::Channel::ReceiveOnClosed`](/type/X/Channel/ReceiveOnClosed). The [method list](/type/Channel#method_list) returns all the items on the [`Channel`](/type/Channel) and will block until further items are queued unless the channel is closed: ```raku my $channel = Channel.new; await (^10).map: -> $r { start { sleep $r; $channel.send($r); } } $channel.close; for $channel.list -> $r { say $r; } ``` There is also the non-blocking [method poll](/type/Channel#method_poll) that returns an available item from the channel or [`Nil`](/type/Nil) if there is no item or the channel is closed. This does mean that the channel must be checked to determine whether it is closed: ```raku my $c = Channel.new; # Start three Promises that sleep for 1..3 seconds, and then # send a value to our Channel ^3 .map: -> $v { start { sleep 3 - $v; $c.send: "$v from thread {$*THREAD.id}"; } } # Wait 3 seconds before closing the channel Promise.in(3).then: { $c.close } # Continuously loop and poll the channel, until it's closed my $is-closed = $c.closed; loop { if $c.poll -> $item { say "$item received after {now - INIT now} seconds"; } elsif $is-closed { last; } say 'Doing some unrelated things...'; sleep .6; } # Doing some unrelated things... # Doing some unrelated things... # 2 from thread 5 received after 1.2063182 seconds # Doing some unrelated things... # Doing some unrelated things... # 1 from thread 4 received after 2.41117376 seconds # Doing some unrelated things... # 0 from thread 3 received after 3.01364461 seconds # Doing some unrelated things... ``` The [method closed](/type/Channel#method_closed) returns a [`Promise`](/type/Promise) that will be kept (and consequently will evaluate to True in a Boolean context) when the channel is closed. The `.poll` method can be used in combination with `.receive` method, as a caching mechanism where lack of value returned by `.poll` is a signal that more values need to be fetched and loaded into the channel: ```raku sub get-value { return $c.poll // do { start replenish-cache; $c.receive }; } sub replenish-cache { for ^20 { $c.send: $_ for slowly-fetch-a-thing(); } } ``` Channels can be used in place of the [`Supply`](/type/Supply) in the `whenever` of a `react` block described earlier: ```raku my $channel = Channel.new; my $p = start { react { whenever $channel { say $_; } } } await (^10).map: -> $r { start { sleep $r; $channel.send($r); } } $channel.close; await $p; ``` It is also possible to obtain a [`Channel`](/type/Channel) from a [`Supply`](/type/Supply) using the [Channel method](/type/Supply#method_Channel) which returns a [`Channel`](/type/Channel) which is fed by a `tap` on the [`Supply`](/type/Supply): ```raku my $supplier = Supplier.new; my $supply = $supplier.Supply; my $channel = $supply.Channel; my $p = start { react { whenever $channel -> $item { say "via Channel: $item"; } } } await (^10).map: -> $r { start { sleep $r; $supplier.emit($r); } } $supplier.done; await $p; ``` [`Channel`](/type/Channel) will return a different [`Channel`](/type/Channel) fed with the same data each time it is called. This could be used, for instance, to fan-out a [`Supply`](/type/Supply) to one or more [`Channel`](/type/Channel)s to provide for different interfaces in a program. ## [Proc::Async](#Concurrency "go to top of document")[§](#Proc::Async "direct link") [`Proc::Async`](/type/Proc/Async) builds on the facilities described to run and interact with an external program asynchronously: ```raku my $proc = Proc::Async.new('echo', 'foo', 'bar'); $proc.stdout.tap(-> $v { print "Output: $v" }); $proc.stderr.tap(-> $v { print "Error: $v" }); say "Starting..."; my $promise = $proc.start; await $promise; say "Done."; # Output: # Starting... # Output: foo bar # Done. ``` The path to the command as well as any arguments to the command are supplied to the constructor. The command will not be executed until [start](/type/Proc/Async#method_start) is called, which will return a [`Promise`](/type/Promise) that will be kept when the program exits. The standard output and standard error of the program are available as [`Supply`](/type/Supply) objects from the methods [stdout](/type/Proc/Async#method_stdout) and [stderr](/type/Proc/Async#method_stderr) respectively which can be tapped as required. If you want to write to the standard input of the program you can supply the `:w` adverb to the constructor and use the methods [write](/type/Proc/Async#method_write), [print](/type/Proc/Async#method_print) or [say](/type/Proc/Async#method_say) to write to the opened pipe once the program has been started: ```raku my $proc = Proc::Async.new(:w, 'grep', 'foo'); $proc.stdout.tap(-> $v { print "Output: $v" }); say "Starting..."; my $promise = $proc.start; $proc.say("this line has foo"); $proc.say("this one doesn't"); $proc.close-stdin; await $promise; say "Done."; # Output: # Starting... # Output: this line has foo # Done. ``` Some programs (such as `grep` without a file argument in this example, ) won't exit until their standard input is closed so [close-stdin](/type/Proc/Async#method_close-stdin) can be called when you are finished writing to allow the [`Promise`](/type/Promise) returned by `start` to be kept. # [Low-level APIs](#Concurrency "go to top of document")[§](#Low-level_APIs "direct link") ## [Threads](#Concurrency "go to top of document")[§](#Threads "direct link") The lowest level interface for concurrency is provided by [`Thread`](/type/Thread). A thread can be thought of as a piece of code that may eventually be run on a processor, the arrangement for which is made almost entirely by the virtual machine and/or operating system. Threads should be considered, for all intents, largely un-managed and their direct use should be avoided in user code. A thread can either be created and then actually run later: ```raku my $thread = Thread.new(code => { for 1 .. 10 -> $v { say $v }}); # ... $thread.run; ``` Or can be created and run at a single invocation: ```raku my $thread = Thread.start({ for 1 .. 10 -> $v { say $v }}); ``` In both cases the completion of the code encapsulated by the [`Thread`](/type/Thread) object can be waited on with the `finish` method which will block until the thread completes: ```raku $thread.finish; ``` Beyond that there are no further facilities for synchronization or resource sharing which is largely why it should be emphasized that threads are unlikely to be useful directly in user code. ## [Schedulers](#Concurrency "go to top of document")[§](#Schedulers "direct link") The next level of the concurrency API is supplied by classes that implement the interface defined by the role [`Scheduler`](/type/Scheduler). The intent of the scheduler interface is to provide a mechanism to determine which resources to use to run a particular task and when to run it. The majority of the higher level concurrency APIs are built upon a scheduler and it may not be necessary for user code to use them at all, although some methods such as those found in [`Proc::Async`](/type/Proc/Async), [`Promise`](/type/Promise) and [`Supply`](/type/Supply) allow you to explicitly supply a scheduler. The current default global scheduler is available in the variable `$*SCHEDULER`. The primary interface of a scheduler (indeed the only method required by the [`Scheduler`](/type/Scheduler) interface) is the `cue` method: ```raku method cue(:&code, Instant :$at, :$in, :$every, :$times = 1; :&catch) ``` This will schedule the [`Callable`](/type/Callable) in `&code` to be executed in the manner determined by the adverbs (as documented in [`Scheduler`](/type/Scheduler)) using the execution scheme as implemented by the scheduler. For example: ```raku my $i = 0; my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 ); sleep 20; ``` Assuming that the `$*SCHEDULER` hasn't been changed from the default, will print the numbers 0 to 10 approximately (i.e with operating system scheduling tolerances) every two seconds. In this case the code will be scheduled to run until the program ends normally, however the method returns a [`Cancellation`](/type/Cancellation) object which can be used to cancel the scheduled execution before normal completion: ```raku my $i = 0; my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 ); sleep 10; $cancellation.cancel; sleep 10; ``` should only output 0 to 5. Despite the apparent advantage the [`Scheduler`](/type/Scheduler) interface provides over that of [`Thread`](/type/Thread) all of functionality is available through higher level interfaces and it shouldn't be necessary to use a scheduler directly, except perhaps in the cases mentioned above where a scheduler can be supplied explicitly to certain methods. A library may wish to provide an alternative scheduler implementation if it has special requirements, for instance a UI library may want all code to be run within a single UI thread, or some custom priority mechanism may be required, however the implementations provided as standard and described below should suffice for most user code. ### [ThreadPoolScheduler](#Concurrency "go to top of document")[§](#ThreadPoolScheduler "direct link") The [`ThreadPoolScheduler`](/type/ThreadPoolScheduler) is the default scheduler, it maintains a pool of threads that are allocated on demand, creating new ones as necessary. Rakudo allows the maximum number of threads allowed in the default scheduler to be set by the environment variable `RAKUDO_MAX_THREADS` at the time the program is started. If the maximum is exceeded then `cue` may queue the code until a thread becomes available. ### [CurrentThreadScheduler](#Concurrency "go to top of document")[§](#CurrentThreadScheduler "direct link") The [`CurrentThreadScheduler`](/type/CurrentThreadScheduler) is a very simple scheduler that will always schedule code to be run straight away on the current thread. The implication is that `cue` on this scheduler will block until the code finishes execution, limiting its utility to certain special cases such as testing. ## [Locks](#Concurrency "go to top of document")[§](#Locks "direct link") The class [`Lock`](/type/Lock) provides the low level mechanism that protects shared data in a concurrent environment and is thus key to supporting thread-safety in the high level API, this is sometimes known as a "Mutex" in other programming languages. Because the higher level classes ([`Promise`](/type/Promise), [`Supply`](/type/Supply) and [`Channel`](/type/Channel)) use a [`Lock`](/type/Lock) where required it is unlikely that user code will need to use a [`Lock`](/type/Lock) directly. The primary interface to [`Lock`](/type/Lock) is the method [protect](/type/Lock#method_protect) which ensures that a block of code (commonly called a "critical section") is only executed in one thread at a time: ```raku my $lock = Lock.new; my $a = 0; await (^10).map: { start { $lock.protect({ my $r = rand; sleep $r; $a++; }); } } say $a; # OUTPUT: «10␤» ``` `protect` returns whatever the code block returns. Because `protect` will block any threads that are waiting to execute the critical section the code should be as quick as possible. # [Safety concerns](#Concurrency "go to top of document")[§](#Safety_concerns "direct link") Some shared data concurrency issues are less obvious than others. For a good general write-up on this subject see this [blog post](https://6guts.wordpress.com/2014/04/17/racing-to-writeness-to-wrongness-leads/). One particular issue of note is when container autovivification or extension takes place. When an [`Array`](/type/Array) or a [`Hash`](/type/Hash) entry is initially assigned the underlying structure is altered and that operation is not async safe. For example, in this code: ```raku my @array; my $slot := @array[20]; $slot = 'foo'; ``` The third line is the critical section as that is when the array is extended. The simplest fix is to use a [`Lock`](/type/Lock) to protect the critical section. A possibly better fix would be to refactor the code so that sharing a container is not necessary.
## rolecontainer.md role Metamodel::RoleContainer Metaobject that supports holding/containing roles ```raku role Metamodel::RoleContainer {} ``` *Warning*: this role is part of the Rakudo implementation, and is not a part of the language specification. Implements the ability to hold roles to be held for composition. ```raku class A does SomeRole {} ``` roughly corresponds to ```raku class A { BEGIN A.^add_role(SomeRole); } ``` # [Methods](#role_Metamodel::RoleContainer "go to top of document")[§](#Methods "direct link") ## [method add\_role](#role_Metamodel::RoleContainer "go to top of document")[§](#method_add_role "direct link") ```raku method add_role($obj, Mu $role) ``` Adds the `$role` to the list of roles to be composed. ## [method roles\_to\_compose](#role_Metamodel::RoleContainer "go to top of document")[§](#method_roles_to_compose "direct link") ```raku method roles_to_compose($obj --> List:D) ``` returns a list of roles added with `add_role`, which are to be composed at type composition time.
## dist_zef-raku-community-modules-Proc-Q.md [![Actions Status](https://github.com/raku-community-modules/Proc-Q/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Proc-Q/actions) # NAME Proc::Q - Queue up and run a herd of Procs # SYNOPSIS ``` use Proc::Q; # Run 26 procs; each receiving stuff on STDIN and putting stuff out # to STDOUT, as well as sleeping for increasingly long periods of # time. The timeout of 3 seconds will kill all the procs that sleep # longer than that. my @stuff = 'a'..'z'; my $proc-chan = proc-q @stuff.map({«perl6 -e "print '$_' ~ \$*IN.slurp; sleep $($++/5)"»}), tags => @stuff.map('Letter ' ~ *), in => @stuff.map(*.uc), timeout => 3; react whenever $proc-chan { say "Got a result for {.tag}: STDOUT: {.out}" ~ (". Killed due to timeout" if .killed) } # OUTPUT: # Got a result for Letter a: STDOUT: aA # Got a result for Letter b: STDOUT: bB # Got a result for Letter c: STDOUT: cC # Got a result for Letter d: STDOUT: dD # Got a result for Letter e: STDOUT: eE # Got a result for Letter f: STDOUT: fF # Got a result for Letter g: STDOUT: gG # Got a result for Letter h: STDOUT: hH # Got a result for Letter i: STDOUT: iI # Got a result for Letter j: STDOUT: jJ # Got a result for Letter k: STDOUT: kK # Got a result for Letter l: STDOUT: lL # Got a result for Letter m: STDOUT: mM # Got a result for Letter n: STDOUT: nN # Got a result for Letter o: STDOUT: oO. Killed due to timeout # Got a result for Letter p: STDOUT: pP. Killed due to timeout # Got a result for Letter s: STDOUT: sS. Killed due to timeout # Got a result for Letter t: STDOUT: tT. Killed due to timeout # Got a result for Letter v: STDOUT: vV. Killed due to timeout # Got a result for Letter w: STDOUT: wW. Killed due to timeout # Got a result for Letter q: STDOUT: qQ. Killed due to timeout # Got a result for Letter r: STDOUT: rR. Killed due to timeout # Got a result for Letter u: STDOUT: uU. Killed due to timeout # Got a result for Letter x: STDOUT: xX. Killed due to timeout # Got a result for Letter y: STDOUT: yY. Killed due to timeout # Got a result for Letter z: STDOUT: zZ. Killed due to timeout ``` # DESCRIPTION **Requires Rakudo 2017.06 or newer**. Got a bunch of [`Procs`](https://docs.perl6.org/type/Proc) you want to queue up and run, preferably with some timeout for Procs that get stuck? Well, good news! # EXPORTED SUBROUTINES AND TYPES ## proc-q Defined as: ``` sub proc-q( +@commands where .so && .all ~~ List & .so, :@tags where .elems == @commands = @commands, :@in where { .elems == @commands|0 and all .map: {$_ ~~ Cool:D|Blob:D|Nil or $_ === Any} } = (Nil xx @commands).List, Numeric :$timeout where .DEFINITE.not || $_ > 0, UInt:D :$batch where .so = 8, :$out where Bool:D|'bin' = True, :$err where Bool:D|'bin' = True, Bool:D :$merge where .not | .so & ( $out & $err & ( ($err eq 'bin' & $out eq 'bin') | ($err ne 'bin' & $out ne 'bin'))) = False, --> Channel:D ) ``` See SYNOPSIS for sample use. Returns a [`Channel`](https://docs.raku.org/type/Channel) of `Proc::Q::Res` objects. Batches the `@commands` in batches of `$batch` and runs those via in parallel, optionally feeding STDIN with corresponding data from `@in`, as well as capturing STDOUT/STDERR, and [killing the process](https://docs.raku.org/type/Proc::Async#method_kill) after `$timeout`, if specified. Arguments are as follows: ### +@commands A list of lists, where each of inner lists is a list of arguments to [`Proc::Async.new`](https://docs.raku.org/type/Proc::Async#method_new). You do not need to specify the `:w` argument, and if you do, its value will be ignored. Must have at least one list of commands inside `@commands`. ### :@tags To make it possible to match the input with the output, you can `tag` each of the commands in `@commands` by specifying the value via `@tags` argument at the same index as the command is at. The given tag will be available via `.tag` method of the `Proc::Q::Res` object responsible. Any object can be used as a tag. If <:@tags> is provided, it must have the same number of elements as `+@commands` argument. If it's not provided, it defaults to `@commands`. ### :@in Optionally, you can send stuff to STDIN of your procs, by giving a `Blob` or `Str` in `:@in` arg at the same index as the the index of the command for that proc in `@commands`. If specified, the number of elements in `@in` must be the same as number of elements in `@commands`. Specify undefined value to avoid sending STDIN to a particular proc. TIP: is your queue hanging for some reason? Ensure the procs you're running arent's sitting and waiting for STDIN. Try passing an empty strings in `:@in`. ### :$batch Takes a positive `Int`. Defaults to `8`. Specifies how many `@commands` to run at the same time. ### :$timeout By default is not specified. Takes a positive `Numeric` specifying the number of seconds after which a proc should be killed, if it did not complete yet. Timer starts ticking once the proc is [`.ready`](https://docs.raku.org/type/Proc::Async#method_ready). The process is killed with `SIGTERM` signal and if after 1 second it's still alive, it gets another kill with `SIGSEGV`. ### :$out Defaults to `True`. If set to `True` or string `'bin'`, the routine will capture STDOUT from the procs, and make it available in `.out` method of `Proc::Q::Res` object. If set to string <'bin'>, the output will be captured in binary and `.out` method will contain a `Blob` instead of `Str`. ### :$err Same as `:$out` except as applied to procs' STDERR. ### :$merge Defaults to `False`. If set to `True`, both `:$err` and `:$out` must be set to `True` or both set to string `'bin'`. If set to `True`, the `.merged` method will contain the merged output of STDOUT and STDERR (so it'll be a `Str` or, if the `:$out`/`:$err` arei set to `'bin'`, a `Blob`). **Note** that there's no order guarantee. Output from a proc sent to STDERR after output to STDOUT, might end up *before* STDOUT's data in `.merged` object. ## Proc::Q::Res Each of the item sent to the `Channel` from `proc-q` routine will be a `Proc::Q::Res` object (technically, it might also be an `Exception` object if something explodes while trying to launch and wait for a proc, but it's of the "should never happen" variety; the `Exception` will be the reason why stuff exploded). While the `@commands` to be executed will be batched in `:$batch` items, the order within batches is not guaranteed. Use `:@tags` to match the `Proc::Q::Res` to the input commands. The `Proc::Q::Res` type contains information about the proc that was ran and provides these methods: ### .tag The same object that was given as a tag via `:@tags` argument (by default, the command from `@commands` that was executed). The purpose of the `.tag` is to match this `Proc::Q::Res` object to the proc you ran. ### .out Contains a `Stringy` with STDOUT of the proc if `:$out` argument to `proc-q` is set to a true value. ### .err Contains a `Stringy` with STDERR of the proc if `:$err` argument to `proc-q` is set to a true value. ### .merged Contains a `Stringy` with merged STDOUT and STDERR of the proc if `:$merge` argument to `proc-q` is set to a true value. Note that even when `:$merge` is in use, the `.out` and `.err` methods will contain the separated streams. ### .exitcode Contains [the exit code](https://docs.raku.org/type/Proc#method_exitcode) of the executed proc. ### .killed A `Bool:D` that is `True` if this proc was killed due to the `:$timeout`. More precisely, this is an indication that the timeout expired and the kill code started to run. It **is** possible for a proc to successfully complete in this small window opportunity between the attribute being set and the signal from [`.kill`](https://docs.raku.org/type/Proc::Async#method_kill) being received by the process. # AUTHOR Zoffix Znet # COPYRIGHT AND LICENSE Copyright 2017 - 2018 Zoffix Znet Copyright 2019 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-thundergnat-Text-Levenshtein.md [![Actions Status](https://github.com/thundergnat/Text-Levenshtein/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Text-Levenshtein/actions) # NAME Text::Levenshtein - A port of the Perl 5 Text::Levenshtein # SYNOPSIS Find the Levenshtein edit distance. This is a direct port of the Perl 5 version and should be close to 100% similar other then some Raku idioms. The fastdistance routine was not ported since the logic was buggy and the code to fix it made it the same speed as the regular distance routine. ``` use Text::Levenshtein qw(distance); print distance("foo","four"); # prints "2" my @words=("four","foo","bar"); my @distances=distance("foo",@words); print "@distances"; # prints "2 0 3" ``` # DESCRIPTION This module implements the Levenshtein edit distance. The Levenshtein edit distance is a measure of the degree of proximity between two strings. This distance is the number of substitutions, deletions or insertions ("edits") needed to transform one string into the other one (and vice versa). When two strings have distance 0, they are the same. A good point to start is: <http://www.merriampark.com/ld.htm> # AUTHOR Copyright 2002 Dree Mistrut [[email protected]](mailto:[email protected]) Raku port: 2010 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.
## dist_zef-bradclawsie-WebService-AWS-Auth-V4.md [![](https://img.shields.io/badge/License-BSD-yellow.svg)](https://opensource.org/licenses/BSD-2-Clause) [![ci](https://github.com/bradclawsie/Net-IP-Parse/workflows/test/badge.svg)](https://github.com/bradclawsie/Webservice-AWS-Auth-V4/actions) # WebService::AWS::Auth::V4 A library for AWS Auth V4 methods. ## DESCRIPTION AWS employs a set of signing processes in order to create authorized requests. This library provides an implementation of the v4 signing requirements as described here: <http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html> This library conforms to a set of published conformance tests that AWS publishes here: <http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html> This library passes these tests. This is not a general purpose library for using AWS services, although v4 signing is a requirement for any toolkit that provides an AWS API, so this library may be useful as a foundation for an AWS API. ## SYNOPSIS ``` use v6; use Test; use WebService::AWS::Auth::V4; my constant $service = 'iam'; my constant $region = 'us-east-1'; my constant $secret = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'; my constant $access_key = 'AKIDEXAMPLE'; my constant $get = 'GET'; my constant $aws_sample_uri = 'https://iam.amazonaws.com/?Action=ListUsers&Version=2010-05-08'; my Str @aws_sample_headers = "Host:iam.amazonaws.com", "Content-Type:application/x-www-form-urlencoded; charset=utf-8", "X-Amz-Date:20150830T123600Z"; my $v4 = WebService::AWS::Auth::V4.new(method => $get, body => '', uri => $aws_sample_uri, headers => @aws_sample_headers, region => $region, service => $service, secret => $secret, access_key => $access_key); my $cr = $v4.canonical_request(); my $cr_sha256 = WebService::AWS::Auth::V4::sha256_base16($cr); is WebService::AWS::Auth::V4::sha256_base16($cr), 'f536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59', 'match aws test signature for canonical request'; is $v4.string_to_sign, "AWS4-HMAC-SHA256\n20150830T123600Z\n20150830/us-east-1/iam/aws4_request\nf536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59", 'string to sign'; is $v4.signature, '5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7', 'signature'; is $v4.signing_header(), 'Authorization: AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7', 'authorization header'; ``` ## AUTHOR Brad Clawsie (zef:bradclawsie, email:[email protected]) ## Notice This repository was uploaded via `fez` under the username `b7j0c`, and later `bradclawsie`. This change was made so the username would match Github. Sorry for any confusion. ## Installation ``` zef install Webservice::AWS::Auth::V4 ```
## dist_cpan-MARTIMM-Unicode-PRECIS.md [![Build Status](https://travis-ci.org/MARTIMM/unicode-precis.svg?branch=master)](https://travis-ci.org/MARTIMM/unicode-precis) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/MARTIMM/unicode-precis?branch=master&passingText=Windows%20-%20OK&failingText=Windows%20-%20FAIL&pendingText=Windows%20-%20pending&svg=true)](https://ci.appveyor.com/project/MARTIMM/unicode-precis/branch/master) [![License](http://martimm.github.io/label/License-label.svg)](http://www.perlfoundation.org/artistic_license_2_0) # PRECIS Framework: Preparation, Enforcement, and Comparison of Internationalized Strings in Application Protocols Many tests are based on the Unicode® database as well as the unicode tools from perl6. Not all methods and functions are in place e.g. uniprop() is not yet available in the jvm. Also perl6 seems to be based on Unicode version 8.0.0 but is scheduled for 9.0.0. However parts are working in version 9.0.0 now. Not available in jvm yet are uniprop, uniprop-bool, uniprop-int, uniprop-str. ## Synopsis ``` use Unicode::PRECIS; use Unicode::PRECIS::Identifier::UsernameCasePreserved; my Unicode::PRECIS::Identifier::UsernameCaseMapped $uname-profile .= new; my Str $username = "نجمة-الصباح"; my TestValue $tv = $uname-profile.enforce($username); if $tv ~~ Str { say "Username $username accepted but converted to $tv"; } elsif $tv ~~ Bool { say "Username not accepted"; } ``` ## RFC's and program documentation #### Module documentation * [Bugs, known limitations and todo](https://github.com/MARTIMM/unicode-precis/blob/master/doc/TODO.md) * [Release notes](https://github.com/MARTIMM/unicode-precis/blob/master/doc/CHANGES.md) #### Base information for the modules I've started to study rfc4013 for SASLprep. Then recognized it was a profile based on Stringprep specified in rfc3454. Both are obsoleted by rfc7613 and rfc7564 resp because they are tied to Unicode version 3.2. The newer rfc's are specified to be free of any Unicode version. * rfc3454 - Preparation of Internationalized Strings ("stringprep"). * [rfc7564 - PRECIS Framework: Preparation, Enforcement, and Comparison of Internationalized Strings in Application Protocols](https://tools.ietf.org/html/rfc7564#section-4.1) Obsoletes rfc3454. * rfc4013 - SASLprep: Stringprep Profile for User Names and Passwords * [rfc7613 - Preparation, Enforcement, and Comparison of Internationalized Strings Representing Usernames and Passwords](https://tools.ietf.org/html/rfc7613#section-3.1) Obsoletes rfc4013. #### Further needed information * [rfc5892 - The Unicode Code Points and Internationalized Domain Names for Applications (IDNA)](https://tools.ietf.org/html/rfc5892#section-2.8) * [rfc5893 - Right-to-Left Scripts for Internationalized Domain Names for Applications (IDNA)](https://tools.ietf.org/html/rfc5893#section-2) Several files are found at the Unicode® Character Database to generate the tables needed to find the proper character classes. #### From unicode.org * [UnicodeData.txt](http://www.unicode.org/Public/9.0.0/ucd/UnicodeData.txt) * [Whole zip file UCD.zip of version 9.0.0 including UnicodeData.txt](http://www.unicode.org/Public/9.0.0/ucd/UCD.zip) * Unicode Data File Format * [Unicode Normalization Forms #15](http://unicode.org/reports/tr15/) * [Unicode Character Database #44](http://unicode.org/reports/tr44/) * [East Asian Width #11](http://unicode.org/reports/tr11/) * [Unicode Bidirectional Algorithm #9](http://unicode.org/reports/tr9/) ## Perl 6 Perl 6 uses graphemes as a base for the Str string type. These are the visible entities which show as a single symbol and are counted as such with the `Str.chars` method. From this, normal forms can be generated using the string methods uniname, uninames, unival, univals, NFC, NFD, NFKC and NFKD. Furthermore the strings can be encoded to utf-8. #### Versions of perl, moarvm This project is tested with latest Rakudo built on MoarVM implementing Perl v6.c. ## Implementation track First the basis of the PRECIS framework will be build. As soon as possible a profile for usernames and passwords follows. This is my first need. When this functions well enough, other profiles can be inserted. Much of it is now Implemented. Naming of modules; * Unicode::PRECIS using rfc7564 * Unicode::PRECIS::Identifier using rfc7564 * Unicode::PRECIS::Identifier::UsernameCaseMapped using rfc7613 * Unicode::PRECIS::Identifier::UsernameCasePreserved using rfc7613 * Unicode::PRECIS::Freeform using rfc7564 * Unicode::PRECIS::Freeform::OpaqueString using rfc7613 ## Authors ``` Marcel Timmerman translation of the modules for perl 6 ``` ## Contact MARTIMM [on github](https://github.com/MARTIMM)
## dist_github-ugexe-Text-Levenshtein-Damerau.md ## Text::Levenshtein::Damerau Levenshtein and Damerau Levenshtein edit distances ## Synopsis ``` use Text::Levenshtein::Damerau; say dld('Neil','Niel'); # damerau levenstein distance # prints 1 say ld('Neil','Niel'); # levenshtein distance prints 2 ``` ## Description Returns the true Levenshtein or Damerau Levenshtein edit distance of strings with adjacent transpositions. ### Routines #### dld($source, $target, $max? --> Int) Damerau Levenshtein Distance (Levenshtein Distance including transpositions) `$max distance. 0 = unlimited. Default = 0` ``` use Text::Levenshtein::Damerau; say dld('AABBCC','AABCBCD'); # prints 2 # Max edit distance of 1 say dld('AABBCC','AABCBCD',1); # distance is 2 # prints Int ``` #### ld($source, $target, $max? --> Int) Levenshtein Distance (no transpositions) `$max distance. 0 = unlimited. Default = 0` ``` use Text::Levenshtein::Damerau; say ld('AABBCC','AABCBCD'); # prints 3 # Max edit distance of 1 # Uses regular Levenshtein distance (no transpositions) say ld('AABBCC','AABCBCD',1); # distance is 3 # prints Int ``` ## Bugs Please report bugs to: <https://github.com/ugexe/Raku-Text--Levenshtein--Damerau/issues>
## unique.md unique Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_unique "direct link") See primary documentation [in context](/type/Any#method_unique) for **method unique**. ```raku multi method unique() multi method unique( :&as!, :&with! ) multi method unique( :&as! ) multi method unique( :&with! ) ``` Creates a sequence of unique elements either of the object or of `values` in the case it's called as a `sub`. ```raku <1 2 2 3 3 3>.unique.say; # OUTPUT: «(1 2 3)␤» say unique <1 2 2 3 3 3>; # OUTPUT: «(1 2 3)␤» ``` The `:as` and `:with` parameters receive functions that are used for transforming the item before checking equality, and for checking equality, since by default the [`===`](/routine/===) operator is used: ```raku ("1", 1, "1 ", 2).unique( as => Int, with => &[==] ).say; # OUTPUT: «(1 2)␤» ``` Please see [`unique`](/type/independent-routines#routine_unique) for additional examples that use its sub form. # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_routine_unique "direct link") See primary documentation [in context](/type/independent-routines#routine_unique) for **routine unique**. ```raku multi unique(+values, |c) ``` Returns a sequence of **unique** values from the invocant/argument list, such that only the first occurrence of each duplicated value remains in the result list. `unique` uses the semantics of the [===](/routine/===) operator to decide whether two objects are the same, unless the optional `:with` parameter is specified with another comparator. The order of the original list is preserved even as duplicates are removed. Examples: ```raku say <a a b b b c c>.unique; # OUTPUT: «(a b c)␤» say <a b b c c b a>.unique; # OUTPUT: «(a b c)␤» ``` (Use [squish](/routine/squish) instead if you know the input is sorted such that identical objects are adjacent.) The optional `:as` parameter allows you to normalize/canonicalize the elements before unique-ing. The values are transformed for the purposes of comparison, but it's still the original values that make it to the result list; however, only the first occurrence will show up in that list: Example: ```raku say <a A B b c b C>.unique(:as(&lc)) # OUTPUT: «(a B c)␤» ``` One can also specify the comparator with the optional `:with` parameter. For instance if one wants a list of unique hashes, one could use the `eqv` comparator. Example: ```raku my @list = %(a => 42), %(b => 13), %(a => 42); say @list.unique(:with(&[eqv])) # OUTPUT: «({a => 42} {b => 13})␤» ``` **Note:** since `:with` [`Callable`](/type/Callable) has to be tried with all the items in the list, this makes `unique` follow a path with much higher algorithmic complexity. You should try to use the `:as` argument instead, whenever possible. # [In Supply](#___top "go to top of document")[§](#(Supply)_method_unique "direct link") See primary documentation [in context](/type/Supply#method_unique) for **method unique**. ```raku method unique(Supply:D: :$as, :$with, :$expires --> Supply:D) ``` Creates a supply that only provides unique values, as defined by the optional `:as` and `:with` parameters (same as with [`unique`](/type/independent-routines#routine_unique)). The optional `:expires` parameter how long to wait (in seconds) before "resetting" and not considering a value to have been seen, even if it's the same as an old value.
## made.md made Combined from primary sources listed below. # [In Match](#___top "go to top of document")[§](#(Match)_method_made "direct link") See primary documentation [in context](/type/Match#method_made) for **method made**. ```raku method made() ``` Returns the payload that was set with [`make`](/routine/make).
## dist_zef-2colours-HTML-Template.md # A simple almost-port of CPAN's HTML::Template to Raku This is the fork from: <https://github.com/masak/html-template> ## License information Module `HTML::Template` is free and opensource software, so you can redistribute it and/or modify it under the terms of the [The Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0). ## TODO Nested IF statements don't seem to work: ``` <TMPL_IF a> <TMPL_IF b> </TMPL_IF> </TMPL_IF> ``` It seems that in `<TMPL_VAR name>` *name* is case sensitive. ## Authors Originally taken from `AUTHORS` file: Here is a list of people and their CPAN id. These people have either submitted patches or suggestions, or their bug reports or comments have inspired the appropriate patches. Corrections, additions, deletions welcome: ``` Ilya Belikin (aka Ihrd) Илья Беликин <[email protected]> Moritz Lenz (MORITZ) Lyle <http://groups.google.com/group/november-wiki/browse_thread/thread/c046d7892a60eaa5> Carl Masak (MASAK) Carl Mäsak <[email protected]> Johan Viklund (VIKLUND) <[email protected]> ```
## dist_zef-vrurg-Test-Async.md # NAME `Test::Async` - asynchronous, thread-sage testing # SYNOPSYS ``` use Test::Async; plan 2, :parallel; subtest "Async 1" => { plan 1; pass "a test" } subtest "Async 2" => { plan 1; pass "another test" } ``` # DESCRIPTION `Test::Async` provides a framework and a base set of tests tools compatible with the standard Raku `Test` module. But contrary to the standard, `Test::Async` has been developed with two primary goals in mind: concurrency and extensibility. Here is the key features provided: * event-driven, threaded, and OO core * easy development of 3rd party test bundles * asynchronous and/or random execution of subtests * support of threaded user code The SYNOPSYS section provides an example where two subtests would be started in parallel, each in its own thread. This allows to achieve two goals: speed up big test suits by splitting them in smaller chunks; and testing for possible concurrency problems in tested code. With ``` plan $count, :random; ``` subtests will be executed in random order. In this mode it is possible to catch another class of errors caused by code being dependent on the order execution. It is also possible to combine both *parallel* and *random* modes of operation. # WAY MORE IN * [`Test::Async::Manual`](docs/md/Test/Async/Manual.md) * [`Test::Async::CookBook`](docs/md/Test/Async/CookBook.md) * [`Test::Async`](docs/md/Test/Async.md) * [`Test::Async::Base`](docs/md/Test/Async/Base.md) * [`ChangeLog`](ChangeLog.md) * [`INDEX`](INDEX.md) # COPYRIGHT (c) 2023, Vadim Belman [[email protected]](mailto:[email protected]) # LICENSE Artistic License 2.0 See the [*LICENSE*](LICENSE) file in this distribution.
## empty.md Empty Combined from primary sources listed below. # [In Slip](#___top "go to top of document")[§](#(Slip)_constant_Empty "direct link") See primary documentation [in context](/type/Slip#constant_Empty) for **constant Empty**. `Empty` is a `Slip` of the empty [`List`](/type/List). ```raku say "".comb ~~ Empty; # OUTPUT: «True␤» ``` For example, these constructs with a failing test return `Empty`: ```raku do if 0 {}; (42 if 0); do with Any {}; (42 with Any); ```
## dist_cpan-MELEZHIK-Sparrowdo-VSTS-YAML-DotNet.md # Sparrowdo::VSTS::YAML:DotNet Sparrowdo module to generate VSTS yaml steps to build dotnet application. ``` $ cat sparrowfile module_run "VSTS::YAML::DotNet", %( build-dir => "cicd/build", project => "app.csproj", # The path to the csproj file(s) to use. You can use wildcards; configuration => "debug", # Build configuration, default value display-name => "Build app.csproj", # optional ); $ sparrowdo --local_mode --no_sudo ``` # Parameters ## project The path to the csproj file(s) to use. You can use wildcards ## configuration Build configuration # See also * Sparrowdo::VSTS::YAML::Solution * Sparrowdo::VSTS::YAML::MsBuild # Author Alexey Melezhik
## dist_zef-tbrowder-Number-More.md [![Actions Status](https://github.com/tbrowder/Number-More/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/Number-More/actions) [![Actions Status](https://github.com/tbrowder/Number-more/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/Number-More/actions) [![Actions Status](https://github.com/tbrowder/Number-More/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/Number-More/actions) # Number::More **Note: This module will be deprecated when new module 'Number' is released as version 1.0.0.** ## Synopsis ``` use Number::More :ALL; my $bin = '11001011'; # do not enter any prefix my $hex = bin2hex $bin; say $hex; # OUTPUT: 'CB' ``` ## The Number::More module This module provides some convenience functions to convert unsigned integers between different, commonly used number bases: decimal, hexadecimal, octal, and binary. There is also a function to convert between bases 2 through 62. Note that bases greater than 36 will use a set of digits consisting of a case-sensitive set of ASCII characters in an array indexed from 0..base-1, and the reverse mapping is in a hash. Both exported variables are shown in [NUMBERS](https://github.com/tbrowder/Number-More/blob/master/docs/NUMBERS.md). Also included in that document is more information on other exported variables, number systems (and references), and their use in this module. The current subroutines are described in detail in [SUBS](https://github.com/tbrowder/Number-More/blob/master/docs/SUBS.md) which shows a short description of each exported routine along along with its complete signature. The functions in this module are recommended for users who don't want to have to deal with the messy code involved with such transformations and who want an easy interface to get the various results they may need. As an example of the detail involved, any transformation from a non-decimal base to another non-decimal base requires an intermediate step to convert the first non-decimal number to decimal and then convert the decimal number to the final desired base. In addition, adding prefixes, changing to lower-case where appropriate, and increasing lengths will involve more processing. The following illustrates the process using Raku routines for the example above: ``` my $bin = '11001011'; # use a sub: my $dec = parse-base $bin, 2; # or use a method on $bin: $dec = $bin.parse-base: 2; # finally, get the hex value: my $hex = $dec.base: 16; say $hex; # OUTPUT 'CB' ``` The default for each provided function is to take a string (valid decimals may be entered as numbers) representing a valid number in one base and transform it into the desired base with no leading zeroes or descriptive prefix (such as '0x', '0o', and '0b') to indicate the type of number. The default is also to use upper-case characters for the non-decimal characters for all bases greater than 10 and less than 37. Bases greater than 36 use a mixture of upper-case and lower-case characters, so those non-decimal characters are case-sensitive and retain their results.. There is an optional parameter to define desired lengths of results (which will result in adding leading zeroes if needed). There are named parameters to have results in lower-case (`:$LC`) for bases between 11 and 36 and add appropriate prefixes to transformed numbers (`:$prefix`) in bases 2 (binary), 8 (octal), and 16 (hecadecimal). Note that requested prefixes will take two characters in a requested length. There is also an option (`:$suffix`) to add the appropriate base suffix to any number, the result of which will look like this (the number itself with the base shown as a trailing subscript in smaller characters): ``` '2Zz3' ~ '62' ``` Attempting to use both a length and a prefix or suffix provides any padding to the left side of the number as leading zeroes. Note use of both :prefix and :suffix will throw an exception. The use of :prefix only affects numbers of bases 2, 8, 10, and 16. Any length requested that is too short for the number of characters plus any prefix will be silently handled properly by default. However, the user can set an environment variable ('LENGTH\_HANDLING') to the desired reponse to situations where the transformed length is greater than the requested length: (1) 'ignore' and provide the required length (the default), (2) 'warn' of the increased length but provide it, or (3) 'fail' to throw an exception and report the offending data. ## Contributing Interested users are encouraged to contribute improvements and corrections to this module, and pull requests, bug reports, and suggestions are always welcome. ## Credits Thanks to 'timotimo' on IRC **#perl6** (now **#raku**) for the suggestion of the name 'rebase' for the general base transformation subroutine. ## LICENSE and COPYRIGHT Artistic 2.0. See [LICENSE](https://github.com/tbrowder/Number-More/blob/master/LICENSE). Copyright (C) 2017-2025 Thomas M. Browder, Jr. <[[email protected]](mailto:[email protected])>
## -solidus.md / Combined from primary sources listed below. # [In Operators](#___top "go to top of document")[§](#(Operators)_infix_/ "direct link") See primary documentation [in context](/language/operators#infix_/) for **infix /**. ```raku multi infix:</>(Any, Any --> Numeric:D) ``` Division operator. Coerces both argument to [`Numeric`](/type/Numeric) and divides the left through the right number. Division of [`Int`](/type/Int) values returns [`Rat`](/type/Rat), otherwise the "wider type" rule described in [`Numeric`](/type/Numeric) holds. Note there is also [`div`](#infix_div) for [`Int`](/type/Int) division.