## dist_zef-Kaiepi-Kind.md
[![Build Status](https://github.com/Kaiepi/ra-Kind/actions/workflows/test.yaml/badge.svg)](https://github.com/Kaiepi/ra-Kind/actions/workflows/test.yaml)

# NAME

Kind - Typechecking based on kinds

# SYNOPSIS

```
use Kind;

my constant Class = Kind[Metamodel::ClassHOW];

proto sub is-class(Mu --> Bool:D)  {*}
multi sub is-class(Class --> True) { }
multi sub is-class(Mu --> False)   { }

say Str.&is-class;  # OUTPUT: True
say Blob.&is-class; # OUTPUT: False

```

# DESCRIPTION

`Kind` is an uninstantiable parametric type that can be used to typecheck values based off their kind. A parameterization produces a type object that can process the HOW of a type in a typecheck context with `ACCEPTS` when available, otherwise falling back to the bare typecheck.

`Kind` is documented. You can view the documentation for it and its methods at any time using `WHY`.

# METAMETHODS

## method parameterize

```
method ^parameterize(|args) is raw

```

Produces a parameterization by delegating to `^kind` with `args`.

## method kind

```
method ^kind(Mu $obj is raw, Mu \K, Mu:U \T = Mu) is raw

```

Produces a cached subset with a refinement (`where`) built from `K` and a refinement (`of`) from `T` if present. This backs `^parameterize` so as to allow for a different parameterizer in a subtype. This is more or less a wrapper for `Metamodel::Primitives.parameterize_type`.

Some useful values with which to produce a type are:

* a metaclass or metarole

```
# Smartmatches any class.
Kind[Metamodel::ClassHOW]

```

* a junction of metaclasses or metaroles

```
# Smartmatches any type that supports naming, versioning, and documenting.
Kind[Metamodel::Naming & Metamodel::Versioning & Metamodel::Documenting]

```

* a block

```
# Smartmatches any parametric type.
Kind[{ use nqp; nqp::hllbool(nqp::can($_, 'parameterize')) }]

```

* a metaobject

```
# This class' metamethods constrain their metaobject to itself or its subtypes.
class Configurable {
    my constant K := Kind[$?CLASS.HOW.WHAT, $?CLASS];

    my constant %configuration := hash;

    method ^configure(K $obj, %config --> Map:D) {
        %configuration{$obj.WHAT.WHICH} := %config.Map
    }

    method ^configuration(K $obj --> Map:D) {
        %configuration{$obj.WHAT.WHICH} // Map.new
    }
}

```

For more examples of parameterizations of `Kind`, refer to `t/01-typecheck.t`.

# SYMBOLS

## &set\_parameterizer

```
our sub set_parameterizer(Mu $obj is raw, &parameterizer = &parameterize --> Nil)

```

Applies the parameterizer of `Kind` to a metaobject, providing it with a parameterization cache. A subtype needs to apply this at `BEGIN`-time in order to parameterize with the default metamethods, for instance:

```
class Kind::Instantiable is Kind {
    BEGIN Kind::set_parameterizer($?CLASS);
}

```

A `&parameterizer` may be provided, in which case that will be set instead. This should carry a compatible signature with `&parameterize`.

For more examples of how to subclass `Kind`, refer to `t/02-meta.t`.

## &parameterize

```
our sub parameterize(Mu $root is raw, Any $args) is raw

```

Given the `$root` metaobject of the parameterization and its `$args`, produces a type object minus the caching. `$args` is assumed to carry `K` at position `0` and `T`, if present, at position `1`.

# 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.


## dist_zef-FCO-Highlight-Terminal.md
[![Actions Status](https://github.com/FCO/Highlight-Terminal/actions/workflows/test.yml/badge.svg)](https://github.com/FCO/Highlight-Terminal/actions)

# NAME

Highlight::Terminal - Highlight code using terminal colors

# SYNOPSIS

```
use Highlight::Terminal;

say Q"my $bla = 42; for $bla/2 .. $bla { .say }.AST.DEPARSE: Highlight::Terminal;

```

![Highlighted code](highlighted.png)

# DESCRIPTION

Highlight::Terminal is a way to highlight Raku code using `RakuAST` and terminal colors.

# TODO

* Improve default theme
* Make layout customisable

# AUTHOR

Fernando Corrêa de Oliveira [fco@cpan.org](mailto:fco@cpan.org)

# COPYRIGHT AND LICENSE

Copyright 2024 Fernando Corrêa de Oliveira

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


## dist_cpan-JNTHN-Concurrent-Queue.md
# Concurrent::Queue

A lock-free queue data structure, safe for concurrent use.

## Synopsis

```
use Concurrent::Queue;

my $queue = Concurrent::Queue.new;
$queue.enqueue('who');
$queue.enqueue('what');
$queue.enqueue('why');
say $queue.dequeue;         # who
say ?$queue;                # True
say $queue.elems;           # 2
say $queue.Seq;             # (what why)
say $queue.list;            # (what why)
say $queue.dequeue;         # what
$queue.enqueue('when');
say $queue.dequeue;         # why
say $queue.dequeue;         # when
say ?$queue;                # False
say $queue.elems;           # 0

my $val = $queue.dequeue;
say $val.WHO;               # Failure
say $val.exception.WHO;     # X::Concurrent::Queue::Empty

```

## Overview

Lock-free data structures may be safely used from multiple threads, yet do not
use locks in their implementation. They achieve this through the use of atomic
operations provided by the hardware. Nothing can make contention between
threads cheap - synchronization at the CPU level is still synchronization -
but lock-free data structures tend to scale better.

This lock-free queue data structure implements an [algorithm described by
Maged M. Michael and Michael L. Scott](https://www.research.ibm.com/people/m/michael/podc-1996.pdf).
The only (intended) differences are:

* A `Failure` is returned to indicate emptiness, rather than a combination of
  boolean return value and out parameter, in order that this type feels more
  natural to Perl 6 language users
* There is an out-of-band element count (which doesn't change the algorithm at
  all, just increments and decrements the count after an enqueue/dequeue)
* Perl 6 doesn't need ABA-problem mitigation thanks to having GC

The `elems` and `Bool` method should not be used to decide whether to dequeue,
unless it is known that no other thread could be performing an enqueue or
dequeue. Their only use in the presence of concurrent use of the queue is for
getting an approximate idea of queue size. In the presence of a single thread,
the element count will be accurate (so if many workers were to enqueue data,
and are known to have completed, then at that point the `elems` will be an
accurate reflection of how many values were placed in the queue).

Note that there is no blocking dequeue operation. If looking for a blocking
queue, consider using the Perl 6 built-in `Channel` class. (If tempted to
write code that sits in a loop testing if `dequeue` gives back a `Failure` -
don't. Use `Channel` instead.)

### Methods

#### enqueue(Any $value)

Puts the value into the queue at its tail. Returns `Nil`.

#### dequeue()

If the queue is not empty, removes the head value and returns it. Otherwise,
returns a `Failure` containing an exception of type `X::Concurrent::Queue::Empty`.

#### elems()

Returns the number of elements in the queue. This value can only be relied upon
when it is known that no threads are interacting with the queue at the point this
method is called. Never use the result of `elems` to decide whether to `dequeue`,
since another thread may `enqueue` or `dequeue` in the meantime. Instead, check
if `dequeue` returns a `Failure`.

#### Bool()

Returns `False` if the queue is empty and `True` if the queue is non-empty.
The result can only be relied upon when it is known that no threads are
interacting with the queue at the point this method is called. Never use
the result of `Bool` to decide whether to `dequeue`, since another thread
may `enqueue` or `dequeue` in the meantime. Instead, check if `dequeue`
returns a `Failure`.

#### Seq

Returns a `Seq` that will iterate the queue contents. The iteration will
include all values that had not been dequeued at the point the `Seq`
method was called. Additionally, it will incorporate any values that
are enqueued during the iteration, meaning that if values are being
enqueued at a rate at least as fast as the iteration is visiting them
then the iteration may not terminate.

If wanting to prevent this, consider limiting the result length to
that of the result of `elems` (e.g. `$cq.head($cq.elems)`). If
using the queue to collect values in many threads and then iterate
them in one thread afterwards, this is not a concern, since nothing
will be enqueueing further values at that point. However, consider
using `Concurrent::Stack` instead, since a concurrent stack's
operations are cheaper than those of a concurrent queue (the same
algorithmic order, but a lower constant factor).

#### list

Equivalent to `.Seq.list`; see the description of `Seq` for caveats,
and remember that a `List` preserves its elements, so the potentially
endless iteration could also eat endless memory.


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

# NAME

URI::Encode - a Raku module for encoding / decoding URIs

# SYNOPSIS

```
use URI::Encode;

# for encoding whole URIs, ignores reserved chars: :/?#[]@!$&'()*+,;=
my $encoded_uri = uri_encode('http://www.example.com/?name=john doe&age=54');

# encode every reserved char
my $encoded_uri_component = uri_encode_component('some text/to encode+ safely');

# remove percent encoding
my $decoded_uri = uri_decode('http://www.example.com/?name=john%20doe&age=54');

# provided for symmetry, is the same as uri_decode()
my $decoded_component = uri_decode_component('some%20text%2Fto%20%2B%20safely');

```

# DESCRIPTION

URI::Encode is a module that exports four subroutines:

* uri\_encode - encode a whole URI
* uri\_encode\_component - encode every reserved char
* uri\_decode - decode a whole URI
* uri\_decode\_component - decode every reserved char

# SEE ALSo

[`URI`](https://raku.land/github:raku-community-modules/URI) is another implementation that covers this area, including encoding and decoding of URIs.

# AUTHOR

David Farrell

# COPYRIGHT AND LICENSE

Copyright 2014 - 2015 David Farrell

Copyright 2016 - 2025 Raku Community

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


## dist_zef-atroxaper-App-RaCoCo.md
[![Ubuntu](https://github.com/atroxaper/raku-RaCoCo/actions/workflows/ubuntu.yml/badge.svg)](https://github.com/atroxaper/raku-RaCoCo/actions/workflows/ubuntu.yml)
[![MacOS](https://github.com/atroxaper/raku-RaCoCo/actions/workflows/macos.yml/badge.svg)](https://github.com/atroxaper/raku-RaCoCo/actions/workflows/macos.yml)
[![Windows](https://github.com/atroxaper/raku-RaCoCo/actions/workflows/windows.yml/badge.svg)](https://github.com/atroxaper/raku-RaCoCo/actions/workflows/windows.yml)
[![Coverage Status](https://coveralls.io/repos/github/atroxaper/raku-RaCoCo/badge.svg?branch=master)](https://coveralls.io/github/atroxaper/raku-RaCoCo?branch=master)

# NAME

`App::RaCoCo` - Raku Code Coverage tool.

# SYNOPSIS

```
> racoco -l
[...]
All tests successful.
Files=16, Tests=114,  6 wallclock secs
Result: PASS
Coverage: 89.2%

> racoco --fail-level=95
[...]
Coverage: 89.2%
# exit code: 6

> racoco --html --silent
Visualisation: file://.racoco/report.html
Coverage: 89.2%
> browsername .racoco/report.html

```

# INSTALLATION

If you use zef, then `zef install App::RaCoCo`, or `pakku add App::RaCoCo` if you use Pakku.

# DESCRIPTION

`App::RaCoCo` provides the `racoco` application, which can be used to run tests and calculate code coverage.

You may specify the following options:

* **--exec** - command, which needs to be executed to run tests. For example, you may pass `--exec='prove --exec raku'` to use Perl's `prove` util instead of default `prove6`. Use `--/exec` option to not run tests and use coverage data from the previous run;
* **-l** - short-cut for `--exec='prove6 -l'`;
* **-I** - short-cut for `--exec='prove6 -I.'`;
* **--lib** - path to directory with target source files (`'./lib'` by default);
* **--raku-bin-dir** - path to directory with `raku` and `moar` binaries, which supposed to be used in the `--exec` (`$*EXECUTABLE.parent` by default);
* **--fail-level** - integer number - if the coverage level will be less than it then `racoco` will exit with a non-zero exit code;
* **--cache-dir** - path to directory where project related files racoco will be stored (`'./.racoco'` by default);
* **--silent** - hide test result output;
* **--append** - append the previous run result to the new one;
* **--html** - produce a simple HTML page to visualize results. It is short-cut for `--reporter=html`;
* **--color-blind** - use with `--html` option to make more readable colors than green/red pare. It is short-cut for `--reporter=html-color-blind`;
* **--reporter** - name of a custom result reporter;
* **--properties** - pass custom properties here;
* **configuration-name** - name of section with properties in `racoco.ini` to use in tests (see below [CONFIGURATION FILE](#configuration-file))

# NOTES

* RaCoCo application works only with MoarVM backended Raku compiler;
* It is common practice to not include `use lib 'lib'` line in test files. In a such case, we need to run tests with a command like `prove6 -l`. RaCoCo has a special short-cut option `-l` for you, then you do not need to write `racoco --exec='prove6 -l'`;
* Unfortunately, the current Rakudo implementation may produce a little different coverage log from run to run. Probably, it is because of some runtime optimisations.

# CONFIGURATION FILE

Tests are a thing that it is customary to run frequently. If you run tests with a command more complicated than just `racoco -l`, then you will like the fact that you can write all the configurations to a special `racoco.ini` file. For example, you regularly run `racoco -l` and `racoco -l --silent --html --fail-level=82` before commit. Then you can create a `racoco.ini` file in the root directory of your project with the following content:

```
exec = prove6 -l

[commit]
silent = true
reporter = html
fail-level = 82

```

After that just run `racoco` regularly and `racoco commit` before commit. As an alternative for configuration file you can use environment variables with appropriate names, or `--property=name:value;name:value` command-line option, or a combination of them. The priority is: command-line arguments > `--property` option > environment variables > `racoco.ini` file.

# CUSTOM REPORTERS

In addition to the output of results to the console, Racoco supports additional reporters with the `--reporter` option. Examples of such reporters are `html` or `html-color-blind` which build a simple HTML page with results. Please look for other reporters in the [Ecosystem](https://raku.land/?q=racoco).

## Information for Developers

A custom reporter must implement `App::Racoco::Report::Reporter` role, has full qualified name like `App::Racoco::Report::ReporterTheName` and live in `App::Racoco::Report::ReporterTheName` compilation unit (file). Then you can address to it through `--reporter=the-name`. For example, see `ReportHtmlColorBlind.rakumod`.

# AUTHOR

Mikhail Khorkov <atroxaper[at]cpan.org>

Sources can be found at: [github](https://github.com/atroxaper/raku-RaCoCo). The new Issues and Pull Requests are welcome.

# COPYRIGHT AND LICENSE

Copyright 2023 Mikhail Khorkov

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


## dist_github-azawawi-Clean.md
# Clean

[![Build Status](https://travis-ci.org/azawawi/perl6-clean.svg?branch=master)](https://travis-ci.org/azawawi/perl6-clean) [![Build status](https://ci.appveyor.com/api/projects/status/github/azawawi/perl6-clean?svg=true)](https://ci.appveyor.com/project/azawawi/perl6-clean/branch/master)

Provides a routine `clean` that takes an object and an anonymous code block
which takes an object that does `Cleanable`. This basically ensures that your
objects can be cleaned after your code block has finished running. Thus it
provides an object-oriented `clean` method (aka destructor).

## Example

```
# A class that needs to close or free resources
class Foo does Cleanable {

  # Guaranteed to be called once the anonymous block finishes execution
  method clean {
    # Close or free resources here
  }
}

clean(
  # The object we need to be cleaned up
  Foo.new,

  # The anonymous block
  -> $obj {
    # Do interesting stuff with $obj of type Cleanable
  }
);

```

## Installation

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

```
$ zef install Clean

```

## Testing

To run tests:

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

```

To run author tests, you need to manually install [Test::META](https://github.com/jonathanstowe/Test-META):

```
$ zef install Test::META
$ TEST_AUTHOR=1 prove -e "perl6 -Ilib"

```

## Author

Ahmad M. Zawawi, azawawi on #perl6, <https://github.com/azawawi/>

## License

MIT License


## dist_zef-jmaslak-BusyIndicator.md
# NAME

busy-indicator.raku - Luxafor Indicators based on Google Calendar and Webcam Status

# SYNOPSIS

```
# busy-indicator.rakuo --calendar=you@example.com

```

# DESCRIPTION

This controls Luxafor flag indicators based on a combination of Google Calendar meetings (when in a meeting, the flag is on, as well as two minutes before and after the meeting) and webcam usage (when the webcam is in use, it turns the Luxafor flag on). It also provides for manual control of the Luxafor flag.

This allows people to know if I'm "busy" or not without disturbing me or a conference call I might be on.

# OPTIONAL PARAMETERS

## --calendar=

This is a comma-seperated list of Google calendars your Google account has access to examine and which you want to use to control the Luxafor flag.

To access these calendars, this program uses the `gcalcli` program. Thus, you need to install `gcalcli` before using this option. You also need to execute gcalcli once from the command line (which will open a browser for you to authenticate to Google) to have `gcalcli` cache a Google access token.

If you don't want to use Google calendar integration, simply don't provide this option.

## --externalrgb=command

A script to execute (you should provide the full path) when an RGB color change occurs (I.E. going from "free" to "busy" or similar. This allows use of indicators other than (or in addition to) Luxafor flags. This script must take three parameters--the red, green, and blue color values. Each value will be an integer between zero and 255. The full path to the script should be specified.

## --interval=

This determines how often the script fetches Google calendar entries and writes a status line to the screen. The default is `60` seconds.

## --port=

This determines what control port is used for this script. By default, it is 0 (disabled). If you use a control port (this is an advanced usage), you must specify a port number. Note that no authentication is used for this port, so it must not be firewalled or otherwise protected from outside access.

## --ignore-ooo

Ignores meetings on the calendar with a title of "OOO" (in any case). I use these as "out of office" meetings to block time, but have a meeting visible in another calendar that has details, so the OOO meetings provide no useful additional context.

# USER INTERFACE

Once you run the program, every minute (or whatever you specified for the `--interval` option) it will update the screen with a status. This status will indicate if you are currently in a meeting or, otherwise, the next meeting that is scheduled for today.

There are some keyboard commands that can be used to override the automatic busy indications:

The "b" command will turn the light(s) on (with a red light).

The "o" command will turn the light(s) off until the next meeting.

The "g" command will turn the light on, but as a green light.

The "n" displays the next meeting on your calendar.

The "a" shows you an "agenda" view of your upcoming meetings.

# INSTALLATION PREREQUISITES

You must have a Luxafor flag to use this program.

You need relatively recent Raku to be installed. Download Raku for your OS from: <https://www.raku.org/>

You must install `LibUSB` development libraries. On Ubuntu, this is done with:

```
sudo apt-get install libusb-1.0-0-dev

```

You must also install `gcalcli` if using the Google Calendar integration. To do that on Ubuntu:

```
sudo apt-get install gcalcli

```

Then you'll want to run gcalcli the first time, and log into Google with your proper credentials (the first time you run gcalcli, it'll open a browser for you to log into your Google account): gcalcli agenda

You must ensure that the Luxafor Flag is not bound to the `usbhid` module. To do that on Ubuntu, create a file `/etc/modprobe.d/luxafor.conf` that contains:

```
options usbhid quirks=0x04d8:0xf372:0x0004

```

You will need to reboot after making this change for it to take effect.

If you wish to run this program as a standard user (highly recommended), you also need to create a file named `/etc/udev/rules.d/luxafor.rules` with the following content:

```
SUBSYTEM=="usb", ATTR{idVendor}="04d8", ATTR{idProduct}=="f372" MODE="0664" OWNER="jmaslak"

```

Replace `jmaslak` in the above file with your username. Then you will need to reboot for this change to take effect.

As root (or another user depending on your Raku installation), you can install this package with: zef install BusyIndicator

Now you can run the script using "busy-indicator-raku" from the command line!

# COPYRIGHT

Copyright © 2019-2023 Joelle Maslak This application is free software; you can distribute it and/or modify it under the Artistic License 2.0

Also included is a modified version of Travis Gibson's `LibUSB` which has a copyright: Copyright © 2020 Travis Gibson It is also licensed under the Artistic License 2.0.


## dist_zef-frithnanth-Math-Libgsl-Matrix.md
## Chunk 1 of 2
[![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-Matrix/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-Matrix/actions)

# NAME

Math::Libgsl::Matrix Math::Libgsl::Vector - An interface to libgsl, the Gnu Scientific Library - Vector and matrix algebra.

# SYNOPSIS

```
use Math::Libgsl::Vector;
use Math::Libgsl::Matrix;

```

# DESCRIPTION

Math::Libgsl::Matrix provides an interface to the vector and matrix algebra 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.

This module comes with two classes, Vector and Matrix, available in 12 data types, so it offers 24 classes:

* Math::Libgsl::Vector - default, corresponding to a Math::Libgsl::Vector::Num64
* Math::Libgsl::Vector::Num32
* Math::Libgsl::Vector::Int32
* Math::Libgsl::Vector::UInt32
* Math::Libgsl::Vector::Int64
* Math::Libgsl::Vector::UInt64
* Math::Libgsl::Vector::Int16
* Math::Libgsl::Vector::UInt16
* Math::Libgsl::Vector::Int8
* Math::Libgsl::Vector::UInt8
* Math::Libgsl::Vector::Complex32
* Math::Libgsl::Vector::Complex64
* Math::Libgsl::Matrix - default, corresponding to a Math::Libgsl::Matrix::Num64
* Math::Libgsl::Matrix::Num32
* Math::Libgsl::Matrix::Int32
* Math::Libgsl::Matrix::UInt32
* Math::Libgsl::Matrix::Int64
* Math::Libgsl::Matrix::UInt64
* Math::Libgsl::Matrix::Int16
* Math::Libgsl::Matrix::UInt16
* Math::Libgsl::Matrix::Int8
* Math::Libgsl::Matrix::UInt8
* Math::Libgsl::Matrix::Complex32
* Math::Libgsl::Matrix::Complex64

All the following methods are available for the classes correspondig to each datatype, except where noted.

## Vector

### new(Int $size!)

### new(Int :$size!)

The constructor accepts one parameter: the vector's size; it can be passed as a Pair or as a single value.

### get(Int:D $index! where \* < $!vector.size --> Num)

This method returns the value of a vector's element. It is possible to address a vector element as a Raku array element:

```
say $vector[1];

```

or even:

```
say $vector[^10];

```

### set(Int:D $index! where \* < $!vector.size, Num(Cool)

This method sets the value of a vector's element. This method can be chained. It is possible to address a vector element as a Raku array element:

```
$vector[1] = 3;

```

Note that it's not possible to set a range of elements (yet). When used as a Raku array, this method can't be chained.

### setall(Num(Cool))

Sets all the elements of the vector to the same value. This method can be chained.

### zero()

Sets all the elements of the vector to zero. This method can be chained.

### basis(Int:D $index! where \* < $!vector.size)

Sets all the elements of the vector to zero except for the element at $index, which is set to one. This method can be chained.

### size(--> UInt)

This method outputs the vector's size.

### write(Str $filename!)

Writes the vector to a file in binary form. This method can be chained.

### read(Str $filename!)

Reads the vector from a file in binary form. This method can be chained.

### printf(Str $filename!, Str $format!)

Writes the vector to a file using the specified format. This method can be chained.

### scanf(Str $filename!)

Reads the vector from a file containing formatted data. This method can be chained.

### copy(Math::Libgsl::Vector $src where $!vector.size == .vector.size)

This method copies the vector $src into the current object. This method can be chained.

### swap(Math::Libgsl::Vector $w where $!vector.size == .vector.size)

This method exchanges the elements of the current vector with the ones of the vector $w. This method can be chained.

### swap-elems(Int $i where \* < $!vector.size, Int $j where \* < $!vector.size)

This method exchanges the $i-th and $j-th elements in place. This method can be chained.

### reverse()

This method reverses the order of the elements of the vector. This method can be chained.

### add(Math::Libgsl::Vector $b where $!vector.size == .vector.size)

### sub(Math::Libgsl::Vector $b where $!vector.size == .vector.size)

### mul(Math::Libgsl::Vector $b where $!vector.size == .vector.size)

### div(Math::Libgsl::Vector $b where $!vector.size == .vector.size)

These methods perform operations on the elements of two vectors. The object on which the method is called is the one whose values are changed. All these methods can be chained.

### scale(Num(Cool) $x)

This method multiplies the elements of the vector by a factor $x. This method can be chained.

### add-constant(Num(Cool) $x)

This method adds a constant to the elements of the vector. This method can be chained.

### sum(--> Num)

This method returns the sum of the elements of the vector. This method fails if the underlying C library's version is less than 2.7.

### axpby(Num(Cool) $alpha, Num(Cool) $beta, Math::Libgsl::Vector $b where $!vector.size == .vector.size)

This method performs the operation αx + βy and returns the result in the vector $b. This method can be chained. This method fails if the underlying C library's version is less than 2.7.

### max(--> Num)

### min(--> Num)

These two methods return the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.

### minmax(--> List)

This method returns a list of two values: the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.

### max-index(--> Int)

### min-index(--> Int)

These two methods return the index of the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.

### minmax-index(--> List)

This method returns a list of two values: the indices of the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.

### is-null(--> Bool)

### is-pos(--> Bool)

### is-neg(--> Bool)

### is-nonneg(--> Bool)

These methods return True if all the elements of the vector are zero, strictly positive, strictly negative, or non-negative.

### is-equal(Math::Libgsl::Vector $b --> Bool)

This method returns True if the two vectors are equal element-wise.

## Views

Views are extremely handy, but their C-language interface uses a couple of low-level tricks that makes difficult to write a simple interface for high-level languages. A View is a reference to data in a Vector, Matrix, or array, so it makes possible to work on a subset of that data without having to duplicate it in memory or do complex address calculation to access it. Since a View is a reference to an object, the programmer needs to take care that the original object doesn't go out of scope, or the virtual machine might deallocate its memory causing the underlying C library to crash. Look in the **examples/** directory for more programs showing what can be done with views.

## Vector View

```
use Math::Libgsl::Vector;

my Math::Libgsl::Vector $v .= new(30);                            # Create a 30-element vector
my Math::Libgsl::Vector::View $vv .= new;                         # Create a Vector View
my Math::Libgsl::Vector $v1 = $vv.subvector-stride($v, 0, 3, 10); # Get a subvector view with stride
$v1.setall(42);                                                   # Set all elements of the subvector view to 42
say $v[^30]; # output: (42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0)

```

There are two kinds of Vector Views: a Vector View on a Vector or a Vector View on a Raku array. These are Views of the first kind:

### subvector(Math::Libgsl::Vector $v, size\_t $offset where \* < $v.vector.size, size\_t $n --> Math::Libgsl::Vector)

Creates a view on a subset of the vector, starting from $offset and of length $n. This method returns a new Vector object. Any operation done on this view affects the original vector as well.

### subvector-stride(Math::Libgsl::Vector $v, size\_t $offset where \* < $v.vector.size, size\_t $stride, size\_t $n --> Math::Libgsl::Vector)

Creates a view on a subset of the vector, starting from $offset and of length $n, with stride $stride. This method returns a new Vector object. Any operation done on this view affects the original vector as well.

Views on a Raku array are a bit more complex, because it's not possible to simply pass a Raku array to a C-language function. So for this to work the programmer has to *prepare* the array to be passed to the library. Both the View object and the *prepared* array must not go out of scope.

There are three ways to access a Raku array as a Math::Libgsl::Vector object:

* The hard way - use NativeCall's CArray to create a C-language-happy array.
* The easy way - use the \*-prepvec sub to convert a Raku array into a C array.
* The easiest way - use the \*-array-vec sub, pass it the Raku array or list and a closure or anonymous sub.

This is an example of the "hard way":

```
use Math::Libgsl::Vector;
use NativeCall;

my CArray[num64] $array .= new: (1 xx 10)».Num;         # define a CArray
my Math::Libgsl::Vector::View $vv .= new;               # view: an object that will contain the view information
my Math::Libgsl::Vector $v = $vv.array($array);         # create an Math::Libgsl::Vector object
$v[0] = 2;                                              # assign a value to the first vector element
say $v[^10];                                            # output: (2 1 1 1 1 1 1 1 1 1)

```

This is an example of the "easy way":

```
use Math::Libgsl::Vector;

my @array = 1 xx 10;                                    # define an array
my $parray = num64-prepvec(@array);                     # prepare the array to be used as a Math::Libgsl::Vector
my Math::Libgsl::Vector::View $vv .= new;               # view: an object that will contain the view information
my Math::Libgsl::Vector $v = $vv.array($parray);        # create an Math::Libgsl::Vector object
$v[0] = 2;                                              # assign a value to the first vector element
say $v[^10];                                            # output: (2 1 1 1 1 1 1 1 1 1)

```

Here are some examples of the "easiest way":

```
use Math::Libgsl::Vector;

my @array = ^10;                                                    # initialize an array
my ($min, $max) = num64-array-vec(-> $vec { $vec.minmax }, @array); # find min and max value
say "$min $max";                                                    # output: 0 9

```

```
use Math::Libgsl::Constants;
use Math::Libgsl::Vector;
use Math::Libgsl::MovingWindow;

my @array = ^10;                                        # initialize an array
my Math::Libgsl::MovingWindow $mw .= new: :samples(5);  # initialize a MovingWindow object with a 5-sample window
                                                        # compute the moving-window mean of the array
my $w = num64-array-vec(-> $vec { $mw.mean($vec, :endtype(GSL_MOVSTAT_END_PADVALUE)) }, @array);
say $w[^10];                                            # output: (0.6 1.2 2 3 4 5 6 7 7.8 8.4)

```

Even using this last construct, if the Vector object is to be used outside of the closure it must be declared before calling array-vec.

```
use Math::Libgsl::Vector;

my @array = 1 xx 10;                                            # define an array
my Math::Libgsl::Vector $v .= new: 10;                          # declare a Math::Libgsl::Vector
num64-array-vec(-> $vec { $v.copy($vec); $v[0] = 2; }, @array); # assign a value to the first vector element
say $v[^10];                                                    # output: (2 1 1 1 1 1 1 1 1 1)

```

### num64-prepvec(@array)

This is just a sub, not a method; it gets a regular array and outputs a *prepared* array, kept in a scalar variable. There are similar functions for every data type, so for example if one is working with int16 Vectors, one will use the **int16-prepvec** sub. The num64, being the default data type, has a special **prepvec** alias. Once *prepared*, the original array can be discarded.

### array($parray --> Math::Libgsl::Vector)

This method gets a *prepared* array and returns a Math::Libgsl::Vector object.

### array-stride($array, size\_t $stride --> Math::Libgsl::Vector)

This method gets a *prepared* array and a **$stride** and returns a Math::Libgsl::Vector object.

### sub num64-array-vec(Block $bl, \*@data)

This sub arguments are a Block to execute and a regular Raku array. Internally it uses a vector view to convert the array into libgsl's own vector data type, obtains the Math::Libgsl::Vector from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Vector object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-vec** alias.

### sub num64-array-stride-vec(Block $bl, size\_t $stride, \*@data)

This sub arguments are a Block to execute, a stride, and a regular Raku array. Internally it uses a vector view to convert the array into libgsl's own vector data type, obtains the Math::Libgsl::Vector from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Vector object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-stride-vec** alias.

## Matrix

### new(Int $size1!, Int $size2!)

### new(Int :$size1!, Int :$size2!)

The constructor accepts two parameters: the matrix sizes; they can be passed as Pairs or as single values.

### get(Int:D $i! where \* < $!matrix.size1, Int:D $j! where \* < $!matrix.size2 --> Num)

This method returns the value of a matrix element. It is possible to address a matrix element as a Raku shaped array element:

```
say $matrix[1;2];

```

### set(Int:D $i! where \* < $!matrix.size1, Int:D $j! where \* < $!matrix.size2, Num(Cool)

This method sets the value of a matrix element. This method can be chained. It is possible to address a matrix element as a Raku shaped array element:

```
$matrix[1;3] = 3;

```

### setall(Num(Cool))

Sets all the elements of the matrix to the same value. This method can be chained.

### zero()

Sets all the elements of the matrix to zero. This method can be chained.

### identity()

Sets all elements of the matrix to the corrisponding elements of the identity matrix.

### size1(--> UInt)

### size2(--> UInt)

### size(--> List)

These methods return the first, second, or both the matrix sizes.

### write(Str $filename!)

Writes the matrix to a file in binary form. This method can be chained.

### read(Str $filename!)

Reads the matrix from a file in binary form. This method can be chained.

### printf(Str $filename!, Str $format!)

Writes the matrix to a file using the specified format. This method can be chained.

### scanf(Str $filename!)

Reads the matrix from a file containing formatted data. This method can be chained.

### copy(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)

This method copies the $src matrix into the current one. This method can be chained.

### swap(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)

This method swaps elements of the $src matrix and the current one. This method can be chained.

### tricpy(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2, Int $Uplo, Int $Diag)

This method copies the upper or lower trianglular matrix from **$src** to **self**. Use the **cblas-uplo** enumeration to specify which triangle copy. Use the **cblas-diag** enumeration to specify whether to copy the matrix diagonal. This method can be chained.

### get-row(Int:D $i where \* < $!matrix.size1)

This method returns an array from row number $i.

### get-col(Int:D $j where \* < $!matrix.size2)

This method returns an array from column number $j.

### set-row(Int:D $i where \* ≤ $!matrix.size1, @row where \*.elems == $!matrix.size2)

### set-row(Int:D $i where \* ≤ $!matrix.size1, Math::Libgsl::Vector $v where .vector.size == $!matrix.size2)

These methods set row number $i of the matrix from a Raku array or a Vector object. This method can be chained.

### set-col(Int:D $j where \* ≤ $!matrix.size2, @col where \*.elems == $!matrix.size1)

### set-col(Int:D $j where \* ≤ $!matrix.size2, Math::Libgsl::Vector $v where .vector.size == $!matrix.size1)

These methods set column number $j of the matrix from a Raku array or a Vector object. This method can be chained.

### swap-rows(Int:D $i where \* ≤ $!matrix.size1, Int:D $j where \* ≤ $!matrix.size1)

This method swaps rows $i and $j. This method can be chained.

### swap-cols(Int:D $i where \* ≤ $!matrix.size2, Int:D $j where \* ≤ $!matrix.size2)

This method swaps columns $i and $j. This method can be chained.

### swap-rowcol(Int:D $i where \* ≤ $!matrix.size1, Int:D $j where \* ≤ $!matrix.size1)

This method exchanges row number $i with column number $j of a square matrix. This method can be chained.

### copy-transpose(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size2 && $!matrix.size2 == .matrix.size1)

This method copies a matrix into the current one, while transposing the elements. This method can be chained.

### transpose()

This method transposes the current matrix. This method can be chained.

### transpose-tricpy(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size2 && $!matrix.size2 == .matrix.size1, Int $Uplo, Int $Diag)

This method copies a triangle from the **$src** matrix into the current one, while transposing the elements. Use the **cblas-uplo** enumeration to specify which triangle copy. Use the **cblas-diag** enumeration to specify whether to copy the matrix diagonal. This method can be chained.

### add(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)

This method adds a matrix to the current one element-wise. This method can be chained.

### sub(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)

This method subtracts a matrix from the current one element-wise. This method can be chained.

### mul(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)

This method multiplies a matrix to the current one element-wise. This method can be chained.

### div(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)

This method divides the current matrix by another one element-wise. This method can be chained.

### scale(Num(Cool) $x)

This method multiplies the elements of the current matrix by a constant value. This method can be chained.

### scale-rows(Math::Libgsl::Vector $x where .size == $!matrix.size1)

This method scales the rows of the M-by-N matrix by the elements of the vector $x, of length N. The i-th row of the matrix is multiplied by $xᵢ. This method can be chained. This method fails if the underlying C library's version is less than 2.7.

### scale-columns(Math::Libgsl::Vector $x where .size == $!matrix.size1)

This method scales the columns of the M-by-N matrix by the elements of the vector $x, of length N. The j-th column of the matrix is multiplied by $xⱼ. This method can be chained. This method fails if the underlying C library's version is less than 2.7.

### add-constant(Num(Cool) $x)

This method adds a constant to the elements of the current matrix. This method can be chained.

### max(--> Num)

### min(--> Num)

These two methods return the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.

### minmax(--> List)

This method returns a list of two values: the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.

### max-index(--> Int)

### min-index(--> Int)

These two methods return the index of the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.

### minmax-index(--> List)

This method returns a list of two values: the indices of the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.

### is-null(--> Bool)

### is-pos(--> Bool)

### is-neg(--> Bool)

### is-nonneg(--> Bool)

These methods return True if all the elements of the matrix are zero, strictly positive, strictly negative, or non-negative.

### is-equal(Math::Libgsl::Matrix $b --> Bool)

This method returns True if the matrices are equal element-wise.

### norm1(--> Num)

This method returns the 1-norm of the m-by-n matrix, defined as the maximum column sum. This method fails if the underlying C library's version is less than 2.7.

## Matrix View

```
use Math::Libgsl::Matrix;

my Math::Libgsl::Matrix $m1 .= new(:size1(3), :size2(4));      # create a 3x4 matrix
$m1.setall(1);                                                 # set all elements to 1
my Math::Libgsl::Matrix::View $mv .= new;                      # create a Matrix View
my Math::Libgsl::Matrix $m2 = $mv.submatrix($m1, 1, 1, 2, 2);  # get a submatrix
$m2.setall(12);                                                # set the submatrix elements to 12
$m1.get-row($_)».fmt('%2d').put for ^3;                        # print the original matrix
# output:
# 1  1  1  1
# 1 12 12  1
# 1 12 12  1

```

There are three kinds of Matrix Views: a Matrix View on a Matrix, a Matrix View on a Vector, and a Matrix View on a Raku array.

This is the View of the first kind:

### submatrix(Math::Libgsl::Matrix $m, size\_t $k1 where \* < $m.size1, size\_t $k2 where \* < $m.size2, size\_t $n1, size\_t $n2 --> Math::Libgsl::Matrix)

Creates a view on a subset of the matrix, starting from coordinates ($k1, $k2) with $n1 rows and $n2 columns. This method returns a new Matrix object. Any operation done on the returned matrix affects the original matrix as well.

These three methods create a matrix view on a Raku array:

There are three ways to view a Raku array as a Math::Libgsl::Vector object:

* The hard way - use NativeCall's CArray to create a C-language-happy array.
* The easy way - use the \*-prepvec sub to convert a Raku array into a C array.
* The easiest way - use the \*-array-vec sub, pass it the Raku array or list and a closure or anonymous sub.

This is an example of the "hard way":

```
use Math::Libgsl::Matrix;
use NativeCall;

my CArray[num64] $array .= new: (1..6)».Num;            # define a CArray
my Math::Libgsl::Matrix::View $mv .= new;               # view: an object that will contain the view information
my Math::Libgsl::Matrix $m = $mv.array($array, 2, 3);   # create an Math::Libgsl::Matrix object
$m[0;0] = 2;                                            # assign a value to the first matrix element
say $m.get-row($_) for ^2;
# output:
# 2 2 3
# 4 5 6

```

This is an example of the "easy way":

Views on a Raku array are a bit more complex, because it's not possible to simply pass a Raku array to a C-language function. So for this to work the programmer has to *prepare* the array to be passed to the library. Both the View object and the *prepared* array must not go out of scope.

```
use Math::Libgsl::Matrix;

my @array = 1 xx 10;                                    # define an array
my $parray = prepmat(@array);                           # prepare the array to be used as a Math::Libgsl::Matrix
my Math::Libgsl::Matrix::View $mv .= new;               # view: an object that will contain the view information
my Math::Libgsl::Matrix $m = $mv.array($parray, 2, 5);  # create an Math::Libgsl::Matrix object
$m[0;0] = 2;                                            # assign a value to the first matrix element
$m.get-row($_).put for ^2;
# output:
# 2 1 1 1 1
# 1 1 1 1 1

```

This is an example of the "easiest way":

```
use Math::Libgsl::Matrix;

my @array = 1..6;                                                                 # initialize an array
my Math::Libgsl::Matrix $matrix .= new: 2, 3;                                     # declare a Math::Libgsl::Matrix
num64-array-mat(-> $mat { $matrix.copy($mat); $matrix[0;0] = 0 }, 2, 3, @array);  # assign 0 to matrix element [0;0]
$matrix.get-row($_).put for ^2;
# output:
# 0 2 3
# 4 5 6

```

### num64-prepmat(@array)

This is just a sub, not a method; it gets a regular array and outputs a *prepared* array, kept in a scalar variable. There are similar functions for every data type, so for example if one is working with int16 Vectors, one will use the **int16-prepmat** sub. The num64, being the default data type, has a special **prepmat** alias. Once *prepared*, the original array can be discarded.

### array($array, UInt $size1, UInt $size2 --> Math::Libgsl::Matrix)

This method gets a *prepared* array and returns a Math::Libgsl::Matrix object.

### array-tda($array, UInt $size1, UInt $size2, size\_t $tda where \* > $size2 --> Math::Libgsl::Matrix)

This method gets a *prepared* array with a number of physical columns **$tda**, which may differ from the corresponding dimension of the matrix, and returns a Math::Libgsl::Matrix object.

### sub num64-array-mat(Block $bl, UInt $size1, UInt $size2, \*@data)

This sub arguments are a Block to execute, the sizes of the desired resulting matrix, and a regular Raku array. Internally it uses a matrix view to convert the array into libgsl's own matrix data type, obtains the Math::Libgsl::Matrix from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Matrix object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-mat** alias.

### sub num64-array-tda-mat(Block $bl, UInt $size1, UInt $size2, size\_t $tda where \* > $size2, \*@data)

This sub arguments are a Block to execute, the sizes of the desired resulting matrix, the number of physical columns **$tda**, and a regular Raku array. Internally it uses a matrix view to convert the array into libgsl's own matrix data type, obtains the Math::Libgsl::Matrix from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Matrix object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-tda-mat** alias.

There are two methods to create a Matrix View on a Vector:

### vector(Math::Libgsl::Vector $v, size\_t $n1, size\_t $n2 --> Math::Libgsl::Matrix)

This method creates a Matrix object from a Vector object. The resultimg matrix will have $n1 rows and $n2 columns.

### vector-tda(Math::Libgsl::Vector $v, size\_t $n1, size\_t $n2, size\_t $tda where \* > $n2 --> Math::Libgsl::Matrix)

This method creates a Matrix object from a Vector object, with a physical number of columns $tda which may differ from the correspondig dimension of the matrix. The resultimg matrix will have $n1 rows and $n2 columns.

## Vector View on a Matrix

There is a fourth kind of View that involves a Matrix: a Vector View on a Matrix. The following are methods of the Matrix class, not of the Matrix::View class, take a Vector::View argument, and deliver a Vector object. The Matrix object must not go out of scope while one is operating on the resulting Vector.

### row-view(Math::Libgsl::Vector::View $vv, size\_t $i where \* < $!matrix.size1 --> Math::Libgsl::Vector)

This method creates a Vector object from row $i of the matrix.

### col-view(Math::Libgsl::Vector::View $vv, size\_t $j where \* < $!matrix.size2 --> Math::Libgsl::Vector)

This method creates a Vector object from column $j of the matrix.

### subrow-view(Math::Libgsl::Vector::View $vv, size\_t $i where \* < $!matrix.size1, size\_t $offset, size\_t $n --> Math::Libgsl::Vector)

This method creates a Vector object from row $i of the matrix, starting from $offset and containing $n elements.

### subcol-view(Math::Libgsl::Vector::View $vv, size\_t $j where \* < $!matrix.size2, size\_t $offset, size\_t $n --> Math::Libgsl::Vector)

This method creates a Vector object from column $j of the matrix, starting from $offset and containing $n elements.

### diagonal-view(Math::Libgsl::Vector::View $vv --> Math::Libgsl::Vector)

This method creates a Vector object from the diagonal of the matrix.

### subdiagonal-view(Math::Libgsl::Vector::View $vv, size\_t $k where \* < min($!matrix.size1, $!matrix.size2) --> Math::Libgsl::Vector)

This method creates a Vector object from the subdiagonal number $k of the matrix.

### superdiagonal-view(Math::Libgsl::Vector::View $vv, size\_t $k where \* < min($!matrix.size1, $!matrix.size2) --> Math::Libgsl::Vector)

This method creates a Vector object from the superdiagonal number $k of the matrix.

# 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


## dist_zef-frithnanth-Math-Libgsl-Matrix.md
## Chunk 2 of 2
-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::Matrix

```

# AUTHOR

Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2020 Fernando Santagata

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


## is-int.md
is-int

Combined from primary sources listed below.

# [In Range](#___top "go to top of document")[§](#(Range)_method_is-int "direct link")

See primary documentation
[in context](/type/Range#method_is-int)
for **method is-int**.

```raku
method is-int(Range:D: --> Bool:D)
```

Returns `True` if both end points are [`Int`](/type/Int) values.

```raku
say ('a'..'d').is-int;                            # OUTPUT: «False␤»
say (1..^5).is-int;                               # OUTPUT: «True␤»
say (1.1..5.5).is-int;                            # OUTPUT: «False␤»
```


## dist_github-finanalyst-Inform.md
# Inform Module

Provides a GTK dialog box from a Raku program. It is easy to add buttons and simple entry widgets to the box. Information is returned to a capture object.

The module is a stripped down version of the gtk-simple module minus all the unused widgets.

On Linux distributions, the GTK library is almost guaranteed, but there will be an error
unless the `dev` library (something like `libgtk-dev`) is installed.

On Windows, GTK is likely not installed. A build check is incorporated. If it fails, the GTK
library has not been found. A place to look for installation help is the [GTK project](https://www.gtk.org/docs/installations/windows/)
installation page.

The example uses the inform procedural style subroutine, but the object based style can be seen by looking at inform.

For example

```
#!/usr/bin/env raku
use v6.c;
use Informative;
=comment
  Show a box with some information on screen, has a destructor x on window, but removes itself after 10s.
  Notice that there is a countdown time for information.
  The string can be marked up with pango markup.

inform( 'This is <span color="blue">blue</span> and <span color="red" weight="bold">red</span> information'  );
=comment
  The label shown in the box is 'This is blue and red information' (with colours).
  The default title is 'Inform'

=comment
  New title and for a shorter time (5s), note that a timer of 0 is forever.

my $popup = inform( 'Shorter time span for me', :timer(5), :title<More> );
=comment
  The title of the window is now 'More'.
  The C<inform> subroutine returning an instance of the C<Informing> class, which is then shown.

=comment
  The C<Informing> object in $popup can be reused with changes in message, countdown and timer.
  The title, buttons and entries are only allowed when creating a new C<Informing> object.
  The C<show> method is available in the C<Informing> object.

$popup.show( 'See no countdown, but timer is unchanged', :!show-countdown );
=comment
  The timer is now no longer showing

=comment
  The colour (in USA color) of the countdown can be changed from the default 'red' to any colour accepted by Pango.

$popup = inform( 'I prefer the blues', :timer(5), :countdown-colour<blue> );

=comment
  Oops blues originated in the USA

$popup = inform( 'The blues spread in the movies', :timer(5), :countdown-color<#9c5d7c> );

=comment
  Add some buttons

my $gui-response = inform( 'Do you want to continue?',
    :buttons( OK=>'OK',b2=>'Not on your life', 'Cancel'=> "I don't want to")
    );
say "We have {$gui-response.response} ";
=comment
  The box contains the label 'Do you want to continue' and has three buttons
  with labels 'OK', 'Not on your life' and "I don't want to"
  The name of the button clicked (OK, b2, Cancel) is printed

=comment
  Access response

say 'Ok continuing' if $gui-response.response eq 'OK';
=comment
  Check other responses

say 'I am heedful of your desires' if $gui-response.response ~~ any <b2 Cancel>;
=comment
  Check whether the destruct x was clicked

say 'So you don\'t like the options I gave you, huh?' if $gui-response.response eq '_destruct';

=comment
  Add an entry widget and some buttons
  Note that if an entry widget is requested, but no buttons are requested, then
  Cancel and OK are added automatically.
  An entry widget without buttons is not allowed (design decision)

my $data = inform('Give me some things to clean',
    :buttons(Cancel => 'None today', :Response('Here you go')),
    :entries( Laundry => 'Enter your laundry list',)
    );
=comment
  The box contains a label, then one or more entry widgets, then a row of boxes.
  The formatting will depend on gtk defaults.
  NOTE: 'buttons' and 'entries' each expect a list of pairs, not a hash. So the comma
  after '...laundry list' and before the bracket is essential to force a list. With
  two elements, as in the buttons expression, a list already forms.

if $data.response eq 'Cancel' { say 'Great, more free time for me' }
elsif $data.response eq 'Response' {
  for $data.data<Laundry>.comb(/\w+/) { say "I will clean your $_" }
}

=comment
    An entry widget can mask input, as in password requests, by adding _pw or -pw onto the
    name of the entry.

my $login = inform('Please supply your username and password',
    :entries(un => 'User name', pw_pw => 'Password')
    );

if $login.response eq 'OK' { say "user name is \<{$login.data<un>}> and password is \<{$login.data<pw_pw>}>" };

```

A design goal his to keep the module as simple and small as possible, and to result in a popup that is intuitive to the user. Hence:

* A buttonless lable has a countdown timer to show when it is disappearing.
* Entries are not permitted without buttons. In principle, gtk\_entry has an Activate signal that could be attached to an Entry widget (when text is ended with a Return key). However, a dialog box with only an entry form with no obvious way to respond would be difficult to understand.
* All Buttons act in the same way: if Entry widgets are present, the text is stored in the data attribute, and the dialog box is closed. It is for the user to determine how to handle the data.
* A dialog box that is destroy by clicking on the x will not store Entry data.

There are no limits in the module on the number of buttons or entry widgets that can be added. However, in practice, the reliance on gtk default formating will probably quickly make the inform box look ugly.

If more sophisticated button behaviours, different widgets or formatting are required, look at the Gtk::Simple module.


## dist_cpan-SAMGWISE-Net-NNG.md
[![Build Status](https://travis-ci.org/samgwise/Net-NNG.svg?branch=master)](https://travis-ci.org/samgwise/Net-NNG)

# NAME

Net::NNG - NanoMSG networking with libnng

# SYNOPSIS

```
use Net::NNG;

my $url = "tcp://127.0.0.1:8887";

my $pub = nng-pub0-open;
nng-listen $pub, $url;

my @clients = do for 1..8 {
    start {
        CATCH { warn "Error in client $_: { .gist }" }

        my $sub nng-sub0-open;
        nng-dial = $sub, $url;
        for 1..15 -> $client-id {
            nng-subscribe $sub, "/count";

            # Take the number at the end of the /count message
            say "Client $client-id: ", nng-recv($sub).tail.decode('utf8')
        }
        nng-close $sub
    }
}

my $server = start {
    CATCH { warn "Error in server: { .gist }" }

    for 1..15 {
        nng-send $pub, "/count$_".encode('utf8');
        sleep 0.5;
    }
}

await Promise.allof: |@clients, $server;

nng-close $pub

```

# DESCRIPTION

Net::NNG is a NativeCall binding for [libnng](https://github.com/nanomsg/nng) a lightweight implementation of the nanomsg distributed messaging protocol. By default supported transports are inproc, IPC and IP. Additional transport layers such as TLS, Websockets and ZeroTier can be included when the library is compiled.

This is currently an early release and isn't yet feature complete but provides usable subscribe/publish, request/reply and survey/responder patterns. Other patterns currently offered by libnng such as the bus patterns are yet to be included in this interface.

This module does not yet handle providing you with a libnng library on your system so you will need to either build or install the library yourself. If you are compiling from source be sure to provide the -DBUILD\_SHARED\_LIBS option when building the cmake project else you will only be build static objects.

# AUTHOR

Sam Gillespie [samgwise@gmail.com](mailto:samgwise@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2018 Sam Gillespie

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

### multi sub nng-setopt

```
multi sub nng-setopt(
    Net::NNG::NNGSocket $socket,
    Str $name,
    Str $value
) returns Mu

```

Set a string option for a socket. An options enum is defined in Net::NNG::Options.

### multi sub nng-setopt

```
multi sub nng-setopt(
    Net::NNG::NNGSocket $socket,
    Str $name,
    Bool $value
) returns Mu

```

Set a boolean option for a socket. An options enum is defined in Net::NNG::Options.

### multi sub nng-setopt

```
multi sub nng-setopt(
    Net::NNG::NNGSocket $socket,
    Str $name,
    Int $value,
    Bool :$ms = Bool::False
) returns Mu

```

Set an integer value for an option on a socket. If the option is a millisecond value, passing the named ms flag. An options enum is defined in Net::NNG::Options.

### sub nng-subscribe

```
sub nng-subscribe(
    Net::NNG::NNGSocket $socket,
    Str $header
) returns Bool

```

Set an active subscription on a socket You must subscribe with a header to receive messages on subscription socket. The header can be any string and will also be present in the blob of the received message. Returns True on success and a Failure on error.

### sub nng-req0-open

```
sub nng-req0-open() returns Net::NNG::NNGSocket

```

Creates a new request (version 0) socket for making requests to a reply socket. Returns a NNGSocket pointer or Failure on error.

### sub nng-rep0-open

```
sub nng-rep0-open() returns Net::NNG::NNGSocket

```

Creates a new reply (version 0) socket for responding to requests. Returns a NNGSocket pointer or Failure on error.

### sub nng-pub0-open

```
sub nng-pub0-open() returns Net::NNG::NNGSocket

```

Create a new publish (version 0) socket for sending to subscribers. Returns a NNGSocket pointer or failure on error.

### sub nng-sub0-open

```
sub nng-sub0-open() returns Net::NNG::NNGSocket

```

Create a new socket for subscribing to a publisher socket. Returns a NNGSocket pointer or failure on error.

### sub nng-survey-duration

```
sub nng-survey-duration(
    Net::NNG::NNGSocket $socket,
    Int $duration
) returns Bool

```

Set survey duration on a socket. This function accepts a duration in milliseconds. Returns True on success and a Failure on error.

### sub nng-surveyor0-open

```
sub nng-surveyor0-open() returns Net::NNG::NNGSocket

```

Create a new socket for handling survey (version 0) requests. Use nng-listen to attach this socket to a protocol and address.

### sub nng-respondent0-open

```
sub nng-respondent0-open() returns Net::NNG::NNGSocket

```

Create a respondent (version 0) socket for replying to surveys. use nng-listen to attach this socket to a protocol and address.

### sub nng-listen

```
sub nng-listen(
    Net::NNG::NNGSocket $socket,
    Str $url
) returns Bool

```

Start listening on a socket. Returns True on success or Failure on error. Valid URLs will vary depending on the features your libnng is compiled for. At the time of writing tcp, ipc, among others are supported by default. Additional dependencies are required for secure protocols such as https, wss. Additional dependencies are also required for XeroTier Networking. Check the nng docs for more details.

### sub nng-dial

```
sub nng-dial(
    Net::NNG::NNGSocket $socket,
    Str $url
) returns Bool

```

Connects the given socket to a listening socket at the URL provided. Returns True on success and Failure on error. See nng-listen for a discussion of transports.

### sub nng-recv

```
sub nng-recv(
    Net::NNG::NNGSocket:D $socket
) returns Blob

```

Receives messages on a socket. Returns a Blob of the message on success or a Failure on error.

### sub nng-send

```
sub nng-send(
    Net::NNG::NNGSocket:D $socket,
    Blob $message
) returns Bool

```

Sends a Blob with the socket provided. Returns True on success or Failure on error.


## dist_zef-dwarring-CSS-Writer.md
[[Raku CSS Project]](https://css-raku.github.io)
/ [[CSS-Writer]](https://css-raku.github.io/CSS-Writer-raku)

# CSS-Writer-raku

AST writer/serializer module. Compatible with CSS:Module and CSS::Grammar.

## Examples

#### Serialize a declaration (ruleset); converting named colors to RGB masks

```
use CSS::Writer;
my CSS::Writer $css-writer .= new( :!pretty, :color-values, :color-masks );
say $css-writer.write(
    :ruleset{
        :selectors[ :selector[ { :simple-selector[ { :element-name<h1> } ] } ] ],
        :declarations[
             { :ident<font-size>, :expr[ :pt(12) ] },
             { :ident<color>,     :expr[ :ident<white> ] },
             { :ident<z-index>,   :expr[ :num(-9) ] },
            ],
    });

# output: h1 { font-size:12pt; color:#FFF; z-index:-9; }

```

#### Tidy and reduce size of CSS

```
use CSS::Writer;
use CSS::Grammar::CSS3;

sub parse-stylesheet($css) {
    use CSS::Grammar::CSS3;
    use CSS::Grammar::Actions;
    my CSS::Grammar::Actions $actions .= new;
    CSS::Grammar::CSS3.parse($css, :$actions)
       or die "unable to parse: $css";

    return $/.ast
}

my CSS::Writer $css-writer .= new( :!pretty );
my $stylesheet = parse-stylesheet( 'H1{  cOlor: RED; z-index  : -3}' );

say $css-writer.write( $stylesheet );

# output: h1 { color:red; z-index:-3; }

```

## Writer Options

* **`:ast`** Provide a default ast. This enables stringification, e.g.

```
my CSS::Writer $css .= new( :ast( :string('Hello World!' ) ) );
say ~$css;  # output: 'Hello World!'

```

* **`:color-masks`** Prefer hex mask notation for RGB values, .e.g. `#0085FF` instead of `rgb(0, 133, 255)`
* **`:color-names`** Convert RGB values to color names
* **`:color-values`** Convert color names to RGB values
* **`:!pretty`** write each stylesheet element on a single line, without indentation. Don't write comments.

## Usage Notes

* The initial version CSS::Writer is based on the objects, values and serialization rules described in <http://dev.w3.org/csswg/cssom/>.


## stubbed.md
class X::Package::Stubbed

Compilation error due to a stubbed package that is never defined

```raku
class X::Package::Stubbed does X::Comp { }
```

Thrown at `CHECK` time when there are packages stubbed but not later defined.

For example

```raku
class A { ... }     # literal ...
class B { ... }     # literal ...

```

dies with

｢text｣ without highlighting

```

```

===SORRY!===
The following packages were stubbed but not defined:
    A
    B

```

```

# [Methods](#class_X::Package::Stubbed "go to top of document")[§](#Methods "direct link")

## [method packages](#class_X::Package::Stubbed "go to top of document")[§](#method_packages "direct link")

```raku
method packages(--> Positional:D)
```

Returns a list of packages that were stubbed but not defined.


## dist_zef-p6steve-Physics-Error.md
# raku-Physics-Error

some code to handle physical measurement errors (nothing to do with programming errors!)

[![Build Status](https://app.travis-ci.com/p6steve/raku-Physics-Error.svg?branch=main)](https://app.travis-ci.com/p6steve/raku-Physics-Error)

# Instructions

Installs automatically with`zef --verbose install Physics-Measure`
uninstall with, `zef uninstall Physics::Measure` and `zef uninstall Physics::Error`

# Context

In wikipedia, the general topic is <https://en.wikipedia.org/wiki/Propagation_of_uncertainty>

* this gets fairly heavy fairly quickly ... real world physical errors can be non-linear and accelerate rapidly
* this module is definitively LINEAR ONLY ;-)

#### this module is not intended for use in mission critical applications

# Synopsis

Take a look at your keyboard... there's probably a '±' key?

Physics::Error works with the [Physics::Measure](https://github.com/p6steve/raku-Physics-Measure) and [Physics::Unit](https://github.com/p6steve/raku-Physics-Unit) modules to do this:

```
use Physics::Measure :ALL;

my $x1 = 12.5nm ± 1;                                                    #SI units as raku postfix operators
my $x2 = Length.new(value => 12.5, units => 'nm', error => '4.3%');     #standard raku .new syntax
my $x3 = ♎ '12.5 ft ±0.5';                                              #libra prefix shorthand

# Error values are included in Measures when output
say ~$x1;                                       #12.5nm ±4% or 12.5nm ±1

# They can be accessed directly via the .error object
say $x1.error.absolute;                         #1
say $x1.error.relative;                         #0.08
say $x1.error.relative.^name;                   #Rat
say $x1.error.percent;                          #8%

```

All of the main Measure capabilities work as expected...

```
# Unit conversions and normalization
my $y = Length.new(value => 12.5e2, units => 'nm', error => '4.3%');
say ~$y;                                        #1250nm ±53.75
say ~$y.in('mm');                               #0.00125mm ±0.0000538
say ~$y.norm;                                   #1.25μm ±0.05375

my $t = Time.new(value => 10, units => 'ms', error => 0.2);
say ~( 17 / $t );                               #1700Hz ±34

# Measure math adjusts units and error automagically
say ~( $y / $t );                               #0.000125m/s ±0.000007875e0

# works with add, subtract, multiply, divide, power and root
# add & subtract add absolute error
# multiply & divide add relative error
# power and root multiply relative error by power

my Length $w = Length.new(value => 10, units => 'm', error => '2%');
my $z = $w ** 3;  say ~$z;                      #1000m^3 ±60
$z = $z ** <1/3>; say ~$z;                      #10m ±2.00e-01

# As do Measure cmp operators (to within error limits)
say $w cmp $y;                                  #More

```

Controls for Error output format and rounding of percentage errors (here with default values). These only act on the .Str output rendering and leave the .error.absolute "truth" untouched.

```
$Physics::Error::default   = 'absolute';    #default error output [absolute|percent]
$Physics::Error::round-per = 0.001;         #control rounding of percent

```

Two ways for Measure output precision control. These only act on the .Str output rendering and leave the Measure .value and .error.absolute "truth" untouched.

#### Automagic

This option uses .error.denorm to right shift the error value and align to the mantissa precision of the measure value. The number of significant digits in the error is then used to round the measure value.

```
# Here's the mass of the electron Em in action...
my \Em = 9.109_383_701_5e-31kg ±0.000_000_002_8e-31;

say ~Em;                                        #9.1093837015e-31kg ±0.0000000028e-31
say Em.error.absolute;                          #2.8e-40
say Em.error.relative;                          #3.0737534961217373e-10
say Em.error.relative.^name;                    #Num
say Em.error.percent;                           #0%

```

#### Manual

Manual precision can be set - this overrides the automagic behaviour.

```
$Physics::Measure::round-val = 0.01;

my $c = ♎ '299792458 m/s';
my $ℎ = ♎ '6.626070015e-34 J.s';

my \λ = 2.5nm;
is ~λ, '2.5nm',									'~λ';

my \ν = $c / λ;
is ~ν.norm, '119.92PHz',						'~ν.norm';

my \Ep = $ℎ * ν;
is ~Ep.norm, '79.46aJ',						    '~Ep.norm';

```

Physics::Error supports the three use cases for making Measure objects with value, units & error as outlined in the Physics::Measure [README.md](https://github.com/p6steve/raku-Physics-Measure/edit/master/README.md). The formats are dissected below:

#### Option 1: Postfix Operator Syntax (SI Units)

```
my Length $x = 12.5nm ± 10%;
   ------ -- - ------ - ---
      |    | |   |  | |  |
      |    | |   |  | |  > Rat percent error [or '±4.2%' Rat relative error]
      |    | |   |  | |
      |    | |   |  | > ± symbol as custom raku infix operator
      |    | |   |  |
      |    | |   |  > 'nm' Unit constructor as custom raku postfix operator (no ws)
      |    | |   |
      |    | |   > Real number
      |    | |
      |    | > assignment of new Object from postfix rhs
      |    |
      |    > a scalar variable
      |
      > Type (Length is Measure) ... can be omitted

```

#### Option 2: Object Constructor Syntax

```
my Length $x = Length.new(value => 12.5, units => 'nm', error => [0.5|'4.3%']);
say ~$x; #42 ±4.2nanometre

```

#### Option 3: Libra Shorthand Syntax

```
my Length $x = ♎ '12.5 nm ±0.05';
   ------ --   --  ---- -- -----
      |    |    |   |   |  |  |
      |    |    |   |   |  |  |
      |    |    |   |   |  |  >  Real absolute error [or '±4.2%' Rat relative error]
      |    |    |   |   |  |
      |    |    |   |   |  > '±' symbol as custom raku prefix operator
      |    |    |   |   |
      |    |    |   |   > Str units (of Type Length is Measure)
      |    |    |   |
      |    |    |   > Real number
      |    |    |
      |    |    > parse rhs string, construct object and assign to lhs (♎ <-- custom <libra> operator)
      |    |
      |    > a scalar variable
      |
      > Type (Length is Measure) ... can be omitted

```

#### Help Wanted

Over time I imagine an eco-system of equation parsing / pde plugins and machine calibration matrices - feel free to continue the journey in this direction with a pull request!


## newline.md
Newline handling in Raku

How the different newline characters are handled, and how to change the behavior

Different operating systems use different characters, or combinations of them, to represent the transition to a new line. Every language has its own set of rules to handle this. Raku has the following ones:

* `\n` in a string literal means Unicode codepoint 10.
* The default [nl-out](/routine/nl-out) that is appended to a string by say is also `\n`.
* On output, when on Windows, the encoder will by default transform a `\n` into a `\r\n` when it's going to a file, process, or terminal (it won't do this on a socket, however).
* On input, on any platform, the decoder will by default normalize `\r\n` into `\n` for input from a file, process, or terminal (again, not socket).
* These above two points together mean that you can - socket programming aside - expect to never see a `\r\n` inside of your program (this is how things work in numerous other languages too).

* The [`:$translate-nl`](/type/Encoding#method_decoder) named parameter exists in various places to control this transformation, for instance, in [`Proc::Async.new`](/type/Proc/Async#method_new) and [`Proc::Async.Supply`](/type/Proc/Async#method_Supply).
* A `\n` in the [regex](/language/regexes) language is logical, and will match a `\r\n`.

You can change the default behavior for a particular handle by setting the `:nl-out` attribute when you create that handle.

```raku
my $crlf-out = open(IO::Special.new('<STDOUT>'), :nl-out("\\\n\r"));
$*OUT.say: 1;     # OUTPUT: «1␤»
$crlf-out.say: 1; # OUTPUT: «1\␤␍»
```

In this example, where we are replicating standard output to a new handle by using [`IO::Special`](/type/IO/Special), we are appending a `\` to the end of the string, followed by a newline `␤` and a carriage return `␍`; everything we print to that handle will get those characters at the end of the line, as shown.

In regular expressions, [`\n`](/language/regexes#\n_and_\N) is defined in terms of the [Unicode definition of logical newline](https://unicode.org/reports/tr18/#Line_Boundaries). It will match `.` and also `\v`, as well as any class that includes whitespace.


## print-nl.md
print-nl

Combined from primary sources listed below.

# [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_print-nl "direct link")

See primary documentation
[in context](/type/IO/Handle#method_print-nl)
for **method print-nl**.

```raku
method print-nl(IO::Handle:D: --> True)
```

Writes the value of `$.nl-out` attribute into the handle. This attribute, by default, is `␤`, but see the [page on newline](/language/newline) for the rules it follows in different platforms and environments.

Attempting to call this method when the handle is [in binary mode](/type/IO/Handle#method_encoding) will result in [`X::IO::BinaryMode`](/type/X/IO/BinaryMode) exception being thrown.

```raku
my $fh = 'path/to/file'.IO.open: :w, :nl-out("\r\n");
$fh.print: "some text";
$fh.print-nl; # prints \r\n
$fh.close;

```


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

# NAME

nano - provide term for epoch in nano seconds

# SYNOPSIS

```
use nano;

say nano;  # 1657823392165615978

```

# DESCRIPTION

The `nano` module exports a single term `nano` that returns the number of nano-seconds since January 1, 1970 UTC (1970-01-01T00:00:00Z). It is a more accurate version of the `time` term.

# AUTHOR

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

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

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

# COPYRIGHT AND LICENSE

Copyright 2022, 2025 Elizabeth Mattijsen

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


## dist_github-finanalyst-Task-Popular.md
# Task::Popular

[Introduction](#introduction)
[Module Listing](#modules-in-this-distribution)
[Date of Compilation](#date-of-compilation)
[Problems](#problems)
[Updates and Algorithm](#updates-and-algorithm)

## Introduction

The developers of Perl6 decided that the implementation
of the language (eg. Rakudo) would be available with a bare minimum of "core" modules.
Some modules are essential, such as Test, or the module manager (previously `panda`, currently `zef`).

The intention is for users / user groups to contribute distributions that meet a specific topic area.
Rakudo itself is available in a package called `Rakudo Star` with a minimal number of modules.

This distribution list takes another, data driven, approach.

Modules are intended to provide common functionality, and so are `use`d or **cited** by other modules in the Ecosystem. A set of modules that are
frequently used can be fairly safely assumed will be regularly maintained. Failures in these modules will affect many other modules, and there will be pressure to get them fixed.

This list uses [Citation Indices](http://finanalyst.github.io/ModuleCitation/) to identify the 30 modules most recursively popular modules in the Ecosystem.

## Modules in this distribution

| Module Name | Recursive Citation Index | Module Description |
| --- | --- | --- |
| JSON::Fast | 37.87 | OOps description not found, please file issue at github repository of p6-task-popular |
| URI | 31.56 | A URI implementation using Perl 6 grammars to implement RFC 3986 BNF |
| MIME::Base64 | 28.9 | Encoding and decoding Base64 ASCII strings |
| File::Directory::Tree | 26.58 | Port of File::Path::Tiny - create and delete directory trees |
| File::Temp | 25.91 | Create temporary files & directories |
| HTTP::Status | 23.59 | Get the text message associated with an HTTP status code |
| JSON::Tiny | 18.94 | OOps description not found, please file issue at github repository of p6-task-popular |
| OpenSSL | 17.94 | OpenSSL bindings |
| JSON::Name | 16.28 | Provides a trait to store an alternative JSON Name |
| Encode | 15.61 | Character encodings in Perl 6 |
| DateTime::Parse | 15.28 | DateTime parser |
| JSON::Unmarshal | 15.28 | Turn JSON into objects |
| HTTP::UserAgent | 14.95 | Web user agent |
| JSON::Marshal | 14.95 | Simple serialisation of objects to JSON |
| Terminal::ANSIColor | 14.95 | Colorize terminal output |
| JSON::Class | 14.29 | role to provide simple serialisation/deserialisation of objects to/from JSON |
| HTML::Escape | 12.96 | Utility of HTML escaping |
| LibraryMake | 11.96 | An attempt to simplify native compilation |
| META6 | 11.63 | Work with Perl 6 META files |
| File::Find | 11.3 | File::Find for Perl 6 |
| Digest | 10.96 | Pure perl6 implementation of digest algorigthms. |
| XML | 10.63 | A full-featured, pure-perl XML library (parsing, manipulation, emitting, queries, etc.) |
| Test::META | 10.3 | Test a distributions META file |
| IO::Socket::SSL | 9.97 | IO::Socket::SSL for Perl 6 using OpenSSL |
| PSGI | 9.3 | A PSGI helper library. |
| URI::Encode | 8.97 | Encode and decode URIs according to RFC 3986 |
| File::Which | 8.31 | Cross platform Perl 6 executable path finder (aka which on UNIX) |
| Digest::HMAC | 7.97 | Generic HMAC implementation |
| HTTP::Easy | 7.31 | HTTP servers made easy, including PSGI |
| JSON::Pretty | 7.31 | A minimal JSON (de)serializer that produces easily readable JSON |

## Date of Compilation

This list was compiled on 2018-01-01.

## Problems

Inevitably for commonly needed functionality, there may be multiple modules that provide the same functionality.
An example is JSON::Tiny and JSON::Fast. J/Fast was designed to be a drop-in replacement for J/Tiny, which
was first written to demonstrate how to use Perl6 and not as a workhorse module. However, for some reason J/Tiny
has a lot of support, although J/Fast is taking over (see the ModuleCitation page to trace the historical change).

So the Task::Popular list may have alternate modules for the same functionality. But for a newcomer to the Ecosystem
that might in fact be interesting as it provides a choice, and the opportunity to compare coding styles.

## Updates and Algorithm

The aim is to update the list regularly (eg. monthly).

The algorithm for generating the distribution list is implemented as a method in the [ModuleCitation class](https://github.com/finanalyst/ModuleCitation).


## dist_zef-grizzlysmit-Parse-Paths.md
## Table of Contents

* [NAME](#name)
* [AUTHOR](#author)
* [VERSION](#version)
* [TITLE](#title)
* [SUBTITLE](#subtitle)
* [COPYRIGHT](#copyright)
* [Introduction](#introduction)

  * [Motivations](#motivations)
* [Grammars](#grammars)

  * [grammar BasePaths & actions BasePathsActions](#grammar-basepaths--actions-basepathsactions)
  * [grammar Paths & actions class PathsActions](#grammar-paths--actions-class-pathsactions)
* [check-path(…)](#check-path)

# NAME

Parse::Paths

# AUTHOR

Francis Grizzly Smit ([grizzly@smit.id.au](mailto:grizzly@smit.id.au))

# VERSION

v0.1.2

# TITLE

Parse::Paths

# SUBTITLE

A Raku module to provide path parsing and validation for assorted programs.

# COPYRIGHT

LGPL V3.0+ [LICENSE](https://github.com/grizzlysmit/Parse-Paths/blob/main/LICENSE)

# Introduction

A Raku module to provide path parsing and validation services to Raku programs.

Basically a grammar and a role for inclusion in your own code.

[Top of Document](#table-of-contents)

## Motivations

I need to parse paths a lot in other grammars so I am centralising it.

[Top of Document](#table-of-contents)

## BadPath

**`BadPath`** is an exception for when paths don't parse.

```
class BadPath is Exception is export {
    has Str:D $.msg = 'Error: Highlighter Failed.';
    method message( --> Str:D) {
        $!msg;
    }
}

```

# Grammars

## grammar BasePaths & actions BasePathsActions

A grammar action pair to act as a basis of path parsing. See **`GUI::Editors`** and **`Usage::Utils`** for other examples.

```
grammar BasePaths is export {
    regex base-path           { [ <absolute-path> || <relative-path> ] }
    regex absolute-path       { <lead-in>  <path-segments>? }
    regex lead-in             { [ '/' || '~/' || '~' ] }
    regex relative-path       { <path-segments> }
    regex path-segments       { <path-segment> [ '/' <path-segment> ]* '/' }
    token path-segment        { [ <with-space-in-it> || <with-other-stuff> ] }
    token with-space-in-it    { <with-other-stuff> <trailing-sp-stuff>+ }
    token trailing-sp-stuff   { <spaces> <tail-other-stuff> }
    token spaces              { ' '+ }
    token with-other-stuff    { [ <start-other-stuff> <tail-other-stuff>* || <tail-other-stuff>+ ] }
    token start-other-stuff   { \w+ }
    token tail-other-stuff    { <other-stuff>+ <tails-tail>? }
    token tails-tail          { \w+ }
    token other-stuff         { [ '-' || '+' || ':' || '@' || '=' || ',' || '&' || '%' || '.' ] }
}

role BasePathsActions is export {
    #token with-other-stuff    { [ <start-other-stuff> <tail-other-stuff>* || <tail-other-stuff>+ ] }
    method with-other-stuff($/) {
        my $with-other-stuff;
        my @tailotherstuff;
        if $/<tail-other-stuff> {
            @tailotherstuff = $/<tail-other-stuff>».made;
        }
        if $/<start-other-stuff> {
            $with-other-stuff = $/<start-other-stuff>.made ~ @tailotherstuff.join();
        } else {
            $with-other-stuff = @tailotherstuff.join();
        }
        make $with-other-stuff;
    }
    #token editor-name         { <with-other-stuff> }
    method editor-name($/) {
        my $edname = $/<with-other-stuff>.made;
        make $edname;
    }
    method lead-in($/) {
        my $leadin = ~$/;
        make $leadin;
    }
    #token spaces              { ' '+ }
    method spaces($/) {
        my $spaces = ~$/;
        make $spaces;
    }
    #token trailing-sp-stuff   { <spaces> <tail-other-stuff> }
    method trailing-sp-stuff($/) {
        my $trailing-sp-stuff = $/<spaces>.made ~ $/<tail-other-stuff>.made;
        make $trailing-sp-stuff;
    }
    #token with-space-in-it    { <with-other-stuff> <trailing-sp-stuff>+ }
    method with-space-in-it($/) {
        my @trailing = $/<trailing-sp-stuff>».made;
        my $with-space-in-it = $/<with-other-stuff>.made ~ @trailing.join();
        make $with-space-in-it;
    }
    #token start-other-stuff   { \w+ }
    method start-other-stuff($/) {
        my $start-other-stuff = ~$/;
        make $start-other-stuff;
    }
    #token tails-tail          { \w+ }
    method tails-tail($/) {
        my $tails-tail = ~$/;
        make $tails-tail;
    }
    #token other-stuff         { [ '-' || '+' || ':' || '@' || '=' || ',' || '%' || '.' ] }
    method other-stuff($/) {
        my $other-stuff = ~$/;
        make $other-stuff;
    }
    #token tail-other-stuff    { <other-stuff>+ <tails-tail>? }
    method tail-other-stuff($/) {
        my @otherstuff = $/<other-stuff>».made;
        my $tail-other-stuff = @otherstuff.join();
        if $/<tails-tail> {
            $tail-other-stuff ~= $<tails-tail>.made;
        }
        make $tail-other-stuff;
    }
    #token path-segment        { [ <with-space-in-it> || <with-other-stuff> ] }
    method path-segment($/) {
        my $path-segment = ~$/;
        make $path-segment;
    }
    method path-segments($/) {
        my @path-seg = $/<path-segment>».made;
        make @path-seg.join('/');
    }
    method base-path($/) {
        my Str $abs-rel-path;
        if $/<absolute-path> {
            $abs-rel-path = $/<absolute-path>.made;
        } elsif $/<relative-path> {
            $abs-rel-path = $/<relative-path>.made;
        }
        make $abs-rel-path;
    }
    method absolute-path($/) {
        my Str $abs-path = $/<lead-in>.made;
        if $/<path-segments> {
            $abs-path ~= $/<path-segments>.made;
        }
        make $abs-path;
    }
    method relative-path($/) {
        my Str $rel-path = '';
        if $/<path-segments> {
            $rel-path ~= $/<path-segments>.made;
        }
        make $rel-path;
    }
} # role BasePathsActions is export #

```

[Top of Document](#table-of-contents)

### grammar Paths & actions class PathsActions

A front end that uses BasePaths & BasePathsActions to implement a path parser.

```
grammar Paths is BasePaths is export {
    TOP    { [ <base-path> <path-segment>? || <path-segment> ] }
}

class PathsActions does BasePathsActions is export {
    method TOP($made) {
        my $top = '';
        if $made<base-path> {
            $top ~= $made<base-path>.made;
        }
        if $made<path-segment> {
            $top ~= $made<path-segment>.made;
        }
        $made.make: $top;
    }
} # class PathsActions does BasePathsActions is export #

```

[Top of Document](#table-of-contents)

### check-path(…)

Check that the path is valid.

```
sub check-path(Str:D $path --> Str:D) is export {
    my $actions = PathsActions;
    my $tmp = Paths.parse($path, :enc('UTF-8'), :$actions).made;
    BadPath.new(:msg("Error: path $path did not parse.")).throw if $tmp === Any;
    my Str:D $result = $tmp;
    return $result;
} # sub check-path(Str:D $path --> Str:D) is export #

```

[Top of Document](#table-of-contents)