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

# NAME

Terminal::LineEditor - Generalized terminal line editing

# SYNOPSIS

```
### PREP

use Terminal::LineEditor;
use Terminal::LineEditor::RawTerminalInput;

# Create a basic CLI text input object
my $cli = Terminal::LineEditor::CLIInput.new;

### BASICS

# Preload some input history
$cli.load-history($history-file);
$cli.add-history('synthetic input', 'more synthetic input');

# Prompt for input, supporting common edit commands,
# scrolling the field to stay on one line
my $input = $cli.prompt('Please enter your thoughts: ');

# Prompt for a password, masking with asterisks (suppresses history)
my $pass  = $cli.prompt('Password: ', mask => '*');

# Prompt defaults to empty
my $stuff = $cli.prompt;

# Review and save history
.say for $cli.history;
$cli.save-history($history-file);

### TYPICAL USE

loop {
    # Get user's input
    my $in = $cli.prompt("My prompt >");

    # Exit loop if user indicated finished
    last without $in;

    # Add line to history if it is non-empty
    $cli.add-history($in) if $in.trim;

    # Do something with the input line; here we just echo it
    say $in;
}

```

# DESCRIPTION

`Terminal::LineEditor` is a terminal line editing package similar to `Linenoise` or `Readline`, but **not** a drop-in replacement for either of them. `Terminal::LineEditor` has a few key design differences:

* Implemented in pure Raku; `Linenoise` and `Readline` are NativeCall wrappers.
* Features strong separation of concerns; all components are exposed and replaceable.
* Useable both directly for simple CLI apps and embedded in TUI interfaces.

## Use with Rakudo REPL

A [PR for Rakudo](https://github.com/rakudo/rakudo/pull/4623) has been created to allow `Terminal::LineEditor` to be used as the REPL line editor when Rakudo is used in interactive mode. If your Rakudo build includes this PR, you can set the following in your environment to use `Terminal::LineEditor` by default:

```
export RAKUDO_LINE_EDITOR=LineEditor

```

If the environment variable is *not* specified, but `Terminal::LineEditor` is the only line editing module installed, Rakudo will auto-detect and enable it.

## Default Keymap

The latest version of the default keymap is specified in `Terminal::LineEditor::KeyMappable.default-keymap()`, but the below represents the currently implemented, commonly used keys:

Commonly Used Keys

| KEY | FUNCTION | NOTES |
| --- | --- | --- |
| Ctrl-A | move-to-start |  |
| Ctrl-B | move-char-back |  |
| Ctrl-C | abort-input |  |
| Ctrl-D | abort-or-delete | Abort if empty, or delete-char-forward |
| Ctrl-E | move-to-end |  |
| Ctrl-F | move-char-forward |  |
| Ctrl-H | delete-char-back |  |
| Ctrl-J | finish | LF (Line Feed) |
| Ctrl-K | delete-to-end |  |
| Ctrl-L | refresh-all |  |
| Ctrl-M | finish | CR (Carriage Return) |
| Ctrl-N | history-next |  |
| Ctrl-P | history-prev |  |
| Ctrl-T | swap-chars |  |
| Ctrl-U | delete-to-start |  |
| Ctrl-V | literal-next |  |
| Ctrl-W | delete-word-back |  |
| Ctrl-Y | yank |  |
| Ctrl-Z | suspend |  |
| Ctrl-\_ | undo | Ctrl-Shift-<hyphen> on some keyboards |
| Backspace | delete-char-back |  |
| CursorLeft | move-char-back |  |
| CursorRight | move-char-forward |  |
| CursorHome | move-to-start |  |
| CursorEnd | move-to-end |  |
| CursorUp | history-prev |  |
| CursorDown | history-next |  |
| Alt-b | move-word-back |  |
| Alt-c | tclc-word | Readline treats this as Capitalize |
| Alt-d | delete-word-forward |  |
| Alt-f | move-word-forward |  |
| Alt-l | lowercase-word |  |
| Alt-t | swap-words |  |
| Alt-u | uppercase-word |  |
| Alt-< | history-start | Alt-Shift-<comma> on some keyboards |
| Alt-> | history-end | Alt-Shift-<period> on some keyboards |

All bindable edit functions are defined in the `Terminal::LineEditor::SingleLineTextInput` role (in each corresponding method beginning with `edit-`) or is one of the following special actions:

Special Actions

| ACTION | MEANING |
| --- | --- |
| abort-input | Throw away input so far and return an undefined Str |
| abort-or-delete | abort-input if empty, otherwise delete-char-forward |
| finish | Accept and return current input line |
| literal-next | Insert a literal control character into the buffer |
| suspend | Suspend the program with SIGTSTP, wait for SIGCONT |
| history-start | Switch input to first line in history |
| history-prev | Switch input to previous line in history |
| history-next | Switch input to next line in history |
| history-end | Switch input to last line in history (the partial input) |

## Architecture

`Terminal::LineEditor` is built up in layers, starting from the most abstract:

* `EditableBuffer` -- Basic interface role for editable buffers of all sorts
* `SingleLineTextBuffer` -- An `EditableBuffer` that knows how to apply simple insert/delete/replace operations at arbitrary positions/ranges, tracks a yank item (the most recently deleted text), and creates and manages undo/redo information to allow infinite undo
* `SingleLineTextBuffer::Cursor` -- A cursor class that knows how to move around within a `SingleLineTextBuffer` without moving outside the content area, and knows whether edit operations should automatically adjust its position
* `SingleLineTextBuffer::WithCursors` -- A wrapper of `SingleLineTextBuffer` that supports multiple simultaneous cursors, and handles automatically updating them appropriately whenever applying a basic edit operation
* `SingleLineTextInput` -- An input field role that tracks its own insert position as an auto-updating cursor, and provides a range of edit methods that operate relative to the current insert position
* `ScrollingSingleLineInput` -- A `SingleLineTextInput` that knows how to scroll within a limited horizontal display width to ensure that the insert position is always visible, no longer how long the input
* `ScrollingSingleLineInput::ANSI` -- A further extension of `ScrollingSingleLineInput` that is aware of cursor position and movement using ANSI/VT escape codes
* `CLIInput` -- A driver for `ScrollingSingleLineInput::ANSI` that deals with raw terminal I/O, detects terminal size and cursor position, supports a control key map for common edit operations, and handles suspend/resume without corrupting terminal state

## Edge Cases

There are a few edge cases for which `Terminal::LineEditor` chose one of several possible behaviors. Here's the reasoning for each of these otherwise arbitrary decisions:

* Attempting to apply an edit operation or create a new cursor outside the buffer contents throws an exception, because these indicate a logic error elsewhere.
* Attempting to move a previously correct cursor outside the buffer contents silently clips the new cursor position to the buffer endpoints, because users frequently hold down cursor movement keys (and thus repeatedly try to move past an endpoint).
* Undo'ing a delete operation, where one or more cursors were within the deleted region, results in all such cursors moving to the end of the undo; this is consistent with the behavior of an insert operation at the same position as the delete undo.
* For the same reason as for delete operations, replace operations that overlap cursor locations will move them to the end of the replaced text.

## Unmapped Functionality

Some of the functionality supported by lower layers of `Terminal::LineEditor` is not exposed in the default keymap of `Terminal::LineEditor::KeyMappable`. This is generally because no commonly-agreed shell keys map to this functionality.

For example, `Terminal::LineEditor::SingleLineTextBuffer` can treat replace as an atomic operation, but basic POSIX shells generally don't; they instead expect the user to delete and insert as separate operations.

That said, if I've missed a commonly-supported key sequence for any of the unmapped functionality, please open an issue for this repository with a link to the relevant docs so I can expand the default keymap.

# AUTHOR

Geoffrey Broadwell [gjb@sonic.net](mailto:gjb@sonic.net)

# COPYRIGHT AND LICENSE

Copyright 2021-2024 Geoffrey Broadwell

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


## classhow.md
class Metamodel::ClassHOW

Metaobject representing a Raku class.

```raku
    class Metamodel::ClassHOW
        does Metamodel::Naming
        does Metamodel::Documenting
        does Metamodel::Versioning
        does Metamodel::Stashing
        does Metamodel::AttributeContainer
        does Metamodel::MethodContainer
        does Metamodel::PrivateMethodContainer
        does Metamodel::MultiMethodContainer
        does Metamodel::RoleContainer
        does Metamodel::MultipleInheritance
        does Metamodel::DefaultParent
        does Metamodel::C3MRO
        does Metamodel::MROBasedMethodDispatch
        does Metamodel::MROBasedTypeChecking
        does Metamodel::Trusting
        does Metamodel::BUILDPLAN
        does Metamodel::Mixins
        does Metamodel::ArrayType
        does Metamodel::BoolificationProtocol
        does Metamodel::REPRComposeProtocol
        does Metamodel::Finalization
            { }

```

*Warning*: this class is part of the Rakudo implementation, and is not a part of the language specification.

`Metamodel::ClassHOW` is the metaclass behind the `class` keyword.

```raku
say so Int.HOW ~~ Metamodel::ClassHOW;    # OUTPUT: «True␤»
say Int.^methods(:all).pick.name;         # OUTPUT: «random Int method name␤»
```

# [Methods](#class_Metamodel::ClassHOW "go to top of document")[§](#Methods "direct link")

## [method add\_fallback](#class_Metamodel::ClassHOW "go to top of document")[§](#method_add_fallback "direct link")

```raku
method add_fallback($obj, $condition, $calculator)
```

Installs a method fallback, that is, add a way to call methods that weren't statically added.

Both `$condition` and `$calculator` must be callables that receive the invocant and the method name once a method is called that can't be found in the method cache.

If `$condition` returns a true value, `$calculator` is called with the same arguments, and must return the code object to be invoked as the method, and is added to the method cache.

If `$condition` returns a false value, the next fallback (if any) is tried, and if none matches, an exception [of type X::Method::NotFound](/type/X/Method/NotFound) is thrown.

User-facing code (that is, code not dabbling with metaclasses) should use method `FALLBACK` instead.

## [method can](#class_Metamodel::ClassHOW "go to top of document")[§](#method_can "direct link")

```raku
method can($obj, $method-name)
```

Given a method name, it returns a [`List`](/type/List) of methods that are available with this name.

```raku
class A      { method x($a) {} };
class B is A { method x()   {} };
say B.^can('x').elems;              # OUTPUT: «2␤»
for B.^can('x') {
    say .arity;                     # OUTPUT: «1, 2␤»
}
```

In this example, class `B` has two possible methods available with name `x` (though a normal method call would only invoke the one installed in `B` directly). The one in `B` has arity 1 (i.e. it expects one argument, the invocant (`self`)), and the one in `A` expects 2 arguments (`self` and `$a`).

## [method lookup](#class_Metamodel::ClassHOW "go to top of document")[§](#method_lookup "direct link")

```raku
method lookup($obj, $method-name --> Method:D)
```

Returns the first matching [`Method`](/type/Method) with the provided name. If no method was found, returns a VM-specific sentinel value (typically a low-level NULL value) that can be tested for with a test for [definedness](/routine/defined). It is potentially faster than `.^can` but does not provide a full list of all candidates.

```raku
    say Str.^lookup('Int').raku; # OUTPUT: «method Int (Str:D $: *%_) { #`(Method|39910024) ... }␤»

    for <uppercase  uc> {
        Str.^lookup: $^meth andthen .("foo").say
            orelse "method `$meth` not found".say
    }
    # OUTPUT:
    # method `uppercase` not found
    # FOO

```

## [method compose](#class_Metamodel::ClassHOW "go to top of document")[§](#method_compose "direct link")

```raku
method compose($obj)
```

A call to `compose` brings the metaobject and thus the class it represents into a fully functional state, so if you construct or modify a class, you must call the compose method before working with the class.

It updates the method cache, checks that all methods that are required by roles are implemented, does the actual role composition work, and sets up the class to work well with language interoperability.

## [method new\_type](#class_Metamodel::ClassHOW "go to top of document")[§](#method_new_type "direct link")

```raku
method (:$name, :$repr = 'P6opaque', :$ver, :$auth)
```

Creates a new type from the metamodel, which we can proceed to build

```raku
my $type = Metamodel::ClassHOW.new_type(name => "NewType",
                                        ver => v0.0.1,
                                        auth => 'github:raku' );
$type.HOW.add_method($type,"hey", method { say "Hey" });
$type.hey;     # OUTPUT: «Hey␤»
$type.HOW.compose($type);
my $instance = $type.new;
$instance.hey; # OUTPUT: «Hey␤»
```

We add a single method by using [Higher Order Workings](/language/mop#HOW) methods, and then we can use that method directly as class method; we can then `compose` the type, following which we can create already an instance, which will behave in the exact same way.


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

# NAME

Reaper::Control - An OSC controller interface for Reaper

# SYNOPSIS

```
use Reaper::Control;

# Start listening for UDP messages from sent from Reaper.
my $listener = reaper-listener(:host<127.0.0.1>, :port(9000));

# Respond to events from Reaper:
react whenever $listener.reaper-events {
    when Reaper::Control::Event::Play {
        put 'Playing'
    }
    when Reaper::Control::Event::Stop {
        put 'stopped'
    }
    when Reaper::Control::Event::PlayTime {
        put "seconds: { .seconds }\nsamples: { .samples }\nbeats: { .beats }"
    }
    when Reaper::Control::Event::Mixer {
        put "levels: ", join ',', .master.vu, .tracks.map( *.vu ).Slip
    }
    when Reaper::Control::Event::Unhandled {
        .perl.say
    }
}

```

# DESCRIPTION

Reaper::Control is an [OSC controller interface](https://www.reaper.fm/sdk/osc/osc.php) for [Reaper](https://www.reaper.fm), a digital audio workstation. Current features are limited and relate to listening for play/stop, playback position and mixer levels but there is a lot more which can be added in the future.

To start listening call the `reaper-listener` subroutine, you can then obtain a `Supply` of events from the listener's `.reaper-events` method. All events emitted from the supply are subclasses of the `Reaper::Control::Event` role. Messages not handled by the default message handler are emitted as `Reaper::Control::Unhandled` objects, their contents can be accessed in the message attribute.

To skip the default message handler you may instead tap the lister's `.reaper-raw` method. This supply emits `Net::OSC::Bundle` objects, see the Net::OSC module for more on this object.

# AUTHOR

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

# COPYRIGHT AND LICENSE

Copyright 2018 Sam Gillespie

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

### sub reaper-listener

```
sub reaper-listener(
    Str :$host,
    Int :$port,
    Str :$protocol = "UDP"
) returns Reaper::Control::Listener

```

Create a Listener object which encapsulates message parsing and event parsing. The protocol argument currently only accepts UDP. Use the reaper-events method to obtain a Supply of events received, by the Listener, from Reaper.

### Reaper::Control::Listener

This class bundles up a series of tapped supplies which define a listener workflow. To construct a new listener call the listener-udp method to initialise a UDP listener workflow.

### Reaper::Control::Event

Base class for all reaper events. No functionality here, just an empty class.

### Reaper::Control::Event::PlayState

An abstract class defining the methods of Play and Stop classes. Use this type if you need to accept either Play or Stop objects.

### Reaper::Control::Event::Play

The Play version of the PlayState role. This object is emitted when playback is started.

### Reaper::Control::Event::Stop

The Stop version of the PlayState role. This object is emitted when playback is stopped.

### Reaper::Control::Event::PlayTime

This message bundles up elapsed seconds, elapsed samples and a string of the current beat position.

### Reaper::Control::Event::Level

This message bundles up audio levels from the mixer.

### Reaper::Control::Event::Mixer

This message bundles up audio level information from the mixer. Master level is held in the master attribute and tracks are stored in the tracks attribute.

### Reaper::Control::Event::Unhandled

A generic wrapper for messages not handled by the core interface


## dist_zef-bduggan-WebService-Nominatim.md
[![Actions Status](https://github.com/bduggan/raku-webservice-nominatim/actions/workflows/linux.yml/badge.svg)](https://github.com/bduggan/raku-webservice-nominatim/actions/workflows/linux.yml)
[![Actions Status](https://github.com/bduggan/raku-webservice-nominatim/actions/workflows/macos.yml/badge.svg)](https://github.com/bduggan/raku-webservice-nominatim/actions/workflows/macos.yml)

# NAME

WebService::Nominatim - Client for the OpenStreetMap Nominatim Geocoding API

# SYNOPSIS

```
use WebService::Nominatim;

my \n = WebService::Nominatim.new;

say n.search('Grand Central Station').first.<name lat lon>;
# (Grand Central Terminal 40.75269435 -73.97725295036929)

my $geo = n.search: '221B Baker Street, London, UK';
my $geo = n.search: query => '221B Baker Street, London, UK';
my $geo = n.search: query => { street => '221B Baker Street', city => 'London', country => 'UK' };
say $geo.head.<lat lon>;
# (51.5233879 -0.1582367)

say n.search: 'Grand Place, Brussels', :format<geojson>, :raw;
{"type":"FeatureCollection", ...

```

```

{"type":"FeatureCollection","licence":"Data © OpenStreetMap contributors, ODbL 1.0. http://osm.org/copyright","features":[{"type":"Feature","properties":{"place_id":97663568,"osm_type":"way","osm_id":991425177,"place_rank":25,"category":"boundary","type":"protected_area","importance":0.4874302285645721,"addresstype":"protected_area","name":"Grand-Place - Grote Markt","display_name":"Grand-Place - Grote Markt, Quartier du Centre - Centrumwijk, Pentagone - Vijfhoek, Bruxelles - Brussel, Brussel-Hoofdstad - Bruxelles-Capitale, Région de Bruxelles-Capitale - Brussels Hoofdstedelijk Gewest, 1000, België / Belgique / Belgien"},"bbox":[4.3512177,50.8460246,4.3537194,50.8474356],"geometry":{"type": "Point","coordinates": [4.352408060161565, 50.84672905]}}]}

```

# DESCRIPTION

This is an interface to OpenStreetMap's Nominatim Geocoding API, <https://nominatim.org>.

# EXPORTS

```
use WebService::Nominatim;
my \n = WebService::Nominatim.new;

```

Equivalent to:

```
use WebService::Nominatim 'n';

```

Add debug output:

```
use WebService::Nominatim 'n' '-debug';

```

If an argument is provided, a new instance will be returned. If `-debug` is provided, the instance will send logs to stderr. Note this is different from the `debug` attribute, which gets debug information from the server.

# ATTRIBUTES

## url

The base URL for the Nominatim API. Defaults to `https://nominatim.openstreetmap.org`.

## email

The email address to use in the `email` query parameter. Optional, but recommended if you are sending a lot of requests.

## debug

Optionally send debug => 1 in search requests. Responses will be HTML.

## dedupe

Optionally send dedupe => 1 to search request.

# EXPORTS

If an argument is given to the module, it is assumed to be a name and the module creates a new `WebService::Nominatim` object. Also "-debug" will send debug output to stderr. These are equivalent:

```
use WebService::Nominatim 'nom', '-debug';

```

and

```
use WebService::Nominatim;;
my \nom = WebService::Nominatim.new;
nom.logger.send-to: $*ERR;

```

# METHODS

## search

Search for a location using either a string search or a structured search. This will always return a list. The items in the list may be strings or hashes, depending on the format (json formats will be parsed into hashes). Use `:raw` to return strings.

### Usage

```
$n.search('Grand Central Station');
say .<display_name> for $n.search: 'Main St', :limit(5);
$n.search: '221B Baker Street, London, UK';
$n.search: query => '221B Baker Street, London, UK';
$n.search: query => { street => '221B Baker Street', city => 'London', country => 'UK' }, limit => 5;

```

### Parameters

See <https://nominatim.org/release-docs/develop/api/Search/> for details about meanings of the parameters.

* `$query`

  The search query. This can be a string or a hash of search parameters.
  It can be a named parameter, or the first positional parameter.
* `:raw`

  If set to a true value, the raw response will be returned as a string, without JSON parsing.
* `:format`

  The format of the response. Defaults to jsonv2. Other options are xml, json, geojson, and geocodejson.

Other parameters:

* `:layer`
* `:featureType`
* `:addressdetails`
* `:limit`
* `:extratags`
* `:namedetails`
* `:accept-language`
* `:countrycodes`
* `:exclude_place_ids`
* `:viewbox`
* `:bounded`
* `:polygon_geojson`
* `:polygon_kml`
* `:polygon_svg`
* `:polygon_text`
* `:polygon_threshold`

## lookup

Look up an object.

```
say n.lookup('R1316770', :format<geojson>);
say n.lookup(relation-id => '1316770', :format<geojson>);
say n.lookup(relation-ids => [ 1316770, ], :format<geojson>, :polygon_geojson);

```

### Parameters

Many of the same parameters as `search` are available.

Additionally, `node-ids`, `way-ids`, and `relation-ids` can be used to look up multiple objects. And `node-id`, `way-id`, and `relation-id` can be used to look up a single object.

See <https://nominatim.org/release-docs/develop/api/Lookup/> for more details.

## status

Get the status of the Nominatim server.

```
say n.status;

```

# SEE ALSO

<https://nominatim.org/release-docs/develop/api/Search/>

# AUTHOR

Brian Duggan


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

# NAME

Raku port of Perl's List::AllUtils module 0.14

# SYNOPSIS

```
use List::AllUtils qw( first any );

# _Everything_ from List::Util, List::MoreUtils, and List::UtilsBy
use List::AllUtils qw( :all );

my @numbers = ( 1, 2, 3, 5, 7 );
# or don't import anything
return List::AllUtils::first { $_ > 5 } @numbers;

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `List::AllUtils` module as closely as possible in the Raku Programming Language.

Are you sick of trying to remember whether a particular helper is defined in List::Util, List::MoreUtils or List::UtilsBy? Now you don't have to remember. This module will export all of the functions that either of those three modules defines.

## Which One Wins?

`List::AllUtils` always favors the version provided by List::Util, List::MoreUtils or List::UtilsBy in that order.

## Where is the documentation?

Rather than copying the documentation and running the risk of getting out of date, please check the original documentation using the following mapping:

### List::Util

```
all any first max maxstr min minstr none notall pairfirst pairgrep pairkeys
pairmap pairs pairvalues product reduce shuffle sum sum0 uniq uniqnum uniqstr
unpairs

```

### List::MoreUtils

```
after after_incl all_u any_u apply arrayify before before_incl binsert
bremove bsearch bsearch_index bsearch_insert bsearch_remove bsearchidx
distinct duplicates each_array each_arrayref equal_range false first_index
first_result first_value firstidx firstres firstval frequency indexes
insert_after insert_after_string last_index last_result last_value lastidx
lastres lastval listcmp lower_bound mesh minmax minmaxstr mode natatime
none_u notall_u nsort_by occurrences one one_u only_index only_result
only_value onlyidx onlyres onlyval pairwise part qsort reduce_0 reduce_1
reduce_u samples singleton sort_by true upper_bound zip zip6 zip_unflatten

```

### List::UtilsBy

```
bundle_by count_by extract_by extract_first_by max_by min_by minmax_by
nmax_by nmin_by nminmax_by partition_by rev_nsort_by rev_sort_by uniq_by
unzip_by weighted_shuffle_by zip_by

```

# AUTHOR

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

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

# COPYRIGHT AND LICENSE

Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen

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

Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version developed by Dave Rolsky.


## dist_zef-tony-o-System-Query.md
# WELCOME TO WARTHOG

I does build decisions.

## Usage

```
use System::Query;
use JSON::Fast;

my $json      = from-json("build.json".IO.slurp);
my $decisions = system-collapse($json);

qw<...>;

```

## Input

Calling `parse` with the following JSON will run through and choose what it thinks is the best options in the environment.

```
{
  "nested": {
    "test": "data"
  },
  "nested2": {
    "test2": "data2"
  },
  "options": {
    "run": {
      "by-distro.name": {
        "macosx": {
          "by-distro.version": {
            "10.0+": "10make",
            "9.0+": "9make",
            "8.0+": "8make"
          }
        },
        "win32": {
          "by-distro.version": {
            "6+": "6winmake",
            "5+": "5winmake"
          }
        },
        "": "null-make"
      }
    }
  },
  "default-test": {
    "second-test": "string-val, no decisions",
    "first-test": {
      "by-distro.name": {
        "": "default-option1"
      }
    }
  }
}

```

## Output

This is the result of the parse; notice that the distro/kernel/etc queries collapse to show the decisions based on variables.

```
{
  default-test => {
    first-test  => "default-option1".Str,
    second-test => "string-val, no decisions".Str,
  },
  nested       => {
    test => "data".Str,
  },
  nested2      => {
    test2 => "data2".Str,
  },
  options      => {
    run => "10make".Str,
  },
}

```


## dist_cpan-JMERELO-Pod-Load.md
[![Build Status](https://travis-ci.com/JJ/p6-pod-load.svg?branch=master)](https://travis-ci.com/JJ/p6-pod-load) [![Build status](https://ci.appveyor.com/api/projects/status/lq9rqjq6hljdfqw4?svg=true)](https://ci.appveyor.com/project/JJ/p6-pod-load)

# NAME

Pod::Load - Loads and compiles the Pod documentation of an external file

# SYNOPSIS

```
use Pod::Load;

# Read a file handle.
my $pod = load("file-with.pod6".IO);
say $pod.perl; # Process it as a Pod

# Or use simply the file name
my @pod = load("file-with.pod6");
say .perl for @pod;

my $string-with-pod = q:to/EOH/;

```

This ordinary paragraph introduces a code block:

EOH

```
say load( $string-with-pod ).perl;

```

# DESCRIPTION

Pod::Load is a module with a simple task: obtain the documentation of an external file in a standard, straighworward way. Its mechanism is inspired by [`Pod::To::BigPage`](https://github.com/perl6/perl6-pod-to-bigpage), from where the code to use the cache is taken from.

### multi sub load

```
multi sub load(
    Str $string
) returns Mu

```

Loads a string, returns a Pod.

### multi sub load

```
multi sub load(
    Str $file where { ... }
) returns Mu

```

If it's an actual filename, loads a file and returns the pod

### multi sub load

```
multi sub load(
    IO::Path $io
) returns Mu

```

Loads a IO::Path, returns a Pod.

# INSTRUCTIONS

This is mainly a reminder to myself, although it can help you if you create a distribution just like this one.

Write:

```
export VERSION=0.x.x

```

And

```
make dist

```

To create a tar file ready for CPAN.

# AUTHOR

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

# COPYRIGHT AND LICENSE

Copyright 2018, 2019 JJ Merelo

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


## dist_zef-tony-o-Mux.md
# mux

use this to obtain great parallel powers. also to alleviate the headache that comes with queues and managing workers.

## Mux.new(:callable, :channels)

`:callable` should be something callable. this is the method you write that is going to do all of your work for you and it should take one argument. eg. `sub ($elem) { }`

`:channels` this should be the maximum level of parallelization that you'd like. defaults to `int(max_threads / 1.5)`. this will warn but not puke if you specify higher than max\_threads parallelization and be warned that if you exceed the scheduler you may find your application locked.

## .demux(callable)

this sets what demuxes the return values from your workers should you so need them.

```
my Mux $m .=new(
  :callable(sub (Int() $x) { $x * 2; }),
);

$m.demux(-> $rval {
  #rval will be 2, then 2, then 4, then 6, etc
});

$q.start: 1,1,2,3; #etc;

```

## .error(callable)

this is a `sub ($error) { }` to be called when there is an unhandled error in the worker (if it's not in your sub then please open a ticket).

## .drain(callable)

this is a `sub (Mux:D) { }` called when the work queue is complete.

## .pause

for pausing the queue, you can still feed the muxer but don't put your fingers in its mouth.

## .paused

will let you know if the muxer is paused

## .unpause

let's the hedonistic muxer consume

## .unpaused

lets you know whether you should keep your hands away from the cage

## .block

finally, if you want to block until the muxer is done processing the queue

## .feed(\*@ )

you can feed the muxer while its running, this will not reset the queue or alter current processing but it will cause `.drain` to be called later


## dist_github-codesections-Pod-Weave.md
[![Actions Status](https://github.com/codesections/pod-weave/workflows/test/badge.svg)](https://github.com/codesections/pod-weave/actions)

# NAME

Pod::Weave - Weave documentation from Raku source

# SYNOPSIS

Installation (assuming you already have Raku and [zef](https://github.com/ugexe/zef) installed):

```
zef install Pod::Weave

```

You can use Pod::Weave via it's command-line tool, `pod-weave`

```
pod-weave source.raku > woven.md

```

# DESCRIPTION

Pod::Weave renders documentation from Raku source files. The documentation consists of formatted pod blocks interwoven with formatted code blocks containing all of the source code from the Raku file. The goal of doing so is to support basic [literate programming](https://en.wikipedia.org/wiki/Literate_programming) in Raku. You can use Pod::Weave to generate any of the output formats located in the Pod::Weave::To module.

For additional details, please see the announcement blog post: [www.codesections.com/blog/weaving-raku](https://www.codesections.com/blog/weaving-raku).

# AUTHOR

codesections [daniel@codesections.com](mailto:daniel@codesections.com)

# COPYRIGHT AND LICENSE

ⓒ 2020 Daniel Sockwell

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


## announcements.md
Announcements page

A date-stamped list of notes relevant to the Raku documentation site.

This Block name is not known, could be a typo or missing plugin

# [Note](#Announcements_page "go to top of document")

Contents are

An announcements page is now available. The most recent announcement will pop up when the website is loaded, but it will not appear again.

Announcements can contain all the RakuDoc elements, including:

* lists as here
* format / markup codes such `inline code`, **bolded text**, *Italics*, ***bolded italics***.

The only constraint is how much space is used in the popup.


## dist_github-nige123-jmp.md
# jmp.nigelhamilton.com

jmp - jump to files in your workflow

Usage:

```
jmp                                         -- show most recent
jmp to '[<search-terms> ...]'               -- lines matching search terms in files

# jmp on files in command output. For example:
jmp locate README                           -- files in the filesystem
jmp tail /some.log                          -- files mentioned in log files
jmp ls                                      -- files in a directory
jmp find .                                  -- files returned from the find command
jmp git status                              -- files in git
jmp perl test.pl                            -- Perl output and errors
jmp raku test.raku                          -- Raku output and errors

jmp config                                  -- edit ~/.jmp config to set the editor
                                            -- and search commands
jmp help                                    -- show this help

jmp edit <filename> [<line-number>]         -- start editing at a line number
jmp edit <filename> '[<search-terms> ...]'  -- start editing at a matching line

```

![](images/demo.gif?raw=true)


## dist_cpan-TYIL-Ops-SI.md
# Ops::SI

Add postfix operators for [SI
prefixes](https://en.wikipedia.org/wiki/Metric_prefix).

## Installation

Installation can be done through [zef](https://github.com/ugexe/zef):

```
$ zef install Ops::SI

```

## Usage

In your Perl 6 code, use the module and you're all set.

```
use Ops::SI;

dd 1k; # 1000
dd 2T; # 2000000000000
dd 3µ; # 0.000003
dd 4y; # 4e-24

```

## License

This module is distributed under the terms of the AGPL version 3.0. You can
find it in the `LICENSE` file distributed with the module.


## dist_zef-FCO-SixPM.md
# 🕕 - 6pm

6pm is a NPM for raku

## Create META6.json

```
$ mkdir TestProject
$ cd TestProject/
$ 6pm init
Project name [TestProject]:
Project tags:
raku version [6.*]:

```

## Locally install a Module

```
$ 6pm install Heap
===> Searching for: Heap
===> Testing: Heap:ver('0.0.1')
===> Testing [OK]: Heap:ver('0.0.1')
===> Installing: Heap:ver('0.0.1')

```

## Locally install a Module and add it on depends of META6.json

```
$ 6pm install Heap --save
===> Searching for: Heap
===> Testing: Heap:ver('0.0.1')
===> Testing [OK]: Heap:ver('0.0.1')
===> Installing: Heap:ver('0.0.1')

```

## Run code using the local dependencies

```
$ 6pm exec -- raku -MHeap -e 'say Heap.new: <q w e r>'
Heap.new: [e r q w]

```

## Run a file using the local dependencies

```
$ echo "use Heap; say Heap.new: <q w e r>" > bla.p6
$ 6pm exec-file bla.p6
Heap.new: [e r q w]

```

## Make your code always use 6pm

```
$ echo "use SixPM; use Heap; say Heap.new: <q w e r>" > bla.p6
$ raku bla.p6
Heap.new: [e r q w]

```

## Running scripts

Add your script at your META6.json scripts field and run it with:

```
$ cat META6.json
{
  "name": "TestProject",
  "source-url": "",
  "perl": "6.*",
  "resources": [

  ],
  "scripts": {
    "test": "zef test .",
    "my-script": "raku -MHeap -e 'say Heap.new: ^10'"
  },
  "depends": [

  ],
  "test-depends": [
    "Test",
    "Test::META"
  ],
  "provides": {

  },
  "tags": [

  ],
  "version": "0.0.1",
  "authors": [
    "fernando"
  ],
  "description": ""
}
$ 6pm run my-script
Heap.new: [0 1 2 3 4 5 6 7 8 9]

```


## dist_cpan-TYIL-Config.md
# Config

Extensible configuration class for the Raku programming language.

## Installation

This module can be installed using `zef`:

```
zef install Config

```

Depending on the type of configuration file you want to work on, you will need a
`Config::Parser::` module as well. If you just want an easy-to-use configuration
object without reading/writing a file, no parser is needed.

## Usage

To start off, specify a *template* of your configuration. `Config` will check
a couple of directories for a configuration file (based on the XDG base
directory spec), and will also automatically try to see if there's any
configuration specified in environment variables.

To specify a template, pass it as an argument to `new`.

```
my $config = Config.new({
	keyOne => Str,
	keyTwo => {
		NestedKey => "default value",
	},
	keyThree => Int,
}, :name<foobar>);

```

Important to note here is the `name` attribute which is being set. This name
is used to look up configuration files in default locations and the
environment. For this particular example, it will check any directory specified
in `$XDG_CONFIG_DIRS` for files matching `foobar.*` and `foobar/config.*`.
Afterwards, it will check `$XDG_CONFIG_HOME` for the same files. If these
variables are not set, it will just check `$HOME/.config` for those files.

Additionally, the environment will be checked for `$FOOBAR_KEYONE`,
`$FOOBAR_KEYTWO_NESTEDKEY`, and `$FOOBAR_KEYTHREE`. The former two will be cast
to `Str` appropriately, with `$FOOBAR_KEYTHREE` being cast to an `Int`. This
ensures that the values are of the correct type, even if they're pulled from a
shell environment. This also works for `IO::Path`!

*If you're using the Raku `Log` module, you can set `RAKU_LOG_LEVEL` to `7` to
see which places it actually checks and reads for values.*

You can also manually read configuration files or hashes of values.

```
# Load a simple configuration hash
$config.=read({
    keyOne => 'value',
    keyTwo => {
        NestedKey => 'other value'
    }
});

# Load a configuration files
$config.=read('/etc/config.yaml');

# Load a configuration file with a specific parser
$config.=read('/etc/config', Config::Parser::ini);

```

Do note the use of `.=` here. `Config` returns a new `Config` object if you
change its values, it is an immutable object. The `.=` operator provided by
Raku is a shorthand for `$config = $config.read(...)`.

To read values from the `Config` object, you can use the `get` method, or treat
it as a `Hash`.

```
# Retrieve a value
$config.get('keyOne');

# Same as above, but treating it as a Hash
$config<keyOne>;

# Retrieve a value by nested key
$config.get('keyTwo.NestedKey');

```

The `Config` object can also write it's current configuration back to a file.
You must specify a particular `Config::Parser` implementation as well.

```
# Write out the configuration using the json parser
$config.write($*HOME.add('.config/foobar/config.json', Config::Parser::json);

```

### Available parsers

Because there's so many ways to structure your configuration files, the parsers
for these are their own modules. This allows for easy implementing new parsers,
or providing a custom parser for your project's configuration file.

The parser will be loaded during runtime, but you have to make sure it is
installed yourself.

The following parsers are available:

* json:
  * [`Config::Parser::json`](https://github.com/arjancwidlak/p6-Config-Parser-json)
  * [`Config::Parser::json`](https://github.com/robertlemmen/perl6-config-json)
* [`Config::Parser::toml`](https://github.com/scriptkitties/p6-Config-Parser-toml)
* [`Config::Parser::yaml`](https://github.com/scriptkitties/p6-Config-Parser-yaml)

### Writing your own parser

If you want to make your own parser, simply make a new class which extends the
`Config::Parser` class, and implements the `read` and `write` methods. The
`read` method *must* return a `Hash`. The `write` method *must* return a
`Bool`, `True` when writing was successful, `False` if not. Throwing
`Exception`s to indicate the kind of failure is recommended.

## Contributing

If you want to contribute to `Config`, you can do so by mailing your patches to
`~tyil/raku-devel@lists.sr.ht`. Any questions or other forms of feedback are
welcome too!

## License

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3, as published by
the Free Software Foundation.

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

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


## proto.md
proto

Combined from primary sources listed below.

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

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

`proto` is a way to formally declare commonalities between `multi` candidates. It acts as a wrapper that can validate but not modify arguments. Consider this basic example:

```raku
proto congratulate(Str $reason, Str $name, |) {*}
multi congratulate($reason, $name) {
   say "Hooray for your $reason, $name";
}
multi congratulate($reason, $name, Int $rank) {
   say "Hooray for your $reason, $name -- got rank $rank!";
}

congratulate('being a cool number', 'Fred');     # OK
congratulate('being a cool number', 'Fred', 42); # OK
```

```raku
congratulate('being a cool number', 42);         # Proto match error

```

The proto insists that all `multi congratulate` subs conform to the basic signature of two strings, optionally followed by further parameters. The `|` is an un-named [`Capture`](/type/Capture) parameter, and allows a `multi` to take additional arguments. The first two calls succeed, but the third fails (at compile time) because `42` doesn't match [`Str`](/type/Str).

```raku
say &congratulate.signature # OUTPUT: «(Str $reason, Str $name, | is raw)␤»

```

You can give the `proto` a function body, and place the `{*}` (note there is no whitespace inside the curly braces) where you want the dispatch to be done. This can be useful when you have a "hole" in your routine that gives it different behavior depending on the arguments given:

```raku
# attempts to notify someone -- False if unsuccessful
proto notify(Str $user, Str $msg) {
   my \hour = DateTime.now.hour;
   if 8 < hour < 22 {
      return {*};
   } else {
      # we can't notify someone when they might be sleeping
      return False;
   }
}
```

Since `proto` is a wrapper for `multi` candidates, the signatures of the routine's `multi` candidates do not necessarily have to match that of the `proto`; arguments of `multi` candidates may have subtypes of those of the `proto`, and the return types of the `multi` candidates may be entirely different from that of the `proto`. Using differing types like this is especially useful when giving `proto` a function body:

```raku
enum DebugType <LOG WARNING ERROR>;

#|[ Prints a message to stderr with a color-coded key. ]
proto debug(DebugType:D $type, Str:D $message --> Bool:_) {
    note sprintf qb/\e[1;%dm[%s]\e[0m %s/, {*}, $type.key, $message
}
multi debug(LOG;; Str:D --> 32)     { }
multi debug(WARNING;; Str:D --> 33) { }
multi debug(ERROR;; Str:D --> 31)   { }

```

`{*}` always dispatches to candidates with the parameters it's called with. Parameter defaults and type coercions will work but are not passed on.

```raku
proto mistake-proto(Str() $str, Int $number = 42) {*}
multi mistake-proto($str, $number) { say $str.^name }
mistake-proto(7, 42);  # OUTPUT: «Int␤» -- not passed on

```

```raku
mistake-proto('test'); # fails -- not passed on

```

A longer example using `proto` for methods shows how to extract common functionality into a proto method.

```raku
class NewClass {
    has $.debug is rw = False;
    has $.value is rw = 'Initial value';
    proto method handle( | ) {
        note "before value is ｢$.value｣" if $.debug;
        {*}
        note "after value is ｢$.value｣" if $.debug;
    }
    multi method handle(Str $s) {
        $.value = $s;
        say 'in string'
    }
    multi method handle(Positional $s) {
        $.value = $s[0];
        say 'in positional'
    }
    multi method handle( $a, $b ) {
        $.value = "$a is looking askance at $b";
        say 'with more than one value'
    }
}
my NewClass $x .= new;
$x.handle('hello world');
$x.handle(<hello world>);
$x.debug = True;
$x.handle('hello world');
$x.handle(<hello world>);
$x.handle('Claire', 'John');
# OUTPUT:
# in string
# in positional
# before value is ｢hello｣
# in string
# after value is ｢hello world｣
# before value is ｢hello world｣
# in positional
# after value is ｢hello｣
# before value is ｢hello｣
# with more than one value
# after value is ｢Claire is looking askance at John｣

```


## dist_zef-coke-Slang-Date.md
# Slang::Date

A Slang for Raku that adds support for literal dates in ISO-8601 style.

## Examples

Replaces the ISO String with a QAST node that generates a call to Date.new...;

```
my $a = 2023-01-13;
say "Happy Friday the 13th" if  $a.day-of-week == 5;

```

Invalid dates will error out as expected:

```
my $b = 2023-01-99;

```

```
Day out of range. Is: 99, should be in 1..31
  in block <unit> at -e line 1

```

## Notes

Requires a 4 digit year, 2 digit month, and 2 digit day.


## path.md
path

Combined from primary sources listed below.

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

See primary documentation
[in context](/type/IO/Handle#method_path)
for **method path**.

```raku
method path(IO::Handle:D:)
```

For a handle opened on a file this returns the [`IO::Path`](/type/IO/Path) that represents the file. For the standard I/O handles [`$*IN`](/language/variables#index-entry-%24%2AIN), [`$*OUT`](/language/variables#index-entry-%24%2AOUT), and [`$*ERR`](/language/variables#index-entry-%24%2AERR) it returns an [`IO::Special`](/type/IO/Special) object.

# [In X::IO::Unlink](#___top "go to top of document")[§](#(X::IO::Unlink)_method_path "direct link")

See primary documentation
[in context](/type/X/IO/Unlink#method_path)
for **method path**.

Returns the path that [unlink](/routine/unlink) failed to delete.

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

See primary documentation
[in context](/type/Proc/Async#method_path)
for **method path**.

```raku
method path(Proc::Async:D:)
```

**Deprecated as of v6.d**. Use [command](/routine/command) instead.

Returns the name and/or path of the external program that was passed to the `new` method as first argument.

# [In IO::Notification::Change](#___top "go to top of document")[§](#(IO::Notification::Change)_method_path "direct link")

See primary documentation
[in context](/type/IO/Notification/Change#method_path)
for **method path**.

Returns the path of the file that's being watched.

# [In IO::Spec::Unix](#___top "go to top of document")[§](#(IO::Spec::Unix)_method_path "direct link")

See primary documentation
[in context](/type/IO/Spec/Unix#method_path)
for **method path**.

```raku
method path(--> Seq:D)
```

Splits the value of `%*ENV<PATH>` on colons (`":"`), replaces empty parts with `"."`, and returns a [`Seq`](/type/Seq) with each of the resultant parts. Returns an empty [`Seq`](/type/Seq) if `%*ENV<PATH>` is not set or is an empty string.

```raku
%*ENV<PATH> = 'foo:bar/ber::foo:';
IO::Spec::Unix.path.raku.say;
# OUTPUT: «("foo", "bar/ber", ".", "foo", ".").Seq␤»
```

# [In X::IO::Rmdir](#___top "go to top of document")[§](#(X::IO::Rmdir)_method_path "direct link")

See primary documentation
[in context](/type/X/IO/Rmdir#method_path)
for **method path**.

Returns the path [rmdir](/routine/rmdir) failed to remove

# [In X::IO::Dir](#___top "go to top of document")[§](#(X::IO::Dir)_method_path "direct link")

See primary documentation
[in context](/type/X/IO/Dir#method_path)
for **method path**.

Returns the path that [dir](/routine/dir) failed to read.

# [In IO::Pipe](#___top "go to top of document")[§](#(IO::Pipe)_method_path "direct link")

See primary documentation
[in context](/type/IO/Pipe#method_path)
for **method path**.

```raku
method path(IO::Pipe: --> IO::Path:U)
```

Returns an [`IO::Path`](/type/IO/Path) type object.

# [In IO::CatHandle](#___top "go to top of document")[§](#(IO::CatHandle)_method_path "direct link")

See primary documentation
[in context](/type/IO/CatHandle#method_path)
for **method path**.

```raku
method path(IO::CatHandle:D:)
```

Returns the value of [`.path` attribute](/type/IO/Handle#method_path) of the currently active source handle, or [`Nil`](/type/Nil) if the [source handle queue has been exhausted](/type/IO/CatHandle#method_next-handle). Basically, if your CatHandle is based on files, this is the way to get the path of the file the CatHandle is currently reading from.

```raku
(my $f1 = 'foo'.IO).spurt: "A\nB\nC";
(my $f2 = 'bar'.IO).spurt: "D\nE";

my $line;
my $cat = IO::CatHandle.new: :on-switch{ $line = 1 }, $f1, $f2;
say "{$cat.path}:{$line++} $_" for $cat.lines;
# OUTPUT:
# foo:1 A
# foo:2 B
# foo:3 C
# bar:1 D
# bar:2 E

```

# [In X::IO::DoesNotExist](#___top "go to top of document")[§](#(X::IO::DoesNotExist)_method_path "direct link")

See primary documentation
[in context](/type/X/IO/DoesNotExist#method_path)
for **method path**.

Returns the path that was passed to the failed call.

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

See primary documentation
[in context](/type/Cool#method_path)
for **method path**.

```raku
method path(Cool:D: --> IO::Path:D)
```

**DEPRECATED**. *It's been deprecated as of the 6.d version. Will be removed in the next ones.*

Stringifies the invocant and converts it to [`IO::Path`](/type/IO/Path) object. Use the [`.IO method`](/routine/IO) instead.

# [In X::IO::Chdir](#___top "go to top of document")[§](#(X::IO::Chdir)_method_path "direct link")

See primary documentation
[in context](/type/X/IO/Chdir#method_path)
for **method path**.

Returns the path that was passed to the failed `chdir` call.

# [In X::IO::Mkdir](#___top "go to top of document")[§](#(X::IO::Mkdir)_method_path "direct link")

See primary documentation
[in context](/type/X/IO/Mkdir#method_path)
for **method path**.

Returns the path that the [mkdir](/routine/mkdir) operation failed to create.

# [In IO::Spec::Win32](#___top "go to top of document")[§](#(IO::Spec::Win32)_method_path "direct link")

See primary documentation
[in context](/type/IO/Spec/Win32#method_path)
for **method path**.

```raku
method path(--> Seq:D)
```

Splits the value of `%*ENV<PATH>` (or `%*ENV<Path>` if the former is not set) on semicolons (`";"`) and returns a [`Seq`](/type/Seq) with each of the resultant parts, always adding element `"."` to the head. Removes all double quotes (`"`) it finds.

```raku
%*ENV<PATH> = 'foo;"bar"/"ber"';
IO::Spec::Win32.path.raku.say; # OUTPUT: «(".", "foo", "bar/ber").Seq␤»
```


## dist_zef-antononcube-Data-Reshapers.md
# Raku Data::Reshapers

[![MacOS](https://github.com/antononcube/Raku-Data-Reshapers/actions/workflows/macos.yml/badge.svg)](https://github.com/antononcube/Raku-Data-Reshapers/actions/workflows/macos.yml)
[![Linux](https://github.com/antononcube/Raku-Data-Reshapers/actions/workflows/linux.yml/badge.svg)](https://github.com/antononcube/Raku-Data-Reshapers/actions/workflows/linux.yml)
[![Win64](https://github.com/antononcube/Raku-Data-Reshapers/actions/workflows/windows.yml/badge.svg)](https://github.com/antononcube/Raku-Data-Reshapers/actions/workflows/windows.yml)
[![](https://raku.land/zef:antononcube/Data::Reshapers/badges/version)](https://raku.land/zef:antononcube/Data::Reshapers)
[![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0)

This Raku package has data reshaping functions for different data structures that are
coercible to full arrays.

The supported data structures are:

* Positional-of-hashes
* Positional-of-arrays

The most important data reshaping provided by the package over those data structures are:

* Cross tabulation, `cross-tabulate`
* Long format conversion, `to-long-format`
* Wide format conversion, `to-wide-format`
* Join across (aka `SQL JOIN`), `join-across`
* Transpose, `transpose`

The first four operations are fundamental in data wrangling and data analysis;
see [AA1, Wk1, Wk2, AAv1-AAv2].

(Transposing of tabular data is, of course, also fundamental, but it also can be seen as a
basic functional programming operation.)

There are other reshaping functions for:

* Flattening and tallying,
* Simple and stratified (dataset) splitting
* Taking, renaming, and deleting of table columns,
* Table column separation

An overview is given in (some part of) the presentation
["TRC 2022 Implementation of ML algorithms in Raku"](https://youtu.be/efRHfjYebs4?si=-KHucA8exZ8Cxx-w&t=1335),
[AAv4].

More detailed explanations of the data wrangling methodology and workflows is given in the article
["Introduction to data wrangling with Raku"](https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku/), [AA2].
(And its Bulgarian version [AA3].)

This package is one of the translation targets of the interpreter(s) provided by the package
["DSL::English::DataQueryWorkflows"](https://github.com/antononcube/Raku-DSL-English-DataQueryWorkflows), [AAp2].

---

## Usage examples

### Cross tabulation

Making contingency tables -- or cross tabulation -- is a fundamental statistics and data analysis operation,
[Wk1, AA1].

Here is an example using the
[Titanic](https://en.wikipedia.org/wiki/Titanic)
dataset (that is provided by this package through the function `get-titanic-dataset`):

```
use Data::Reshapers;

my @tbl = get-titanic-dataset();
my $res = cross-tabulate( @tbl, 'passengerSex', 'passengerClass');
say $res;

```

```
# {female => {1st => 144, 2nd => 106, 3rd => 216}, male => {1st => 179, 2nd => 171, 3rd => 493}}

```

```
to-pretty-table($res);

```

```
# +--------+-----+-----+-----+
# |        | 3rd | 2nd | 1st |
# +--------+-----+-----+-----+
# | female | 216 | 106 | 144 |
# | male   | 493 | 171 | 179 |
# +--------+-----+-----+-----+

```

### Long format

Conversion to long format allows column names to be treated as data.

(More precisely, when converting to long format specified column names of a tabular dataset become values
in a dedicated column, e.g. "Variable" in the long format.)

```
my @tbl1 = @tbl.roll(3);
.say for @tbl1;

```

```
# {id => 2, passengerAge => 0, passengerClass => 1st, passengerSex => male, passengerSurvival => survived}
# {id => 858, passengerAge => 30, passengerClass => 3rd, passengerSex => male, passengerSurvival => survived}
# {id => 636, passengerAge => 20, passengerClass => 3rd, passengerSex => male, passengerSurvival => died}

```

```
.say for to-long-format( @tbl1 );

```

```
# {AutomaticKey => 0, Value => 0, Variable => passengerAge}
# {AutomaticKey => 0, Value => survived, Variable => passengerSurvival}
# {AutomaticKey => 0, Value => male, Variable => passengerSex}
# {AutomaticKey => 0, Value => 1st, Variable => passengerClass}
# {AutomaticKey => 0, Value => 2, Variable => id}
# {AutomaticKey => 1, Value => 30, Variable => passengerAge}
# {AutomaticKey => 1, Value => survived, Variable => passengerSurvival}
# {AutomaticKey => 1, Value => male, Variable => passengerSex}
# {AutomaticKey => 1, Value => 3rd, Variable => passengerClass}
# {AutomaticKey => 1, Value => 858, Variable => id}
# {AutomaticKey => 2, Value => 20, Variable => passengerAge}
# {AutomaticKey => 2, Value => died, Variable => passengerSurvival}
# {AutomaticKey => 2, Value => male, Variable => passengerSex}
# {AutomaticKey => 2, Value => 3rd, Variable => passengerClass}
# {AutomaticKey => 2, Value => 636, Variable => id}

```

```
my @lfRes1 = to-long-format( @tbl1, 'id', [], variablesTo => "VAR", valuesTo => "VAL2" );
.say for @lfRes1;

```

```
# {VAL2 => male, VAR => passengerSex, id => 2}
# {VAL2 => 1st, VAR => passengerClass, id => 2}
# {VAL2 => 0, VAR => passengerAge, id => 2}
# {VAL2 => survived, VAR => passengerSurvival, id => 2}
# {VAL2 => male, VAR => passengerSex, id => 636}
# {VAL2 => 3rd, VAR => passengerClass, id => 636}
# {VAL2 => 20, VAR => passengerAge, id => 636}
# {VAL2 => died, VAR => passengerSurvival, id => 636}
# {VAL2 => male, VAR => passengerSex, id => 858}
# {VAL2 => 3rd, VAR => passengerClass, id => 858}
# {VAL2 => 30, VAR => passengerAge, id => 858}
# {VAL2 => survived, VAR => passengerSurvival, id => 858}

```

### Wide format

Here we transform the long format result `@lfRes1` above into wide format --
the result has the same records as the `@tbl1`:

```
to-pretty-table( to-wide-format( @lfRes1, 'id', 'VAR', 'VAL2' ) );

```

```
# +-------------------+----------------+-----+--------------+--------------+
# | passengerSurvival | passengerClass |  id | passengerAge | passengerSex |
# +-------------------+----------------+-----+--------------+--------------+
# |      survived     |      1st       |  2  |      0       |     male     |
# |        died       |      3rd       | 636 |      20      |     male     |
# |      survived     |      3rd       | 858 |      30      |     male     |
# +-------------------+----------------+-----+--------------+--------------+

```

### Transpose

Using cross tabulation result above:

```
my $tres = transpose( $res );

to-pretty-table($res, title => "Original");

```

```
# +--------------------------+
# |         Original         |
# +--------+-----+-----+-----+
# |        | 2nd | 3rd | 1st |
# +--------+-----+-----+-----+
# | female | 106 | 216 | 144 |
# | male   | 171 | 493 | 179 |
# +--------+-----+-----+-----+

```

```
to-pretty-table($tres, title => "Transposed");

```

```
# +---------------------+
# |      Transposed     |
# +-----+--------+------+
# |     | female | male |
# +-----+--------+------+
# | 1st |  144   | 179  |
# | 2nd |  106   | 171  |
# | 3rd |  216   | 493  |
# +-----+--------+------+

```

---

## Type system

Earlier versions of the package implemented a type "deduction" system.
Currently, the type system is provided by the package ["Data::TypeSystem"](https://resources.wolframcloud.com/FunctionRepository), [AAp1].

The type system conventions follow those of Mathematica's
[`Dataset`](https://reference.wolfram.com/language/ref/Dataset.html)
-- see the presentation
["Dataset improvements"](https://www.wolfram.com/broadcast/video.php?c=488&p=4&disp=list&v=3264).

Here we get the Titanic dataset, change the "passengerAge" column values to be numeric,
and show dataset's dimensions:

```
my @dsTitanic = get-titanic-dataset(headers => 'auto');
@dsTitanic = @dsTitanic.map({$_<passengerAge> = $_<passengerAge>.Numeric; $_}).Array;
dimensions(@dsTitanic)

```

```
# (1309 5)

```

Here is a sample of dataset's records:

```
to-pretty-table(@dsTitanic.pick(5).List, field-names => <id passengerAge passengerClass passengerSex passengerSurvival>)

```

```
# +------+--------------+----------------+--------------+-------------------+
# |  id  | passengerAge | passengerClass | passengerSex | passengerSurvival |
# +------+--------------+----------------+--------------+-------------------+
# | 1097 |      0       |      3rd       |     male     |        died       |
# | 340  |      0       |      2nd       |     male     |      survived     |
# | 367  |      50      |      2nd       |     male     |        died       |
# |  70  |      -1      |      1st       |    female    |      survived     |
# | 584  |      40      |      2nd       |    female    |      survived     |
# +------+--------------+----------------+--------------+-------------------+

```

Here is the type of a single record:

```
use Data::TypeSystem;
deduce-type(@dsTitanic[12])

```

```
# Struct([id, passengerAge, passengerClass, passengerSex, passengerSurvival], [Str, Int, Str, Str, Str])

```

Here is the type of single record's values:

```
deduce-type(@dsTitanic[12].values.List)

```

```
# Tuple([Atom((Str)), Atom((Int)), Atom((Str)), Atom((Str)), Atom((Str))])

```

Here is the type of the whole dataset:

```
deduce-type(@dsTitanic)

```

```
# Vector(Struct([id, passengerAge, passengerClass, passengerSex, passengerSurvival], [Str, Int, Str, Str, Str]), 1309)

```

Here is the type of "values only" records:

```
my @valArr = @dsTitanic>>.values>>.Array;
deduce-type(@valArr)

```

```
# Vector((Any), 1309)

```

Here is the type of the string values only records:

```
my @valArr = delete-columns(@dsTitanic, 'passengerAge')>>.values>>.Array;
deduce-type(@valArr)

```

```
# Vector(Vector(Atom((Str)), 4), 1309)

```

---

## TODO

1. DONE Simpler more convenient interface.

   * ~~Currently, a user have to specify four different namespaces
     in order to be able to use all package functions.~~
2. TODO More extensive long format tests.
3. TODO More extensive wide format tests.
4. DONE Implement verifications for:

   * See the type system implementation -- it has all of functionalities listed here.
   * DONE Positional-of-hashes
   * DONE Positional-of-arrays
   * DONE Positional-of-key-to-array-pairs
   * DONE Positional-of-hashes, each record of which has:

     * Same keys
     * Same type of values of corresponding keys
   * DONE Positional-of-arrays, each record of which has:

     * Same length
     * Same type of values of corresponding elements
5. DONE Implement "nice tabular visualization" using
   [Pretty::Table](https://gitlab.com/uzluisf/raku-pretty-table)
   and/or
   [Text::Table::Simple](https://github.com/ugexe/Perl6-Text--Table--Simple).
6. DONE Document examples using pretty tables.
7. DONE Implement transposing operation for:

   * hash of hashes
   * hash of arrays
   * array of hashes
   * array of arrays
   * array of key-to-array pairs
8. DONE Implement to-pretty-table for:

   * hash of hashes
   * hash of arrays
   * array of hashes
   * array of arrays
   * array of key-to-array pairs
9. DONE Implement join-across:

   * DONE inner, left, right, outer
   * DONE single key-to-key pair
   * DONE multiple key-to-key pairs
   * DONE optional fill-in of missing values
   * TODO handling collisions
10. DONE Implement semi- and anti-join
11. TODO Implement to long format conversion for:

    * TODO hash of hashes
    * TODO hash of arrays
12. TODO Speed/performance profiling.

    * TODO Come up with profiling tests
    * TODO Comparison with R
    * TODO Comparison with Python
13. TODO Type system.

    * DONE Base type (Int, Str, Numeric)
    * DONE Homogenous list detection
    * DONE Association detection
    * DONE Struct discovery
    * TODO Enumeration detection
    * DONE Dataset detection
      * List of hashes
      * Hash of hashes
      * List of lists
14. DONE Refactor the type system into a separate package.
15. DONE "Simple" or fundamental functions

    * `flatten`
    * `take-drop`
    * `tally`
      * Currently in "Data::Summarizers".
      * Can be easily, on the spot, "implemented" with `.BagHash.Hash`.

---

## References

### Articles

[AA1] Anton Antonov,
["Contingency tables creation examples"](https://mathematicaforprediction.wordpress.com/2016/10/04/contingency-tables-creation-examples/),
(2016),
[MathematicaForPrediction at WordPress](https://mathematicaforprediction.wordpress.com).

[AA2] Anton Antonov,
["Introduction to data wrangling with Raku"](https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku/),
(2021),
[RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com).

[AA3] Anton Antonov,
["Увод в обработката на данни с Raku"](https://rakuforprediction.wordpress.com/2022/05/24/%D1%83%D0%B2%D0%BE%D0%B4-%D0%B2-%D0%BE%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0%D1%82%D0%B0-%D0%BD%D0%B0-%D0%B4%D0%B0%D0%BD%D0%BD%D0%B8-%D1%81-raku/),
(2022),
[RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com).

[Wk1] Wikipedia entry, [Contingency table](https://en.wikipedia.org/wiki/Contingency_table).

[Wk2] Wikipedia entry, [Wide and narrow data](https://en.wikipedia.org/wiki/Wide_and_narrow_data).

### Functions, repositories

[AAf1] Anton Antonov,
[CrossTabulate](https://resources.wolframcloud.com/FunctionRepository/resources/CrossTabulate),
(2019),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).

[AAf2] Anton Antonov,
[LongFormDataset](https://resources.wolframcloud.com/FunctionRepository/resources/LongFormDataset),
(2020),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).

[AAf3] Anton Antonov,
[WideFormDataset](https://resources.wolframcloud.com/FunctionRepository/resources/WideFormDataset),
(2021),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).

[AAf4] Anton Antonov,
[RecordsSummary](https://resources.wolframcloud.com/FunctionRepository/resources/RecordsSummary),
(2019),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).

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

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

### Videos

[AAv1] Anton Antonov,
["Multi-language Data-Wrangling Conversational Agent"](https://www.youtube.com/watch?v=pQk5jwoMSxs),
(2020),
[YouTube channel of Wolfram Research, Inc.](https://www.youtube.com/channel/UCJekgf6k62CQHdENWf2NgAQ).
(Wolfram Technology Conference 2020 presentation.)

[AAv2] Anton Antonov,
["Data Transformation Workflows with Anton Antonov, Session #1"](https://www.youtube.com/watch?v=iXrXMQdXOsM),
(2020),
[YouTube channel of Wolfram Research, Inc.](https://www.youtube.com/channel/UCJekgf6k62CQHdENWf2NgAQ).

[AAv3] Anton Antonov,
["Data Transformation Workflows with Anton Antonov, Session #2"](https://www.youtube.com/watch?v=DWGgFsaEOsU),
(2020),
[YouTube channel of Wolfram Research, Inc.](https://www.youtube.com/channel/UCJekgf6k62CQHdENWf2NgAQ).

[AAv4] Anton Antonov,
["TRC 2022 Implementation of ML algorithms in Raku](https://youtu.be/efRHfjYebs4?si=-KHucA8exZ8Cxx-w),
(2022),
[YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4prediction).


## dist_zef-masukomi-Listicles.md
A collection of helper methods to make working with Arrays a little easier.

### method all-are

```
method all-are(
    &truthy_function
) returns Bool

```

Returns True if the function passed in returns true for all items. Function must take a single paramater and return True or False Ex. to see if all numbers are even $my\_array.all-are(-> $x {$x mod 2 == 0})

### method any-are

```
method any-are(
    &truthy_function
) returns Bool

```

Returns True if the function passed in returns true for any item. Function must take a single paramater and return True or False Ex. to see if any numbers are even $my\_array.any-are(-> $x {$x mod 2 == 0})

### method car

```
method car() returns Mu

```

Returns the first element of the Array. Throws an exception if the array is empty. Intended to satisfy lisp people.

### method cdr

```
method cdr() returns Array

```

Returns everything but the first element of the array. Throws an exception if the array is empty. Intended to satisfy lisp people.

### method drop

```
method drop(
    Int $count,
    Bool :$all_or_nothing = Bool::False
) returns Array:D

```

Returns a new list without the first or last $count elements of the array depending on if count is positive or negative.

### method flatten

```
method flatten() returns Seq:D

```

Fully, and deeply flattens a list, and returns it as a Seq (like flat).

### method includes

```
method includes(
    $x,
    Bool :$ducktyped = Bool::False
) returns Bool

```

Tests if the array includes the item passed in. Set ducktyped to True for ducktyped matches. For example "4" will match 4 with ducktyped matches.

### method is-empty

```
method is-empty() returns Bool

```

Tests if the array is empty

### method rest

```
method rest() returns Array

```

Returns a new array with everything but the first element. If the array is empty, or only has one element, it will return an empty array.

### method split-by

```
method split-by(
    Int $size,
    Bool :$only_perfect_splits = Bool::False
) returns Array:D

```

Splits a Array into an array of arrays of the specified length (or smaller). If the array is not evenly divisble then the last array will contain the remainder. If only\_perfect\_splits is set to True it will throw an exception if the Array is not evenly divisible by $size.

### method take

```
method take(
    Int $count,
    Bool :$all_or_nothing = Bool::False
) returns Array:D

```

Take returns $count elements of the Array from the beginning or end depending on if $count is positive or negative. If there are fewer elements than $count it will return whatever is available. Set all\_or\_nothing to True and it will throw an exception if there are insufficient elements.

### method to-hash

```
method to-hash(
    :$one_based = Bool::False
) returns Hash:D

```

creates a hash with the stringified index of each element as its key. Set one\_based to True to have it start the keys at 1 instead of 0. Example: ["foo", "bar"] -> {"0"=>"foo", "1"=>"bar"}

### method all-are

```
method all-are(
    &truthy_function
) returns Bool

```

Returns True if the function passed in returns true for all items. Function must take a single paramater and return True or False Ex. to see if all numbers are even $my\_seq.all-are(-> $x {$x mod 2 == 0})

### method any-are

```
method any-are(
    &truthy_function
) returns Bool

```

Returns True if the function passed in returns true for any item. Function must take a single paramater and return True or False Ex. to see if any numbers are even $my\_seq.any-are(-> $x {$x mod 2 == 0})

### method flatten

```
method flatten() returns Seq:D

```

Fully, and deeply flattens a list, and returns it as a Seq.

### method is-empty

```
method is-empty() returns Bool

```

Tests if the Seq is empty

### method all-are

```
method all-are(
    &truthy_function
) returns Bool

```

Returns True if the function passed in returns true for all items. Function must take a single paramater and return True or False Ex. to see if all numbers are even $my\_list.all-are(-> $x {$x mod 2 == 0})

### method any-are

```
method any-are(
    &truthy_function
) returns Bool

```

Returns True if the function passed in returns true for any item. Function must take a single paramater and return True or False Ex. to see if any numbers are even $my\_list.any-are(-> $x {$x mod 2 == 0})

### method flatten

```
method flatten() returns Seq:D

```

Fully, and deeply flattens a list, and returns it as a Seq.

### method is-empty

```
method is-empty() returns Bool

```

Tests if the List is empty


## dist_cpan-FRITH-Spreadsheet-Libxlsxio.md
[![Actions Status](https://github.com/frithnanth/raku-Spreadsheet-Libxlsxio/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Spreadsheet-Libxlsxio/actions)

# NAME

Spreadsheet::Libxlsxio - An interface to libxlsxio, a C library to read and write XLSX files

# SYNOPSIS

```
use Spreadsheet::Libxlsxio;
use Spreadsheet::Libxlsxio::Constants;

my @values;

my $ss = Spreadsheet::Libxlsxio::Read.new: 'mydata.xlsx';
$ss.sheet-list(-> $name {
  @values.push: "[$name]";
  $ss.process: $name,
               -> $, $, $value { @values.push: $value with $value; XLSXIOREAD_CONTINUE },
               -> $, $ { XLSXIOREAD_CONTINUE }
});

# Do something with @values

```

# DESCRIPTION

Spreadsheet::Libxlsxio is an interface to libxlsxio, a C library to read and write XLSX files

libxlsxio is a fast C library released under the terms of the MIT License. It has a nice API, which translates easily using Raku pointy blocks (or closures, or lambdas).

Please check the limitations of this library here: <https://brechtsanders.github.io/xlsxio/>.

This module exports two classes:

* Spreadsheet::Libxlsxio::Read
* Spreadsheet::Libxlsxio::Write

The Read class offers two ways to read an XLSX file:

* iterating through rows and cells;
* using callback functions for each cell and after each row.

The Write class has methods for writing one row at the time, cell after cell, with no random access to a single cell.

## Spreadsheet::Libxlsxio::Read

### new(Str $file!)

### new(Str :$file!)

### new(Buf $data!)

### new(Buf :$data!)

This **multi method** constructor requires one simple or named argument, the file name or the **Buf** variable into which the spreadsheet data has been read.

### version(--> Str)

This method returns the C library version as a **Str** or a **List**, if evaluated in a List context.

```
my $ss = Spreadsheet::Libxlsxio::Read.new: :file('mydata.xlsx');
my $version = $ss.version;
say $version;      # '0.2.29'
say $version.List; # (0 2 29)

```

**Methods to iterate through worksheets, rows, and cells**

### sheetlist-open(--> xlsxioreadersheetlist)

This method opens the worksheet list. It return the worksheet list handler.

### sheetlist-next(xlsxioreadersheetlist $sheetlisthandler --> Str)

This method accepts a worksheet list handler and returns the name of the next available worksheet.

For example:

```
my $ss = Spreadsheet::Libxlsxio::Read.new: :file('mydata.xlsx');
my $sl = $ss.sheetlist-open;
while $ss.sheetlist-next($sl) -> $sheetname { say $sheetname }
$ss.sheetlist-close($sl);

```

### sheetlist-close(xlsxioreadersheetlist $sheetlisthandler)

Closes the worksheet list handler.

### sheet-open(Str :$name, Int :$flag = XLSXIOREAD\_SKIP\_EMPTY\_ROWS --> xlsxioreadersheet)

Opens a worksheet by name. The flag values are defined in the **Spreadsheet::Libxlsxio::Constants** module:

* XLSXIOREAD\_SKIP\_NONE
* XLSXIOREAD\_SKIP\_EMPTY\_ROWS
* XLSXIOREAD\_SKIP\_EMPTY\_CELLS
* XLSXIOREAD\_SKIP\_ALL\_EMPTY
* XLSXIOREAD\_SKIP\_EXTRA\_CELLS

This method returns a handler to the specified worksheet.

### sheet-close(xlsxioreadersheet $sheet)

This method takes the worksheet handler and closes the worksheet.

### sheet-flags(xlsxioreadersheet $sheet --> UInt)

This method takes the worksheet handler and returns the flags set when opening the worksheet.

### last-row-read(xlsxioreadersheet $sheet --> UInt)

This method takes the worksheet handler and returns the index of the last row read.

### last-column-read(xlsxioreadersheet $sheet --> UInt)

This method takes the worksheet handler and returns the index of the last column read.

### next-cell(xlsxioreadersheet $sheet --> Str)

This method takes the worksheet handler and returns the value of the last cell read, or a false value if there are no more cells available in the current row.

### next-row(xlsxioreadersheet $sheet --> UInt)

This method takes the worksheet handler and gets the next row, or a false value if there are no more rows available.

This method must be called before each row.

**Methods that use callback functions for each cell and after each row**

### sheet-list(&callback)

This method sets a callback to be called on each worksheet.

The callback function receives the worksheet name. The actual processing can be done by the following method.

### process(Str $sheetname, &cell-callback, &row-callback, UInt :$flags = XLSXIOREAD\_SKIP\_EMPTY\_ROWS --> Int)

This method processes all rows and columns of a worksheet in a XLSX file.

It takes the sheet name, two callback functions and a flag and returns zero on success or non-zero on error. The first callback is called when a cell value is available; it receives three arguments: the row, the column, and the value contained in the cell. It must return one of these two values, available defined in the **Spreadsheet::Libxlsxio::Constants** module:

* XLSXIOREAD\_CONTINUE
* XLSXIOREAD\_ABORT

The second callback is called after each row; it receives two arguments: the row number (starting from 1) and the maximum column number on the row (starting from 1).

For example one might use both the previous methods to scan the entire spreadsheet:

```
my $ss = Spreadsheet::Libxlsxio::Read.new: 't/test.xlsx';

my @values;

$ss.sheet-list(-> $name {
  note "Processing worksheet [$name]";
  $ss.process: $name,
               -> $, $, $value { @values.push: $value with $value; XLSXIOREAD_CONTINUE },
               -> $, $ { XLSXIOREAD_CONTINUE }
});

dd @values;

```

**NOTE**

All the cell values are returned as **Str**. A helper sub is provided to convert a date cell to a Raku DateTime object:

### sub to-date(Str() $value --> DateTime)

## Spreadsheet::Libxlsxio::Write

```
use Spreadsheet::Libxlsxio;

my $ss = Spreadsheet::Libxlsxio::Write.new: :file('mydata.xlsx'), :sheet('Sheet1');
$ss.detection-rows(10)
   .row-height(10)
   .add-column('Col1', 16)
   .add-column('Col2', 0)
   .add-column('Col3', 0)
   .add-column('Col4', 0)
   .write-row;
my $dt = DateTime.new('2021-07-25T00:00:00').Instant.to-posix[0];
for ^10 -> $i {
  $ss.add-string("Test$i").add-int($i).add-num(π).add-datetime($dt).write-row;
}
$ss.close;

```

### new(Str $file!, Str $sheet?)

### new(Str :$file, Str :$sheet)

This **multi method** constructor requires two simple or named arguments: the file name and the worksheet name.

### close

This method closes the spreadsheet file.

### version(--> Str)

This method returns the C library version as a **Str** or a **List**, if evaluated in a List context.

```
my $ss = Spreadsheet::Libxlsxio::Write.new: :file('mydata.xlsx');
my $version = $ss.version;
say $version;      # '0.2.29'
say $version.List; # (0 2 29)

```

**All the following methods return their object, so they may be chained.**

### detection-rows(UInt $rows --> Spreadsheet::Libxlsxio::Write)

This method specifies how many initial rows will be buffered in memory to determine column widths.

### row-height(UInt $height --> Spreadsheet::Libxlsxio::Write)

This method specifies the row height in text lines to use for the current and next rows.

### add-column(Str $name, UInt $width --> Spreadsheet::Libxlsxio::Write)

This method adds a column label cell. It takes two arguments: the label and the column width in characters. It must be called for each column; the row is committed by calling the **write-row** method.

### write-row(--> Spreadsheet::Libxlsxio::Write)

This method marks the end of a row.

### add-string(Str() $value --> Spreadsheet::Libxlsxio::Write)

This method adds a cell containing Str data.

### add-int(Int() $value --> Spreadsheet::Libxlsxio::Write)

This method adds a cell containing Int data.

### add-num(Num() $value --> Spreadsheet::Libxlsxio::Write)

This method adds a cell containing Num data.

### add-datetime(DateTime() $value --> Spreadsheet::Libxlsxio::Write)

This method adds a cell containing DateTime data.

# Installation

To use this module one has to install the libxlsxio C library first.

The library home page is here: <https://brechtsanders.github.io/xlsxio/> and the GitHub project page is <https://github.com/brechtsanders/xlsxio>.

The C library has two dependencies: **expat** (available as libexpat1 on Ubuntu and Debian Linux systems) and one of **minizip** or **libzip** (libminizip1 and libzip5 on Ubuntu or Debian Linux systems).

Installing the library is as simple as typing:

```
sudo make install
sudo ldconfig

```

To install the Raku module using zef (a module management tool):

```
$ zef install Spreadsheet::Libxlsxio

```

# AUTHOR

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

# COPYRIGHT AND LICENSE

Copyright 2021 Fernando Santagata

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


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

# NAME

auto-dynamic - automatically vivify dynamic variables

# SYNOPSIS

```
use auto-dynamic;

$*foo = 42;
say $*foo;  # 42

%*hash<a> = 666;
dd %*hash;

@*array[2] = "ok";
say @*array;

&*handler = { say "duh" }
&*handler();

```

# DESCRIPTION

Unknown dynamic variables return a `Failure` in standard Raku. That may be undesired in some situations.

The `auto-dynamic` distribution enables the automatic vivification of dynamic variables in the scope in which the `use` statement is executed. It is the [`no strict`](https://docs.raku.org/syntax/strict) equivalent for dynamic variables.

# CAUTION

The functionality of this distribution relies on the current way that accesses to dynamic variables are being turned into bytecode. Which *may* change at any point in the future. As such, this distribution is more intended as a proof of concept.

# AUTHOR

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

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

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

# COPYRIGHT AND LICENSE

Copyright 2024 Elizabeth Mattijsen

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


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

# NAME

Raku port of Perl's Tie::StdArray module

# SYNOPSIS

```
use Tie::StdArray;

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `Tie::StdArray` module as closely as possible in the Raku Programming Language.

Tie::StdArray is a module intended to be subclassed by classes using the </P5tie|tie()> interface. It uses the standard `Array` implementation as its "backend".

# SEE ALSO

<P5tie>, Tie::StdArray

# AUTHOR

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

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

# COPYRIGHT AND LICENSE

Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen

Re-imagined from Perl as part of the CPAN Butterfly Plan.

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


## dist_github-skids-Control-Bail.md
# Perl6-Control-Bail

Control::Bail:: Perl 6 module for deferred error cleanup

## Purpose

The Control::Bail module allows nested allocations of resources to be
released in an orderly fashion, without repeating yourself, with no deep
block nesting and with deallocation code placed next to the corresponding
allocation code.

Remember this from your C days?

```
thing *allocthing() {
    thing *res = malloc(sizeof(struct thing));
    if (!thing) goto bail0;
    thing.foo = malloc(sizeof(struct thing2));
    if (!thing.foo) goto bail1;
    thing.foo = malloc(sizeof(struct thing2));
    if (!thing.foo.bar) goto bail2;
    return thing;
bail2:
    free(thing.foo);
bail1:
    free(thing);
bail0:
    fprintf(stderr, "Error allocating thing");
    return NULL;
}

```

...While this had the advantage of avoiding deeply nested if/else
blocks, the code for freeing a resource was visually separated from
the code for allocating it. The other option was to make your
deallocators smart enough to realize when they were passed a partially
constructed object, so you could call it from the constructor
on error:

```
void freething(thing *) {
    if (thing.foo.bar) free thing.foo.bar;
    if (thing.foo) free thing.foo;
    if (thing) free thing;
}

```

All in all that was not a horrible thing, and these days with GC we
often do not have to even bother with manual allocations -- but for
resources other than memory that need to be cleaned up quickly, like
TCP network connections, some languages have a construct, for example,
go's "defer" (example stolen from rosettacode:)

```
import "os"

func processFile() {
    f, err := os.Open("file")
    if err != nil {
        // (probably do something with the error)
        return // no need to close file, it didn't open
    }
    defer f.Close() // file is open.  no matter what, close it on return
    var lucky bool
    // some processing
    if (lucky) {
        // f.Close() will get called here
        return
    }
    // more processing
    // f.Close() will get called here too
}

```

...which can help a lot, but you'd have to add tests to prevent the
deallocation from happening if you wanted to return the allocated object
from the function.

In Perl 6 there is a similar stack of "things that run after a function
returns" through the LEAVE/KEEP/UNDO phasers. These all exist on the same
queue (the LEAVE queue) but the KEEP and UNDO variety allow you to cancel
them by the way you return from the block. This is nice. However, unlike
defer, they are found and attached to the block at compile time:

```
sub makething () {
   LEAVE { 42.say };
   return "thing";
   LEAVE { 43.say };
}
makething(); # Says 43 and then says 42.

```

In the above, even though the return "happens before" the second LEAVE block
visually, that LEAVE block still runs. So you still have to test whether
something has been done before trying to undo it.

This module solves that problem by providing a run-time version of these
phasers which works the way go's "defer" works -- it does not install the
cleanup code unless the flow of control actually reaches the statement.
The "bail", "trail", and "trail-keep" map to UNDO, LEAVE, and KEEP,
respectively.

## Status

Brand spanking new. The names of the provided functions may end up
being capitalized or perhaps changed entirely. Let the bikeshedding
commence. Also, this module uses a lot of metamodel/internal stuff that
is not necessarily nailed down by specification, so it cannot promise
the same stability as one that uses only the tested 6.c features.

## Idioms

```
# This DWYW.  No need to test $skel or $thing to see whether or
# not they were allocated, works in reverse order of bail statements,
# and no bail statements get run when successful.
sub make_thing {
    my $skel = make_skeleton();
    $skel or die "Could not make skeleton";
    bail { destroy_skeleton($skel); }

    my $thing = make_skin($skel);
    $thing or die "Could not make skin";
    bail { destroy_skin($thing); }

    Bool.pick or die("Unpredicable failure");
    $thing;
}

# In the following code:
# If there was a touchdown there is cheering
# ...then...
# The Receiver gets an icepack, but only if he was tackled.
# ...then...
# The Receiver always gets juice, unless the QB was sacked.
# ...then...
# The QB always gets taunted, unless there was a touchdown.
# ...then...
# If there was no touchdown, the failure is thrown.
use Control::Bail;
sub towlboy {
    bail { say "Taunt the QB" }
    Bool.pick or die "sacked!";
    trail { say "Bring Receiver juice" }
    bail { say "Bring Receiver icepack" }
    Bool.pick or die "tackled!";
    say "touchdown!";
}
towlboy();

```


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

# NAME

C::Parser - Grammar for Parsing C in Raku

# SYNOPSIS

```
use C::Parser;

my $ast = C::Parser.parse($source);

```

# DESCRIPTION

The `C::Parser` distribution provides a Raku grammar for parsing C code.

**WARNING** This parser is not production ready. It is experimental, and a work in progress. If you would like to try it out, the recommended way is:

```
my $ast = C::Parser.parse($source);

```

Another thing to note is that it doesn't provide any understanding of C preprocessor directives, so you will have to use `gcc -E` (or the like) before parsing it. This can usually be accomplished by:

```
gcc -E FILE.c | grep -v '^#' | cdump

```

Note that the `cdump` script is also installed along with this distribution.

# TYPEDEFS

Probably the major surprizing thing about this parser is that it doesn't work for obvious inputs, such as `GHashTable hash;`. The reason for this is that the parser has built-in rules that match based on whether an identifier has been previously involved in a `typedef` declaration.

So if your source code compiles with a fully functional compiler, then it should also parse with this parser. But if your source code just happens to match the syntactic definition of C, but not the semantics, then good luck!

For this reason, there are a lot of types that are pre-declared to help ease the pain associated with this issue. Most of them are types that are usually found in system-supplied libraries, such as `libc` and POSIX.

For example, types such as `FILE` and `int64_t` are pre-declared. If you feed a preprocessed source that had include "stdint.h" in it, then the parser will see a `typedef` for `int64_t` at some point. This is perfectly fine. A type can be `typedef`ed multiple times and it will still parse, but not 0 times.

# CONCLUSION

Don't write a compiler with this just yet.

# AUTHOR

Andrew Robbins

# COPYRIGHT AND LICENSE

Copyright 2014 - 2020 Andrew Robbins

Copyright 2024 Raku Community

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