## dist_zef-antononcube-Math-Nearest.md
# Math::Nearest

Raku package for various algorithm for finding Nearest Neighbors (NNs)

The implementation is tested for correctness against Mathematica's [`Nearest`](https://reference.wolfram.com/language/ref/Nearest.html).
(See the resource files.)

### Features

* Finds both top-k Nearest Neighbors (NNs).
* Finds NNs within a ball with a given radius.
* Can return distances, indexes, and labels for the found NNs.
  * The result shape is controlled with the option `:prop`.
* Works with arrays of numbers, arrays of arrays of numbers, and arrays of pairs.
* Utilizes distance functions from ["Math::DistanceFunctions"](https://github.com/antononcube/Raku-Math-DistanceFunctions).
  * Which can be specified by their string names, like, "bray-curtis" or "cosine-distance".
* Allows custom distance functions to be used.
* Currently has two algorithms (simple) Scan and K-Dimensional Tree (KDTree).

---

## Installation

From Zef ecosystem:

```
zef install Math::Nearest

```

From GitHub:

```
zef install https://github.com/antononcube/Raku-Math-Nearest.git

```

---

## Usage examples

### Setup

```
use Math::Nearest;
use Data::TypeSystem;
use Text::Plot;

```

```
# (Any)

```

### Set of points

Make a random set of points:

```
my @points = ([(^100).rand, (^100).rand] xx 30).unique;
deduce-type(@points);

```

```
# Vector(Vector(Atom((Numeric)), 2), 30)

```

### Create the K-dimensional tree object

```
my &finder = nearest(@points);

say &finder;

```

```
# Math::Nearest::Finder(Algorithm::KDimensionalTree(points => 30, distance-function => &euclidean-distance))

```

### Nearest k-neighbors

Use as a search point one from the points set:

```
my @searchPoint = |@points.head;

```

```
# [82.7997137400612 51.815911977937425]

```

Find `4` nearest neighbors:

```
my @res = &finder(@searchPoint, 4);
.say for @res;

```

```
# [82.7997137400612 51.815911977937425]
# [76.74690048700612 45.30314548421236]
# [93.76468756535048 53.45047592032191]
# [71.62175684954694 55.56128771507127]

```

Instead of using the "finder" object as a callable (functor) we can use `nearest`:

```
.say for nearest(&finder, @searchPoint, count => 4)

```

```
# [82.7997137400612 51.815911977937425]
# [76.74690048700612 45.30314548421236]
# [93.76468756535048 53.45047592032191]
# [71.62175684954694 55.56128771507127]

```

Find nearest neighbors within a ball with radius `30`:

```
.say for &finder(@searchPoint, (Whatever, 30))

```

```
# [93.76468756535048 53.45047592032191]
# [82.7997137400612 51.815911977937425]
# [68.66354164361587 52.25273427733615]
# [67.1439347976243 51.678609421192775]
# [76.74690048700612 45.30314548421236]
# [71.62175684954694 55.56128771507127]
# [58.6565707908774 67.61014125155556]
# [80.23300662613086 80.49154195793962]
# [82.92996945428985 71.0086509061165]
# [54.30669960433475 57.177447534448724]

```

### Plot

Plot the points, the found nearest neighbors, and the search point:

```
my @point-char =  <* ⏺ ▲>;
say <data nns search> Z=> @point-char;
say text-list-plot(
[@points, @res, [@searchPoint,]],
:@point-char,
x-limit => (0, 100),
y-limit => (0, 100),
width => 60,
height => 20);

```

```
# (data => * nns => ⏺ search => ▲)
# ++----------+-----------+----------+-----------+----------++
# +                                                    *     + 100.00
# |                                                          |
# |      *                                                   |
# +*   *                      *    *   *         *           +  80.00
# |      *                                                   |
# |    *                                          *          |
# |                                 *                        |
# +                               *                          +  60.00
# |                         *            ** ⏺     ▲     ⏺    |
# |                                            ⏺             |
# + *                                                        +  40.00
# |*   *                                                     |
# |                                                          |
# |                           *                              |
# +                                               *          +  20.00
# |                       *                       *          |
# |              *               *                           |
# +                                                          +   0.00
# ++----------+-----------+----------+-----------+----------++
#  0.00       20.00       40.00      60.00       80.00      100.00

```

---

## TODO

* TODO Implementation
  * TODO Implement the Octree nearest neighbors algorithm.
  * TODO Make the nearest methods work with strings
    * For example, using Hamming distance over a collection of words.
    * Requires using the distance function as a comparator for the splitting hyperplanes.
    * This means, any objects can be used as long as they provide a distance function.
* TODO Documentation
  * DONE Basic usage examples with text plots
  * TODO More extensive documentation with a Jupyter notebook
    * Using "JavaScript::D3".
  * TODO Corresponding blog post
  * MAYBE Corresponding video

---

## References

[AAp1] Anton Antonov, [Math::DistanceFunctions Raku package](https://github.com/antononcube/Raku-Math-DistanceFunctions), (2024), [GitHub/antononcube](https://github.com/antononcube).

[AAp2] Anton Antonov, [Algorithm::KDimensionalTree Raku package](https://github.com/antononcube/Raku-Algorithm-KDimensionalTree), (2024), [GitHub/antononcube](https://github.com/antononcube).

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

[AAp4] Anton Antonov, [Text::Plot Raku package](https://github.com/antononcube/Raku-Text-Plot), (2022), [GitHub/antononcube](https://github.com/antononcube).


## dist_cpan-MARTIMM-Config-DataLang-Refine.md
# Configuration refinements

[![Build Status](https://travis-ci.org/MARTIMM/config-datalang-refine.svg?branch=master)](https://travis-ci.org/MARTIMM/config-datalang-refine)
[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/MARTIMM/config-datalang-refine?branch=master&passingText=Windows%20-%20OK&failingText=Windows%20-%20FAIL&pendingText=Windows%20-%20pending&svg=true)](https://ci.appveyor.com/project/MARTIMM/config-datalang-refine/branch/master)
[![License](http://martimm.github.io/label/License-label.svg)](http://www.perlfoundation.org/artistic_license_2_0)

# Synopsis

The following piece of code

```
use Config::DataLang::Refine;

my Config::DataLang::Refine $c .= new(:config-name<myConfig.toml>);

my Hash $hp1 = $c.refine(<options plugin1 test>);
my Hash $hp2 = $c.refine(<options plugin2 deploy>);

```

With the following config file in **myConfig.toml**

```
[options]
  key1 = 'val1'

[options.plugin1]
  key2 = 'val2'

[options.plugin1.test]
  key1 = false
  key2 = 'val3'

[options.plugin2.deploy]
  key3 = 'val3'

```

Will get you the following as if *$hp\** is set like

```
$hp1 = { key2 => 'val3'};
$hp2 = { key1 => 'val1', key3 => 'val3'};

```

A better example might be from the MongoDB project to test several server setups, the config again in TOML format;

```
[mongod]
  journal = false
  fork = true
  smallfiles = true
  oplogSize = 128
  logappend = true

# Configuration for Server 1
[mongod.s1]
  logpath = './Sandbox/Server1/m.log'
  pidfilepath = './Sandbox/Server1/m.pid'
  dbpath = './Sandbox/Server1/m.data'
  port = 65010

[mongod.s1.replicate1]
  replSet = 'first_replicate'

[mongod.s1.replicate2]
  replSet = 'second_replicate'

[mongod.s1.authenticate]
  auth = true

```

Now, to get run options to start server 1 one does the following;

```
my Config::DataLang::Refine $c .= new(:config-name<mongoservers.toml>);
my Array $opts = $c.refine-str( <mongod s1 replicate1>, :C-UNIX-OPTS-T2);

# Output
# --nojournal, --fork, --smallfiles, --oplogSize=128, --logappend,
# --logpath='./Sandbox/Server1/m.log', --pidfilepath='./Sandbox/Server1/m.pid',
# --dbpath='./Sandbox/Server1/m.data', --port=65010, --replSet=first_replicate

```

Easy to run the server now;

```
my Proc $proc = shell(('/usr/bin/mongod', |@$opts).join(' '));

```

# Description

The **Config::DataLang::Refine** class adds facilities to use a configuration file and gather the key value pairs by searching top down a list of keys thereby refining the resulting set of keys. Boolean values are used to add a key without a value when True or to cancel a previously found key out when False.

# Documentation

Look for documentation and other information at

* [Config::DataLang::Refine](https://github.com/MARTIMM/config-datalang-refine/blob/master/doc/Refine.pdf)
* [Release notes](https://github.com/MARTIMM/config-datalang-refine/blob/master/doc/CHANGES.md)
* [Todo and Bugs](https://github.com/MARTIMM/config-datalang-refine/blob/master/doc/TODO.md)


## dist_zef-thundergnat-Lingua-EN-Numbers.md
[![Actions Status](https://github.com/thundergnat/Lingua-EN-Numbers/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Lingua-EN-Numbers/actions)

# NAME Lingua::EN::Numbers

Various number-string conversion utility routines.

Convert numbers to their cardinal or ordinal representation.

Several other numeric string "prettifying" routines.

# SYNOPSIS

```
use Lingua::EN::Numbers;

# Integers
say cardinal(42);             # forty-two
say cardinal('144');          # one hundred forty-four
say cardinal(76541);          # seventy-six thousand, five hundred forty-one

# Rationals
say cardinal(7/2);            # three and one half
say cardinal(7/2, :improper); # seven halves
say cardinal(7/2, :im );      # seven halves
say cardinal(15/4)            # three and three quarters
say cardinal(3.75)            # three and three quarters
say cardinal(15/4, :improper) # fifteen quarters
say cardinal('3/16');         # three sixteenths

# Years
say cardinal-year(1800)       # eighteen hundred
say cardinal-year(1905)       # nineteen oh-five
say cardinal-year(2000)       # two thousand
say cardinal-year(2015)       # twenty fifteen

# cardinal vs. cardinal-year
say cardinal(1776);           # one thousand, seven hundred seventy-six
say cardinal-year(1776)       # seventeen seventy-six

# Sometimes larger denominators make it difficult to discern where the
# numerator ends and the denominator begins. Change the separator to
# make it easier to tell.

say cardinal(97873/10000000);
# ninety seven thousand, eight hundred seventy-three ten millionths

say cardinal(97873/10000000, :separator(' / '));
# ninety seven thousand, eight hundred seventy-three / ten millionths

# If you want to use a certain denominator in the display and not reduce
# fractions, specify a common denominator.

say cardinal(15/1000);                      # three two hundredths
say cardinal(15/1000, :denominator(1000));  # fifteen thousandths
# or
say cardinal(15/1000, denominator => 1000); # fifteen thousandths
# or
say cardinal(15/1000, :den(1000) );         # fifteen thousandths

# Ordinals
say ordinal(1);               # first
say ordinal(2);               # second
say ordinal(123);             # one hundred twenty-third

# Ordinal digit
say ordinal-digit(22);        # 22nd
say ordinal-digit(1776);      # 1776th
say ordinal-digit(331 :u);    # 331ˢᵗ
say ordinal-digit(12343 :c);  # 12,343rd

# Use pretty-rat() to print rational strings as fractions rather than
# as decimal numbers. Whole number fractions will be reduced to Ints.
say pretty-rat(1.375); # 11/8
say pretty-rat(8/2);   # 4

# no-commas flag

# save state
my $state = no-commas?;

# disable commas
no-commas;

say cardinal(97873/10000000);
# ninety seven thousand eight hundred seventy-three ten millionths

# restore state
no-commas($state);

# Commas routine
say comma( 5.0e9.Int );       # 5,000,000,000
say comma( -123456 );         # -123,456
say comma(  7832.00 );        # 7,832
say comma( '7832.00' );       # 7,832.00

# Super routine
say super('32');              # ³²
say super -47;                # ⁻⁴⁷

```

Or, import the short form routine names:

```
use Lingua::EN::Numbers :short;

say card(42);    # forty-two
say card-y(2020) # twenty twenty
say ord-n(42);   # forty-second
say ord-d(42);   # 42nd
say card(.875)   # seven eights
say prat(.875);  # 7/8

```

# DESCRIPTION

Exports the Subs:

* [cardinal( )](#cardinal) - short: card()
* [cardinal-year( )](#cardinal-year) - short: card-y()
* [ordinal( )](#ordinal) - short: ord-n()
* [ordinal-digit( )](#ordinal-digit) - short: ord-d()
* [comma( )](#comma)
* [pretty-rat( )](#pretty-rat) - short: prat()
* [super( )](#super)

and Flag:

* [no-commas](#no-commas)

Short form routine names are only available if you specifically import them:

`use Lingua::EN::Numbers :short;`

## cardinal( ) - short: card()

Returns cardinal representations of integers following the American English, short scale convention.

See: <https://en.wikipedia.org/wiki/Long_and_short_scales>

### cardinal( $number, :separator($str), :denominator($val), :improper );

* $number

  * value; required, any Real number (Rat, Int, or Num)
* :separator or :sep

  * value; optional, separator between numerator and denominator, defaults to space. Ignored if a non Rat is passed in.
* :denominator or :den

  * value; optional, integer denominator to use for representation, do not reduce to lowest terms. Ignored if a non Rat is passed in.
* :improper or :im

  * flag; optional, do not regularize improper fractions. Ignored if a non Rat is passed in.

Pass `cardinal()` a number or something that can be converted to one; returns its cardinal representation.

Recognizes integer numbers from: -9999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 9999999999999999999999999999999999999999999999999999999999999999999999999999 to 99999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 999999999999999999999999999999999999999999999999999999999999999999999999999

Thats 306 9s, negative, through positive:

nine hundred ninety-nine centillion, nine hundred ninety-nine novemnonagintillion, nine hundred ninety-nine octononagintillion, nine hundred ninety-nine septennonagintillion, nine hundred ninety-nine sexnonagintillion, nine hundred ninety-nine quinnonagintillion, nine hundred ninety-nine quattuornonagintillion, nine hundred ninety-nine trenonagintillion, nine hundred ninety-nine duononagintillion, nine hundred ninety-nine unnonagintillion, nine hundred ninety-nine nonagintillion, nine hundred ninety-nine novemoctogintillion, nine hundred ninety-nine octooctogintillion, nine hundred ninety-nine septenoctogintillion, nine hundred ninety-nine sexoctogintillion, nine hundred ninety-nine quinoctogintillion, nine hundred ninety-nine quattuoroctogintillion, nine hundred ninety-nine treoctogintillion, nine hundred ninety-nine duooctogintillion, nine hundred ninety-nine unoctogintillion, nine hundred ninety-nine octogintillion, nine hundred ninety-nine novemseptuagintillion, nine hundred ninety-nine octoseptuagintillion, nine hundred ninety-nine septenseptuagintillion, nine hundred ninety-nine sexseptuagintillion, nine hundred ninety-nine quinseptuagintillion, nine hundred ninety-nine quattuorseptuagintillion, nine hundred ninety-nine treseptuagintillion, nine hundred ninety-nine duoseptuagintillion, nine hundred ninety-nine unseptuagintillion, nine hundred ninety-nine septuagintillion, nine hundred ninety-nine novemsexagintillion, nine hundred ninety-nine octosexagintillion, nine hundred ninety-nine septensexagintillion, nine hundred ninety-nine sexsexagintillion, nine hundred ninety-nine quinsexagintillion, nine hundred ninety-nine quattuorsexagintillion, nine hundred ninety-nine tresexagintillion, nine hundred ninety-nine duosexagintillion, nine hundred ninety-nine unsexagintillion, nine hundred ninety-nine sexagintillion, nine hundred ninety-nine novemquinquagintillion, nine hundred ninety-nine octoquinquagintillion, nine hundred ninety-nine septenquinquagintillion, nine hundred ninety-nine sexquinquagintillion, nine hundred ninety-nine quinquinquagintillion, nine hundred ninety-nine quattuorquinquagintillion, nine hundred ninety-nine trequinquagintillion, nine hundred ninety-nine duoquinquagintillion, nine hundred ninety-nine unquinquagintillion, nine hundred ninety-nine quinquagintillion, nine hundred ninety-nine novemquadragintillion, nine hundred ninety-nine octoquadragintillion, nine hundred ninety-nine septenquadragintillion, nine hundred ninety-nine sexquadragintillion, nine hundred ninety-nine quinquadragintillion, nine hundred ninety-nine quattuorquadragintillion, nine hundred ninety-nine trequadragintillion, nine hundred ninety-nine duoquadragintillion, nine hundred ninety-nine unquadragintillion, nine hundred ninety-nine quadragintillion, nine hundred ninety-nine novemtrigintillion, nine hundred ninety-nine octotrigintillion, nine hundred ninety-nine septentrigintillion, nine hundred ninety-nine sextrigintillion, nine hundred ninety-nine quintrigintillion, nine hundred ninety-nine quattuortrigintillion, nine hundred ninety-nine tretrigintillion, nine hundred ninety-nine duotrigintillion, nine hundred ninety-nine untrigintillion, nine hundred ninety-nine trigintillion, nine hundred ninety-nine novemvigintillion, nine hundred ninety-nine octovigintillion, nine hundred ninety-nine septenvigintillion, nine hundred ninety-nine sexvigintillion, nine hundred ninety-nine quinvigintillion, nine hundred ninety-nine quattuorvigintillion, nine hundred ninety-nine trevigintillion, nine hundred ninety-nine duovigintillion, nine hundred ninety-nine unvigintillion, nine hundred ninety-nine vigintillion, nine hundred ninety-nine novemdecillion, nine hundred ninety-nine octodecillion, nine hundred ninety-nine septendecillion, nine hundred ninety-nine sexdecillion, nine hundred ninety-nine quindecillion, nine hundred ninety-nine quattuordecillion, nine hundred ninety-nine tredecillion, nine hundred ninety-nine duodecillion, nine hundred ninety-nine undecillion, nine hundred ninety-nine decillion, nine hundred ninety-nine nonillion, nine hundred ninety-nine octillion, nine hundred ninety-nine septillion, nine hundred ninety-nine sextillion, nine hundred ninety-nine quintillion, nine hundred ninety-nine quadrillion, nine hundred ninety-nine trillion, nine hundred ninety-nine billion, nine hundred ninety-nine million, nine hundred ninety-nine thousand, nine hundred ninety-nine

Handles Rats limited to the integer limits for the numerator and denominator.

When converting rational numbers, the word "and" is inserted between any whole number portion and the fractional portions of the number. If you have an "and" in the output, the input number had a fractional portion.

By default, `cardinal()` reduces fractions to their lowest terms. If you want to specify the denominator used to display, pass in an integer to the :denominator option.

It is probably best to specify a denominator that is a common divisor for the denominator. `cardinal()` will work with any integer denominator, and will scale the numerator to match, but will round off the numerator to the nearest integer after scaling, so some error will creep in if denominator is NOT a common divisor with the denominator.

Recognizes Nums up to about 1.79e308. (2¹⁰²⁴ - 1)

When converting Nums, reads out the enumerated digits for the mantissa and returns the ordinal exponent.

E.G. `cardinal(2.712e7)` will return:

```
two point seven one two times ten to the seventh

```

If you want it to be treated like an integer or rational, coerce it to the appropriate type.

`cardinal(2.712e7.Int)` to get:

```
twenty-seven million, one hundred twenty thousand

```

`cardinal(1.25e-3)` returns:

```
one point two five times ten to the negative third

```

`cardinal(1.25e-3.Rat)` returns:

```
one eight hundredth

```

## cardinal-year( ) - short: card-y()

Converts integers from 1 to 9999 to the common American English convention.

### cardinal-year( $year, :oh($str) );

* $year

  * value; must be an integer between 1 and 9999 or something that can be coerced to an integer between 1 and 9999.
* :oh

  * value; optional, string to use for the "0" years after a millennium. Default 'oh-'. Change to ' ought-' or some other string if desired.

Follows the common American English convention for years:

```
2015 -> twenty fifteen.

1984 -> nineteen eighty-four.

```

Even millenniums are returned as thousands:

```
2000 -> two thousand.

```

Even centuries are returned as hundreds:

```
1900 -> nineteen hundred.

```

Years 1 .. 9 in each century are returned as ohs:

```
2001 -> twenty oh-one.

```

Configurable with the :oh parameter. Default is 'oh-'. Change to 'ought-' if you prefer twenty ought-one, or something else if that is your preference.

## ordinal( ) - short: ord-n()

Takes an integer or something that can be coerced to an integer and returns a string similar to the cardinal() routine except it is positional rather than valuation.

E.G. 'first' rather than 'one', 'eleventh' rather than 'eleven'.

### ordinal( $integer )

* $integer

  * value; an integer or something that can be coerced to a sensible integer value.

## ordinal-digit( ) - short: ord-d()

Takes an integer or something that can be coerced to an integer and returns the given numeric value with the appropriate suffix appended to the number. 1 -> 1st, 3 -> 3rd, 24 -> 24th etc.

### ordinal-digit( $integer, :u, :c )

* $integer

  * value; an integer or something that can be coerced to a sensible integer value.
* :u

  * boolean; enable Unicode superscript ordinal suffixes (ˢᵗ, ⁿᵈ, ʳᵈ, ᵗʰ). Default false.
* :c

  * boolean; add commas to the ordinal number. Default false.

## comma( )

Insert commas into a numeric string following the English convention. Groups of 3-orders-of-magnitude for whole numbers, fractional portions are unaffected.

### comma( $number )

* $number

  * value; an integer, rational, int-string, rat-string or numeric string.

Will accept an Integer, Int-String, Rational, Rat-String or a numeric string that looks like an Integer or Rational. Any non-significant leading zeros are dropped. Non-significant trailing zeros are dropped for numeric rationals. If you want to retain non-significant trailing zeros in Rats, pass the argument as a string.

## pretty-rat() - short: prat()

A "prettifying" routine to render rational numbers as a fraction. Rats that have a denominator of 1 will be rendered as integers.

### pretty-rat($number)

* $number

  * value; Any real number. Integers and Nums will be passed along unchanged; Rats will be converted to a fractional representation.

## no-commas

A global flag for the `cardinal()` and `ordinal()` routines that disables / enables returning commas between 3-order-of-magnitude groups.

## pretty-rat() - short: prat()

A "prettifying" routine to render rational numbers as a fraction. Rats that have a denominator of 1 will be rendered as integers.

## super()

A "prettifying" routine to render numbers as Unicode superscripts. Mostly for formatting output strings. Not convieniently usable for a variable exponent.

### super($number)

* $number

  * value; Any real integer or integer string.

Note that a numeric of -0 will be superscripted to ⁰ since Raku treats numeric -0 and 0 as equivalent. If it is important to have the negative sign show up, pass the value as a string "-0". Provides superscript versions of: +-0123456789()ei . Technically, super will work with any numeric, but Unicode does not offer a superscript decimal point, so it is of limited use for rationals and scientific notation.

## no-commas

A global flag for the `cardinal()` and `ordinal()` routines that disables / enables returning commas between 3-order-of-magnitude groups.

### no-commas( $bool )

* $bool

  * A truthy / falsey value to enable / disable inserting commas into spelled out numeric strings.

Takes a Boolean or any value that can be coerced to a Boolean as a flag to disable / enable inserting commas. Absence of a value is treated as True. E.G.

```
no-commas;

```

is the same as

```
no-commas(True);

```

to re-enable inserting commas:

```
no-commas(False);

```

Disabled (False) by default. May be enabled and disabled as desired, even within a single block; the flag is global though, not lexical. If you disable commas deep within a block, it will affect all `ordinal()` and `cardinal()` calls afterwords, even in a different scope. If your script is part of a larger application, you may want to query the `no-commas` state and restore it after any modification.

Query the no-commas flag state with:

```
my $state = no-commas?;

```

Returns the current flag state as a Boolean: True - commas disabled, False - commas enabled. Does not modify the current state.

Restore it with:

```
no-commas($state);

```

NOTE: the `comma()` routine and `no-commas` flag have nothing to do with each other, do not interact, and serve completely different purposes.

---

# BUGS

Doesn't handle complex numbers. Does some cursory error trapping and coercion but the foot cannon is still loaded.

# AUTHOR

Original Integer cardinal code by TimToady (Larry Wall).

See: <http://rosettacode.org/wiki/Number_names#Raku>

Other code by thundergnat (Steve Schulze).

# LICENSE

Licensed under The Artistic 2.0; see LICENSE.


## nfkc.md
class NFKC

Codepoint string in Normal Form KC (compatibility composed)

```raku
class NFKC is Uni {}
```

A Codepoint string in Unicode Normalization Form KC. It is created by Compatibility Decomposition, followed by Canonical Composition. For more information on what this means, see [Unicode TR15](https://www.unicode.org/reports/tr15/).

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

Type relations for `NFKC`

raku-type-graph

NFKC
NFKC

Uni
Uni

NFKC->Uni

Mu
Mu

Any
Any

Any->Mu

Positional
Positional

Stringy
Stringy

Uni->Any

Uni->Positional

Uni->Stringy

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


## dist_cpan-MARTIMM-Gnome-GObject.md
![gtk logo](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-raku.png)

# Gnome GObject - Data structures and utilities for C programs

![L](http://martimm.github.io/label/License-label.svg)

Note that all modules are now in `:api<1>`. This is done to prevent clashes with future distributions having the same class names only differing in this api string. So, add this string to your import statements and dependency modules of these classes in META6.json. Furthermore add this api string also when installing with zef.

## Documentation

* [🔗 License document](http://www.perlfoundation.org/artistic_license_2_0)
* [🔗 Release notes](https://github.com/MARTIMM/gnome-gobject/blob/master/CHANGES.md)
* [🔗 Issues](https://github.com/MARTIMM/gnome-gtk3/issues)

# Installation

Do not install this package on its own. Instead install `Gnome::Gtk3:api<1>`.

`zef install 'Gnome::Gtk3:api<1>'`

# Author

Name: **Marcel Timmerman**
Github account name: **MARTIMM**

# Issues

There are always some problems! If you find one please help by filing an issue at [my Gnome::Gtk3 github project](https://github.com/MARTIMM/gnome-gtk3/issues).

# Attribution

* The developers of Raku of course and the writers of the documentation which helped me out every time again and again.
* The builders of the GTK+ library and its documentation.
* Other helpful modules for their insight and use.


## multi.md
multi

Combined from primary sources listed below.

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

See primary documentation
[in context](/language/functions#Multi-dispatch)
for **Multi-dispatch**.

Raku allows for writing several routines with the same name but different signatures. When the routine is called by name, the runtime environment determines the proper *candidate* and invokes it.

Each candidate is declared with the `multi` keyword. Dispatch happens depending on the parameter [arity](/type/Code#method_arity) (number), type and name; and under some circumstances the order of the multi declarations. Consider the following example:

```raku
# version 1
multi happy-birthday( $name ) {
    say "Happy Birthday $name !";
}

# version 2
multi happy-birthday( $name, $age ) {
    say "Happy {$age}th Birthday $name !";
}

# version 3
multi happy-birthday( :$name, :$age, :$title  = 'Mr' ) {
    say "Happy {$age}th Birthday $title $name !";
}

# calls version 1 (arity)
happy-birthday 'Larry';                        # OUTPUT: «Happy Birthday Larry !␤»
# calls version 2 (arity)
happy-birthday 'Luca', 40;                     # OUTPUT: «Happy 40th Birthday Luca !␤»
# calls version 3
# (named arguments win against arity)
happy-birthday( age => '50', name => 'John' ); # OUTPUT: «Happy 50th Birthday Mr John !␤»
# calls version 2 (arity)
happy-birthday( 'Jack', 25 );                  # OUTPUT: «Happy 25th Birthday Jack !␤»

```

The first two versions of the `happy-birthday` sub differs only in the arity (number of arguments), while the third version uses named arguments and is chosen only when named arguments are used, even if the arity is the same of another `multi` candidate.

When two sub have the same arity, the type of the arguments drive the dispatch; when there are named arguments they drive the dispatch even when their type is the same as another candidate:

```raku
multi happy-birthday( Str $name, Int $age ) {
    say "Happy {$age}th Birthday $name !";
}

multi happy-birthday( Str $name, Str $title ) {
    say "Happy Birthday $title $name !";
}

multi happy-birthday( Str :$name, Int :$age ) {
    say "Happy Birthday $name, you turned $age !";
}

happy-birthday 'Luca', 40;                 # OUTPUT: «Happy 40th Birthday Luca !␤»
happy-birthday 'Luca', 'Mr';               # OUTPUT: «Happy Birthday Mr Luca !␤»
happy-birthday age => 40, name => 'Luca';  # OUTPUT: «Happy Birthday Luca, you turned 40 !␤»

```

Named parameters participate in the dispatch even if they are not provided in the call. Therefore a multi candidate with named parameters will be given precedence.

For more information about type constraints see the documentation on [`Signature` literals](/language/signatures#Type_constraints).

```raku
multi as-json(Bool $d) { $d ?? 'true' !! 'false'; }
multi as-json(Real $d) { ~$d }
multi as-json(@d)      { sprintf '[%s]', @d.map(&as-json).join(', ') }

say as-json( True );                        # OUTPUT: «true␤»
say as-json( 10.3 );                        # OUTPUT: «10.3␤»
say as-json( [ True, 10.3, False, 24 ] );   # OUTPUT: «[true, 10.3, false, 24]␤»
```

For some signature differences (notably when using a where clause or a subset) the order of definition of the multi methods or subs is used, evaluating each possibility in turn. See [multi resolution by order of definition](/language/functions#multi_resolution_by_order_of_definition) below for examples.

`multi` without any specific routine type always defaults to a `sub`, but you can use it on methods as well. The candidates are all the multi methods of the object:

```raku
class Congrats {
    multi method congratulate($reason, $name) {
        say "Hooray for your $reason, $name";
    }
}

role BirthdayCongrats {
    multi method congratulate('birthday', $name) {
        say "Happy birthday, $name";
    }
    multi method congratulate('birthday', $name, $age) {
        say "Happy {$age}th birthday, $name";
    }
}

my $congrats = Congrats.new does BirthdayCongrats;

$congrats.congratulate('promotion','Cindy'); # OUTPUT: «Hooray for your promotion, Cindy␤»
$congrats.congratulate('birthday','Bob');    # OUTPUT: «Happy birthday, Bob␤»
```

Unlike `sub`, if you use named parameters with multi methods, the parameters must be required parameters to behave as expected.

Please note that a non-multi sub or operator will hide multi candidates of the same name in any parent scope or child scope. The same is true for imported non-multi candidates.

Multi-dispatch can also work on parameter traits, with routines with `is rw` parameters having a higher priority than those that do not:

```raku
proto þoo (|) {*}
multi þoo( $ðar is rw ) { $ðar = 42 }
multi þoo( $ðar ) { $ðar + 42 }
my $bar = 7;
say þoo($bar); # OUTPUT: «42␤»

```


## dist_github-Skarsnik-Gumbo.md
[![Build Status](https://travis-ci.org/Skarsnik/perl6-gumbo.svg?branch=master)](https://travis-ci.org/Skarsnik/perl6-gumbo)

# Name Gumbo

# Synopsis

```
use Gumbo;
use LWP::Simple;

my $xml = parse-html(LWP::Simple.get("www.google.com"));
say $xml.lookfor(:TAG<title>); # Google;

```

# Description

From the Gumbo (<https://github.com/google/gumbo-parser>) project page :

Gumbo is an implementation of the HTML5 parsing algorithm implemented as a pure C99 library with no outside dependencies. It's designed to serve as a building block for other tools and libraries such as linters, validators, templating languages, and refactoring and analysis tools.

This module is a binding to this library. It provide a `parse-html` routine that parse a given html string and return a `XML::Document` object. To access all the Gumbo library has to offer you probably want to look at the `Gumbo::Binding` module.

# Installation

Simply use zef. For the tests to pass, you need to install the Gumbo library (see your distribution documentation). If you installed the Gumbo library in your own location you can set the `PERL6_GUMBOLIB` environement variable with the path to the library file.

`zef install Gumbo` or `PERL6_GUMBOLIB="/home/user/gumbo/libgumbo.so.1" zef install Gumbo`

# Usage

## parse-html(Str $html) : XML::Document

Parse a html string and retrurn a `XML::Document`.

## parse-html(Str $html, :$nowhitespace, \*%filters) : XML::Document

This is the full signature of the `parse-html` routine.

* nowhitespace

Tell Gumbo to not include all extra whitespaces that can exist around tag, like intendation put in front of html tags

* \*%filters

The module offer some form of basic filtering if you want to restrict the `XML::Document` returned. You can only filter on elements (understand tags) and not content like the text of a `p` tag.

It inspired by the `elements` method of the `XML::Element` class. The main purpore is to reduce time spent parsing uneccessary content and decrease the memory print of the `XML::Document`.

IMPORTANT: the root will always be the html tag.

* TAG Limits to elements with the given tag name
* SINGLE If set only get the first match
* attrib You can filter on one attribute name with his given value

All the children of the element(s) matched are kept. Like if you search for all the links, you will get the eventuals additionals tags put around the text part.

## $gumbo\_last\_c\_parse\_duration && $gumbo\_last\_xml\_creation\_duration

These two variables hold the time (`Duration`) spend in the two steps of the work parse-html does.

## PERL6\_GUMBOLIB

Set this environment variable to specify where the module can find the gumbo library if it's not in the usual system library path.

# Example

```
use Gumbo;

my $html = q:to/END_HTML/;
<html>
<head>
       <title>Fancy</title>
</head>
<body>
       <p>It's fancy</p>
       <p class="fancier">It's fancier</p>
</body>
</html>

END_HTML

my $xmldoc = parse-html($html);

say $xmldoc.root.elements(:TAG<p>, :RECURSE)[0][0].text; #It's fancy

$xmldoc = parse-html($html, :TAG<p>, :SINGLE);

say $xmldoc[0][0].text; #It's still fancy

$xmldoc = parse-html($html, :TAG<p>, :class<fancier>, :SINGLE);

say $xmldoc[0][0].text; # It's fancier

```

# Gumbo::Parser

This module provide a Gumbo::Parser class that does the role defined by the `HTML::Parser` module. It also provide some additionnals attributes that contains various informations. It work exactly like the `parse-html` method with the same extra optionnals arguments.

```
use Gumbo::Parser;

my $parser = Gumbo::Parser.new;
my $xmldoc = $parser.parse($html);
say $parser.c-parse-duration;
say $parser.xml-creation-duration;
say $parser.stats<xml-objects>; # the number of XML::* created (excluding the XML::Document)
say $parser.stats<whitespaces>; # the number of Whitespaces elements (created or not)
say $parser.stats<elements>; # the number of XML::Element (including root)

```

# See Also

`XML`, `HTML::Parser::XML`

# Copyright

Sylvain "Skarsnik" Colinet [scolinet@gmail.com](mailto:scolinet@gmail.com)

# License

The modules provided by Gumbo are under the same licence as Rakudo, see the LICENCE file


## dist_cpan-PMQS-IO-Compress-Lzop.md
```

                            IO-Compress-Lzop

                             Version 2.094

                             13 July 2020

       Copyright (c) 2005-2020 Paul Marquess. All rights reserved.
          This program is free software; you can redistribute it
           and/or modify it under the same terms as Perl itself.

DESCRIPTION
-----------

This module provides a Perl interface to allow reading and writing of
lzop files/buffers.

PREREQUISITES
-------------

Before you can build IO-Compress-Lzop you need to have the following
installed on your system:

    * Perl 5.006 or better.
    * Compress::LZO
    * IO::Compress::Base

BUILDING THE MODULE
-------------------

Assuming you have met all the prerequisites, the module can now be built
using this sequence of commands:

    perl Makefile.PL
    make
    make test

INSTALLATION
------------

To install IO-Compress-Lzop, run the command below:

    make install

TROUBLESHOOTING
---------------

SUPPORT
-------

General feedback/questions/bug reports should be sent to
https://github.com/pmqs/IO-Compress-Lzop/issues (preferred) or
https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress-Lzop.

FEEDBACK
--------

How to report a problem with IO-Compress-Lzop.

To help me help you, I need all of the following information:

 1. The Versions of everything relevant.
    This includes:

     a. The *complete* output from running this

            perl -V

        Do not edit the output in any way.
        Note, I want you to run "perl -V" and NOT "perl -v".

        If your perl does not understand the "-V" option it is too
        old. This module needs Perl version 5.004 or better.

     b. The version of IO-Compress-Lzop you have.
        If you have successfully installed IO-Compress-Lzop, this one-liner
        will tell you:

           perl -MIO::Compress::Lzop -e 'print qq[ver $IO::Compress::Lzop::VERSION\n]'

        If you are  running windows use this

           perl -MIO::Compress::Lzop -e "print qq[ver $IO::Compress::Lzop::VERSION\n]"

        If you haven't installed IO-Compress-Lzop then search IO::Compress::Lzop.pm
        for a line like this:

          $VERSION = "2.094" ;

 2. If you are having problems building IO-Compress-Lzop, send me a
    complete log of what happened. Start by unpacking the IO-Compress-Lzop
    module into a fresh directory and keep a log of all the steps

        [edit config.in, if necessary]
        perl Makefile.PL
        make
        make test TEST_VERBOSE=1

Paul Marquess

```


## dist_zef-raku-community-modules-Test-Output.md
[![Actions Status](https://github.com/raku-community-modules/Test-Output/workflows/test/badge.svg)](https://github.com/raku-community-modules/Test-Output/actions)

Test::Output - Test the output to STDOUT and STDERR your program generates

# TABLE OF CONTENTS

* [NAME](#name)
* [SYNOPSIS](#synopsis)
* [DESCRIPTION](#description)
* [EXPORTED SUBROUTINES](#exported-subroutines)
  * [`is` Tests](#is-tests)
    * [`output-is`](#output-is)
    * [`stdout-is`](#stdout-is)
    * [`stderr-is`](#stderr-is)
  * [`like` Tests](#like-tests)
    * [`output-like`](#output-like)
    * [`stdout-like`](#stdout-like)
    * [`stderr-like`](#stderr-like)
  * [Output Capture](#output-capture)
    * [`output-from`](#output-from)
    * [`stdout-from`](#stdout-from)
    * [`stderr-from`](#stderr-from)
* [REPOSITORY](#repository)
* [BUGS](#bugs)
* [AUTHOR](#author)
* [LICENSE](#license)

# SYNOPSIS

```
    use v6.d;
    use Test;
    use Test::Output;

    my &test-code = sub {
        say 42;
        note 'warning!';
        say "After warning";
    };

    # Test code's output using exact match ('is')
    output-is   &test-code, "42\nwarning!\nAfter warning\n", 'testing output';
    stdout-is   &test-code, "42\nAfter warning\n",  'testing stdout';
    stderr-is   &test-code, "warning!\n", 'testing stderr';

    # Test code's output using regex ('like')
    output-like &test-code, /42.+warning.+After/, 'testing output (regex)';
    stdout-like &test-code, /42/, 'testing stdout (regex)';
    stderr-like &test-code, /^ "warning!\n" $/, 'testing stderr (regex)';

    # Just capture code's output and do whatever you want with it
    is output-from( &test-code ), "42\nwarning!\nAfter warning\n";
    is stdout-from( &test-code ), "42\nAfter warning\n";
    is stderr-from( &test-code ), "warning!\n";

```

# DESCRIPTION

This module allows you to capture the output (STDOUT/STDERR/BOTH) of a
piece of code and evaluate it for some criteria. It needs version 6.d
of the language, since it's following specs that were deployed for
that version. If you need to go with 6.c, download 1.001001
from
[here](https://github.com/raku-community-modules/Test-Output/releases) or
via `git clone`+

```
git checkout v1.001001
zef install .

```

# EXPORTED SUBROUTINES

## `is` Tests

### `output-is`

![](_chromatin/sub-signature.png)

```
    sub output-is (&code, Str $expected, Str $desc? );

```

![](_chromatin/sub-usage-example.png)

```
    output-is { say 42; note 43; say 44 }, "42\n43\n44\n",
        'Merged output from STDOUT/STDERR looks fine!';

```

Uses `is` function from `Test` module to test whether the combined
STDERR/STDOUT output from a piece of code matches the given string. Takes
an **optional** test description.

---

### `stdout-is`

![](_chromatin/sub-signature.png)

```
    sub stdout-is (&code, Str $expected, Str $desc? );

```

![](_chromatin/sub-usage-example.png)

```
    stdout-is { say 42; note 43; say 44 }, "42\n44\n", 'STDOUT looks fine!';

```

Same as [`output-is`](#output-is), except tests STDOUT only.

---

### `stderr-is`

![](_chromatin/sub-signature.png)

```
    sub stderr-is (&code, Str $expected, Str $desc? );

```

![](_chromatin/sub-usage-example.png)

```
    stderr-is { say 42; note 43; say 44 }, "43\n", 'STDERR looks fine!';

```

Same as [`output-is`](#output-is), except tests STDERR only.

---

## `like` Tests

### `output-like`

![](_chromatin/sub-signature.png)

```
    sub output-like (&code, Regex $expected, Str $desc? );

```

![](_chromatin/sub-usage-example.png)

```
    output-like { say 42; note 43; say 44 }, /42 .+ 43 .+ 44/,
        'Merged output from STDOUT/STDERR matches the regex!';

```

Uses `like` function from `Test` module to test whether the combined
STDERR/STDOUT output from a piece of code matches the given `Regex`. Takes
an **optional** test description.

---

### `stdout-like`

![](_chromatin/sub-signature.png)

```
    sub stdout-like (&code, Regex $expected, Str $desc? );

```

![](_chromatin/sub-usage-example.png)

```
    stdout-like { say 42; note 43; say 44 }, /42 \n 44/,
        'STDOUT matches the regex!';

```

Same as [`output-like`](#output-like), except tests STDOUT only.

---

### `stderr-like`

![](_chromatin/sub-signature.png)

```
    sub stderr-like (&code, Regex $expected, Str $desc? );

```

![](_chromatin/sub-usage-example.png)

```
    stderr-like { say 42; note 43; say 44 }, /^ 43\n $/,
        'STDERR matches the regex!';

```

Same as [`output-like`](#output-like), except tests STDERR only.

---

## Output Capture

### `output-from`

![](_chromatin/sub-signature.png)

```
    sub output-from (&code) returns Str;

```

![](_chromatin/sub-usage-example.png)

```
    my $output = output-from { say 42; note 43; say 44 };
    say "Captured $output from our program!";

    is $output, "42\nwarning!\nAfter warning\n",
        'captured merged STDOUT/STDERR look fine';

```

Captures and returns merged STDOUT/STDERR output from the given piece of code.

---

### `stdout-from`

![](_chromatin/sub-signature.png)

```
    sub stdout-from (&code) returns Str;

```

![](_chromatin/sub-usage-example.png)

```
    my $stdout = stdout-from { say 42; note 43; say 44 };
    say "Captured $stdout from our program!";

    is $stdout, "42\nAfter warning\n", 'captured STDOUT looks fine';

```

Same as [`output-from`](#output-from), except captures STDOUT only.

---

### `stderr-from`

![](_chromatin/sub-signature.png)

```
    sub stderr-from (&code) returns Str;

```

![](_chromatin/sub-usage-example.png)

```
    my $stderr = stderr-from { say 42; note 43; say 44 };
    say "Captured $stderr from our program!";

    is $stderr, "warning\n", 'captured STDERR looks fine';

```

Same as [`output-from`](#output-from), except captures STDERR only.

---

### `test-output-verbosity`

![](_chromatin/sub-signature.png)

```
    sub test-output-verbosity (Bool :$on, Bool :$off) returns Str;

```

![](_chromatin/sub-usage-example.png)

```
    # turn verbosity on
    test-output-verbosity(:on);

    my $output = output-from { do-something-interactive() };
    # test output will now displayed during the test

    # turn verbosity off
    test-output-verbosity(:off);

```

Display the code's output while the test code is executed. This can be
very useful for author tests that require you to enter input based on
the output.

---

# REPOSITORY

Fork this module on GitHub:
<https://github.com/raku-community-modules/Test-Output>

# BUGS

To report bugs or request features, please use
<https://github.com/raku-community-modules/Test-Output/issues>

# ORIGINAL AUTHOR

Zoffix Znet (<http://zoffix.com/>)

# LICENSE

You can use and distribute this module under the terms of the
The Artistic License 2.0. See the `LICENSE` file included in this
distribution for complete details.


## dist_github-kmwallio-Text-TFIdf.md
# Text::TFIdf

Given a set of documents, generates [TF-IDF Vectors](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) for them. [![Build Status](https://travis-ci.org/kmwallio/p6-Text-TFIdf.svg?branch=master)](https://travis-ci.org/kmwallio/p6-Text-TFIdf)

## Installation

```
panda install Text::TFIdf

```

## Usage

```
use Text::TFIdf;

my %stop-words;

my $doc-store = TFIdf.new(:trim(True), :stop-list(%stop-words));

$doc-store.add('perl is cool');
$doc-store.add('i like node');
$doc-store.add('java is okay');
$doc-store.add('perl and node are interesting meh about java');

sub results($id, $score) {
  say $id ~ " got " ~ $score;
}

$doc-store.tfids('node perl java', &results);

```

Output:

```
0 got 0.858454714967854
1 got 0.858454714967854
2 got 0.858454714967854
3 got 2.17296349726238

```

## Acknowledgements

* [Lingua::EN::Stem::Porter](https://github.com/johnspurr/Lingua-EN-Stem-Porter)
* [NaturalNode](https://github.com/NaturalNode/natural) for heavy inspiration?


## dist_zef-dwarring-CSS.md
[![Build Status](https://travis-ci.org/css-raku/CSS-raku.svg?branch=master)](https://travis-ci.org/css-raku/CSS-raku)

[[Raku CSS Project]](https://css-raku.github.io)
/ [[CSS]](https://css-raku.github.io/CSS-raku)

## class CSS

CSS Stylesheet processing

## Synopsis

```
use CSS;
use CSS::Properties;
use CSS::Units :px; # define 'px' postfix operator
use CSS::TagSet::XHTML;
use LibXML::Document;

my $string = q:to<\_(ツ)_/>;
  <!DOCTYPE html>
  <html>
    <head>
      <style>
        @page :first { margin:4pt; }
        body {background-color: powderblue; font-size: 12pt}
        @media screen { h1:first-child {color: blue !important;} }
        @media print { h2 {color: green;} }
        p    {color: red; font-family:'Para';}
        div {font-size: 10pt }
        @font-face {
          font-family:'Para';
          src:url('/myfonts/para.otf');
        }
      </style>
    </head>
    <body>
      <h1>This is a heading</h1>
      <h2>This is a sub-heading</h2>
      <h1>This is another heading</h1>
      <p>This is a paragraph.</p>
      <div style="color:green">This is a div</div>
    </body>
  </html>
\_(ツ)_/

my LibXML::Document $doc .= parse: :$string, :html;

# define a selection media
my CSS::Media $media .= new: :type<screen>, :width(480px), :height(640px), :color;

# Create a tag-set for XHTML specific loading of style-sheets and styling
my CSS::TagSet::XHTML $tag-set .= new();

my CSS $css .= new: :$doc, :$tag-set, :$media, :inherit;

# -- show some computed styles, based on CSS Selectors, media, inline styles and xhtml tags
my CSS::Properties $body-props = $css.style('/html/body');
say $body-props.font-size; # 12pt
say $body-props;           # background-color:powderblue; display:block; font-size:12pt; margin:8px; unicode-bidi:embed;
say $css.style('/html/body/h1[1]');
# color:blue; display:block; font-size:12pt; font-weight:bolder; margin-bottom:0.67em; margin-top:0.67em; unicode-bidi:embed;
say $css.style('/html/body/div');

# color:green; display:block; font-size:10pt; unicode-bidi:embed;
say $css.style($doc.first('/html/body/div'));
# color:green; display:block; font-size:10pt; unicode-bidi:embed;

# -- query first page properties (from @page rules)
say $css.page-properties(:first);     # margin:4pt;

# -- find a font using @font-face declarations
say .Str    # font-family:'Para'; src:url('/myfonts/para.otf')
    with $css.font-sources('12pt Para').head;

```

## Description

[CSS](https://css-raku.github.io/CSS-raku) is a module for parsing style-sheets and applying them to HTML or XML documents.

This module aims to be W3C compliant and complete, including: style-sheets, media specific and inline styling and the application of HTML specific styling (based on tags and attributes).

## Methods

### method new

```
method new(
    LibXML::Document :$doc!,       # document to be styled.
    CSS::Stylesheet :$stylesheet!, # stylesheet to apply
    CSS::TagSet :$tag-set,         # tag-specific styling
    CSS::Media :$media,            # target media
    Bool :$inherit = True,         # perform property inheritance
    :%include (                    # External stylesheet loading:
        Bool :$imports = False,    # - enable '@import' directives
        Bool :$links = False,      # - load <link../> tags (XHTML)
    ),
    URI() :$base-url = $doc.URI,   # base URL for imports and links
) returns CSS;

```

In particular, the `CSS::TagSet :$tag-set` options specifies a tag-specific styler; For example CSS::TagSet::XHTML.

### method style

```
multi method style(LibXML::Element:D $elem) returns CSS::Properties;
multi method style(Str:D $xpath) returns CSS::Properties;

```

Computes a style for an individual element, or XPath to an element.

### method page-properties

```
method page-properties(Bool :$first, Bool :$right, Bool :$left,
                       Str :$margin-box --> CSS::Properties)

```

Query and extract `@page` at rules.

The `:first`, `:right` and `:left` flags can be used to select rules applicable to a given logical page.

In addition, the `:margin-box` can be used to select a specific [Page Margin Box](https://www.w3.org/TR/css-page-3/#margin-boxes). For example given the at-rule `@page { margin:2cm; size:a4; @top-center { content: 'Page ' counter(page); } }`, the top-center page box properties can be selected with `$stylesheet.page(:margin-box<top-center>)`.

### method font-face

```
multi method font-face() returns Array[CSS::Font::Descriptor]
multi method font-face($family) returns CSS::Font::Descriptor

```

* `font-face()` returns a list of all fonts declared with `@font-face` at-rules
* `font-face($family)` returns font-properties for the given font-family;

### method prune

```
method prune(LibXML::Element $node? --> LibXML::Element)

```

Removes all XML nodes with CSS property `display:none;`, giving an approximate representation of a CSS rendering tree.

For example, if an HTML document with an XHTML tag-set is pruned the `head` element will be removed because it has the property `display:none;`. Any other elements that have had `display:none;' applied to them via the tag-set, inline CSS, or CSS Selectors are also removed.

By default, this method acts on the root element of the associated $.doc XML document.

### method font-sources

```
method font-sources(CSS::Font() $font) returns Array[CSS::Font::Resources::Source]

```

Returns a list of [CSS::Font::Resources::Source](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source) objects for natching source fonts, based on `@font-face` rules and (as a fallback) the font's name and characterstics.

## Utility Scripts

* `css-inliner.raku input.xml [output.xml] --style=file.css --prune --tags --type=html|pango|pdf --inherit`

Apply internal or external style-sheets to per-element 'style' attributes

## See Also

* [CSS::Stylesheet](https://css-raku.github.io/CSS-Stylesheet-raku/CSS/Stylesheet) - CSS Stylesheet representations
* [CSS::Module](https://css-raku.github.io/CSS-Module-raku) - CSS Module module
* [CSS::Properties](https://css-raku.github.io/CSS-Properties-raku/CSS/Properties) - CSS Properties module
* [CSS::TagSet](https://css-raku.github.io/CSS-TagSet-raku/CSS/TagSet) - CSS tag-sets (XHTML, Pango, Tagged PDF)
* [LibXML](https://css-raku.github.io/https://libxml-raku.github.io/LibXML-raku/) - LibXML Raku module
* [DOM::Tiny](https://github.com/zostay/raku-DOM-Tiny) - A lightweight, self-contained DOM parser/manipulator

## Todo

* Other At-Rule variants `@document`


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

# CSS-Font-Resources-raku

## Description

This is a light-weight font selector driven by CSS `@font-face` rules.

It is integrated into the [CSS](https://css-raku.github.io) and [CSS::Stylesheet](https://css-raku.github.io/CSS-Stylesheet-raku) modules, but
can also be used for stand-alone font resource loading.

## Classes in this distribution:

* [CSS::Font::Resources](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources) - CSS Font Resources Manager
* [CSS::Font::Resources::Source](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source) - CSS Font Resources abstract source

  * [CSS::Font::Resources::Source::Local](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source/Local) - CSS Font Resources `local` source
  * [CSS::Font::Resources::Source::Url](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source/Url) - CSS Font Resources `url` source
* [CSS::URI](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/URI) - Lightweight object for fetchable URIs.

## Examples

## from CSS::Stylesheet

```
use CSS::Stylesheet;
use CSS::Font::Resources;

my CSS::Stylesheet $css .= parse: q:to<END>, :base-url<my/path/>;

    h1 {color:red}
    h2 {color:blue}

    @font-face {
      font-family: "DejaVu Sans";
      src: url("fonts/DejaVuSans.ttf");
    }
    @font-face {
      font-family: "DejaVu Sans";
      src: url("fonts/DejaVuSans-Bold.ttf");
      font-weight: bold;
    }
    @font-face {
      font-family: "DejaVu Sans";
      src: url("fonts/DejaVuSans-Oblique.ttf");
      font-style: oblique;
    }
    @font-face {
      font-family: "DejaVu Sans";
      src: url("fonts/DejaVuSans-BoldOblique.ttf");
      font-weight: bold;
      font-style: oblique;
    }
    END

my $formats = 'opentype'|'truetype'; # accept first true-type or open-type font
my $font = "bold 12pt times roman, serif";
my CSS::Font::Resources::Source @sources = $css.font-sources($font, :$formats);
my Blob $font-buf = .IO with @sources.first;

```

## stand-alone

```
use CSS::Font::Resources;
use CSS::Font::Descriptor;

my @decls = q:to<END>.split: /^^'---'$$/;
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
---
font-family: serif;
font-weight: bold;
src: local(DejaVuSans-Bold);
END

my CSS::Font::Descriptor @font-face = @decls.map: -> $style {CSS::Font::Descriptor.new: :$font};
my $font = "bold 12pt times roman, serif";
my $formats = 'opentype'|'truetype'; # accept first true-type or open-type font
my CSS::Font::Resources $font-selector .= new: :$font, :@font-face, :base-url</my/path/>, :$formats;
# accept first true-type or open-type font
my CSS::Font::Resources::Source @sources = $font-selector.sources;
my Blob $font-buf = .Blob with @sources.first;

```

## Methods

### new

```
method new(
    CSS::Font:D() :$font!,
    CSS::Font::Descriptor :@font-face,
    URI() $.base-url = './',
    :$formats = 'woff'|'woff2'|'truetype'|'opentype'|'embedded-opentype'|'postscript'|'svg'|'cff',
    --> CSS::Font::Resources
)

```

Returns a new font selector object for the given font and font-descriptor list.

* `$base-url` is used to compute absolute URI's for relative font `src` urls.
* `$formats` is used to filter fonts to a specific format,

### sources

```
multi method sources(
    CSS::Font::Resources:D:
    Bool :$fallback = True
)

multi method sources(
    CSS::Font::Resources:U:
    :$font, :@font-face, :$base-url, :$formats,
    Bool :$fallback = True,
)

```

Returns a list of matching fonts of type CSS::Font::Resources::Source, ordered by preference.

* `$fallback` return a system font source, if there are no matching font-descriptors.

## source

```
method source(|c --> CSS::Font::Resources::Source);

```

Returns the first matching source.


## shell.md
shell

Combined from primary sources listed below.

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

See primary documentation
[in context](/type/Proc#method_shell)
for **method shell**.

```raku
method shell($cmd, :$cwd = $*CWD, :$env --> Bool:D)
```

Runs the `Proc` object with the given command and environment which are passed through to the shell for parsing and execution. See [`shell`](/type/independent-routines#sub_shell) for an explanation of which shells are used by default in the most common operating systems.

# [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_shell "direct link")

See primary documentation
[in context](/type/independent-routines#sub_shell)
for **sub shell**.

```raku
multi shell($cmd, :$in = '-', :$out = '-', :$err = '-',
                Bool :$bin, Bool :$chomp = True, Bool :$merge,
                Str :$enc, Str:D :$nl = "\n", :$cwd = $*CWD, :$env)

```

Runs a command through the system shell, which defaults to `%*ENV<ComSpec> /c` in Windows, `/bin/sh -c` otherwise. All shell metacharacters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on. Shell escapes are a severe security concern and can cause confusion with unusual file names. Use [run](#sub_run) if you want to be safe.

The return value is of [type Proc](/type/Proc).

```raku
shell 'ls -lR | gzip -9 > ls-lR.gz';
```

See [`Proc`](/type/Proc#method_shell) for more details, for example on how to capture output.


## dist_zef-bduggan-Terminal-UI.md
[![Actions Status](https://github.com/bduggan/raku-terminal-ui/actions/workflows/linux.yml/badge.svg)](https://github.com/bduggan/raku-terminal-ui/actions/workflows/linux.yml)
[![Actions Status](https://github.com/bduggan/raku-terminal-ui/actions/workflows/macos.yml/badge.svg)](https://github.com/bduggan/raku-terminal-ui/actions/workflows/macos.yml)

## Terminal::UI

A framework for building terminal interfaces.

## Example

Create a box in full screen with some text in it, wait for a key, then exit:

```
use Terminal::UI 'ui';
ui.setup(:1pane);
ui.pane.put("Hello world.");
ui.get-key;
ui.shutdown;

╔══════════════╗
║Hello world.  ║
║              ║
╚══════════════╝

```

## Example 2

Make a screen split with a line in the middle, with scrollable text on the top
and bottom, and a selected row in the top box. The arrow keys (or j,k) move
the selected line up and down. Tab switches to the other box.

```
use Terminal::UI 'ui';
ui.setup(:2panes);
ui.panes[0].put("$_") for 1..10;
ui.panes[1].put("$_") for <hello world>;
ui.interact;
ui.shutdown;

╔══════════════╗
║8             ║  <- selected in green, scrollable
║9             ║
║10            ║
╟──────────────╢
║hello         ║  <- selected in grey.
║world         ║
╚══════════════╝

```

## Example 3

Like example 2, but also -- pressing Enter in the top box
will some text about add the currently selected row to the
bottom box:

```
ui.setup(:2panes);
ui.panes[0].put("$_") for 1..10;

ui.panes[0].on: select => -> :$raw, :$meta {
  ui.panes[1].put("you chose $raw!")
}

ui.interact;
ui.shutdown;

╔══════════════╗
║8             ║  <- press Enter, and…
║9             ║
║10            ║
╟──────────────╢
║you chose 8!  ║  <- …this appears!
║              ║
╚══════════════╝

```

## Features and design goals

* Easy to quickly make a console interface with custom behavior, but practical defaults.
* Scrolling with some optimization, such as using ANSI scroll region escape sequences.
* Thread safe. Concurrency friendly. Unicode compatibile.
* Dynamic geometry calculation, for smart handling of window resizing.

## More examples

See the [eg](https://github.com/bduggan/raku-terminal-ui/blob/master/eg/) directory.

## See also

<https://blog.matatu.org/terminal-ui>

## Description

The best place for documentation is the
[examples](https://github.com/bduggan/raku-terminal-ui/blob/master/eg/) directory.

There is also reference documentation with links to the source code -- see
[Terminal::UI](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI.md). Other classes
with documentation are:

* [Terminal::UI::Screen](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Screen.md)
* [Terminal::UI::Frame](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Frame.md)
* [Terminal::UI::Pane](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Pane.md)
* [Terminal::UI::Style](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Style.md)
* [Terminal::UI::Input](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Input.md)

## BUGS

Probably!

If you find some bugs, or just have something to say, feel free to contact the author.

## Author

Brian Duggan (bduggan at matatu.org)


## dist_zef-jmaslak-TCP-LowLevel.md
[![Build Status](https://travis-ci.org/jmaslak/Raku-TCP-LowLevel.svg?branch=master)](https://travis-ci.org/jmaslak/Raku-TCP-LowLevel)

# NAME

TCP::LowLevel - Raku bindings for NativeCall TCP on Linux w/ Non-NativeCall Fallback`

# SYNOPSIS

## SERVER

```
use TCP::LowLevel;

react {
  my $server = TCP::LowLevel.new;
  $server-tcp.listen;
  whenever $server-tcp.acceptor -> $conn {
    whenever $conn.Supply -> $msg {
      say "Received: $msg";
    }
  }

  say "Listening on port: " ~ $server.socket-port.result;
}

```

## CLIENT

```
use TCP::LowLevel;

react {
  my $client = TCP::LowLevel.new;
  my $conn   = $client.connect('127.0.0.1', 12345).result;

  $conn.print("Hello!");

  whenever $conn.Supply -> $msg{
    say "Received: $msg";
  }
}

```

# DESCRIPTION

On Linux, this module utilizes NativeCall to use the low level socket library in an asyncronous way. This allows enhanced functionality, such as the use of the MD5 authentication header option (see internet RFC 2385). When not using Linux, this module is essentially a factory for the built-in asyncronous network libraries, although functionality such as MD5 authentication headers is not available in this mode.

# WARNING

This module may experience some interface changes as I determine the best possible interface. I will however try to keep the existing public interface working as documented in this documentation.

# ATTRIBUTES

## my-host

```
my $server = TCP::LowLevel.new(:my-host('127.0.0.1'));

```

This is the source IP used to create the socket. It defaults to 0.0.0.0, which represents all IPv4 addresses on the system. You can set this to `::` if your host supports IPv6, to allow listenig on both IPv4 and IPv6 addresses.

Setting the value of this attribute is only supported at consturction time as an argument to the constructor.

## my-port

```
my $server = TCP::LowLevel.new(:my-port(55666));

```

This is the source port used to create the socket. It defaults to 0, meaning to assign a random source port. This is usually set if you desire to create a listening socket on a static port number.

Setting the value of this attribute is only supported at consturction time as an argument to the constructor.

## socket-port

```
my $port = $server.socket-port.result;

```

This contains a promise that is kept when the source port being actively used is known. This is useful when listening on a random port, to determine what port was selected. Note that this value will not necessaril be the same as the value of `my-port`, as `my-port` may be zero, while this will never return zero.

This value is not settable by the user.

## sock

This contains the socket object belonging to a current connection. It is not anticipated that this would be used directly.

# METHODS

## listen

```
$server.listen;

```

This creates a listening socket on the address specified by `my-host` and the port specified by `my-port`.

## acceptor

```
whenever $server.acceptor -> $conn { … }

```

This, when executed on a listening socket (one which you previously had called `listen()` on) will create a supply of connections, with a new connection emitted for every new connection.

## connect

```
my $conn = $client.connect('127.0.0.1', 8888).result;

```

Creates a TCP connection to the destination address and port provided. This returns a promise that when kept will contain the actual connection object.

## close

```
$server.close;

```

Closes a listening socket.

## add-md5($host, $key)

```
my $server = TCP::LowLevel.new;
$client-tcp.add-md5('127.0.0.1', $key);
$server-tcp.listen;

```

On Linux systems, this module supports RFC 2385 MD5 TCP authentication, which is often used for BGP connections.

It takes two parameters, the host that the MD5 key applies to and the actual key.

This can be used on inbound or outbound connections.

This will throw an exception if MD5 is not supported on the platform.

## supports-md5

```
die("No MD5 support") unless TCP::LowLevel.supports-md5;

```

Returns `True` if MD5 authentication is supported on the platform, `False` otherwise.

# USING CONNECTION OBJECTS

The objects returned by the `acceptor` Supply or the `connect()` Promise may be Raku native objects or the wrapper around the Linux networking libraries.

## METHODS

### Supply(:$bin?)

```
whenever $conn.Supply(:bin) -> $msg { … }

```

This returns a supply that emits received messages. If `:bin` is `True`, the messages are returned as `buf8` objects, othrwise they are returned as `Str` objects.

### print($msg)

```
$conn.print("Hello world!\n");

```

This sends a `Str` across the TCP session.

### write($msg)

```
$conn.write($msg)

```

This sends a `buf8` across the TCP session.

# AUTHOR

Joelle Maslak [jmaslak@antelope.net](mailto:jmaslak@antelope.net)

# COPYRIGHT AND LICENSE

Copyright © 2018-2022 Joelle Maslak

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


## dist_zef-CIAvash-T.md
# NAME

T - An easy way of writing test assertions which output good test descriptions and error messages

# DESCRIPTION

T is a [Raku](https://www.raku-lang.ir/en/) module for writing test
assertions which output good test descriptions and error messages.

It provides the `t` keyword for writing test assertions which takes an expression of form `<got> <infix> <expected>`.

Goals of the module:

* Write less but more readable test code
* Get a useful test description and failure message

# SYNOPSIS

```
use T:auth<zef:CIAash>;

t 4 == 4;
=output ok 1 - 4 == 4

t $my_great_module.return('something') eq 'something';
=output ok 2 - $my_great_module.return('something') eq 'something'

t $my_great_module.return('something else') eq 'something';
=output not ok 3 - $my_great_module.return('something else') eq 'something'
# Failed test '$my_great_module.return('something else') eq 'something''
# at ... line ...
# expected: "something"
#  matcher: 'infix:<eq>'
#      got: "something else"

```

# INSTALLATION

You need to have [Raku](https://www.raku-lang.ir/en) and [zef](https://github.com/ugexe/zef), then run:

```
zef install --/test "T:auth<zef:CIAvash>"

```

or if you have cloned the repo:

```
zef install .

```

# TESTING

```
prove6 -I. -v

```

or:

```
prove -ve 'raku -I.' --ext rakutest

```

# REPOSITORY

<https://codeberg.org/CIAvash/T/>

# BUG

<https://codeberg.org/CIAvash/T/issues>

# AUTHOR

Siavash Askari Nasr - <https://siavash.askari-nasr.com>

# COPYRIGHT

Copyright © 2022 Siavash Askari Nasr

# LICENSE

This file is part of T.

T is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at
yoption) any later version.

T is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.

You should have received a copy of the GNU Lesser General Public
License along with T. If not, see <http://www.gnu.org/licenses/>.


## dist_zef-amano.kenji-File-Name-Editor.md
# File::Name::Editor

Rename files in any text editor that you like.

Cyclic renames such as A to B, B to C, and C to A are possible.

## Programmatic Usage

```
use File::Name::Editor;

my @files = ("file1", "file2", ...);
my $editor = %*ENV<EDITOR>;
edit-file-names(@files, $editor);

```

If there are problems, exceptions are thrown. Catch exceptions if necessary.

```
edit-file-names(@files, $editor, :overwrite);

```

allows `File::Name::Editor` to overwrite files not in `@files`.

## Command Line Usage

```
file-name-editor

```

prints how to use it.

## Installation

You can install it with `zef`.

```
zef install File::Name::Editor

```

This installs file-name-editor in `~/.raku/bin` or some other place.

If your linux distribution has it, you can install it with your distribution's
package manager.


## dist_github-littlebenlittle-Stache.md
# Stache

> **nb**: This project currently has an unstable API! Minor version changes may break existing code.

Stache is an extensible mustache-style templating engine.

## Basic Use

Raku script:

```
use Stache;

my $template = q:to/EOT/;
say '> # This is some {{ lang }} code';
say '> {{ code }}';
say {{ code }};
EOT

say Stache::render(
    $template,
    lang => 'Raku',
    code => '1 + 1',
);

```

Output:

```
say '> # This is some Raku code';
say '> 1 + 1';
say 1 + 1;

```

## Structure Blocks

### With Blocks

Raku script:

```
use Stache;

my $template = q:to/EOT/;
{{ with A }}
name: {{ .name }}
type: {{ .type }}
{{ endwith }}
EOT

say Stache::render(
    $template,
    A => %(
        name => '楽',
        type => 'language',
    ),
);

```

Output:

```
name: 楽
type: language

```

### For Blocks

Raku script:

```
use Stache;

my $template = q:to/EOT/;
{{ for items }}
shape: {{ .shape }}
genus: {{ .holes }}

{{ endfor }}
EOT

say Stache::render(
    $template,
    items => [
        %(
            shape => 'sphere',
            holes => 0,
        ),
        %(
            shape => 'torus',
            holes => 1,
        ),
    ],
);

```

Output:

```
shape: sphere
genus: 0

shape: torus
genus: 1

```


## dist_zef-masukomi-Prettier-Table.md
# Name

`Prettier::Table`, a simple Raku module to make it quick and easy to represent tabular data in visually appealing ASCII tables.

By default it will generate tables using ASCII Box Drawing characters as show in the examples below. But you can also generate [GFM Markdown tables](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables), and MS Word Friendly tables by calling `$my_table.set-style('MARKDOWN')` or `$my_table.set-style('MSWORD-FRIENDLY')` Check out `demo.raku` to see this in action.

This is a fork of [Luis F Uceta's Prettier::Table](https://gitlab.com/uzluisf/raku-pretty-table) which is itself a port of the [Kane Blueriver's PTable library for Python](https://github.com/kxxoling/PTable).

# Synopsis

**Example 1**:

```
use Prettier::Table;

my $table = Prettier::Table.new:
    title => "Australian Cities",
    field-names => ["City name", "Area", "Population", "Annual Rainfall"],
    sort-by => 'Area',
    align => %('City name' => 'l'),
;

given $table {
    .add-row: ["Adelaide",  1295,  1158259,  600.5 ];
    .add-row: ["Brisbane",  5905,  1857594,  1146.4];
    .add-row: ["Darwin",    112,   120900,   1714.7];
    .add-row: ["Hobart",    1357,  205556,   619.5 ];
    .add-row: ["Sydney",    2058,  4336374,  1214.8];
    .add-row: ["Melbourne", 1566,  3806092,  646.9 ];
    .add-row: ["Perth",     5386,  1554769,  869.4 ];
}

say $table;

```

Output:

![actual rendering](https://github.com/masukomi/Prettier-Table/blob/images/images/australian_cities.png?raw=true)

(GitHub displays the raw text incorrectly)

```
    ┌─────────────────────────────────────────────────┐
    │                Australian Cities                │
    ├───────────┬──────┬────────────┬─────────────────┤
    │ City name │ Area │ Population │ Annual Rainfall │
    ├───────────┼──────┼────────────┼─────────────────┤
    │ Darwin    │ 112  │   120900   │      1714.7     │
    │ Adelaide  │ 1295 │  1158259   │      600.5      │
    │ Hobart    │ 1357 │   205556   │      619.5      │
    │ Melbourne │ 1566 │  3806092   │      646.9      │
    │ Sydney    │ 2058 │  4336374   │      1214.8     │
    │ Perth     │ 5386 │  1554769   │      869.4      │
    │ Brisbane  │ 5905 │  1857594   │      1146.4     │
    └───────────┴──────┴────────────┴─────────────────┘

```

**Example 2**:

```
use Prettier::Table;

my $table = Prettier::Table.new;

given $table {
    .add-column('Planet', ['Earth', 'Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']);
    .add-column('Position', [3, 1, 2, 4, 5, 6, 7, 8])
    .add-column('Known Satellites', [1, 0, 0, 2, 79, 82, 27, 14]);
    .add-column('Orbital period (days)', [365.256, 87.969, 224.701, 686.971, 4332.59, 10_759.22, 30_688.5, 60_182.0]);
    .add-column('Surface gravity (m/s)', [9.806, 3.7, 8.87, 3.721, 24.79, 10.44, 8.69, 11.15]);
}

$table.title('Planets in the Solar System');
$table.align(%(:Planet<l>));
$table.float-format(%('Orbital period (days)' => '-10.3f', 'Surface gravity (m/s)' => '-5.3f'));
$table.sort-by('Position');
# If you wish to change any of the characters used in the border
# you could do something like this.
# $table.junction-char('*');

put $table;

```

Output:

![actual rendering](https://github.com/masukomi/Prettier-Table/blob/images/images/planets_of_the_solar_system.png?raw=true)

(GitHub displays the raw text incorrectly)

```
    ┌────────────────────────────────────────────────────────────────────┐
    │                    Planets in the Solar System                     │
    ├─────────┬──────────┬───────────────────────┬───────────────────────┤
    │  Planet │ Position │ Orbital period (days) │ Surface gravity (m/s) │
    ├─────────┼──────────┼───────────────────────┼───────────────────────┤
    │  Earth  │    3     │        365.256        │         9.806         │
    │ Mercury │    1     │         87.969        │          3.7          │
    │  Venus  │    2     │        224.701        │          8.87         │
    │   Mars  │    4     │        686.971        │         3.721         │
    │ Jupiter │    5     │        4332.59        │         24.79         │
    │  Saturn │    6     │        10759.22       │         10.44         │
    │  Uranus │    7     │        30688.5        │          8.69         │
    │ Neptune │    8     │         60182         │         11.15         │
    └─────────┴──────────┴───────────────────────┴───────────────────────┘

```

# Installation

Using zef:

```
zef install Prettier::Table

```

From source:

```
$ git clone
$ cd raku-pretty-table
$ zef install .

```

# Quickstart

`Prettier::Table` supports two kinds of usage:

## As a module

```
use Prettier::Table;
my $x = Prettier::Table.new;

```

Check out the attributes in `Prettier::Table` to see the full list of things that can be set / configured. Most notably the `*-char` attributes, used to control the look of the border. Additionally, the named parameters in the `get-string` method.

## AUTHORS

* [Luis F Uceta's Prettier::Table](https://gitlab.com/uzluisf/raku-pretty-table)
* [masukomi](https://masukomi.org)

## LICENSE

MIT. See LICENSE file.

# Methods

## Getter and Setter Methods

**NOTE**: These methods's names are the same as their respective attributes. To set a specific attribute during the instantiation of a `Prettier::Table` object, use its method's name. For instance, to set `title`, `Prettier::Table.new(title => "Table's title")`. Thus, all methods listed here have an associated attribute that can be set during object construction.

### multi method field-names

```
multi method field-names() returns Array

```

Return a list of field names.

### multi method field-names

```
multi method field-names(
    @values
) returns Nil

```

Set a list of field names.

### multi method align

```
multi method align() returns Hash

```

Return how the alignment of fields is controlled.

### multi method align

```
multi method align(
    $val
) returns Nil

```

Set how the alignment of fields is controlled. Either an alignment string (l, c, or r) or a hash of field-to-alignment pairs.

### multi method valign

```
multi method valign() returns Hash

```

Return how the vertical alignment of fields is controlled.

### multi method valign

```
multi method valign(
    $val
) returns Nil

```

Set how the vertical alignment of fields is controlled. Either an alignment string (t, m, or b) or a hash of field-to-alignment pairs.

### multi method max-width

```
multi method max-width() returns Prettier::Table::Constrains::NonNeg

```

Return the maximum width of fields.

### multi method max-width

```
multi method max-width(
    $val where { ... }
) returns Nil

```

Set the maximum width of fields.

### multi method min-width

```
multi method min-width() returns Hash

```

Return the minimum width of fields.

### multi method min-width

```
multi method min-width(
    $val
) returns Nil

```

Set the minimum width of fields.

### multi method min-table-width

```
multi method min-table-width() returns Prettier::Table::Constrains::NonNeg

```

Return the minimum desired table width, in characters.

### multi method min-table-width

```
multi method min-table-width(
    $val where { ... }
) returns Mu

```

Set the minimum desired table width, in characters.

### multi method max-table-width

```
multi method max-table-width() returns Mu

```

Return the maximum desired table width, in characters.

### multi method max-table-width

```
multi method max-table-width(
    $val where { ... }
) returns Mu

```

Set the minimum desired table width, in characters.

### multi method fields

```
multi method fields() returns Array

```

Return the list of field names to include in displays.

### multi method fields

```
multi method fields(
    @values
) returns Mu

```

Return the list of field names to include in displays.

### multi method title

```
multi method title() returns Str

```

Return the table title (if existent).

### multi method title

```
multi method title(
    Str $val
) returns Mu

```

Set the table title.

### multi method start

```
multi method start() returns Prettier::Table::Constrains::NonNeg

```

Return the start index of the range of rows to print.

### multi method start

```
multi method start(
    $val where { ... }
) returns Mu

```

Set the start index of the range of rows to print.

### multi method end

```
multi method end() returns Mu

```

Return the end index of the range of rows to print.

### multi method end

```
multi method end(
    $val
) returns Mu

```

Set the end index of the range of rows to print.

### multi method sort-by

```
multi method sort-by() returns Mu

```

Return the name of field by which to sort rows.

### multi method sort-by

```
multi method sort-by(
    Str $val where { ... }
) returns Mu

```

Set the name of field by which to sort rows.

### multi method reverse-sort

```
multi method reverse-sort() returns Bool

```

Return the direction of sorting, ascending (False) vs descending (True).

### multi method reverse-sort

```
multi method reverse-sort(
    Bool $val
) returns Nil

```

Set the direction of sorting (ascending (False) vs descending (True).

### multi method sort-key

```
multi method sort-key() returns Callable

```

Return the sorting key function, applied to data points before sorting.

### multi method sort-key

```
multi method sort-key(
    &val
) returns Nil

```

Set the sorting key function, applied to data points before sorting.

### multi method header

```
multi method header() returns Bool

```

Return whether the table has a heading showing the field names.

### multi method header

```
multi method header(
    Bool $val
) returns Nil

```

Set whether the table has a heading showing the field names.

### multi method header-style

```
multi method header-style() returns Prettier::Table::Constrains::HeaderStyle

```

Return style to apply to field names in header ("cap", "title", "upper", or "lower").

### multi method header-style

```
multi method header-style(
    $val where { ... }
) returns Mu

```

Set style to apply to field names in header ("cap", "title", "upper", or "lower").

### multi method border

```
multi method border() returns Bool

```

Return whether a border is printed around table.

### multi method border

```
multi method border(
    Bool $val
) returns Mu

```

Set whether a border is printed around table.

### multi method hrules

```
multi method hrules() returns Prettier::Table::Constrains::HorizontalRule

```

Return how horizontal rules are printed after rows.

### multi method hrules

```
multi method hrules(
    $val where { ... }
) returns Mu

```

Set how horizontal rules are printed after rows. Allowed values: FRAME, ALL, HEADER, NONE

### multi method vrules

```
multi method vrules() returns Prettier::Table::Constrains::VerticalRule

```

Return how vertical rules are printed between columns.

### multi method vrules

```
multi method vrules(
    $val where { ... }
) returns Mu

```

Set how vertical rules are printed between columns. Allowed values: FRAME, ALL, NONE

### multi method int-format

```
multi method int-format() returns Mu

```

Return how the integer data is formatted.

### multi method int-format

```
multi method int-format(
    $val
) returns Nil

```

Set how the integer data is formatted. The value can either be a string or a hash of field-to-format pairs.

### multi method float-format

```
multi method float-format() returns Mu

```

Return how the integer data is formatted.

### multi method float-format

```
multi method float-format(
    $val
) returns Nil

```

Set how the integer data is formatted. The value can either be a string or a hash of field-to-format pairs.

### multi method padding-width

```
multi method padding-width() returns Prettier::Table::Constrains::NonNeg

```

Return the number of empty spaces between a column's edge and its content.

### multi method padding-width

```
multi method padding-width(
    $val where { ... }
) returns Nil

```

Set the number of empty spaces between a column's edge and its content.

### multi method left-padding-width

```
multi method left-padding-width() returns Prettier::Table::Constrains::NonNeg

```

Return the number of empty spaces between a column's left edge and its content.

### multi method left-padding-width

```
multi method left-padding-width(
    $val where { ... }
) returns Nil

```

Set the number of empty spaces between a column's left edge and its content.

### multi method right-padding-width

```
multi method right-padding-width() returns Prettier::Table::Constrains::NonNeg

```

Return the number of empty spaces between a column's right edge and its content.

### multi method right-padding-width

```
multi method right-padding-width(
    $val where { ... }
) returns Nil

```

Set the number of empty spaces between a column's right edge and its content.

### multi method vertical-char

```
multi method vertical-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw vertical lines.

### multi method vertical-char

```
multi method vertical-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw vertical lines.

### multi method horizontal-char

```
multi method horizontal-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw horizontal lines.

### multi method horizontal-char

```
multi method horizontal-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw horizontal lines.

### multi method junction-char

```
multi method junction-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw mid-line junctions.

### multi method junction-char

```
multi method junction-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw mid-line junctions.

### multi method left-junction-char

```
multi method left-junction-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw left-edge line junctions.

### multi method left-junction-char

```
multi method left-junction-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw left-edge line junctions.

### multi method right-junction-char

```
multi method right-junction-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw right-edge line junctions.

### multi method right-junction-char

```
multi method right-junction-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw right-edge line junctions.

### multi method top-junction-char

```
multi method top-junction-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw top edge mid-line junctions.

### multi method top-junction-char

```
multi method top-junction-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw top edge mid-line junctions.

### multi method bottom-junction-char

```
multi method bottom-junction-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw bottom edge mid-line junctions.

### multi method bottom-junction-char

```
multi method bottom-junction-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw bottom edge mid-line junctions.

### multi method bottom-left-corner-char

```
multi method bottom-left-corner-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw bottem edge left corners.

### multi method bottom-left-corner-char

```
multi method bottom-left-corner-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw bottom edge left corners.

### multi method bottom-right-corner-char

```
multi method bottom-right-corner-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw bottom right corners.

### multi method bottom-right-corner-char

```
multi method bottom-right-corner-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw bottom right corners.

### multi method top-left-corner-char

```
multi method top-left-corner-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to draw top left corners.

### multi method top-left-corner-char

```
multi method top-left-corner-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to top left corners.

### multi method top-right-corner-char

```
multi method top-right-corner-char() returns Prettier::Table::Constrains::Char

```

Return character used when printing table borders to top right corners.

### multi method top-right-corner-char

```
multi method top-right-corner-char(
    $val where { ... }
) returns Nil

```

Set character used when printing table borders to draw top right corners.

### multi method format

```
multi method format() returns Bool

```

Return whether or not HTML tables are formatted to match styling options.

### multi method format

```
multi method format(
    Bool $val
) returns Nil

```

Set whether or not HTML tables are formatted to match styling options.

### multi method print-empty

```
multi method print-empty() returns Bool

```

Return whether or not empty tables produce a header and frame or just an empty string.

### multi method print-empty

```
multi method print-empty(
    Bool $val
) returns Nil

```

Set whether or not empty tables produce a header and frame or just an empty string.

### multi method old-sort-slice

```
multi method old-sort-slice() returns Bool

```

Return whether to slice rows before sorting in the "old style".

### multi method old-sort-slice

```
multi method old-sort-slice(
    Bool $val
) returns Nil

```

Return whether to slice rows before sorting in the "old style".

## Style of Table

### multi method set-style

```
multi method set-style(
    TableStyle $style
) returns Nil

```

Set the style to be used for the table. Allowed values: DEFAULT: Show header and border, hrules and vrules are FRAME and ALL respectively, paddings are 1, ASCII Box Drawing characters used for borders. MSWORD-FRIENDLY: Show header and border, hrules is NONE, paddings are 1, and vert. char is | MARKDOWN: GitHub Flavored Markdown table. - Removes title, only hrule below column headers, paddings are 1, and vert. char is | PLAIN-COLUMNS: Show header and hide border, hrules is NONE, padding is 1, left padding is 0, and right padding is 8 RANDOM: random style

### method set-default-style

```
method set-default-style() returns Nil

```

Single character string used to draw vertical lines. Single character string used to draw horizontal lines. Single character string used to draw line junctions.

### method set-markdown-style

```
method set-markdown-style() returns Nil

```

modifies border characters to produce markdown output

## Data Input Methods

### method add-row

```
method add-row(
    @row
) returns Nil

```

Add a row to the table.

## class Mu $

Row of data, should be a list with as many elements as the table has fields.

### method del-row

```
method del-row(
    Int $row-index
) returns Nil

```

Delete a row from the table.

## class Mu $

Index of the row to delete (0-based index).

### method add-column

```
method add-column(
    Str $fieldname,
    @column,
    $align where { ... } = "c",
    $valign where { ... } = "m"
) returns Nil

```

Add a column to the table.

## class Mu $

Name of the field to contain the new column of data.

## class Mu $

Column of data, should be a list with as many elements as the table has rows.

## class Mu $

Desired alignment for this column - "l" (left), "c" (center), and "r" (right).

## class Mu $

Desired vertical alignment for new columns - "t" (top), "m" (middle), and "b" (bottom).

### method clear-rows

```
method clear-rows() returns Nil

```

Delete all rows from the table but keep the current field names.

### method clear

```
method clear() returns Nil

```

Delete all rows and field names from the table, maintaining nothing but styling options.

## Plain Text String methods

### method get-string

```
method get-string(
    Str :$title = Str,
    :$start where { ... } = Prettier::Table::Constrains::NonNeg,
    :$end where { ... } = Prettier::Table::Constrains::NonNeg,
    :@fields,
    Bool :$header = Bool,
    Bool :$border = Bool,
    :$hrules where { ... } = Prettier::Table::Constrains::HorizontalRule,
    :$vrules where { ... } = Prettier::Table::Constrains::VerticalRule,
    Str :$int-format = Str,
    Str :$float-format = Str,
    :$padding-width where { ... } = Prettier::Table::Constrains::NonNeg,
    :$left-padding-width where { ... } = Prettier::Table::Constrains::NonNeg,
    :$right-padding-width where { ... } = Prettier::Table::Constrains::NonNeg,
    :$vertical-char where { ... } = Prettier::Table::Constrains::Char,
    :$horizontal-char where { ... } = Prettier::Table::Constrains::Char,
    :$junction-char where { ... } = Prettier::Table::Constrains::Char,
    :$left-junction-char where { ... } = Prettier::Table::Constrains::Char,
    :$right-junction-char where { ... } = Prettier::Table::Constrains::Char,
    :$top-junction-char where { ... } = Prettier::Table::Constrains::Char,
    :$bottom-junction-char where { ... } = Prettier::Table::Constrains::Char,
    :$bottom-left-corner-char where { ... } = Prettier::Table::Constrains::Char,
    :$bottom-right-corner-char where { ... } = Prettier::Table::Constrains::Char,
    :$top-left-corner-char where { ... } = Prettier::Table::Constrains::Char,
    :$top-right-corner-char where { ... } = Prettier::Table::Constrains::Char,
    Str :$sort-by = Str,
    :&sort-key,
    Bool :$reverse-sort = Bool,
    Bool :$old-sort-slice = Bool,
    Bool :$print-empty = Bool
) returns Str

```

Return string representation of table in current state.

## class Mu $

See method title

## class Mu $

See method start

## class Mu $

See method end

## class Mu $

See method fields

## class Mu $

See method header

## class Mu $

See method border

## class Mu $

See method hrules

## class Mu $

See method vrules

## class Mu $

See method int-format

## class Mu $

See method float-format

## class Mu $

See method padding-width

## class Mu $

See method left-padding-width

## class Mu $

See method right-padding-width

## class Mu $

See method vertical-char

## class Mu $

See method horizontal-char

## class Mu $

See method junction-char

## class Mu $

See method junction-char

## class Mu $

See method right-junction-char

## class Mu $

See method top-junction-char

## class Mu $

See method bottom-junction-char

## class Mu $

See method bottom-left-corner-char

## class Mu $

See method bottom-right-corner-char

## class Mu $

See method top-left-corner-char

## class Mu $

See method top-right-corner-char

## class Mu $

See method sort-by

## class Mu $

See method sort-key

## class Mu $

See method reverse-sort

## class Mu $

see method old-sort-slice

## class Mu $

See method print-empty

## Miscellaneous Methods

### method row-count

```
method row-count() returns Int

```

Return the number of rows.

### method col-count

```
method col-count() returns Int

```

Return the number of columns.

### method slice

```
method slice(
    *@indices
) returns Prettier::Table

```

Return a sliced-off new Prettier::Table. The indices must between 0 and the table's number of rows (exclusive). Alternatively, the postcircumfix operator [] can be used.