## dist_zef-p6steve-Dan-Pandas.md
# raku Dan::Pandas

Dan::Pandas is the first specializer for the raku [Dan](https://github.com/p6steve/raku-Dan) **D**ata **AN**alysis Module.

Dan::Pandas uses the raku [Inline::Python](https://raku.land/cpan:NINE/Inline::Python) module 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 [p6steve@furnival.net](mailto:p6steve@furnival.net) to share ideas!*

# Installation

* docker run -it p6steve/raku-dan:pandas-2022.02-amd64 -or- :pandas-2022.02.arm64 (see Dockerfile)
* zef install <https://github.com/p6steve/raku-Dan-Pandas.git>
* cd /usr/share/perl6/site/bin && ./synopsis-dan-pandas.raku

# SYNOPOSIS

The raku Dan [README.md](https://github.com/p6steve/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/p6steve/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

```


## dist_github-khalidelboray-Pastebin-Pasteee.md
# Pastebin::Pasteee

### DESCRIPTION

```
use paste.ee API via Raku

```

# Example

```
    use Pastebin::Pasteee::Paste;
    use Pastebin::Pasteee::Paste::Section;
    use Pastebin::Pasteee;
    my $p = Pastebin::Pasteee.new: :token<your_api_token>;
    my $paste-url = $p.paste:
            Pastebin::Pasteee::Paste.new: :description("Test"),
                    :sections(
                        Pastebin::Pasteee::Paste::Section.new:
                            :name<Section1>,
                            :syntax<perl>,
                            :contents('print "Hellow World!"')
                    );
    say $paste-url; # https://paste.ee/p/<paste_id>

```

## class Pastebin::Pasteee

use paste.ee API via Raku

### method pastes

```
method pastes(
    Int :$page = 1,
    Int :$perpage = 25
) returns Mu

```

Get user pastes.

### multi method paste

```
multi method paste(
    Pastebin::Pasteee::Paste :$paste!
) returns Mu

```

Create a paste

### multi method paste

```
multi method paste(
    Str $id
) returns Mu

```

Fetch Paste info

### multi method paste

```
multi method paste(
    Str $id,
    Bool :$delete!
) returns Mu

```

Delete a paste

### method delete

```
method delete(
    Str $id
) returns Mu

```

Delete a paste

### method fetch

```
method fetch(
    Str $id
) returns Mu

```

Fetch Paste info

### method info

```
method info() returns Mu

```

User/key information


## dist_cpan-JFORGET-Date-Calendar-FrenchRevolutionary.md
# NAME

Date::Calendar::FrenchRevolutionary - Conversions from / to the French Revolutionary calendar

# SYNOPSIS

Converting a Gregorian date (e.g. 9th November 1799) into French
Revolutionary (18 Brumaire VIII).

```
use Date::Calendar::FrenchRevolutionary;
my Date                                $Bonaparte's-coup-gr;
my Date::Calendar::FrenchRevolutionary $Bonaparte's-coup-fr;

$Bonaparte's-coup-gr .= new(1799, 11, 9);
$Bonaparte's-coup-fr .= new-from-date($Bonaparte's-coup-gr);
say $Bonaparte's-coup-fr.strftime("%A %e %B %Y");

```

Converting a French Revolutionary date (e.g. 9th Thermidor II) to
Gregorian (which gives 27th July 1794).

```
use Date::Calendar::FrenchRevolutionary;
my Date::Calendar::FrenchRevolutionary $Robespierre's-downfall-fr;
my Date                                $Robespierre's-downfall-gr;

$Robespierre's-downfall-fr .= new(year    =>  2
                                , month   => 11
                                , day     =>  9);
$Robespierre's-downfall-gr =  $Robespierre's-downfall-fr.to-date;
say $Robespierre's-downfall-gr;

```

# INSTALLATION

```
zef install Date::Calendar::FrenchRevolutionary

```

or

```
git clone https://github.com/jforget/raku-Date-Calendar-FrenchRevolutionary.git
cd raku-Date-Calendar-FrenchRevolutionary
zef install .

```

# DESCRIPTION

Date::Calendar::FrenchRevolutionary is a class representing dates in
the French Revolutionary calendar. It allows you to convert a
Gregorian date into a French Revolutionary date or the other way.

The Revolutionary calendar was in use in France from 24 November 1793
(4 Frimaire II) to 31 December 1805 (10 Nivôse XIV). The modules in
this distribution extend the calendar to the present and to a few
centuries in the future, not limiting to Gregorian year 1805.

This new calendar was an attempt to apply the decimal rule (the basis
of the metric system) to the calendar. Therefore, the week
disappeared, replaced by the décade, a 10-day period. In addition, all
months have exactly 3 décades, no more, no less.

Since 12 months of 30 days each do not make a full year (365.24 days),
there are 5 or 6 additional days at the end of a year. These days are
called "Sans-culottides", named after a political faction, but we
often find the phrase "jours complémentaires" (additional days). These
days do not belong to any month, but for programming purposes, it is
convenient to consider they form a 13th month.

At first, the year was beginning on the equinox of autumn, for two
reasons. First, the republic had been established on 22 September
1792, which happened to be the equinox, and second, the equinox was
the symbol of equality, the day and the night lasting exactly 12 hours
each. It was therefore in tune with the republic's motto "Liberty,
Equality, Fraternity". But it was not practical, so Romme proposed a
leap year rule similar to the Gregorian calendar rule.

The distribution contains two other classes, one where there was no
reform and the automn equinox rule stayed in effect, another where the
arithmetic rule was established since the beginning of the calendar.

# AUTHOR

Jean Forget [JFORGET@cpan.org](mailto:JFORGET@cpan.org)

# COPYRIGHT AND LICENSE

Copyright © 2019, 2020 Jean Forget, all rights reserved

This library is free software; you can redistribute it and/or modify
it under the Artistic License 2.0.


## dist_github-retupmoca-UUID.md
# UUID

```
my $uuid = UUID.new;
say ~$uuid;

my $uuid = UUID.new(:version(4));

```

Currently supports version 4 (random) UUID generation.


## dist_github-lestrrat-p6-Crust-Middleware-Session.md
[![Build Status](https://travis-ci.org/lestrrat/p6-Crust-Middleware-Session.svg?branch=master)](https://travis-ci.org/lestrrat/p6-Crust-Middleware-Session)

# NAME

Crust::Middleware::Session - Session Middleware for Crust Framework

# SYNOPSIS

```
use Crust::Builder;
use Crust::Middleware::Session;

# $store can be anything that implements Crust::Middleware:Session::StoreRole.
# This here is a dummy that stores everything in memory
my $store = Crust::Middleware::Session::Store::Memory.new();
builder {
  enable 'Session', :store($store);
  &app;
};

```

# DESCRIPTION

Crust::Middleware::Session manages sessions for your Crust app. This
module uses cookies to keep session state and does not support URI
based session state.

A session object will be available under the kye `p6sgix.session` in
the P6SGI environment hash. You can use this to access session data

```
my &app = ->%env {
    %env<p6sgix.session>.get("username").say;
    ...
};

```

# AUTHOR

Daisuke Maki [lestrrat@gmail.com](mailto:lestrrat@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2015 Daisuke Maki

This library is free software; you can redistribute it and/or modify
it under the Artistic License 2.0.


## dist_zef-tbrowder-Date-Easter.md
[![Actions Status](https://github.com/tbrowder/Date-Easter/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/Date-Easter/actions) [![Actions Status](https://github.com/tbrowder/Date-Easter/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/Date-Easter/actions) [![Actions Status](https://github.com/tbrowder/Date-Easter/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/Date-Easter/actions)

# NAME

Date::Easter - Provides routines to calculate the dates of Easter and related events in the Christian calendar

# SYNOPSIS

```
use Date::Easter;
say Easter 2022; # OUTPUT: «2022-04-17␤»

```

# DESCRIPTION

**Date::Easter** is a module which provides a subroutine to calculate the dates of Easter in the Christian calendar. The sub returns a Raku **Date** object.

The routine's code is the Raku version of the algorithm shown at [Isn’t there a simpler way to calculate Easter?](https://www.tondering.dk/claus/cal/easter.php#simplecalc). The website is a treasure trove of calendar information, courtesy of the very generous and talented **Claus Tøndering**, to whom I am greatly indebted.

Another routine returns a hash of `Date::Event`s for use with the `Calendar` module. The hash is keyed by a `Date` with each key's value an array of `Date::Event` objects whose attributes describe the Lenten and post-Lenten Christian celebratory events of:

* Ash Wednesday

  The beginning of Lent [46 days before Easter]
* Palm Sunday

  Jesus Christ's entry into Jerusalem [the Sunday before Easter]
* Good Friday

  Jesus Christ's crucifixion [the Friday before Easter]
* Easter Sunday

  The resurrection of Jesus Christ
* Ascension

  The ascension into Heaven of Jesus Christ [40 days after Easter]
* Pentecost

  The descent of the Holy Sprit upon the Virgin Mary and the Disciples of Jesus Christ [50 days after Easter]

## The subroutine exporting all the events

```
sub get-easter-events-hashlist(:$year --> Hash) is export {...}

```

# AUTHOR

Tom Browder [tbrowder@acm.org](mailto:tbrowder@acm.org)

# COPYRIGHT AND LICENSE

© 2021-2024 Tom Browder

This library is free software; you may redistribute it or modify it under the Artistic License 2.0.


## dist_cpan-JMERELO-App-Game-Concentration.md
[![Build Status](https://travis-ci.org/JJ/p6-app-concentration.svg?branch=master)](https://travis-ci.org/JJ/p6-app-concentration)

# NAME

App::Game::Concentration - Implementation of the game of Concentration

# SYNOPSIS

```
use App::Game::Concentration;

```

# DESCRIPTION

App::Game::Concentration is a fast and dirty implementation of Concentration: <https://en.wikipedia.org/wiki/Concentration_(card_game)>

# Methods and subs

## new()

Generates a random deck.

## `select( Pair $first, Pair $second --` Array )> and `select( @positions --` Array )>

Takes an array of Pairs, and selects the cards in that position. If the cards are paired (same number), they are substituted by `✖✖✖`, "eliminating" them from the deck. If the cards are paired, the array returned will have the "Pair" trait mixed in. You can check for it using `$returned-array.?Str eq "Pair"`.

## sub paired( $first-card, $second-card)

Checks if the cards are paired by extracting the figure from the suit.

# AUTHOR

JJ Merelo [jjmerelo@gmail.com](mailto:jjmerelo@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2019 JJ Merelo

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_github-retupmoca-Web-RF.md
# Web::RF

See <https://github.com/retupmoca/egeler.us> for a more comprehensive example.

Web::RF is a simple routing web framework designed to work with Crust. It attempts
to decouple your controller code from the URL's used to access them.

Note that this framework doesn't handle data storage or templating - it simply
gets program flow into one of your controllers and lets you do whatever is needed.

```
# Site/Root.pm6
use Web::RF;

use Page::Home;
# etc

unit class Site::Root is Web::RF::Router;

# the route strings here are passed to Path::Router, so any of the variable
# features in that package can be used here
method routes {
    $.route('', Page::Home); # Web::RF::Controller class
    $.route('login', Page::Login);
    $.route('blog/', Site::Blog); # can include other Web::RF::Routers to create trees
    $.route('redirect', Web::RF::Redirect.new(301, '/blog/'));
}

# gets called before every request is routed
method before(:$request) {
    return Web::RF::Redirect.go(301, 'https://my-site.com'~$request.request-uri) unless $request.secure; # force https
}

method error(:$request, :$exception) {
    given $exception {
        when X::NotFound {  # will return an empty 404 response if not handled
            return Page::NotFound.handle(:$request);
        }
        when X::BadRequest { # will return an empty 400 response if not handled
            return Page::BadRequest.handle(:$request);
        }
        default {   # will rethrow the exception if not handled
            return Page::ShowError.handle(:$request, :$exception);
        }
    }
}

```

```
# Page/Home.pm6
use Web::RF;

unit class Page::Home is Web::RF::Controller;

# %mapping is the mapping created by Path::Router (for variables in the URL)
method handle(:$request, :%mapping) {
    return [200, [ Content-Type => 'text/html' ], [ $content-here ]];
}

```

```
# bin/app.p6sgi
use Web::RF;
use Site::Root;

my $webrf = Web::RF.new(:root(Site::Root.new));

my $app = sub (%env) { $webrf.handle(%env) };

```


## failure.md
class Failure

Delayed exception

```raku
class Failure is Nil { }
```

A `Failure` is a *soft* or *unthrown* [`Exception`](/type/Exception), usually generated by calling `&fail`. It acts as a wrapper around an [`Exception`](/type/Exception) object.

Sink (void) context causes a `Failure` to throw, i.e. turn into a regular exception. The [`use fatal` pragma](/language/pragmas#fatal) causes this to happen in all contexts within the pragma's scope. Inside [`try` blocks](/language/exceptions#try_blocks), `use fatal` is automatically set, and you can *disable* it with `no fatal`.

That means that Failures are generally only useful in cases of code that normally would produce an rvalue; Failures are more or less equivalent to Exceptions in code that will frequently be called in sink context (i.e., for its side-effects, such as with `say`).

Similarly, you should generally use `&fail` only inside code that is normally expected to return something.

Checking a Failure for truth (with the `Bool` method) or definedness (with the `defined` method) marks the failure as handled, and causes it not to throw in sink context anymore.

You can call the `handled` method to check if a failure has been handled.

Calling methods on unhandled failures propagates the failure. The specification says the result is another `Failure`; in Rakudo it causes the failure to throw.

Because a Failure is [`Nil`](/type/Nil), which is undefined, a common idiom for safely executing code that may fail uses a [`with/else`](/language/control#with_orwith_without) statement:

```raku
sub may_fail( --> Numeric:D ) {
  my $value = (^10).pick || fail "Zero is unacceptable";
  fail "Odd is also not okay" if $value % 2;
  return $value;
}

with may_fail() -> $value { # defined, so didn't fail
  say "I know $value isn't zero or odd."
} else { # undefined, so failed, and the Failure is the topic
  say "Uh-oh: {.exception.message}."
}

```

# [Methods](#class_Failure "go to top of document")[§](#Methods "direct link")

## [method new](#class_Failure "go to top of document")[§](#method_new "direct link")

```raku
multi method new(Failure:D:)
multi method new(Failure:U:)
multi method new(Failure:U: Exception:D \exception)
multi method new(Failure:U: $payload)
multi method new(Failure:U: |cap (*@msg))
```

Returns a new `Failure` instance with payload given as argument. If called without arguments on a `Failure` object, it will throw; on a type value, it will create an empty `Failure` with no payload. The latter can be either an [`Exception`](/type/Exception) or a payload for an [`Exception`](/type/Exception). A typical payload would be a [`Str`](/type/Str) with an error message. A list of payloads is also accepted.

```raku
my $e = Failure.new(now.DateTime, 'WELP‼');
say $e;
CATCH{ default { say .^name, ': ', .Str } }
# OUTPUT: «X::AdHoc: 2017-09-10T11:56:05.477237ZWELP‼␤»
```

## [method handled](#class_Failure "go to top of document")[§](#method_handled "direct link")

```raku
method handled(Failure:D: --> Bool:D) is rw
```

Returns `True` for handled failures, `False` otherwise.

```raku
sub f() { fail }; my $v = f; say $v.handled; # OUTPUT: «False␤»
```

The `handled` method is an [lvalue](/language/glossary#lvalue), see [routine trait `is rw`](/type/Routine#trait_is_rw), which means you can also use it to set the handled state:

```raku
sub f() { fail }
my $v = f;
$v.handled = True;
say $v.handled; # OUTPUT: «True␤»
```

## [method exception](#class_Failure "go to top of document")[§](#method_exception "direct link")

```raku
method exception(Failure:D: --> Exception)
```

Returns the [`Exception`](/type/Exception) object that the failure wraps.

```raku
sub failer() { fail };
my $failure = failer;
my $ex = $failure.exception;
put "$ex.^name(): $ex";
# OUTPUT: «X::AdHoc: Failed␤»
```

## [method self](#class_Failure "go to top of document")[§](#method_self "direct link")

```raku
method self(Failure:D: --> Failure:D)
```

If the invocant is a [handled](/routine/handled) `Failure`, returns it as is. If not handled, throws its [`Exception`](/type/Exception). Since [`Mu`](/type/Mu) type [provides `.self`](/type/Mu#method_self) for every class, calling this method is a handy way to explosively filter out Failures:

```raku
my $num1 = '♥'.Int;
# $num1 now contains a Failure object, which may not be desirable

my $num2 = '♥'.Int.self;
# .self method call on Failure causes an exception to be thrown

my $num3 = '42'.Int.self;
# Int type has a .self method, so here $num3 has `42` in it

(my $stuff = '♥'.Int).so;
say $stuff.self; # OUTPUT: «(HANDLED) Cannot convert string to number…»
# Here, Failure is handled, so .self just returns it as is
```

## [method Bool](#class_Failure "go to top of document")[§](#method_Bool "direct link")

```raku
multi method Bool(Failure:D: --> Bool:D)
```

Returns `False`, and marks the failure as handled.

```raku
sub f() { fail };
my $v = f;
say $v.handled; # OUTPUT: «False␤»
say $v.Bool;    # OUTPUT: «False␤»
say $v.handled; # OUTPUT: «True␤»
```

## [method Capture](#class_Failure "go to top of document")[§](#method_Capture "direct link")

```raku
method Capture()
```

Throws `X::Cannot::Capture` if the invocant is a type object or a [handled](/routine/handled) `Failure`. Otherwise, throws the invocant's [exception](/routine/exception).

## [method defined](#class_Failure "go to top of document")[§](#method_defined "direct link")

```raku
multi method defined(Failure:D: --> Bool:D)
```

Returns `False` (failures are officially undefined), and marks the failure as handled.

```raku
sub f() { fail };
my $v = f;
say $v.handled; # OUTPUT: «False␤»
say $v.defined; # OUTPUT: «False␤»
say $v.handled; # OUTPUT: «True␤»
```

## [method list](#class_Failure "go to top of document")[§](#method_list "direct link")

```raku
multi method list(Failure:D:)
```

Marks the failure as handled and throws the invocant's [exception](/type/Failure#method_exception).

## [sub fail](#class_Failure "go to top of document")[§](#sub_fail "direct link")

```raku
multi fail(--> Nil)
multi fail(*@text)
multi fail(Exception:U $e  --> Nil )
multi fail($payload --> Nil)
multi fail(|cap (*@msg) --> Nil)
multi fail(Failure:U $f --> Nil)
multi fail(Failure:D $fail --> Nil)
```

Exits the calling [`Routine`](/type/Routine) and returns a `Failure` object wrapping the exception `$e` - or, for the `cap` or `$payload` form, an [`X::AdHoc`](/type/X/AdHoc) exception constructed from the concatenation of `@text`. If the caller activated fatal exceptions via the pragma `use fatal;`, the exception is thrown instead of being returned as a `Failure`.

```raku
# A custom exception defined
class ForbiddenDirectory is Exception {
    has Str $.name;

    method message { "This directory is forbidden: '$!name'" }
}

sub copy-directory-tree ($dir) {
    # We don't allow for non-directories to be copied
    fail "$dir is not a directory" if !$dir.IO.d;
    # We don't allow 'foo' directory to be copied too
    fail ForbiddenDirectory.new(:name($dir)) if $dir eq 'foo';
    # or above can be written in method form as:
    # ForbiddenDirectory.new(:name($dir)).fail if $dir eq 'foo';
    # Do some actual copying here
    ...
}

# A Failure with X::AdHoc exception object is returned and
# assigned, so no throwing Would be thrown without an assignment
my $result = copy-directory-tree("cat.jpg");
say $result.exception; # OUTPUT: «cat.jpg is not a directory␤»

# A Failure with a custom Exception object is returned
$result = copy-directory-tree('foo');
say $result.exception; # OUTPUT: «This directory is forbidden: 'foo'␤»
```

If it's called with a generic `Failure`, an ad-hoc undefined failure is thrown; if it's a defined `Failure`, it will be marked as unhandled.

```raku
sub re-fail {
    my $x = +"a";
    unless $x.defined {
        $x.handled = True;
        say "Something has failed in \$x ", $x.^name;
        # OUTPUT: «Something has failed in $x Failure␤»
        fail($x);
        return $x;
    }
}

my $x = re-fail;
say $x.handled; # OUTPUT: «False␤»

```

# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")

Type relations for `Failure`

raku-type-graph

Failure
Failure

Nil
Nil

Failure->Nil

Mu
Mu

Any
Any

Any->Mu

Cool
Cool

Cool->Any

Nil->Cool

[Expand chart above](/assets/typegraphs/Failure.svg)


## dist_zef-dwarring-Pod-To-PDF.md
# TITLE

Pod::To::PDF

# SUBTITLE

Render Pod to PDF via Cairo

# Usage

From command line:

```
$ raku --doc=PDF lib/To/Class.rakumod --save-as=To-Class.pdf

```

From Raku:

```
use Pod::To::PDF;
use Cairo;

=NAME
foobar.pl

=head2 SYNOPSIS
=code foobar.pl <options> files ...

my Cairo::Surface::PDF $pdf = pod2pdf($=pod, :save-as<foobar.pdf>);
$pdf.finish();

```

### Command Line Options:

**--save-as=pdf-filename**

File-name for the PDF output file. If not given, the output will be saved to a temporary file. The file-name is echoed to `stdout`.

**--width=n**

Page width in points (default: 592)

**--height=n**

Page height in points (default: 792)

**--margin=n --margin-left=n --margin-right=n --margin-top=n --margin-bottom=n**

Page margin in points (default: 20)

**--/toc**

Disable table of contents

**--/index**

Disable index of terms

**--page-numbers**

Add page numbers (bottom right)

**--compress**

Compress the rendered PDF. The optional [Compress::PDF](https://raku.land/zef:tbrowder/Compress::PDF) module needs to be installed to use this option.

**--page-style**

```
-raku --doc=PDF lib/to/class.rakumod --page-style='margin:10px 20px; width:200pt; height:500pt" --save-as=class.pdf

```

Perform CSS `@page` like styling of pages. At the moment, only margins (`margin`, `margin-left`, `margin-top`, `margin-bottom`, `margin-right`) and the page `width` and `height` can be set. The optional [CSS::Properties](https://css-raku.github.io/CSS-Properties-raku/) module needs to be installed to use this option.

# Exports

* `class Pod::To::PDF;`
* `sub pod2pdf; # See below`

From Raku code, the `pod2pdf` function returns a Cairo::Surface::PDF object which can be further manipulated, or finished to complete rendering.

# Description

This module does simple rendering of Pod to PDF documents via Cairo.

The generated PDF has a table of contents and is tagged for accessibility and testing purposes.

It uses HarfBuzz for font shaping and glyph selection and FontConfig for system font loading.

# Subroutines

### sub pod2pdf()

```
sub pod2pdf(
    Pod::Block $pod
) returns Cairo::Surface::PDF;

```

#### pod2pdf() Options

**`Str() :$save-as`**

A filename for the output PDF file.

**`Cairo::Surface::PDF :$surface`**

A surface to render to

**`UInt:D :$width, UInt:D :$height`**

The page size in points (there are 72 points per inch).

**`UInt:D :$margin`**

The page margin in points (default 20).

**`Hash :@fonts`**

By default, Pod::To::PDF loads system fonts via FontConfig. This option can be used to preload selected fonts.

```
use Pod::To::PDF;
use Cairo;
my @fonts = (
    %(:file<fonts/Raku.ttf>),
    %(:file<fonts/Raku-Bold.ttf>, :bold),
    %(:file<fonts/Raku-Italic.ttf>, :italic),
    %(:file<fonts/Raku-BoldItalic.ttf>, :bold, :italic),
    %(:file<fonts/Raku-Mono.ttf>, :mono),
);

my Cairo::Surface::PDF $pdf = pod2pdf($=pod, :@fonts, :save-as<out.pdf>);
$pdf.finish();

```

Each font entry should have a `file` entry and various combinations of `bold`, `italic` and `mono` flags. Note that `mono` is used to render code blocks and inline code.

**`Str :%metadata`**

This can be used to preset values for `title`, `subtitle`, `name`, `author` or `version`.

This is an alternative to, and will override `=TITLE`, `=SUBTITLE`, `=NAME`, `=AUTHOR` or `=VERSION` directives.

Note: All of these are options are provided for compatibility, however only `=TITLE` and `=AUTHOR` are directly supported in PDF metadata.

**`:!contents`**

Disables Table of Contents generation.

**`:!index`**

Disable writing of a `Index` section to the table of contents.

**`:$linker`**

Provides a class or object to intercept and sanitise or rebase links. The class/object should provide a method `resolve-link` that accepts the target component of C<L<>> formatting codes and returns the actual link to be embedded in the PDF. The link is omitted, if the method returns an undefined value.

**`:%replace`**

Specify replacements for `R<>` placeholders in the POD. Replacement values should be simple strings (`Str`), Pod blocks (type `Pod::Block`), or a `List`. For example:

```
use Pod::To::PDF;
my $title = 'Sample Title';
my Str() $date = now.Date;
my $author = 'David Warring';
my $description = "sample Pod with replaced content";
my %replace = :$date, :$title, :$author, :$description;
my $renderer = pod2pdf($=pod, :%replace, :save-as<replace-example.pdf>);
$renderer.finish();

=begin pod
=TITLE R<title>
=AUTHOR R<author>
=DATE R<date>
=head2 Description
=para R<description>;
=end pod

```

# Installation

This module's dependencies include [HarfBuzz](https://harfbuzz-raku.github.io/HarfBuzz-raku/), [Font::FreeType](https://pdf-raku.github.io/Font-FreeType-raku/), [FontConfig](https://raku.land/zef:dwarring/FontConfig) and [Cairo](https://raku.land/github:timo/Cairo), which further depend on native `harfbuzz`, `freetype6`, `fontconfig` and `cairo` libraries.

Please check these module's installation instructions.

# Testing

Note that installation of the PDF::Tags::Reader module enables structural testing.

For example, to test this module from source.

```
$ git clone https://github.com/pod-to-pdf/Pod-To-PDF-raku
$ cd Pod-To-PDF-raku
$ zef install PDF::Tags::Reader # enable structural tests
$ zef APP::Prove6
$ zef --deps-only install .
$ prove6 -I .

```


## dist_zef-raku-community-modules-Algorithm-LCS.md
[![Actions Status](https://github.com/raku-community-modules/Algorithm-LCS/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-LCS/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-LCS/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-LCS/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-LCS/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-LCS/actions)

# NAME

Algorithm::LCS - Implementation of the longest common subsequence algorithm

# SYNOPSIS

```
use Algorithm::LCS;

# regular usage
say lcs(<A B C D E F G>, <A C F H J>); # prints T<A C F>

# custom comparator via :compare
say lcs(<A B C>, <D C F>, :compare(&infix:<eq>));

# extra special custom comparison via :compare-i
my @a        = slurp('one.txt');
my @b        = slurp('two.txt');
my @a-hashed = @a.map({ hash-algorithm($_) });
my @b-hashed = @b.map({ hash-algorithm($_) });
say lcs(@a, @b, :compare-i({ @a-hashed[$^i] eqv @b-hashed[$^j] }));

```

# DESCRIPTION

This module contains a single subroutine, `lcs`, that calculates the longest common subsequence between two sequences of data. `lcs` takes two lists as required parameters; you may also specify the comparison function (which defaults to `eqv`) via the `&compare` named parameter).

Sometimes you may want to maintain a parallel array of information to consult during calculation (for example, if you're comparing long lines of a file, and you'd like a speedup by comparing their hashes rather than their contents); for that, you may use the `&compare-i` named argumeny

# SUBROUTINES

### sub lcs

```
sub lcs(
    @a,
    @b,
    :&compare = Code.new,
    :&compare-i is copy
) returns Mu

```

Returns the longest common subsequence of two sequences of data.

## class Mu $

The first sequence

## class Mu $

The second sequence

## class Mu $

The comparison function (defaults to C)

## class Mu $

The compare-by-index function (defaults to using &compare)

# SEE ALSO

[Wikipedia article](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem)

# AUTHORS

* Rob Hoelz
* Raku Community

# COPYRIGHT AND LICENSE

Copyright (c) 2014 - 2017 Rob Hoelz

Copyright (c) 2024 Raku Community

This library is free software; you can redistribute it and/or modify it under the MIT license.


## dist_zef-librasteve-Rat-Power.md
[![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0)

# Rat::Power

# SYNOPSIS

```
use Rat::Power;

say 64 ** ⅓;        #Int
say 64 ** ⅔;        #Int
say 60 ** ⅓;        #Num

```

### Caveats

* exponent must be Rat where \* == (½,⅓,⅔,¼,¾).any
* base and result must be Int

# AUTHOR

librasteve [librasteve@furnival.net](mailto:librasteve@furnival.net)

# COPYRIGHT AND LICENSE

Copyright 2024 librasteve

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_cpan-TYIL-Config-Parser-yaml.md
# Config::Parser::yaml

A YAML parser for [Config](https://github.com/scriptkitties/p6-Config).

[![Build Status](https://travis-ci.org/scriptkitties/p6-Config-Parser-yaml.svg?branch=master)](https://travis-ci.org/scriptkitties/p6-Config-Parser-yaml)

## Installation

```
zef install Config::Parser::yaml

```

## License

This program is free software: you can redistribute it and/or modify it under
the terms of 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 program 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 <http://www.gnu.org/licenses/>.


## dist_github-shantanubhadoria-Printer-ESCPOS.md
# NAME

Printer::ESCPOS - Interface to ESCPOS printers

# SYNOPSIS

## Network printer in asynchronous mode

```
    use Printer::ESCPOS::Network::Async;

    // Asynchronous control over your network ESCPOS printer
    await Printer::ESCPOS::Network::Async.connect('10.0.13.108', 9100).then( -> $p {
      if $p.status {
        given $p.result {
          .init;
          .barcode("TEST", system => 'CODE93');
          .lf;
          .tab-positions(3,1,2);
          $printer.tab;
          .send('hmargin 1');
          .lf;
          .send('margin 2');
          .lf;

          .cut-paper;
          .lf;
          .close;
        }
      }
    });

```

## Network printer in synchronous mode

```
    use Printer::ESCPOS::Network;

    my $printer = Printer::ESCPOS::Network.new(:host<10.0.13.108>, :port(9100));
    $printer.init;
    $printer.barcode("TEST", system => 'CODE93');
    $printer.lf;
    $printer.tab-positions(3,1,2);
    $printer.tab;
    $printer.send('hmargin 1');
    $printer.lf;
    $printer.send('margin 2');
    $printer.lf;

    $printer.cut-paper;
    $printer.lf;
    $printer.close;

```

# DESCRIPTION

ESC/P, short for Epson Standard Code for Printers and sometimes styled Escape/P, is a printer control language developed by Epson to control computer printers. It was mainly used in dot matrix printers and some inkjet printers, and is still widely used in many receipt printers. During the era of dot matrix printers, it was also used by other manufacturers (e.g. NEC), sometimes in modified form. At the time, it was a popular mechanism to add formatting to printed text, and was widely supported in software. These days its almost a standard communication mode for talking to thermal and dot-matrix receipt printers used for printing bills, receipts etc. in retail outlets, restaurants etc. There are several variants of ESC/P, as not all printers implement all commands. Epson refers to a more recent variant of ESC/P as ESC/P2. ESC/P2 is backward compatible with ESC/P, but adds commands for new printer features such as scalable fonts and enhanced graphics printing.

# ADDING A CONNECTION CLASS

Perl 6 classes allow easy extendability of the Printer::ESCPOS to support newer communication ports/protocols. See below examples for examples of how I have added TCP IP support(for Async and Synchronous modes):

## Extending IO::Socket::INET in just 4 lines of code:

IO::Socket::INET allows synchronous communication with a TCP device. Watch how we can use this module to talk to ESCPOS printers in just 4 lines of code.

```
use v6;
use Printer::ESCPOS;

class Printer::ESCPOS::Network is IO::Socket::INET is Printer::ESCPOS {
  method send(Str $string) { # Send is the subroutine called by Printer::ESCPOS to send data to the Printer
                             # Since IO::Socket::INET uses print() method to send data to the peer. We route data
                             # Sent on send() to IO::Socket::INET's print() method.
    self.print($string);
  }
}

```

Now you can use Printer::ESCPOS::Network class to talk to any network printer:

```
use Printer::ESCPOS::Network;

my $printer = Printer::ESCPOS::Network.new(:host<10.0.13.108>, :port(9100));
$printer.init;
$printer.barcode("TEST", system => 'CODE93');
$printer.lf;
$printer.tab-positions(3,1,2);
$printer.tab;
$printer.send('hmargin 1');
$printer.lf;
$printer.send('margin 2');
$printer.lf;

$printer.cut-paper;
$printer.lf;
$printer.close;

```

## Extending IO::Socket::Async in just 4 lines of code:

IO::Socket::Async allows asynchronous communication with a TCP device. Watch how we can use this module to talk to ESCPOS printers in just 4 lines of code.

```
use v6;
use Printer::ESCPOS;

class Printer::ESCPOS::Network::Async is IO::Socket::Async is Printer::ESCPOS {
  method send(Str $string) {
    self.print($string);
  }
}

```

Now you can use Printer::ESCPOS::Network::Async class to talk to any network printer:

```
use Printer::ESCPOS::Network::Async;

await Printer::ESCPOS::Network::Async.connect('10.0.13.108', 9100).then( -> $p {
  if $p.status {
    given $p.result {
      .init;
      .text-size(height => 3, width => 2);
      .barcode("TEST", system => 'CODE93');
      .lf;
      .tab-positions(3,1,2);
      .send('hmargin 1');
      .lf;
      .send('margin 2');
      .lf;

      .cut-paper;
      .lf;
      .close;
    }
  }
});

```

# ATTRIBUTES

At the moment the attributes used are dependent on the communication protocol/port that you use. If your Printer is connected over a network you will need to provide a IP Address and port number. At the moment only network driver is supported. USB, Serial and Bluetooth support will be added as Modules for the same become available in Perl 6

```
use Printer::ESCPOS;

class Printer::ESCPOS::Network::Async is IO::Socket::Async is Printer::ESCPOS {
  method send(Str $string) {
    self.print($string);
  }
}

use Printer::ESCPOS::Network::Async;

await Printer::ESCPOS::Network::Async.connect('10.0.13.108', 9100).then( -> $p {
  if $p.status {
    given $p.result {
      .init;
      .barcode("TEST", system => 'CODE93');
      .lf;
      .send('hmargin 1');
      .lf;
      .cut-paper;
      .close;
    }
  }
});

```

# METHODS

## init

Initializes the Printer. Clears the data in print buffer and resets the printer to the mode that was in effect when the power was turned on. This function is automatically called on creation of printer object.

# SUPPORT

## Bugs / Feature Requests

Please report any bugs or feature requests through github at <https://github.com/shantanubhadoria/p6-printer-escpos/issues>. You will be notified automatically of any progress on your issue.

## Source Code

This is open source software. The code repository is available for public review and contribution under the terms of the license.

<https://github.com/shantanubhadoria/p6-printer-escpos>

```
git clone git://github.com/shantanubhadoria/p6-printer-escpos.git

```

# AUTHOR

Shantanu Bhadoria [shantanu@cpan.org](mailto:shantanu@cpan.org) <https://www.shantanubhadoria.com>

# COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by Shantanu Bhadoria.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 6 programming language system itself.


## dist_zef-lizmat-Unix-errno.md
[![Actions Status](https://github.com/lizmat/Unix-errno/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Unix-errno/actions) [![Actions Status](https://github.com/lizmat/Unix-errno/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Unix-errno/actions)

# NAME

Unix::errno - Provide transparent access to errno

# SYNOPSIS

```
use Unix::errno;  # exports errno, set_errno

set_errno(2);

say errno;              # No such file or directory (errno = 2)
say "failed: {errno}";  # failed: No such file or directory
say +errno;             # 2

```

# DESCRIPTION

This module provides access to the `errno` variable that is available on all Unix-like systems. Please note that in a threaded environment such as Raku is, the value of `errno` is even more volatile than it has been already. For now, this issue is ignored.

# CAVEATS

Since setting of any "extern" variables is not supported yet by `NativeCall`, the setting of `errno` is faked. If `set_errno` is called, it will set the value only in a shadow copy. That value will be returned as long as the underlying "real" errno doesn't change (at which point that value will be returned.

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

Source can be located at: <https://github.com/lizmat/Unix-errno> . Comments and Pull Requests are welcome.

If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!

# COPYRIGHT AND LICENSE

Copyright 2018, 2021, 2024, 2025 Elizabeth Mattijsen

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_github-jaffa4-Rakudo-Perl6-Format.md
# Rakudo::Perl6::Format

Format Perl6 code.

Known limitations: if there is a `BEGIN`, there will not be any formatting.
Also, if classes are imported from nqp.

## Usage

```
use Rakudo::Perl6::Format;

my $f = Rakudo::Perl6::Format.new(); # create a new object
say $f.format({indentsize=>4},$content); # format using indentsize 4.

```

Only identation size can be set now.

## Command line access:

```
$ perl6 format.p6 -h

$ perl6 format.p6 -is 4 \<Dagrammar.p6 \>formatted.p6

```


## dist_zef-bbkr-UpRooted.md
# Extract subtrees of data from relational databases in [Raku](https://www.raku.org) language.

[![test](https://github.com/bbkr/UpRooted/actions/workflows/test.yml/badge.svg)](https://github.com/bbkr/UpRooted/actions/workflows/test.yml)

## DESCRIPTION

This module allows to extract tree of data from relational database and process it.
Tree of data may be for example some user account and all records in related tables that belong to him.
Useful for cases like:

* Transferring users between database shards for better load balancing.
* Cloning user data from production environment to devel to debug some issues in isolated manner.
* Saving user state for backup or legal purposes.

This module is NOT continuous replication tool (like for example Debezium).

## SYNOPSIS

Let's say you have MySQL database and want to save user of `id = 1` from `users` table with all his data from other tables to `.sql` file.

```
my $connection = DBIish.connect( 'mysql', host => ..., port => ..., ... );

use UpRooted::Schema::MySQL;
my $schema = UpRooted::Schema::MySQL.new( :$connection );

use UpRooted::Tree;
my $tree = UpRooted::Tree.new( root-table => $schema.table( 'users' ) );

use UpRooted::Reader::MySQL;
my $reader = UpRooted::Reader::MySQL.new( :$connection, :$tree );

use UpRooted::Writer::MySQLFile;
my $writer = UpRooted::Writer::MySQLFile.new;

$writer.write( $reader, id => 1 );

```

Your user will be saved as `out.sql` file.

## DOCKER

If you do not have Raku installed UpRooted is also available as [Docker image](https://hub.docker.com/repository/docker/bbkr2/uprooted).

## MODULES

This section explains role of every module in `UpRooted` stack and tells which variants of each module are available.

### UpRooted::Schema

`UpRooted::Schema` describes relation between `UpRooted::Tables`.

It can be discovered automatically by plugins like:

* `UpRooted::Schema::MySQL`
* `UpRooted::Schema::PostgreSQL`

In rare cases you may need to construct or fine tune `UpRooted::Schema` manually. For example if you use MySQL MyISAM engine or MySQL partitioning. Or you use PostgreSQL foreign keys relying on unique keys instead of unique constraints. Without proper foreign keys relations between `UpRooted::Table`s cannot be auto discovered and must be defined by hand. There is [separate manual](docs/Schema.md) describing this process.

Creating `UpRooted::Schema` must be done only once per schema.

### UpRooted::Tree

`UpRooted::Tree` knows how to reach each leaf `UpRooted::Table` from chosen root `UpRooted::Table`.
It also resolves `UpRooted::Table`s order correctly to satisfy foreign key constraints, which is important for example when writing data tree to online database.

You can derive many `UpRooted::Tree`s from single `UpRooted::Schema`, depending on which root `UpRooted::Table` is used.

Creating `UpRooted::Tree` must be done only once per root `UpRooted::Table`.

### UpRooted::Reader

`UpRooted::Reader` transforms `UpRooted::Tree` to series of queries allowing to extract data that belong to given row in root `UpRooted::Table`. This is always database engine specific.

Available variants:

* `UpRooted::Reader::MySQL`
* `UpRooted::Reader::PostgreSQL`

Creating `UpRooted::Reader` must be done only once per `UpRooted::Tree`.

### UpRooted::Writer

`UpRooted::Writer` writes data provided by `UpRooted::Reader`.

Available variants:

* `UpRooted::Writer::MySQL` - Write directly to another MySQL database.
* `UpRooted::Writer::MySQLFile` - Write to `.sql` file compatible with MySQL.
* `UpRooted::Writer::PostgreSQL` - Write directly to another PostgreSQL database.
* `UpRooted::Writer::PostgreSQLFile` - Write to `.sql` file compatible with PostgreSQL.

Note that `UpRooted::Reader` and `UpRooted::Writer` are independent. You can read from MySQL database and write directly to PostgreSQL database if needed.

Disabling `UpRooted::Schema` name in Fully Qualified Names in queries may be useful for example when you need to write data to whatever schema is / will be used in connection.
To do so provide flag to constructor like this: `UpRooted::Writer::MySQL.new( :!use-schema-name )`.
To find other options accepted by each `UpRooted::Writer` call `p6doc` on chosen module.

Note that not every `UpRooted::Writer` can save every data type provided by `UpRooted::Reader`. For example MySQL does not support PostgreSQL array types and will save them as joined strings.

## CACHING

Creating instances of modules mentioned above are heavy operations, especially on large schemas. You can reuse all of them for great speed improvement.

For example if you need to save multiple users you need to create `UpRooted::Schema`, `UpRooted::Tree`, `UpRooted::Reader` and `UpRooted::Writer` only once.

```
my $schema = ...;
my $tree = ...;
my $reader = ...;
my $writer = UpRooted::Writer::MySQLFile.new(
    # name generator to avoid file name conflicts
    file-naming => sub ( $tree, %conditions ) {
        %conditions{ 'id' } ~ '.sql'
    }
);

$writer.write( $reader, id => 1 );
$writer.write( $reader, id => 2 );
$writer.write( $reader, id => 3 );

```

It will create `1.sql`, `2.sql`, `3.sql` files without rediscovering everything every time.

## EXTENSIONS

`UpRooted` is written with extensibility in mind.

Base version will focus on MySQL and PostgreSQL databases, as those are the two most common open source ones.

However if you need for example to create `UpRooted::Schema` from Red ORM, make `UpRooted::Writer` to save set of CSV files or even implement whole `UpRooted` stack to work with MS SQL - do not be afraid to implement it. Interfaces are simple, well documented and checking existing MySQL / PostgreSQL code will give you the idea how little is actually needed to extend `UpRooted` capabilities.

## SCHEMA DESIGN ISSUES

Relational databases are extremly flexible in terms of schema design.
However there are few rules you must follow if you want to work with data trees.

If you use `UpRooted` but do not get expected results please go through this list carefully before creating issue on GitHub.

### Data is transformed (extra rows, counters are too high) when written to another database

**Cause:** There are `ON INSERT` triggers changing data.

This one is very easy to overlook.
Triggers are convenient, relaible and cheap way of managing entangled data state.
For example when row is inserted into `orders` table increase counter in `order_stats` table by `1`.

But those triggers will get in a way of copying / moving data trees literally between databases, because they will "replay" their logic when data tree is written to another database.

**Fix:** When designing schema with data tree reading / writing in mind triggers can be only used to verify constraints.

### Data tree is not writable to another database without disabling foreign key constraints

**Cause 1:** There are self-looped tables. Usually implementing tree logic.

By default `UpRooted` resolves dependencies and whole purpose of `UpRooted::Tree` is to provide data in correct order. However it may be not possible if table is directly referencing itself.

```
    +----------+
    | users    |
    +----------+
    | id       |----------------------+
    | login    |                      |
    | password |                      |
    +----------+                      |
                                      |
              +--------------------+  |
              | albums             |  |
              +--------------------+  |
          +---| id                 |  |
          |   | user_id            |>-+
          +--<| parent_album_id    |
              | name               |
              +--------------------+

```

For example user has album with `id = 2` as subcategory of album with `id = 1`. Then he rearranges his collection, so that the album with `id = 2` is on top. In such scenario if database returned data tree rows in primary key order then it will not be possible to insert album with `id = 1` because it requires presence of album with `id = 2`.

**Hint 1:**

You can check if `UpRooted::Tree` has loops by running:

```
my $tree = ...;
say $tree.paths.grep: *.is-looped;

```

**Fix 1:** Have separate table that establishes tree hierarchy between rows:

```
    +----------+
    | users    |
    +----------+
    | id       |----------------------+
    | login    |                      |
    | password |                      |
    +----------+                      |
                                      |
              +--------------------+  |
              | albums             |  |
              +--------------------+  |
      +-+=====| id                 |  |
      | |     | user_id            |>-+
      | |     | name               |
      | |     +--------------------+
      | |
      | |    +------------------+
      | |    | album_hierarchy  |
      | |    +------------------+
      | +---<| parent_album_id  |
      +-----<| child_album_id   |
             +------------------+

```

**Cause 2:** Jailbreak. Data from one tree links to data from another tree. Usually implementing relations or activities between users.

```
      +----------+        +------------+
      | users    |        | blog_posts |
      +----------+        +------------+
    +-| id       |---+    | id         |---+
    | | login    |   +---<| user_id    |   |
    | | password |        | text       |   |
    | +----------+        +------------+   |
    |                                      |
    |    +--------------+                  |
    |    | comments     |                  |
    |    +--------------+                  |
    |    | blog_post_id |>-----------------+
    +---<| user_id      |
         | text         |
         +--------------+

```

For example user with `id = 1` created a blog post that was commented by user with `id = 2`. Now record from `comments` table has two owners, one direct (belongs to user with `id = 2`) and one indirect (belongs to post written by user with `id =` 1`).

**Fix 2:** Unfortunately the only way to detach two data trees in such case is to remove one of foreign key constraints.

### Some rows from table are missing

**Cause:** Ambiguity in correct way of reaching rows in table. Only multiple nullable relation paths to this table exist.

```
                  +----------+
                  | users    |
                  +----------+
    +-------------| id       |-------------+
    |             | login    |             |
    |             | password |             |
    |             +----------+             |
    |                                      |
    |  +-----------+        +-----------+  |
    |  | time      |        | distance  |  |
    |  +-----------+        +-----------+  |
    |  | id        |--+  +--| id        |  |
    +-<| user_id   |  |  |  | user_id   |>-+
       | amount    |  |  |  | amount    |
       +-----------+  |  |  +-----------+
                      |  |
                   (nullable)
                      |  |
                      |  |
             +--------+  +---------+
             |                     |
             |   +-------------+   |
             |   | parts       |   |
             |   +-------------+   |
             +--<| time_id     |   |
                 | distance_id |>--+
                 | name        |
                 +-------------+

```

This time our product is application that helps you with car maintenance schedule. Our users car has 4 tires that must be replaced after 10 years or 100000km and 4 spark plugs that must be replaced after 100000km. So 4 indistinguishable rows for tires are added to parts table (they reference both time and distance) and 4 indistinguishable rows are added for spark plugs (they reference only distance).

Now to extract to shard we have to find which rows from parts table does he own. By following relations through time table we will get 4 tires. But because this path is nullable at some point we are not sure if we found all records. And indeed, by following relations through distance table we found 4 tires and 4 spark plugs. Since this path is also nullable at some point we are not sure if we found all records. So we must combine result from time and distance paths, which gives us... 8 tires and 4 spark plugs? Well, that looks wrong. Maybe let's group it by time and distance pair, which gives us... 1 tire and 1 spark plug? So depending how you combine indistinguishable rows from many nullable paths to get final row set, you may suffer either data duplication or data loss.

To understand this issue better consider two answers to question `How many legs does the horse have?`:

* `Eight. Two front, two rear, two left and two right.` This answer is incorrect because each leg is counted multiple times from different nullable relations.
* `Four. Those attached to it.` This answer is correct because each leg is counted exactly once through not nullable relation.

**Hint:**

You can check if `UpRooted::Tree` has ambiguities by running:

```
my $tree = ...;
say $tree.paths.grep: *.is-ambiguous;

```

**Fix:** Redesign schema so that at least one not nullable relations path leads to every table.


## dist_github-azawawi-GTK-Simpler.md
# GTK::Simpler [Build Status](https://travis-ci.org/azawawi/perl6-gtk-simpler) [Build status](https://ci.appveyor.com/project/azawawi/perl6-gtk-simpler/branch/master)

This module provides a simpler API for
[GTK::Simple](https://github.com/perl6/gtk-simple). The idea here is to load
GTK::Simple widgets lazily at runtime and type less characters. For example
instead of writing the following:

```
# This is slow since it will load a lot of GTK::Simple widgets by default
use GTK::Simple;

my $app = GTK::Simple::App.new(title => "Hello");

```

you write the more concise shorter form:

```
# Exports a bunch of subroutines by default
use GTK::Simpler;

# GTK::Simple::App is loaded and created only here
my $app = app(title => "Hello");

```

## Example

```
use v6;
use GTK::Simpler;

my $app = app(title => "Hello GTK!");

$app.set-content(
    vbox(
        my $first-button  = button(label => "Hello World!"),
        my $second-button = button(label => "Goodbye!")
    )
);

$app.border-width        = 20;
$second-button.sensitive = False;

$first-button.clicked.tap({
    .sensitive = False;
    $second-button.sensitive = True
});

$second-button.clicked.tap({
    $app.exit;
});

$app.run;

```

For more examples, please see the <examples> folder.

## Documentation

Please see the [GTK::Simpler](doc/GTK-Simpler.md) generated documentation.

## Installation

Please check [GTK::Simple prerequisites](https://github.com/perl6/gtk-simple/blob/master/README.md#prerequisites) section
for more information.

To install it using zef (a module management tool bundled with Rakudo Star):

```
$ zef install GTK::Simpler

```

## Testing

* To run tests:

```
$ prove -e "perl6 -Ilib"

```

* To run all tests including author tests (Please make sure
  [Test::Meta](https://github.com/jonathanstowe/Test-META) is installed):

```
$ zef install Test::META
$ AUTHOR_TESTING=1 prove -ve "perl6 -Ilib"

```

## Author

Ahmad M. Zawawi, [azawawi](https://github.com/azawawi/) on #perl6

## License

MIT License


## dist_github-alabamenhu-Regex-FuzzyToken.md
![](resources/logo.png)

A Raku module enabling the use of fuzzy tokens in regexen and grammars:

```
use Regex::FuzzyToken;
my @fruits = <apple banana mango orange kiwi>;
"My favorite fruit is a bnana" ~~ /My favorite fruit is a <fuzzy: @fruits>/;
say $<fuzzy>.fuzz; # bnana
say $<fuzzy>.Str;  # banana

```

Support for more flexible capturing options is forthcoming. The signature for
the fuzzy token are the following:

```
fuzzy(*@words,
      :$i  = False,
      :$m  = False,
      :$ws = True,
      :$q  = 33,
      :$capture = (@words.tail ~~ Regex
                     ?? @words.tail
                     !! /\w+/ )
)

```

Basically, you should provide a list of strings to be the “goal” words you want to find,
but will accept if they're slightly misspelled. The `i`, `m`, and `ws` options mimic
the regex matching behavior, and will make comparisons ignore differences in case (**i**),
marks (**m**) or white space (**ws**). The `q` option is the minimum Q-gram score desired to
allow for a match. The default of 33 is fine for most cases, but through testing you
may find it necessary to increase or decrease the sensitivity (100 = only match exact,
0 = match everything).

The final option of :$capture allows you to specify the capture regex to use. By
default it will only capture a sequence of word characters, but that will cause
problems if you need it to match spaces/apostrophes. While you *can* make things
explicit with `:capture(/foo/)`, the signature was designed to allow you to
specify the final item as the capture regex, and so the following are equivalent:

```
<fuzzy: @foo, /bar/>
<fuzzy: @foo, :capture(/bar/)>

```

# To do

It could be interesting to allow for a more complex capture, for example, that
matches only as many characters as it needs using `.match($capture, :exhaustive)` on a
substring from the current `.pos`. That would require some tuning of the Q gram algorithm
and in many cases could take exponentially more time, but would be more accurate / usable.

# Licenses

All code is and documentation is licensed under the Artistic License 2.0, included with
the module. The image used on Github is based on
[this butterfly](https://www.piqsels.com/en/public-domain-photo-frbsj)
which is licensed under CC-0 and modified in accordance with that license and released
under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/)


## dist_zef-FCO-Heap.md
[![Build Status](https://travis-ci.org/FCO/Heap.svg?branch=master)](https://travis-ci.org/FCO/Heap)

Impleementation of Heap data structure

### has Callable &.cmp

The comparator function

### has Positional[Any] @.data

The array with the heap data

### method new

```
method new(
    +@arr is copy
) returns Mu

```

Receives a array and transforms that array in a Heap (O(n))

### method push

```
method push(
    $new
) returns Mu

```

Add a ney value on the Heap

### method pop

```
method pop() returns Mu

```

Removes and returns the first element of the heap

### method peek

```
method peek() returns Mu

```

Returns the first element of the heap

### method all

```
method all() returns Mu

```

Pops the Heap until its empty

# Heap

A simple perl6 module implementing the heap data structure.

```
my Heap $heap .= new: 9, 7, 5, 3, 1;
$heap.push: 8;
say $heap.pop;		# 1
say $heap.pop;		# 3
say $heap.pop;		# 5

say $heap.all		# (7, 8, 9)

```

```
my Heap[-*] $heap .= new: <9 7 5 3 1>;
$heap.push: 8;
say $heap.pop;		# 9
say $heap.pop;		# 8
say $heap.pop;		# 7

```

```
my Heap[{$^b <=> $^a}] $heap .= new: <9 7 5 3 1>;
$heap.push: 8;
say $heap.pop;		# 9
say $heap.pop;		# 8
say $heap.pop;		# 7

```

```
my Heap[*<order>] $heap .= new:
	{:something<ble>, :order<2>},
	{:something<bla>, :order<1>},
	{:something<bli>, :order<3>},
	{:something<blu>, :order<5>},
;
$heap.push: {:something<blo>, :order<4>},
say $heap.pop;		# {:something<bla>, :order<1>}
say $heap.pop;		# {:something<ble>, :order<2>}
say $heap.pop;		# {:something<bli>, :order<3>}

```


## dist_zef-antononcube-Lingua-Stem-Portuguese.md
# Lingua::Stem::Portuguese Raku package

## Introduction

This Raku package is for stemming Portuguese words.
It implements the Snowball algorithm presented in
[[SNa1](http://snowball.tartarus.org/algorithms/portuguese/stemmer.html)].

---

## Usage examples

The `PortugueseStem` function is used to find stems:

```
use Lingua::Stem::Portuguese;
say PortugueseStem('brotação')

```

```
# brot

```

`PortugueseStem` also works with lists of words:

```
say PortugueseStem('Os brotos são aguardados com paciência, bebida e bacon.'.words)

```

```
# (Os brot sao aguard com paciencia, beb e bacon.)

```

The function `portuguese-word-stem` can be used as a synonym of `PortugueseStem`.

---

## Command Line Interface (CLI)

The package provides the CLI function `PortugueseStem`. Here is its usage message:

```
PortugueseStem --help

```

```
# Usage:
#   PortugueseStem <text> [--splitter=<Str>] [--format=<Str>] -- Finds stems of Portuguese words in text.
#   PortugueseStem [<words> ...] [--format=<Str>] -- Finds stems of Portuguese words.
#   PortugueseStem [--format=<Str>] -- Finds stems of Portuguese words in (pipeline) input.
#
#     <text>              Text to spilt and its words stemmed.
#     --splitter=<Str>    String to make a split regex with. [default: '\W+']
#     --format=<Str>      Output format one of 'text', 'lines', or 'raku'. [default: 'text']
#     [<words> ...]       Words to be stemmed.

```

Here are example shell commands of using the CLI function `PortugueseStem`:

```
PortugueseStem Boataria

```

```
# Boat

```

```
PortugueseStem --format=raku "Módulo Raku que fornece um procedimento para a língua portuguesa."

```

```
# ["Modul", "Raku", "que", "fornec", "um", "proced", "par", "a", "lingu", "portugu", ""]

```

```
PortugueseStem Verificar a exatidão da seleção usando dicionários e regras

```

```
# Verific a exatid da selec us dicion e regr

```

Here is a pipeline example using the CLI function `get-tokens` of the package
["Grammar::TokenProcessing"](https://github.com/antononcube/Raku-Grammar-TokenProcessing),
[AAp1]:

```
get-tokens ./DataQueryPhrases-template | PortugueseStem --format=raku

```

**Remark:** These kind of tokens (literals) transformations are used in the packages
["DSL::Bulgarian"](https://github.com/antononcube/Raku-DSL-Bulgarian), [AAp2],
["DSL::Portuguese"](https://github.com/antononcube/Raku-DSL-Portuguese), [AAp3],
and
["DSL::Russian"](https://github.com/antononcube/Raku-DSL-Russian), [AAp4],

---

## Implementation notes

* Reprogrammed to Raku from : <https://github.com/neilb/Lingua-PT-Stemmer/blob/master/lib/Lingua/PT/Stemmer.pm> .

---

## TODO

* TODO Respect the word case in the returned result.

  * `PortugueseStem('TABLADO')` should return `'TABL'`.
  * (Not `'tabl'` as it currently does.)
* DONE CLI that can be inserted in UNIX pipelines.
* TODO Gallician stemmer.
* TODO Performance statistics.
* TODO More detailed documentation.

---

## References

### Articles

[SNa1] Snowball Team,
[Portuguese stemming algorithm](http://snowball.tartarus.org/algorithms/portuguese/stemmer.html),
(2002),
[snowball.tartarus.org](http://snowball.tartarus.org).

### Packages

[AAp1] Anton Antonov,
[Grammar::TokenProcessing Raku package](https://github.com/antononcube/Raku-Grammar-TokenProcessing),
(2022),
[GitHub/antononcube](https://github.com/antononcube).

[AAp2] Anton Antonov,
[DSL::Bulgarian Raku package](https://github.com/antononcube/Raku-DSL-Bulgarian),
(2022),
[GitHub/antononcube](https://github.com/antononcube).

[AAp3] Anton Antonov,
[DSL::Portuguese Raku package](https://github.com/antononcube/Raku-DSL-Portuguese),
(2023),
[GitHub/antononcube](https://github.com/antononcube).

[AAp3] Anton Antonov,
[DSL::Russian Raku package](https://github.com/antononcube/Raku-DSL-Russian),
(2022),
[GitHub/antononcube](https://github.com/antononcube).


## dist_cpan-SCIMON-Game-Sudoku.md
[![Build Status](https://travis-ci.org/Scimon/p6-Game-Sudoku.svg?branch=master)](https://travis-ci.org/Scimon/p6-Game-Sudoku)

# NAME

Game::Sudoku - Store, validate and solve sudoku puzzles

# SYNOPSIS

```
use Game::Sudoku;

# Create an empty game
my $game = Game::Sudoku.new();
# Set some cells
$game.cell(0,0,1).cell(0,1,2);
# Test the results
$game.valid();
$game.full();
$game.complete();

# Get possible values for a cell
$game.possible(0,2);

```

# DESCRIPTION

Game::Sudoku is a simple library to store, test and attempt to solve sudoku puzzles.

Currently the libray can be used as a basis for doing puzzles and can solve a number of them. I hope to add additional functionality to it in the future.

The Game::Sudoku::Solver module includes documenation for using the solver.

# METHODS

## new( Str :code -> Game::Sudoku )

The default constructor will accept and 81 character long string comprising of combinations of 0-9. This code can be got from an existing Game::Sudoku object by calling it's .Str method.

## valid( -> Bool )

Returns True if the sudoku game is potentially valid, IE noe row, colum or square has 2 of any number. A valid puzzle may not be complete.

## full( -> Bool )

Returns True if the sudoku game has all it's cells set to a non zero value. Note that the game may not be valid.

## complete( -> Bool )

Returns True is the sudoku game is both valid and full.

## possible( Int, Int, Bool :$set -> List )

Returns the sorted Sequence of numbers that can be put in the current cell. Note this performs a simple check of the row, column and square the cell is in it does not perform more complex logical checks.

Returns an empty List if the cell already has a value set or if there are no possible values.

If the optional :set parameter is passed then returns a Set of the values instead.

## cell( Int, Int -> Int )

## cell( Int, Int, Int -> Game::Sudoku )

Getter / Setter for individual cells. The setter returns the updated game allowing for method chaining. Note that attempting to set a value defined in the constructor will not work, returning the unchanged game object.

## row( Int -> List(List) )

Returns the list of (x,y) co-ordinates in the given row.

## col( Int -> List(List) )

Returns the list of (x,y) co-ordinates in the given column.

## square( Int -> List(List) )

## square( Int, Int -> List(List) )

Returns the list of (x,y) co-ordinates in the given square of the grid. A square can either be references by a cell within it or by it's index.

```
0|1|2
-----
3|4|5
-----
6|7|8

```

## reset( Str :$code )

Resets the puzzle to the state given in the $code argument. If the previous states initial values are all contained in the new puzzle then they will not be updated. Otherwise the puzzle will be treated as a fresh one with the given state.

# AUTHOR

Simon Proctor [simon.proctor@gmail.com](mailto:simon.proctor@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2017 Simon Proctor

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-lizmat-P5print.md
[![Actions Status](https://github.com/lizmat/P5print/workflows/test/badge.svg)](https://github.com/lizmat/P5print/actions)

# NAME

Raku port of Perl's print() and associated built-ins

# SYNOPSIS

```
use P5print; # exports print, printf, say, STDIN, STDOUT, STDERR

print STDOUT, "foo";

printf STDERR, "%s", $bar;

say STDERR, "foobar";      # same as "note"

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `print`, `printf` and `say` built-ins as closely as possible in the Raku Programming Language.

# ORIGINAL PERL 5 DOCUMENTATION

```
print FILEHANDLE LIST
print FILEHANDLE
print LIST
print   Prints a string or a list of strings. Returns true if successful.
        FILEHANDLE may be a scalar variable containing the name of or a
        reference to the filehandle, thus introducing one level of
        indirection. (NOTE: If FILEHANDLE is a variable and the next token
        is a term, it may be misinterpreted as an operator unless you
        interpose a "+" or put parentheses around the arguments.) If
        FILEHANDLE is omitted, prints to the last selected (see "select")
        output handle. If LIST is omitted, prints $_ to the currently
        selected output handle. To use FILEHANDLE alone to print the
        content of $_ to it, you must use a real filehandle like "FH", not
        an indirect one like $fh. To set the default output handle to
        something other than STDOUT, use the select operation.

        The current value of $, (if any) is printed between each LIST
        item. The current value of $\ (if any) is printed after the entire
        LIST has been printed. Because print takes a LIST, anything in the
        LIST is evaluated in list context, including any subroutines whose
        return lists you pass to "print". Be careful not to follow the
        print keyword with a left parenthesis unless you want the
        corresponding right parenthesis to terminate the arguments to the
        print; put parentheses around all arguments (or interpose a "+",
        but that doesn't look as good).

        If you're storing handles in an array or hash, or in general
        whenever you're using any expression more complex than a bareword
        handle or a plain, unsubscripted scalar variable to retrieve it,
        you will have to use a block returning the filehandle value
        instead, in which case the LIST may not be omitted:

            print { $files[$i] } "stuff\n";
            print { $OK ? STDOUT : STDERR } "stuff\n";

        Printing to a closed pipe or socket will generate a SIGPIPE
        signal. See perlipc for more on signal handling.

printf FILEHANDLE FORMAT, LIST
printf FILEHANDLE
printf FORMAT, LIST
printf  Equivalent to "print FILEHANDLE sprintf(FORMAT, LIST)", except
        that $\ (the output record separator) is not appended. The FORMAT
        and the LIST are actually parsed as a single list. The first
        argument of the list will be interpreted as the "printf" format.
        This means that "printf(@_)" will use $_[0] as the format. See
        sprintf for an explanation of the format argument. If "use locale"
        (including "use locale ':not_characters'") is in effect and
        POSIX::setlocale() has been called, the character used for the
        decimal separator in formatted floating-point numbers is affected
        by the LC_NUMERIC locale setting. See perllocale and POSIX.

        For historical reasons, if you omit the list, $_ is used as the
        format; to use FILEHANDLE without a list, you must use a real
        filehandle like "FH", not an indirect one like $fh. However, this
        will rarely do what you want; if $_ contains formatting codes,
        they will be replaced with the empty string and a warning will be
        emitted if warnings are enabled. Just use "print" if you want to
        print the contents of $_.

        Don't fall into the trap of using a "printf" when a simple "print"
        would do. The "print" is more efficient and less error prone.

say FILEHANDLE LIST
say FILEHANDLE
say LIST
say     Just like "print", but implicitly appends a newline. "say LIST" is
        simply an abbreviation for "{ local $\ = "\n"; print LIST }". To
        use FILEHANDLE without a LIST to print the contents of $_ to it,
        you must use a real filehandle like "FH", not an indirect one like
        $fh.

        This keyword is available only when the "say" feature is enabled,
        or when prefixed with "CORE::"; see feature. Alternately, include
        a "use v5.10" or later to the current scope.

```

# PORTING CAVEATS

## Syntax differences

In Raku, there **must** be a comma after the handle, as opposed to Perl where the whitespace after the handle indicates indirect object syntax.

```
print STDERR "whee!";   # Perl way

print STDERR, "whee!";  # Raku mimicing Perl

```

## Parentheses

Because of some overzealous checks for Perl 5isms, it is necessary to put parentheses when using `print` and `say` as a function. Since the 2018.09 Rakudo compiler release, it is possible to use the `isms` pragma to avoid having to do that:

```
use isms <Perl5>;
$_ = "foo";
say;    # foo

```

## $\_ 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:

```
print;

```

to either:

```
print($_);

```

or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant:

```
.&print;

```

# IDIOMATIC PERL 6 WAYS

When needing to write to specific handle, it's probably easier to use the method form.

```
$handle.print("foo");
$handle.printf("foo");
$handle.say("foo");

```

If you want to do a `say` on `STDERR`, this is easier done with the `note` builtin function:

```
$*ERR.say("foo");  # "foo\n" on standard error
note "foo";        # same

```

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!

Source can be located at: <https://github.com/lizmat/P5print> . 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.


## first.md
first

Combined from primary sources listed below.

# [In List](#___top "go to top of document")[§](#(List)_routine_first "direct link")

See primary documentation
[in context](/type/List#routine_first)
for **routine first**.

```raku
sub    first(Mu $matcher, *@elems, :$k, :$kv, :$p, :$end)
method first(List:D:  Mu $matcher?, :$k, :$kv, :$p, :$end)
```

Returns the first item of the list which smartmatches against `$matcher`, returns [`Nil`](/type/Nil) when no values match. The optional named parameter `:end` indicates that the search should be from the **end** of the list, rather than from the start.

Examples:

```raku
say (1, 22/7, 42, 300).first: * > 5;                  # OUTPUT: «42␤»
say (1, 22/7, 42, 300).first: * > 5, :end;            # OUTPUT: «300␤»
say ('hello', 1, 22/7, 42, 'world').first: Complex;   # OUTPUT: «Nil␤»
```

The optional named parameters `:k`, `:kv`, `:p` provide the same functionality as on slices:

* k

Return the index value of the matching element. Index is always counted from the beginning of the list, regardless of whether the `:end` named parameter is specified or not.

* kv

Return both the index and matched element.

* p

Return the index and the matched element as a [`Pair`](/type/Pair).

Examples:

```raku
say (1, 22/7, 42, 300).first: * > 5, :k;        # OUTPUT: «2␤»
say (1, 22/7, 42, 300).first: * > 5, :p;        # OUTPUT: «2 => 42␤»
say (1, 22/7, 42, 300).first: * > 5, :kv, :end; # OUTPUT: «(3 300)␤»
```

In method form, the `$matcher` can be omitted, in which case the first available item (or last if `:end` is set) will be returned. See also [`head`](/routine/head) and [`tail`](/routine/tail) methods.

# [In Any](#___top "go to top of document")[§](#(Any)_routine_first "direct link")

See primary documentation
[in context](/type/Any#routine_first)
for **routine first**.

```raku
multi method first(Bool:D $t)
multi method first(Regex:D $test, :$end, *%a)
multi method first(Callable:D $test, :$end, *%a is copy)
multi method first(Mu $test, :$end, *%a)
multi method first(:$end, *%a)
multi        first(Bool:D $t, |)
multi        first(Mu $test, +values, *%a)
```

In general, coerces the invocant to a `list` by applying its [`.list`](/routine/list) method and uses [`List.first`](/type/List#routine_first) on it.

However, this is a multi with different signatures, which are implemented with (slightly) different behavior, although using it as a subroutine is equivalent to using it as a method with the second argument as the object.

For starters, using a [`Bool`](/type/Bool) as the argument will always return a [`Failure`](/type/Failure). The form that uses a `$test` will return the first element that smartmatches it, starting from the end if `:end` is used.

```raku
say (3..33).first;           # OUTPUT: «3␤»
say (3..33).first(:end);     # OUTPUT: «33␤»
say (⅓,⅔…30).first( 0xF );   # OUTPUT: «15␤»
say first 0xF, (⅓,⅔…30);     # OUTPUT: «15␤»
say (3..33).first( /\d\d/ ); # OUTPUT: «10␤»
```

The third and fourth examples use the `Mu $test` forms which smartmatches and returns the first element that does. The last example uses as a test a regex for numbers with two figures, and thus the first that meets that criterion is number 10. This last form uses the [`Callable`](/type/Callable) multi:

```raku
say (⅓,⅔…30).first( * %% 11, :end, :kv ); # OUTPUT: «(65 22)␤»
```

Besides, the search for first will start from the `:end` and returns the set of key/values in a list; the *key* in this case is simply the position it occupies in the [`Seq`](/type/Seq). The `:kv` argument, which is part of the `%a` argument in the definitions above, modifies what `first` returns, providing it as a flattened list of keys and values; for a listy object, the key will always be the index.

From version 6.d, the test can also be a [`Junction`](/type/Junction):

```raku
say (⅓,⅔…30).first( 3 | 33, :kv ); # OUTPUT: «(8 3)␤»
```

# [In Supply](#___top "go to top of document")[§](#(Supply)_method_first "direct link")

See primary documentation
[in context](/type/Supply#method_first)
for **method first**.

```raku
method first(Supply:D: :$end, |c)
```

This method creates a supply of the first element, or the last element if the optional named parameter `:end` is truthy, from a supply created by calling the `grep` method on the invocant, with any remaining arguments as parameters. If there is no remaining argument, this method is equivalent to calling on the invocant, without parameter, the `head` or the `tail` method, according to named parameter `:end`.

```raku
my $rand = supply { emit (rand × 100).floor for ^∞ };
my $first-prime = $rand.first: &is-prime;
# output the first prime from the endless random number supply $rand,
# then the $first-prime supply reaches its end
$first-prime.tap: &say;
```


## dist_zef-Altai-man-ASN-META.md
### ASN::META

Experimental Raku module that is able to compile [ASN.1](https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One) specification into set of Raku types.

#### What ASN::META does not?

* It does not generate Raku code (at least, textual form).
* The module knows nothing about ASN.1 encoding means, it purely generates Raku types.
  For this purpose a separate module may be used. Currently, goal is to have full compatibility
  with [ASN::BER](https://github.com/Altai-man/ASN-BER) module.

#### What ASN::META does?

Main workflow is as follows:

* A specification is passed to ASN::META on module `use`
* (internally, `ASN::Grammar` is used to parse the specification)
* ASN::META uses parsed specification to generate appropriate types with [MOP](https://docs.perl6.org/language/mop)
* Generated types for particular ASN.1 specification are precompiled and exported

#### What it does?

#### Synopsis

```
# In file `schema.asn`:
WorldSchema

DEFINITIONS IMPLICIT TAGS ::= BEGIN
Rocket ::= SEQUENCE
{
   name      UTF8String,
   message   UTF8String DEFAULT "Hello World",
   fuel      ENUMERATED {
       solid(0),
       liquid(1),
       gas(2)
   },
   speed     CHOICE {
      mph    [0] INTEGER,
      kmph   [1] INTEGER
   }  OPTIONAL,
   payload   SEQUENCE OF UTF8String
}
END

# In file `User.pm6`:
# Note usage of BEGIN block to gather file's content at compile time
use ASN::META BEGIN [ 'file', slurp 'schema.asn' };
# In case of re-compilation on dependency change, package User may be
# re-built from the place where local paths are useless, in this case use %?RESOURCES:
# `use ASN::META BEGIN { 'file', slurp %?RESOURCES<schema.asn> }`

# `Rocket` type is exported by ASN::META
my Rocket $rocket = Rocket.new(name => 'Rocker', :fuel(solid),
        speed => Speed.new((mph => 9001)),
        payload => Array[Str].new('A', 'B', 'C'));

# As well as inner types being promoted to top level:
say Fuel;  # generated enum
say solid; # value of this enum, (solid ~~ Fuel) == true
say Speed; # Generated type based on ASNChoice from ASN::BER

```


## chars.md
chars

Combined from primary sources listed below.

# [In Match](#___top "go to top of document")[§](#(Match)_method_chars "direct link")

See primary documentation
[in context](/type/Match#method_chars)
for **method chars**.

```raku
method chars()
```

Returns the numbers of characters in the matched string or 0 if there's been no match.

Returns the same as `.Str.chars`.

# [In role Blob](#___top "go to top of document")[§](#(role_Blob)_method_chars "direct link")

See primary documentation
[in context](/type/Blob#method_chars)
for **method chars**.

```raku
method chars(Blob:D:)
```

Throws [`X::Buf::AsStr`](/type/X/Buf/AsStr) with `chars` as payload.

# [In Str](#___top "go to top of document")[§](#(Str)_routine_chars "direct link")

See primary documentation
[in context](/type/Str#routine_chars)
for **routine chars**.

```raku
multi        chars(Cool  $x --> Int:D)
multi        chars(Str:D $x --> Int:D)
multi        chars(str   $x --> int)
multi method chars(Str:D:   --> Int:D)
```

Returns the number of characters in the string in graphemes. On the JVM, this currently erroneously returns the number of codepoints instead.

# [In Cool](#___top "go to top of document")[§](#(Cool)_routine_chars "direct link")

See primary documentation
[in context](/type/Cool#routine_chars)
for **routine chars**.

```raku
multi  chars(Cool $x)
multi  chars(Str:D $x)
multi  chars(str $x --> int)
method chars(--> Int:D)
```

Coerces the invocant (or in sub form, its argument) to [`Str`](/type/Str), and returns the number of characters in the string. Please note that on the JVM, you currently get codepoints instead of graphemes.

```raku
say 'møp'.chars;    # OUTPUT: «3␤»
say 'ã̷̠̬̊'.chars;     # OUTPUT: «1␤»
say '👨👩👧👦🏿'.chars;    # OUTPUT: «1␤»
```

If the string is native, the number of chars will be also returned as a native `int`.

Graphemes are user visible characters. That is, this is what the user thinks of as a “character”.

Graphemes can contain more than one codepoint. Typically the number of graphemes and codepoints differs when `Prepend` or `Extend` characters are involved (also known as [Combining characters](https://en.wikipedia.org/wiki/Combining_character)), but there are many other cases when this may happen. Another example is `\c[ZWJ]` ([Zero-width joiner](https://en.wikipedia.org/wiki/Zero-width_joiner)).

You can check `Grapheme_Cluster_Break` property of a character in order to see how it is going to behave:

```raku
say ‘ã̷̠̬̊’.uniprops(‘Grapheme_Cluster_Break’); # OUTPUT: «(Other Extend Extend Extend Extend)␤»
say ‘👨👩👧👦🏿’.uniprops(‘Grapheme_Cluster_Break’); # OUTPUT: «(E_Base_GAZ ZWJ E_Base_GAZ ZWJ E_Base_GAZ ZWJ E_Base_GAZ E_Modifier)␤»
```

You can read more about graphemes in the [Unicode Standard](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries), which Raku tightly follows, using a method called [NFG, normal form graphemes](/language/glossary#NFG) for efficiently representing them.


## parse-base.md
parse-base

Combined from primary sources listed below.

# [In Str](#___top "go to top of document")[§](#(Str)_routine_parse-base "direct link")

See primary documentation
[in context](/type/Str#routine_parse-base)
for **routine parse-base**.

```raku
multi        parse-base(Str:D $num, Int:D $radix --> Numeric)
multi method parse-base(Str:D $num: Int:D $radix --> Numeric)
```

Performs the reverse of [`base`](/routine/base) by converting a string with a base-`$radix` number to its [`Numeric`](/type/Numeric) equivalent. Will [`fail`](/routine/fail) if radix is not in range `2..36` or if the string being parsed contains characters that are not valid for the specified base.

```raku
1337.base(32).parse-base(32).say; # OUTPUT: «1337␤»
'Raku'.parse-base(36).say;        # OUTPUT: «1273422␤»
'FF.DD'.parse-base(16).say;       # OUTPUT: «255.863281␤»
```

See also: [syntax for number literals](/syntax/Number%20literals)