txt
stringlengths 93
37.3k
|
---|
## method.md
class Method
Member function
```raku
class Method is Routine { }
```
A type for methods that behaves in the same way as [`Routine`](/type/Routine) with some exceptions listed below. For details of a method's parameter list see [`Signature`](/type/Signature).
To create a method outside a [class definition](/language/typesystem#Methods), use the declarators `my` and `method`. If an [identifier](/language/syntax#Identifiers) is provided the methods name will be injected into the scope specified by the declarator.
```raku
my $m = method ($invocant: $param) {
say "$invocant: '$param'";
}
"greeting".$m("hello"); # OUTPUT: «greeting: 'hello'»
<a b c>.&(my method (List:D:) { say self.raku; self }).say;
# OUTPUT: «("a", "b", "c")(a b c)»
```
The invocant of a method defaults to `self`. A type constraint including a type-smiley can be used and is honored both for methods defined in a class and for free floating methods. Call the latter with `.&` on an object.
```raku
my method m(Int:D: $b){
say self.^name
}
my $i = 1;
$i.&m(<a>);
# OUTPUT: «Int»
```
Please note that the main difference between methods defined within and without a class is the need to use `&` to invoke them in the latter case. In case any other sigil is used in the definition, as in the first example, that sigil can also be used.
Methods automatically capture extra named arguments into the special variable `%_`, where other types of [`Routine`](/type/Routine) will throw at runtime. So
```raku
method x() {}
```
is actually equivalent to
```raku
method x(*%_) {}
```
Extra arguments will be forwarded by [`nextsame` and friends](/language/functions#Re-dispatching).
```raku
class A {
multi method m(:$a, :$b) { say "2 named" }
}
class B is A {
method m(:$a) { say "1 named"; nextsame }
}
B.m( :1a, :2b );
# OUTPUT: «1 named2 named»
```
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Method`
raku-type-graph
Method
Method
Routine
Routine
Method->Routine
Mu
Mu
Any
Any
Any->Mu
Callable
Callable
Code
Code
Code->Any
Code->Callable
Block
Block
Block->Code
Routine->Block
Regex
Regex
Regex->Method
[Expand chart above](/assets/typegraphs/Method.svg)
|
## dist_github-mj41-Algorithm-SpiralMatrix.md
# Algorithm::SpiralMatrix
Various Raku Sequences for spirals in matrix (two-dimensional
arrays).
For overview see <docs/test-output.md>
and <docs/distance-variants.md>.
## Synopsis
```
use Algorithm::SpiralMatrix;
my $i = 1;
for square_distance(order => 'clockwise') -> ($x,$y) {
say "{$i++} $x,$y";
last if $i > 25;
}
```
will print
```
1 0,0
2 0,-1
3 1,0
4 0,1
5 -1,0
6 1,-1
8 -1,1
9 -1,-1
...
24 -2,2
25 -2,-2
```
## Description
This module provides implementation of algorithms to generate various
spiral sequences in matrix (two-dimensional array).
## Related links
* [zero2cx/spiral-matrix](https://github.com/zero2cx/spiral-matrix) (Python)
* [bangjunyoung/SpiralMatrixSharp](https://github.com/bangjunyoung/SpiralMatrixSharp) (F#)
* [Exercism: spiral-matrix](https://github.com/exercism/problem-specifications/blob/master/exercises/spiral-matrix/description.md)
## Installation
Rakudo Raku distribution contains *zef*. Use
```
zef install Algorithm::SpiralMatrix
```
If you have a local copy of this repository use
```
zef install .
```
in the module directory.
## Support
Feel free to share your suggestions, patches or comment
<https://github.com/mj41/Algorithm-SpiralMatrix/issues>.
## Licence and Copyright
This is free software. Please see the [LICENCE file](LICENSE).
© Michal Jurosz, 2019
|
## dist_zef-jforget-Date-Calendar-FrenchRevolutionary.md
# NAME
Date::Calendar::FrenchRevolutionary - Conversions from / to the French Revolutionary calendar
# SYNOPSIS
Converting a Gregorian date (e.g. 9th November 1799) into French
Revolutionary (18 Brumaire VIII).
```
use Date::Calendar::FrenchRevolutionary;
my Date $Bonaparte's-coup-gr;
my Date::Calendar::FrenchRevolutionary $Bonaparte's-coup-fr;
$Bonaparte's-coup-gr .= new(1799, 11, 9);
$Bonaparte's-coup-fr .= new-from-date($Bonaparte's-coup-gr);
say $Bonaparte's-coup-fr.strftime("%A %e %B %Y");
```
Converting a French Revolutionary date (e.g. 9th Thermidor II) to
Gregorian (which gives 27th July 1794).
```
use Date::Calendar::FrenchRevolutionary;
my Date::Calendar::FrenchRevolutionary $Robespierre's-downfall-fr;
my Date $Robespierre's-downfall-gr;
$Robespierre's-downfall-fr .= new(year => 2
, month => 11
, day => 9);
$Robespierre's-downfall-gr = $Robespierre's-downfall-fr.to-date;
say $Robespierre's-downfall-gr;
```
# INSTALLATION
```
zef install Date::Calendar::FrenchRevolutionary
```
or
```
git clone https://github.com/jforget/raku-Date-Calendar-FrenchRevolutionary.git
cd raku-Date-Calendar-FrenchRevolutionary
zef install .
```
# DESCRIPTION
Date::Calendar::FrenchRevolutionary is a class representing dates in
the French Revolutionary calendar. It allows you to convert a
Gregorian date into a French Revolutionary date or the other way.
The Revolutionary calendar was in use in France from 24 November 1793
(4 Frimaire II) to 31 December 1805 (10 Nivôse XIV). The modules in
this distribution extend the calendar to the present and to a few
centuries in the future, not limiting to Gregorian year 1805.
This new calendar was an attempt to apply the decimal rule (the basis
of the metric system) to the calendar. Therefore, the week
disappeared, replaced by the décade, a 10-day period. In addition, all
months have exactly 3 décades, no more, no less.
Since 12 months of 30 days each do not make a full year (365.24 days),
there are 5 or 6 additional days at the end of a year. These days are
called "Sans-culottides", named after a political faction, but we
often find the phrase "jours complémentaires" (additional days). These
days do not belong to any month, but for programming purposes, it is
convenient to consider they form a 13th month.
At first, the year was beginning on the equinox of autumn, for two
reasons. First, the republic had been established on 22 September
1792, which happened to be the equinox, and second, the equinox was
the symbol of equality, the day and the night lasting exactly 12 hours
each. It was therefore in tune with the republic's motto "Liberty,
Equality, Fraternity". But it was not practical, so Romme proposed a
leap year rule similar to the Gregorian calendar rule.
The distribution contains two other classes, one where there was no
reform and the automn equinox rule stayed in effect, another where the
arithmetic rule was established since the beginning of the calendar.
# AUTHOR
Jean Forget
# COPYRIGHT AND LICENSE
Copyright (c) 2019, 2020, 2024 Jean Forget, all rights reserved
This library is free software; you can redistribute it and/or modify
it under the Artistic License 2.0.
|
## dist_cpan-TITSUKI-MeCab.md
[](https://travis-ci.org/titsuki/raku-MeCab)
# NAME
MeCab - A Raku bindings for libmecab ( <http://taku910.github.io/mecab/> )
# SYNOPSIS
## EXAMPLE 1
```
use MeCab;
use MeCab::Tagger;
my Str $text = "すもももももももものうち。";
my $mecab-tagger = MeCab::Tagger.new('-C');
loop ( my MeCab::Node $node = $mecab-tagger.parse-tonode($text); $node; $node = $node.next ) {
say ($node.surface, $node.feature).join("\t");
}
# OUTPUT«
# BOS/EOS,*,*,*,*,*,*,*,*
# すもも 名詞,一般,*,*,*,*,すもも,スモモ,スモモ
# も 助詞,係助詞,*,*,*,*,も,モ,モ
# もも 名詞,一般,*,*,*,*,もも,モモ,モモ
# も 助詞,係助詞,*,*,*,*,も,モ,モ
# もも 名詞,一般,*,*,*,*,もも,モモ,モモ
# の 助詞,連体化,*,*,*,*,の,ノ,ノ
# うち 名詞,非自立,副詞可能,*,*,*,うち,ウチ,ウチ
# 。 記号,句点,*,*,*,*,。,。,。
# BOS/EOS,*,*,*,*,*,*,*,*
# »
```
## EXAMPLE 2
```
use MeCab;
use MeCab::Lattice;
use MeCab::Tagger;
use MeCab::Model;
my MeCab::Model $model .= new;
my MeCab::Tagger $tagger = $model.create-tagger;
my MeCab::Lattice $lattice = $model.create-lattice;
$lattice.add-request-type(MECAB_NBEST);
$lattice.sentence("今日も");
if $tagger.parse($lattice) {
say $lattice.nbest-tostr(2);
}
# OUTPUT«
# 今日 名詞,副詞可能,*,*,*,*,今日,キョウ,キョー
# も 助詞,係助詞,*,*,*,*,も,モ,モ
# EOS
# 今日 名詞,副詞可能,*,*,*,*,今日,コンニチ,コンニチ
# も 助詞,係助詞,*,*,*,*,も,モ,モ
# EOS
# »
```
# DESCRIPTION
MeCab is a Raku bindings for libmecab ( <http://taku910.github.io/mecab/> ).
# NOTICE
## COMPATIBILITY
MeCab currently doesn't support Windows. It supports Linux/Unix or Mac OS X.
## BUILDING MeCab
MeCab depends on the following:
* wget
* mecab-0.996
* mecab-ipadic-2.7.0-20070801
Once the build starts, it automatically downloads `mecab-0.996` and `mecab-ipadic-2.7.0-20070801` with `wget` and installs these stuffs under the `$HOME/.p6mecab` directory, where `$HOME` is your home directory.
# Use 3rd-party dictionary
## mecab-ipadic-neologd
* Step1: download and install neologd
Example:
```
$ git clone --depth 1 https://github.com/neologd/mecab-ipadic-neologd.git
$ cd mecab-ipadic-neologd
$ export PATH=$HOME/.p6mecab/bin:$PATH
$ ./bin/install-mecab-ipadic-neologd -p $HOME/.p6mecab/lib/mecab/dic/ipadic-neologd
```
* Step2: Use .new(:dicdir(PATH\_TO\_THE\_DIR))
Example:
```
use MeCab;
use MeCab::Tagger;
my Str $text = "トランプ大統領 ワシントンで大規模軍事パレードを指示";
my $mecab-tagger = MeCab::Tagger.new(:dicdir("$*HOME/.p6mecab/lib/mecab/dic/ipadic-neologd"));
loop ( my MeCab::Node $node = $mecab-tagger.parse-tonode($text); $node; $node = $node.next ) {
say ($node.surface, $node.feature).join("\t");
}
# OUTPUT«
# BOS/EOS,*,*,*,*,*,*,*,*
# トランプ大統領 名詞,固有名詞,人名,一般,*,*,ドナルド・トランプ,トランプダイトウリョウ,トランプダイトウリョー
# ワシントン 名詞,固有名詞,地域,一般,*,*,ワシントン,ワシントン,ワシントン
# で 助詞,格助詞,一般,*,*,*,で,デ,デ
# 大規模 名詞,一般,*,*,*,*,大規模,ダイキボ,ダイキボ
# 軍事パレード 名詞,固有名詞,一般,*,*,*,軍事パレード,グンジパレード,グンジパレード
# を 助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
# 指示 名詞,サ変接続,*,*,*,*,指示,シジ,シジ
# BOS/EOS,*,*,*,*,*,*,*,*
# »
```
# AUTHOR
titsuki [titsuki@cpan.org](mailto:titsuki@cpan.org)
# COPYRIGHT AND LICENSE
Copyright 2016 titsuki
libmecab ( <http://taku910.github.io/mecab/> ) by Taku Kudo is licensed under the GPL, LGPL or BSD Licenses.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-renormalist-Data-DPath.md
[](https://github.com/renormalist/raku-Data-DPath/actions)
# NAME
Data::DPath - DPath is not XPath!
# SYNOPSIS
```
use Data::DPath;
```
# DESCRIPTION
Data::DPath is a re-implementation of the Perl module *Data::DPath*.
WATCH OUT: The early versions are ONLY to get the Raku/Zef/Github infrastructure working, there is no real code yet. If you read this sentence then this module is in its early stages of development and should not be used in any way except for contributing.
# AUTHOR
Steffen Schwigon [ss5@renormalist.net](mailto:ss5@renormalist.net)
# COPYRIGHT AND LICENSE
Copyright 2024 Steffen Schwigon
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
# CAVEATS
This module is not a 1:1 port of the Perl version. So there is potential for subtly different behaviour.
## Different dpath parsing
First of all, it utilizes grammars for the DPaths instead of Text::Balanced. This means it could miss dpath constructs that worked before just because of Text::Balanced. Please report them so the grammar can be extended.
## Different code
Besides the already discussed dpath parsing the remaining code will start out as port from Perl but will be evolve independently. It's quite possible that this eventually means a different feature set.
## Different filter expressions
In the Perl version filter expressions were actually Perl expressions, protected by *Safe.pm*. Here another expression language will be used, not sure yet, what exactly, but obviously not Perl.
## Feature differences
The Perl version provides some Perl-specific features, e.g. references into a data structure. It is not yet clear how these will work out in Raku.
|
## dist_zef-FRITH-Math-Libgsl-Eigensystem.md
[](https://github.com/frithnanth/raku-Math-Libgsl-Eigensystem/actions)
# NAME
Math::Libgsl::Eigensystem - An interface to libgsl, the Gnu Scientific Library - Eigensystems
# SYNOPSIS
```
use Math::Libgsl::Matrix;
use Math::Libgsl::Eigensystem;
my Math::Libgsl::Eigensystem::RealSymm $e .= new: 2;
my Math::Libgsl::Matrix $vm .= new: 2, 2;
$vm[0;0] = 2; $vm[0;1] = 1;
$vm[1;0] = 1; $vm[1;1] = 2
my ($eval) = $e.compute($vm);
put $eval[^2];
```
# DESCRIPTION
Math::Libgsl::Eigensystem is an interface to the Eigensystem functions of libgsl, the Gnu Scientific Library.
This module exports six classes:
* Math::Libgsl::Eigensystem::RealSymm
* Math::Libgsl::Eigensystem::ComplexHerm
* Math::Libgsl::Eigensystem::RealNonSymm
* Math::Libgsl::Eigensystem::RealGenSymm
* Math::Libgsl::Eigensystem::ComplexGenHerm
* Math::Libgsl::Eigensystem::RealGenNonSymm
each encapsulates the methods and the buffers needed to create and compute the eigenvalues and the eigenvectors of different kind of matrices.
All these classes share the same constructor schema:
### multi method new(Int $size!, Bool $vectors?)
### multi method new(Int :$size!, Bool :$vectors?)
The constructor accepts two simple or named arguments: the size of the system we want to compute and the request to compute the eigenvectors besides the eigenvalues.
All the classes have a **compute** method; they differ for the number and type of arguments and the return value(s).
## Math::Libgsl::Eigensystem::RealSymm
This class acts on a real symmetrix matrix.
### method compute(Math::Libgsl::Matrix $A where .matrix.size1 == .matrix.size2, gsl\_eigen\_sort\_t :$sort --> List)
This method computes the eigenvalues and the eigenvectors, if selected during the initialization. The optional named argument **:$sort** specifies the required sort order. The symbolic names for this argument are listed in the **Math::Libgsl::Constants** module as follows:
* **GSL\_EIGEN\_SORT\_VAL\_ASC**: ascending order in numerical value
* **GSL\_EIGEN\_SORT\_VAL\_DESC**: descending order in numerical value
* **GSL\_EIGEN\_SORT\_ABS\_ASC**: ascending order in magnitude
* **GSL\_EIGEN\_SORT\_ABS\_DESC**: descending order in magnitude
This method outputs a List of values: a single **Math::Libgsl::Vector**, which contains the eigenvalues, and an optional **Math::Libgsl::Matrix**, which contains the eigenvectors if they were requested.
## Math::Libgsl::Eigensystem::ComplexHerm
This class acts on a complex hermitian matrix.
### method compute(Math::Libgsl::Matrix::Complex64 $A where .matrix.size1 == .matrix.size2, gsl\_eigen\_sort\_t :$sort --> List)
This method computes the eigenvalues and the eigenvectors, if selected during the initialization. The optional named argument **:$sort** specifies the required sort order.
This method outputs a List of values: a single **Math::Libgsl::Vector**, which contains the eigenvalues, and an optional **Math::Libgsl::Matrix::Complex64**, which contains the eigenvectors if they were requested.
## Math::Libgsl::Eigensystem::RealNonSymm
This class acts on a complex hermitian matrix.
### method compute(Math::Libgsl::Matrix $A where .matrix.size1 == .matrix.size2, Bool :$balance = False, gsl\_eigen\_sort\_t :$sort, Bool :$schur-vectors = False, Bool :$schur = False --> List)
This method computes the eigenvalues and the eigenvectors, if selected during the initialization. The optional named argument **:$balance** requires that a balancing transformation is applied to the matrix prior to computing eigenvalues. The optional named argument **:$schur** requires that it computes the full Schur form T. The optional named argument **:$schur-vectors** requires that it also computes the Schur vectors. The optional named argument **:$sort** specifies the required sort order.
This method outputs a List of values: a single **Math::Libgsl::Vector::Complex64**, which contains the eigenvalues, an optional **Math::Libgsl::Matrix::Complex64**, which contains the eigenvectors if they were requested, and an optional **Math::Libgsl::Matrix** if the Schur vectors were requested.
## Math::Libgsl::Eigensystem::RealGenSymm
### method compute(Math::Libgsl::Matrix $A where .matrix.size1 == .matrix.size2, Math::Libgsl::Matrix $B where .matrix.size1 == .matrix.size2 && .matrix.size1 == $A.matrix.size1, gsl\_eigen\_sort\_t :$sort --> List)
This method computes the eigenvalues and the eigenvectors, if selected during the initialization. It requires two mandatory **Math::Libgsl::Matrix** objects (refer to the very good C Library documentation for the meaning of those two matrices and the computation details). The optional named argument **:$sort** specifies the required sort order.
This method outputs a List of values: a single **Math::Libgsl::Vector**, which contains the eigenvalues, an optional **Math::Libgsl::Matrix**, which contains the eigenvectors if they were requested. On exit the first matrix **$A** is destroyed and the second one **$B** will contain the Cholesky decomposition of the eigenvector matrix.
## Math::Libgsl::Eigensystem::ComplexGenHerm
### method compute(Math::Libgsl::Matrix::Complex64 $A where .matrix.size1 == .matrix.size2, Math::Libgsl::Matrix::Complex64 $B where .matrix.size1 == .matrix.size2 && .matrix.size1 == $A.matrix.size1, gsl\_eigen\_sort\_t :$sort --> List)
This method computes the eigenvalues and the eigenvectors, if selected during the initialization. It requires two mandatory **Math::Libgsl::Matrix::Complex64** objects (refer to the very good C Library documentation for the meaning of those two matrices and the details of the computation). The optional named argument **:$sort** specifies the required sort order.
This method outputs a List of values: a single **Math::Libgsl::Vector**, which contains the eigenvalues, an optional **Math::Libgsl::Matrix::Complex64**, which contains the eigenvectors if they were requested. On exit the first matrix **$A** is destroyed and the second one **$B** will contain the Cholesky decomposition of the eigenvector matrix.
## Math::Libgsl::Eigensystem::RealGenNonSymm
### method compute(Math::Libgsl::Matrix $A where .matrix.size1 == .matrix.size2, Math::Libgsl::Matrix $B where .matrix.size1 == .matrix.size2 && .matrix.size1 == $A.matrix.size1, Bool :$schur-S = False, Bool :$schur-T = False, Bool :$balance = False, Bool :$schur-vectors = False, gsl\_eigen\_sort\_t :$sort --> List)
This method computes the eigenvalues and the eigenvectors, if selected during the initialization. It requires two mandatory **Math::Libgsl::Matrix** objects (refer to the amazing C Library documentation for the meaning of those two matrices and the details of the computation). The optional named argument **:$schur-S** requires that it computes the full Schur form S. The optional named argument **:$schur-T** requires that it computes the full Schur form T. The optional named argument **:$balance** requires that a balancing transformation is applied to the matrix prior to computing eigenvalues (currently ignored by the underlying C library; TBI). The optional named argument **:$schur-vectors** requires that it also computes the Schur vectors. The optional named argument **:$sort** specifies the required sort order.
This method outputs a List of values: one **Math::Libgsl::Vector::Complex64** and one **Math::Libgsl::Vector** object, which contain the eigenvalues (see the C library documentation for the meaning of these two vectors), an optional **Math::Libgsl::Matrix::Complex64**, which contains the eigenvectors if they were requested. If the Schur vectors were requested the left and right Schur vectors are returned as **Math::Libgsl::Matrix** objects. On exit, if **$schur-S** is True, the first matrix **$A** will contain the Schur form S; if **$schur-T** is True, the second matrix **$B** will contain the Schur form T.
# C Library Documentation
For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format.
# Prerequisites
This module requires the libgsl library to be installed. Please follow the instructions below based on your platform:
## Debian Linux and Ubuntu 20.04+
```
sudo apt install libgsl23 libgsl-dev libgslcblas0
```
That command will install libgslcblas0 as well, since it's used by the GSL.
## Ubuntu 18.04
libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries:
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb>
# Installation
To install it using zef (a module management tool):
```
$ zef install Math::Libgsl::Eigensystem
```
# 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_cpan-ROBERTLE-ReadWriteLock.md
# ReadWriteLock
... A lock with shared/exclusive access modes, for the Raku language.
## Features
* Does what a basic `Lock` does, just slower and with more bugs ;)
* Reentrant: the lock can be taken again by a thread that is already holding it
It needs to be unlocked the same number of times it was locked before it can
be taken by another thread
* Fair in the sense of first-come-first-serve
* Shared access: multiple 'readers' can share the lock, yet access is mutually
exclusive between 'readers' and 'writers'
* Lock Upgrade: you can upgrade a shared access mode to an exclusive without
unlocking first, if no other thread is interferring. In this case you do not
need to unlock twice.
## Planned Features
* Read-for-write access mode that guarantees that a lock upgrade can be taken
* Async version that returns threads to the threadpool and returns a promise
from lock()
## Example Usage
```
use ReadWriteLock;
my $l = ReadWriteLock.new;
my $thread-a = Thread.start({
$l.lock-shared();
for ^5 {
sleep 1;
say "thread A doing something under protection of the lock";
}
$l.unlock();
});
my $thread-b = Thread.start({
$l.protect-shared({
for ^5 {
sleep 1;
say "thread B doing something under protection of the lock";
}
});
});
my $thread-c = Thread.start({
$l.protect-exclusive({
for ^5 {
sleep 1;
say "thread C doing something under exclusive protection of the lock";
}
});
});
$thread-a.join;
$thread-b.join;
$thread-c.join;
```
## Documentation
Please see the POD in lib/ReadWriteLock.rakumod for more documentation and usage
scenarios.
## License
ReadWriteLock is licensed under the [Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0).
## Feedback and Contact
Please let me know what you think: Robert Lemmen [robertle@semistable.com](mailto:robertle@semistable.com)
|
## dist_cpan-RYNIX-Graphics-TinyTIFF.md
# NAME
Graphics::TinyTIFF - Perl6 bindings to [a slightly modified] TinyTIFF
# DEPENDANCIES
## Unix
```
git clone https://github.com/ryn1x/TinyTIFF.git
cd TinyTIFF
mkdir build
cd build
cmake ..
make
sudo make install
```
## Windows
```
git clone https://github.com/ryn1x/TinyTIFF.git
cd TinyTIFF
mkdir build
cd build
cmake ..
cmake -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS=TRUE -DBUILD_SHARED_LIBS=TRUE -G "Visual Studio 15 2017 win64" ..
build generated ".sln" file with visual studio
```
# INSTALL
zef install Graphics::TinyTIFF
# SYNOPSIS
```
#!/usr/bin/env perl6
use v6.c;
use NativeCall;
use Graphics::TinyTIFF;
########## reader ##########
my $tiff = TinyTIFFReader_open('cell.tif');
my $frames = TinyTIFFReader_countFrames($tiff);
my $bits = TinyTIFFReader_getBitsPerSample($tiff, 0);
my $width = TinyTIFFReader_getWidth($tiff);
my $height = TinyTIFFReader_getHeight($tiff);
my $description = TinyTIFFReader_getImageDescription($tiff);
my $size = $width * $height;
my $sample-data := CArray[uint8].allocate($size);
TinyTIFFReader_getSampleData($tiff, $sample-data, 0);
# you now have $sample-data for the current frame
# and can manipulate it as you wish!
my $format = TinyTIFFReader_getSampleFormat($tiff);
my $samples-per-pixel = TinyTIFFReader_getSamplesPerPixel($tiff);
my $has-next = ?TinyTIFFReader_hasNext($tiff);
TinyTIFFReader_readNext($tiff) if $has-next;
my $success = ?TinyTIFFReader_success($tiff);
my $was-error = ?TinyTIFFReader_wasError($tiff);
my $last-error = TinyTIFFReader_getLastError($tiff) if $was-error;
TinyTIFFReader_close($tiff);
########## writer ##########
my $tiff-file = TinyTIFFWriter_open('cell2.tif', $bits, $width, $height);
my $description-size = TinyTIFFWriter_getMaxDescriptionTextSize();
TinyTIFFWriter_writeImageVoid( $tiff-file, $sample-data);
TinyTIFFWriter_close( $tiff-file, 'test');
print qq:to/END/;
frames -> $frames
bits -> $bits
width -> $width
height -> $height
description -> $description
format -> $format
samples per pixel -> $samples-per-pixel
has next? -> $has-next
success? -> $success
was error? -> $was-error
description size -> $description-size
sample data -> $sample-data[^3] ...
END
```
Output:
```
frames -> 1
bits -> 8
width -> 191
height -> 159
description -> image description
format -> 1
samples per pixel -> 1
has next? -> False
success? -> True
was error? -> False
description size -> 1024
sample data -> 118 116 112 ...
```
# SUBROUTINES
### sub TinyTIFFReader\_open
```
sub TinyTIFFReader_open(
str $filename
) returns NativeCall::Types::Pointer
```
open tiff file for reading, returns tiff pointer
### sub TinyTIFFReader\_getSampleData
```
sub TinyTIFFReader_getSampleData(
NativeCall::Types::Pointer $tiff,
NativeCall::Types::CArray $sample-data is rw,
uint16 $sample
) returns int32
```
read data from current frame into supplied buffer
### sub TinyTIFFReader\_close
```
sub TinyTIFFReader_close(
NativeCall::Types::Pointer $tiff
) returns Mu
```
close the tiff file
### sub TinyTIFFReader\_getBitsPerSample
```
sub TinyTIFFReader_getBitsPerSample(
NativeCall::Types::Pointer $tiff,
int32 $sample
) returns uint16
```
return bits per sample of current frame
### sub TinyTIFFReader\_getWidth
```
sub TinyTIFFReader_getWidth(
NativeCall::Types::Pointer $tiff
) returns uint32
```
return width of current frame
### sub TinyTIFFReader\_getHeight
```
sub TinyTIFFReader_getHeight(
NativeCall::Types::Pointer $tiff
) returns uint32
```
return height of current frame
### sub TinyTIFFReader\_countFrames
```
sub TinyTIFFReader_countFrames(
NativeCall::Types::Pointer $tiff
) returns uint32
```
return number of frames
### sub TinyTIFFReader\_getSampleFormat
```
sub TinyTIFFReader_getSampleFormat(
NativeCall::Types::Pointer $tiff
) returns uint16
```
return sample format of current frame
### sub TinyTIFFReader\_getSamplesPerPixel
```
sub TinyTIFFReader_getSamplesPerPixel(
NativeCall::Types::Pointer $tiff
) returns uint16
```
return samples per pixel of current frame
### sub TinyTIFFReader\_getImageDescription
```
sub TinyTIFFReader_getImageDescription(
NativeCall::Types::Pointer $tiff
) returns str
```
return image descrition of current frame
### sub TinyTIFFReader\_hasNext
```
sub TinyTIFFReader_hasNext(
NativeCall::Types::Pointer $tiff
) returns int32
```
retun non-zero if another frame exists
### sub TinyTIFFReader\_readNext
```
sub TinyTIFFReader_readNext(
NativeCall::Types::Pointer $tiff
) returns int32
```
read the next frame from a multi-frame tiff
### sub TinyTIFFReader\_success
```
sub TinyTIFFReader_success(
NativeCall::Types::Pointer $tiff
) returns int32
```
return non-zero if no error in last function call
### sub TinyTIFFReader\_wasError
```
sub TinyTIFFReader_wasError(
NativeCall::Types::Pointer $tiff
) returns int32
```
return non-zero if error in last function call
### sub TinyTIFFReader\_getLastError
```
sub TinyTIFFReader_getLastError(
NativeCall::Types::Pointer $tiff
) returns str
```
return last error message
### sub TinyTIFFWriter\_open
```
sub TinyTIFFWriter_open(
str $filename,
uint16 $bits-per-sample,
uint32 $width,
uint32 $height
) returns NativeCall::Types::Pointer
```
create a new tiff file, returns tiff-file pointer
### sub TinyTIFFWriter\_getMaxDescriptionTextSize
```
sub TinyTIFFWriter_getMaxDescriptionTextSize() returns int32
```
get max size for image descrition
### sub TinyTIFFWriter\_writeImageDouble
```
sub TinyTIFFWriter_writeImageDouble(
NativeCall::Types::Pointer $tiff-file,
NativeCall::Types::CArray $sample-data is rw
) returns Mu
```
writes row-major image data to a tiff file
### sub TinyTIFFWriter\_writeImageFloat
```
sub TinyTIFFWriter_writeImageFloat(
NativeCall::Types::Pointer $tiff-file,
NativeCall::Types::CArray $sample-data is rw
) returns Mu
```
writes row-major image data to a tiff file
### sub TinyTIFFWriter\_writeImageVoid
```
sub TinyTIFFWriter_writeImageVoid(
NativeCall::Types::Pointer $tiff-file,
NativeCall::Types::CArray $sample-data is rw
) returns Mu
```
writes row-major image data to a tiff file
### sub TinyTIFFWriter\_close
```
sub TinyTIFFWriter_close(
NativeCall::Types::Pointer $tiff-file,
str $image-description
) returns Mu
```
close the tiff and write image description to first frame
# COPYRIGHT AND LICENSE
Copyright 2018 ryn1x
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-antononcube-ML-Clustering.md
# Raku ML::Clustering
[](https://github.com/antononcube/Raku-ML-Clustering/actions/workflows/macos.yml)
[](https://github.com/antononcube/Raku-ML-Clustering/actions/workflows/linux.yml)
[](https://github.com/antononcube/Raku-ML-Clustering/actions/workflows/windows.yml)
[](https://raku.land/zef:antononcube/ML::Clustering)
[](https://opensource.org/licenses/Artistic-2.0)
This repository has the code of a Raku package for
Machine Learning (ML)
[Clustering (or Cluster analysis)](https://en.wikipedia.org/wiki/Cluster_analysis)
functions, [Wk1].
The Clustering framework includes:
* The algorithms
[K-means](https://en.wikipedia.org/wiki/K-means_clustering)
and
[K-medoids](https://en.wikipedia.org/wiki/K-medoids),
and others
* The distance functions Euclidean, Cosine, Hamming, Manhattan, and others,
and their corresponding similarity functions
The data in the examples below is generated and manipulated with the packages
["Data::Generators"](https://raku.land/zef:antononcube/Data::Generators),
["Data::Reshapers"](https://raku.land/zef:antononcube/Data::Reshapers), and
["Data::Summarizers"](https://raku.land/zef:antononcube/Data::Summarizers), described in the article
["Introduction to data wrangling with Raku"](https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku/),
[AA1].
The plots are made with the package
["Text::Plot"](https://raku.land/zef:antononcube/Text::Plot), [AAp6].
---
## Installation
Via zef-ecosystem:
```
zef install ML::Clustering
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-ML-Clustering
```
---
## Usage example
Here we derive a set of random points, and summarize it:
```
use Data::Generators;
use Data::Summarizers;
use Text::Plot;
my $n = 100;
my @data1 = (random-variate(NormalDistribution.new(5,1.5), $n) X random-variate(NormalDistribution.new(5,1), $n)).pick(30);
my @data2 = (random-variate(NormalDistribution.new(10,1), $n) X random-variate(NormalDistribution.new(10,1), $n)).pick(50);
my @data3 = [|@data1, |@data2].pick(*);
records-summary(@data3)
```
```
# +------------------------------+------------------------------+
# | 0 | 1 |
# +------------------------------+------------------------------+
# | Min => 1.9418286393831807 | Min => 2.5537453527288423 |
# | 1st-Qu => 5.23355791998377 | 1st-Qu => 5.802659698503382 |
# | Mean => 7.812329106122415 | Mean => 8.221053043444616 |
# | Median => 8.529233471757092 | Median => 8.859544342245552 |
# | 3rd-Qu => 9.74722507929462 | 3rd-Qu => 10.392817343154189 |
# | Max => 12.161509848446896 | Max => 11.851232468041157 |
# +------------------------------+------------------------------+
```
Here we plot the points:
```
use Text::Plot;
text-list-plot(@data3)
```
```
# +---+---------+---------+---------+---------+---------+----+
# + + 12.00
# | * * * * |
# | **** * ** ** *** |
# + * * ** ** * + 10.00
# | * **** ** |
# + * * * * + 8.00
# | * * * |
# + * * * ** + 6.00
# | * ** **** * * |
# | * * * * |
# + ** ** * + 4.00
# | * * |
# + + 2.00
# +---+---------+---------+---------+---------+---------+----+
# 2.00 4.00 6.00 8.00 10.00 12.00
```
**Problem:** Group the points in such a way that each group has close (or similar) points.
Here is how we use the function `find-clusters` to give an answer:
```
use ML::Clustering;
my %res = find-clusters(@data3, 2, prop => 'All');
%res<Clusters>>>.elems
```
```
# (30 50)
```
**Remark:** The first argument is data points that is a list-of-numeric-lists.
The second argument is a number of clusters to be found.
(It is in the TODO list to have the number clusters automatically determined -- currently they are not.)
**Remark:** The function `find-clusters` can return results of different types controlled with the named argument "prop".
Using `prop => 'All'` returns a hash with all properties of the cluster finding result.
Here are sample points from each found cluster:
```
.say for %res<Clusters>>>.pick(3);
```
```
# ((6.8442730684339805 2.5537453527288423) (5.988371242806578 6.690825577391333) (3.9052242620581974 5.826205768330279))
# ((10.302490764954882 10.91125277165973) (8.821337333605817 9.715938302825638) (8.278089768928224 8.666124184959127))
```
Here are the centers of the clusters (the mean points):
```
%res<MeanPoints>
```
```
# [(4.693753655533249 4.977193937166397) (9.411502770521118 9.768925531106525)]
```
We can verify the result by looking at the plot of the found clusters:
```
text-list-plot((|%res<Clusters>, %res<MeanPoints>), point-char => <▽ ☐ ●>, title => '▽ - 1st cluster; ☐ - 2nd cluster; ● - cluster centers')
```
```
# ▽ - 1st cluster; ☐ - 2nd cluster; ● - cluster centers
# +--+----------+---------+----------+---------+----------+--+
# + ☐ + 12.00
# | ☐ ☐ ☐☐ ☐☐ ☐ ☐ |
# | ☐ ☐☐☐ ☐☐ ☐ ☐ ☐ |
# + ☐☐ ☐ ●☐☐ ☐☐ ☐ + 10.00
# | ☐ ☐☐ ☐ ☐☐ |
# + ▽ ☐ ☐ ☐ ☐ + 8.00
# | ▽ ▽ |
# + ▽ ▽ ▽ ▽▽ + 6.00
# | ▽ ▽▽ ▽ ▽▽ ▽ ▽ |
# | ▽ ▽ ●▽ ▽ |
# + ▽ ▽ ▽ ▽ ▽ + 4.00
# | |
# + ▽ ▽ + 2.00
# +--+----------+---------+----------+---------+----------+--+
# 2.00 4.00 6.00 8.00 10.00 12.00
```
**Remark:** By default `find-clusters` uses the K-means algorithm. The functions `k-means` and `k-medoids`
call `find-clusters` with the option settings `method=>'K-means'` and `method=>'K-medoids'` respectively.
---
## More interesting looking data
Here is more interesting looking two-dimensional data, `data2D2`:
```
use Data::Reshapers;
my $pointsPerCluster = 200;
my @data2D5 = [[10,20,4],[20,60,6],[40,10,6],[-30,0,4],[100,100,8]].map({
random-variate(NormalDistribution.new($_[0], $_[2]), $pointsPerCluster) Z random-variate(NormalDistribution.new($_[1], $_[2]), $pointsPerCluster)
}).Array;
@data2D5 = flatten(@data2D5, max-level=>1).pick(*);
@data2D5.elems
```
```
# 1000
```
Here is a plot of that data:
```
text-list-plot(@data2D5)
```
```
# +---------------+---------------+---------------+----------+
# | |
# | ***** *** |
# + *************** + 100.00
# | ************** |
# | * * * *** |
# | *********** |
# + *********** + 50.00
# | *** * * |
# | ***** |
# | ******* ********* |
# | ******* **** * ********** |
# + ******* * ** *** + 0.00
# | |
# +---------------+---------------+---------------+----------+
# 0.00 50.00 100.00
```
Here we find clusters and plot them together with their mean points:
```
srand(32);
my %clRes = find-clusters(@data2D5, 5, prop=>'All');
text-list-plot([|%clRes<Clusters>, %clRes<MeanPoints>], point-char=><1 2 3 4 5 ●>)
```
```
# +--------------+-----------------+----------------+--------+
# + 3 33 + 120.00
# | 3 33333 5555 |
# + 333333●355●55555 + 100.00
# | 3335555555555 |
# + 1 11 1 + 80.00
# | 111111111 11 |
# + 11111●111111 + 60.00
# + 1 11 11 1 + 40.00
# | 2 2 |
# + 22222222 22 222222 + 20.00
# | 444444 2222222 ●2222222222 |
# +4444●444 2 222222222 + 0.00
# | 44444 4 2 |
# +--------------+-----------------+----------------+--------+
# 0.00 50.00 100.00
```
---
## Detailed function pages
Detailed parameter explanations and usage examples for the functions provided by the package are given in:
* ["K-means function page"](./doc/K-means-function-page.md)
* "K-medoids function page"
* "Bi-sectional-K-means function page"
---
## Implementation considerations
### UML diagram
Here is a UML diagram that shows package's structure (in Mermaid-JS):
```
to-uml-spec ML::Clustering --format=mermaid
```
```
classDiagram
class k_means {
<<routine>>
}
k_means --|> Routine
k_means --|> Block
k_means --|> Code
k_means --|> Callable
class find_clusters {
<<routine>>
}
find_clusters --|> Routine
find_clusters --|> Block
find_clusters --|> Code
find_clusters --|> Callable
class ML_Clustering_KMeans {
+BUILDALL()
+args-check()
+bray-curtis-distance()
+canberra-distance()
+chessboard-distance()
+cosine-distance()
+euclidean-distance()
+find-clusters()
+get-distance-function()
+hamming-distance()
+known-distance-function-specs()
+manhattan-distance()
+norm()
+squared-euclidean-distance()
}
ML_Clustering_KMeans --|> Math_DistanceFunctionish
```
**Remark:** Maybe it is a good idea to have an abstract class named, say,
`ML::Clustering::AbstractFinder` that is a parent of
`ML::Clustering::KMeans`, `ML::Clustering::KMedoids`, `ML::Clustering::BiSectionalKMeans`, etc.,
but I have not found to be necessary. (At this point of development.)
**Remark:** It seems it is better to have a separate package for the distance functions, named, say,
"ML::DistanceFunctions". (Although distance functions are not just for ML...)
After thinking over package and function names I will make such a package.
---
## TODO
* DONE Factor-out the distance functions in a separate package.
* TODO Implement Bi-sectional K-means algorithm, [AAp1].
* TODO Implement K-medoids algorithm.
* TODO Automatic determination of the number of clusters.
* TODO Allow data points to be `Pair` objects the keys of which are point labels.
* Hence, the returned clusters consist of those labels, not points themselves.
* TODO Implement Agglomerate algorithm.
---
## References
### Articles
[Wk1] Wikipedia entry, ["Cluster Analysis"](https://en.wikipedia.org/wiki/Cluster_analysis).
[AA1] 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).
### Packages
[AAp1] Anton Antonov,
[Bi-sectional K-means algorithm in Mathematica](https://github.com/antononcube/MathematicaForPrediction/blob/master/BiSectionalKMeans.m),
(2020),
[MathematicaForPrediction at GitHub/antononcube](https://github.com/antononcube/MathematicaForPrediction/).
[AAp2] Anton Antonov,
[Data::Generators Raku package](https://github.com/antononcube/Raku-Data-Generators),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[AAp3] Anton Antonov,
[Data::Reshapers Raku package](https://github.com/antononcube/Raku-Data-Reshapers),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[AAp4] Anton Antonov,
[Data::Summarizers Raku package](https://github.com/antononcube/Raku-Data-Summarizers),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[AAp5] Anton Antonov,
[UML::Translators Raku package](https://github.com/antononcube/Raku-UML-Translators),
(2022),
[GitHub/antononcube](https://github.com/antononcube).
[AAp6] Anton Antonov,
[Text::Plot Raku package](https://raku.land/zef:antononcube/Text::Plot),
(2022),
[GitHub/antononcube](https://github.com/antononcube).
|
## dist_zef-sdondley-Mac-Applications-List.md
## Name
Mac::Applications::List - get a list of applications on your macOS machine
## Synopsis
### Functional programming style:
```
use Mac::Applications::List;
my @apps = apps;
my @apps = apps '/some/path';
my @apps = apps < /path/to/dir1 /path/to/dir2 >;
say @apps;
```
### OO programming interface:
```
use Mac::Applications::List;
my $my_apps = MacAppList.new(); # create a MacAppList object
$my_apps.find_apps('/some/dir'); # populate object
$my_apps.exists('Safari'); # test to see if an app exists
$my_apps.print; # print out a list of apps
$my_apps.list; # return an array of apps
```
## Description
This module finds and generates a list of applications found in the standard locations
on macOS.
In the simplest usage, an automatically exported function, `apps`, returns
a List of the apps found.
An OO interface is also provided which provides convenient methods for
determining if an app exists, printing the list of apps, and returning the list
of apps found.
Be default, the module searches `/System/Applications`, `/Applications`, and
`~/Applications` directories. Additional directories can be searched by passing string
arguments, representing the paths of directories to be searched.
## Functions
### sub apps( [ < dir1 dir2 ... >, Bool :$full-path = False ] )
### sub apps( [ 'dir', Bool :$full-path = False ] )
Returns a unique List of application names found in standard
application installation directories on macOS. A string or array of strings of
paths to other directories can be included to search additional directories.
Set the `:full-path` options to have paths to the apps included. Otherwise,
the List contains only the names of the apps.
If the directory does not exist, the module generates a warning. The function
will still return a list of applications found in other directories.
## Methods
### new( [ < dir1 dir2 ... > ] )
### new( [ 'dir' ] )
Creates a new MacAppList object, optionally initialized with directories to
search which will be searched in addition to standard app directory locations.
Initialization also initiates a search for new apps in standard locations,
plus any directories the object was initialized with plus any optional directories
provided.
Returns the `<Mac::Applications::List>` object.
### app-list()
Returns an List of all apps names found.
### app-path-list()
Returns a List of all paths to the apps found.
### exists( Str )
Determines if an app exists. Returns a boolean value.
### print()
Prints out a comma-separated, alphabetical listing of apps to the command line
## INSTALLATION
Assuming Raku and zef is already installed, install the module with:
`zef install Mac::Applications::List`
If you don't have Raku with zef installed yet, it's easiest to install them both with homebrew if you already have brew
installed:
`brew install rakudo-star`
If you don't have brew installed, install it with:
`/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`
Note, however, that the homebrew install may be months out of date.
To ensure you get the absolute latest version of Raku, [see this
page](https://course.raku.org/essentials/how-to-install-rakudo/) for other
installation options. Whatever method you choose to install Raku, just be sure
the `zef` command gets installed and is working on your machine as well.
## Bugs and Limitations
This app will not find apps that have been "localized," i.e. apps contained in
a directory with a ".localized" extension. A future release will address this
issue.
## Author
Steve Dondley
## Copyright and License
©2022 – Cosmic heat death under the [Artistic License, v2.0](https://opensource.org/licenses/Artistic-2.0)
|
## dist_zef-tbrowder-Ask.md
[](https://github.com/tbrowder/Ask/actions)
# NAME
**Ask** - Provides `ask` as an alias for Raku core routine `prompt`
# SYNOPSIS
```
use Ask;
my $answer = ask "Are you well I hope (Y/n)? ";
if $answer ~~ /:i y/ {
say "Good, glad to hear it!";
}
else {
say "Oh, I'm so sorry.";
}
```
# DESCRIPTION
This module exports, by `DEFAULT`, `ask` as an alias for the built-in routine `prompt`.
# AUTHOR
Tom Browder [tbrowder@acm.org](mailto:tbrowder@acm.org)
# COPYRIGHT AND LICENSE
Copyright © 2022 Tom Browder
This library is free software; you can redistribute it or modify it under the Artistic License 2.0.
|
## basename.md
basename
Combined from primary sources listed below.
# [In IO::Spec::Unix](#___top "go to top of document")[§](#(IO::Spec::Unix)_method_basename "direct link")
See primary documentation
[in context](/type/IO/Spec/Unix#method_basename)
for **method basename**.
```raku
method basename(Str:D $path --> Str:D)
```
Takes a path as a string and returns a possibly-empty portion after the last slash:
```raku
IO::Spec::Unix.basename("foo/bar/") .raku.say; # OUTPUT: «""»
IO::Spec::Unix.basename("foo/bar/.").raku.say; # OUTPUT: «"."»
IO::Spec::Unix.basename("foo/bar") .raku.say; # OUTPUT: «"bar"»
```
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_basename "direct link")
See primary documentation
[in context](/type/IO/Path#method_basename)
for **method basename**.
```raku
method basename(IO::Path:D:)
```
Returns the basename part of the path object, which is the name of the filesystem object itself that is referenced by the path.
```raku
"docs/README.pod".IO.basename.say; # OUTPUT: «README.pod»
"/tmp/".IO.basename.say; # OUTPUT: «tmp»
```
Note that in [`IO::Spec::Win32`](/type/IO/Spec/Win32) semantics, the `basename` of a Windows share is `\`, not the name of the share itself:
```raku
IO::Path::Win32.new('//server/share').basename.say; # OUTPUT: «\»
```
# [In IO::Spec::Win32](#___top "go to top of document")[§](#(IO::Spec::Win32)_method_basename "direct link")
See primary documentation
[in context](/type/IO/Spec/Win32#method_basename)
for **method basename**.
```raku
method basename(Str:D $path --> Str:D)
```
Takes a path as a string and returns a possibly-empty portion after the last slash or backslash:
```raku
IO::Spec::Win32.basename("foo/bar/") .raku.say; # OUTPUT: «""»
IO::Spec::Win32.basename("foo/bar\\").raku.say; # OUTPUT: «""»
IO::Spec::Win32.basename("foo/bar/.").raku.say; # OUTPUT: «"."»
IO::Spec::Win32.basename("foo/bar") .raku.say; # OUTPUT: «"bar"»
```
|
## dist_github-tokuhirom-WebSocket.md
[](https://travis-ci.org/tokuhirom/p6-WebSocket)
# NAME
WebSocket - WebSocket library for Perl6
# SYNOPSIS
See WebSocket::P6W.
# DESCRIPTION
WebSocket.pm is a library to write a WebSocket server/client.
See WebSocket::P6W for more details.
There is an example chat server. See eg/chat.psgi <https://github.com/tokuhirom/p6-WebSocket/blob/master/eg/chat.pl6>.
# AUTHOR
Tokuhiro Matsuno [tokuhirom@gmail.com](mailto:tokuhirom@gmail.com)
# COPYRIGHT AND LICENSE
Copyright 2015 Tokuhiro Matsuno
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-timo-Cairo.md
# Cairo 2D Graphics library binding for Raku
## Synopsis
```
use Cairo;
given Cairo::Image.create(Cairo::FORMAT_ARGB32, 128, 128) {
given Cairo::Context.new($_) {
.rgb(0, 0.7, 0.9);
.rectangle(10, 10, 50, 50);
.fill :preserve; .rgb(1, 1, 1);
.stroke
};
.write_png("foobar.png")
}
```
## Native Cairo library
In order to use this module, native `Cairo` library is needed. See instructions at <https://cairographics.org/download/>.
### Examples
doc/screenshot/arc-negative.png

doc/screenshot/arc.png

doc/screenshot/clip-image.png

doc/screenshot/clip.png

doc/screenshot/curve-rectangle.png

doc/screenshot/curve\_to.png

doc/screenshot/dash.png

doc/screenshot/fill-and-stroke.png

doc/screenshot/fill-style.png

doc/screenshot/gradient.png

doc/screenshot/image-pattern.png

doc/screenshot/image.png

doc/screenshot/multi-page-pdf.pdf

doc/screenshot/multi-segment-caps.png

doc/screenshot/rounded-rectangle.png

doc/screenshot/set-line-cap.png

doc/screenshot/set-line-join.png

doc/screenshot/svg-surface.svg

doc/screenshot/text-align-center.png

doc/screenshot/text-extents.png

doc/screenshot/text.png

|
## unlink.md
unlink
Combined from primary sources listed below.
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_routine_unlink "direct link")
See primary documentation
[in context](/type/IO/Path#routine_unlink)
for **routine unlink**.
```raku
method unlink(IO::Path:D: --> True)
sub unlink(*@filenames --> List:D)
```
Delete all specified ordinary files, links, or symbolic links for which there are privileges to do so. See [rmdir](/routine/rmdir) to delete directories.
The subroutine form returns the names of all the files in the list, excluding those for which the filesystem raised some error; since trying to delete a file that does not exist does not raise any error at that level, this list will include the names of the files in the list that do not exist.
The method form returns `True` on success, or [fails](/routine/fail) with [`X::IO::Unlink`](/type/X/IO/Unlink) if the operation could not be completed. If the file to be deleted does not exist, the routine treats it as success.
```raku
'foo.txt'.IO.open(:w).close;
'bar'.IO.mkdir;
say unlink <foo.txt bar not-there.txt>; # OUTPUT: «[foo.txt not-there.txt]»
# `bar` is not in output because it failed to delete (it's a directory)
# `not-there.txt` is present. It never existed, so that's deemed a success.
# Method form `fail`s:
say .exception.message without 'bar'.IO.unlink;
# OUTPUT: «Failed to remove the file […] illegal operation on a directory»
```
|
## dist_cpan-MELEZHIK-Sparrowdo-VSTS-YAML-Nuget.md
# Sparrowdo::VSTS::YAML:Nuget
Sparrowdo module to generate VSTS yaml steps for nuget package manager.
```
$ cat sparrowfile
# Run nuget restore for project located in $work-folder
module_run "VSTS::YAML::Nuget", %(
build-dir => ".vsts",
working-folder => "app/foo", # path to project
solution => "app.sln", # path to solution file, default value
skip-nuget-install => True # do not install nuget client, default value is False
);
$ sparrowdo --local_mode --no_sudo
```
# Author
Alexey Melezhik
|
## dist_zef-codechurch-LR1.md
* [Overview](#orgbc9a0fa)
* [License](#org697df86)
* [Usage](#org4351734)
* [Example](#orgd47fcff)
# Overview
Raku Module LR1 supports LR(1) syntax analysis.
# License
Artistic-2.0
# Usage
* Import
```
use LR1;
```
* Input grammars
LR1Yacc.set-grammar ( @lines )
@lines: yacc code lines.
Return LR1Yacc:D
* LR(1) Analysis:
class LR1Yacc: method analysis()
* Get Yacc Result:
class LR1Yacc: method get-actions-data() return Hash:D
* Compile:
LR1Compiling.syntax-analysis($table, $src, $rank)
$table: The Yacc result
$src : Seq of tokens
$rank : rank action, callable
* Make rank actions:
LR1Compiling.make-rank-actions
To make a callable from a actions dictionary.
# Example
The example implements a simple calculator.
```
#!/usr/bin/env perl6
use v6;
use LR1;
use JSON::Fast;
my $p = LR1Yacc.set-grammar: q:to/EOF/.lines;
%levels = add mul
add = + -
mul = * /
expr -> expr + expr
%% This is a payload for 'expr -> expr + expr'
| expr - expr
| expr * expr
| expr / expr
| ( expr )
| n
| id
stmt -> print expr
| id "=" expr
stmts -> stmt
| stmts stmt
top -> stmts
EOF
$p.analysis;
my $data = $p.get-actions-data;
# to-json($data).say;
my $txt = q:to/END/;
a = 2 * (4+5)
c = 10 + 2*a
print c
END
grammar TXT {
rule TOP { <.ws> [ <tok> <.ws> ]* }
token tok { [<n> | <id> | <op> | <pr> ] }
token n { <digit>+ }
token id { <alpha> }
token pr { 'print' }
token op { ['+' | '-' | '*' | '/' | '(' | ')' | '='] }
}
class TXTAction {
has @.tokens;
method push($t, $s) {
@.tokens.push: lr1token($s.Str, :cata($t))
}
method n ($/) { self.push: 'n', $/ }
method id($/) { self.push: 'id', $/ }
method op($/) { self.push: $/.Str, $/ }
method pr($/) { self.push: $/.Str, $/ }
}
my $pp = TXTAction.new;
TXT.parse: $txt, actions => $pp;
class My_Actions {
has %.vars;
has $.rank is rw;
has @.values;
method make () {
my $act = %(
' ' => {
},
'expr -> expr + expr' => {
.payload.say;
@.values.push: @.values.pop + @.values.pop
},
'expr -> expr - expr' => {
my $a = @.values.pop;
@.values.push: @.values.pop - $a
},
'expr -> expr * expr' => {
my $a = @.values.pop;
@.values.push: @.values.pop * $a
},
'expr -> expr / expr' => {
my $a = @.values.pop;
@.values.push: @.values.pop / $a
},
'expr -> id' => {
my $var = %.vars{.syms[0]};
say "$var is not exist" if !$var;
@.values.push: $var
},
'expr -> n' => {
my $n = .syms[0];
@.values.push: $n.Int
},
'stmt -> print expr' => {
my $a = @.values.pop;
put "$a"
},
'stmt -> id = expr' => {
my $a = @.values.pop;
%.vars{.syms[0]} = $a;
put "set {.syms[0]} <= $a"
}
);
$.rank = LR1Compiling.make-rank-actions: $act;
$.rank
}
}
LR1Compiling.syntax-analysis: $data, $pp.tokens.iterator, My_Actions.new.make;
```
|
## dist_zef-jkramer-Color-Palette.md
[](https://github.com/jkramer/raku-color-palette/actions)
# NAME
Color::Palette
# SYNOPSIS
```
use Color::Palette;
use Color;
my $palette = Color::Palette::from-gpl('pantone.gpl'.IO.slurp);
$palette.add-color(Color.new(0, 0, 0), 'Black');
$palette.add-color(Color.new(255, 0, 0));
$palette.=sort(:by<hsv>);
$palette.=unique(:by<color>);
$palette.name = 'Lots of Colors';
$palette.columns = 5;
say $palette.to-gpl;
```
# DESCRIPTION
Module for working with color palettes. Currently supports:
* parsing and generating GPL (GIMP Palette format v2)
* naive sorting by RGB or HSV values
Todo:
* support more color palette file formats
* implement fancier sorting algorithms, see <https://www.alanzucconi.com/2015/09/30/colour-sorting/>
# ATTRIBUTES
## `@colors`
Array of `NamedColor` objects. `NamedColor` is a simple class that holds a `Color` and an optional color name.
## `$name`
Optional name of the color palette.
## `$columns`
Specifies the number of columns to display the palette on in GIMP (only relevant when generating GPL files for use in GIMP).
# METHODS / SUBS
## `::from-gpl(Str:D $input)`
```
my $palette = Color::Palette::from-gpl('palette.gpl'.IO.slurp);
```
Creates and returns a `Color::Palette` object with the contents parsed from the given input string in GPL format.
## `.to-gpl`
Returns a string with the palette in GPL format.
## `.add-color(Color $color, Str $name?)`
```
$palette.add-color(Color.new(0, 0, 0), 'Black');
$palette.add-color(Color.new(255, 0, 0));
```
Adds a color with an optional color name to the palette.
## `.sort(Str :$by)`
```
$palette.=sort(:by<hsv>, :reverse);
```
Returns a copy of the palette with the colors sorted using the algorithm/criteria. Currently supported:
* `rgb` sorts by the RGB values of the color.
* `hsv` sorts by the HSV values of the color.
* `name` sorts the colors by name.
`:reverse` reverses the order of the colors after sorting.
## `.unique(:by<color>)`
```
$palette.=unique(:by<color>);
```
Returns a copy of the palette with duplicate colors removed. `color` detects duplicates by comparing the RGB values of the color, `name` checks for duplicate names.
# SEE ALSO
* [GIMP Palette Format Version 2 (.gpl)](https://developer.gimp.org/core/standards/gpl/)
* [The incredibly challenging task of sorting colours](https://www.alanzucconi.com/2015/09/30/colour-sorting/)
# AUTHOR
Jonas Kramer [jkramer@mark17.net](mailto:jkramer@mark17.net)
# COPYRIGHT AND LICENSE
Copyright 2024 Jonas Kramer
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-CTILMES-CroX-HTTP-Auth-Munge.md
# CroX::HTTP::Auth::Munge
`CroX::HTTP::Auth::Munge` is a
[`Cro::HTTP::Auth`](https://cro.services/docs/http-auth-and-sessions)
class for using [`Munge`](https://github.com/CurtTilmes/perl6-munge)
authentication with [Cro](https://cro.services).
## Concept
On the client side, a payload that can be any basic data structure (or
just a plain string, or even nothing at all) is optionally encoded
with JSON, then passed to the 'MUNGE' service to encode into a
credential token.
That token is passed from client to server in the `Authorization`
header, with authorization method `MUNGE` (non-standard) followed by
the token. Something like this:
```
Authorization: MUNGE MUNGE:AwQDAACo2CBRY7RWv/KTPN7WgyDcSXbnzrIBOITOEIeroK3nS8ND0GkZuqtaZnuBrZdSxzjZ/C+NwDkqTFHrgmiIbtwrbvKNCNeXYbR2BM6bxDz/PRGyN/I=:
```
The server decodes the token and makes the credentials available to
the HTTP server code.
See the main [MUNGE](https://github.com/dun/munge/wiki) web page for
more information.
## Server
This module gives you two classes (really roles so you can customize):
### `CroX::HTTP::Auth::Munge::Session`
Methods:
`.munge` - returns the `Munge` object used for the decode, you can
query it for things like the `.cipher`, `.zip`, etc. used to encode
the token.
`.uid` - The UID of the user.
`.gid` - The GID of the user.
`.encode-time` - The `DateTime` the token was encoded.
`.addr4` - The dotted quad for the IPv4 address of the host that
encoded the token.
`.payload` - The payload from the token.
`.json` - JSON decoded version of the payload.
### `CroX::HTTP::Auth::Munge`
`Cro::HTTP::Middleware` that can be used to handle the Munge'd
Authorization.
This is parameterized with a session that `does` the
`CroX::HTTP::Auth::Munge::Session` role.
For each `Cro::HTTP::Request` it handles, it will decode the
`Authorization` MUNGE credentials, and create a new session that
stores the decoded credentials that can be queried from within any
route.
### Basic Server:
From a `Cro` `route {}` block, use an instance in a before statement:
```
route {
before CroX::HTTP::Auth::Munge[CroX::HTTP::Auth::Munge::Session].new;
get -> CroX::HTTP::Auth::Munge::Session $session {
# Use $session.uid, $session.gid, $session.json, etc.
# to do something
content 'text/plain', "Ok\n";
}
```
See [eg/server.p6](https://github.com/CurtTilmes/perl6-crox-http-auth-munge/blob/master/eg/server.p6) for a working example.
A default `Munge` object will be used, but you can override with a
custom one if you like:
```
my $munge = Munge.new(cipher => ..., ttl => ...);
before CroX::HTTP::Auth::Munge[CroX::HTTP::Auth::Munge::Session].new(:$munge);
```
### Customize Session Server:
It can be useful to customize a little further to make the session a
little easier to use.
Assume the client will be passing in a data structure like this:
```
{ a => ..., b => ... }
```
You can put in methods to pull those bits out of the JSON:
```
class MySession does CroX::HTTP::Auth::Munge::Session
{
method a { $.json<a> }
method b { $.json<b> }
}
class MyAuth does CroX::HTTP::Auth::Munge[MySession] {}
my $routes = route
{
before MyAuth.new;
get -> MySession $session {
# Use $esssion.uid, $session.a, $session.b
content 'text/plain', "Ok\n";
}
};
```
See [eg/customsession.p6](https://github.com/CurtTilmes/perl6-crox-http-auth-munge/blob/master/eg/customsession.p6) for a working example.
### Client
You can use `curl` as a basic client, adding the `MUNGE` token to the
`Authorization` header on the command line like this (`bash` shell
syntax):
```
curl -v -H "Authorization: MUNGE $(echo -n '{"a":1,"b":2}' | munge)" http://localhost:10000/
```
You can also use the `Munge` module to build the header from within
Perl 6 as a `Cro::HTTP::Header` object:
```
my $cred = Munge.new.encode(to-json($payload));
Cro::HTTP::Header.new(name => 'Authorization', value => "MUNGE $cred");
```
As a convenience, this module includes a
`CroX::HTTP::Auth::Munge::Header` that exports a simple `munge()`
subroutine that does just that.
You can easily use it with `Cro::HTTP::Client`:
```
use Cro::HTTP::Client;
use CroX::HTTP::Auth::Munge::Header;
my %secure = a => 1, b => 2;
my $response = await Cro::HTTP::Client.get: "http://localhost:10000/",
headers => [ munge(%secure) ];
put await $response.body-text;
```
See [eg/client.p6](https://github.com/CurtTilmes/perl6-crox-http-auth-munge/blob/master/eg/client.p6) for a working example.
Note you can never re-use the MUNGE token or header -- it will fail to
decode if replayed. A new token must be produced for each use.
## License
Copyright © 2017 United States Government as represented by the
Administrator of the National Aeronautics and Space Administration.
No copyright is claimed in the United States under Title 17,
U.S.Code. All Other Rights Reserved.
|
## dist_zef-antononcube-Data-Cryptocurrencies.md
# Data::Cryptocurrencies Raku package
This Raku package has functions for cryptocurrency data retrieval.
(At this point, only [Yahoo Finance](https://finance.yahoo.com/crypto/) is used as a data source.)
The implementation follows the Mathematica implementation in [AAf1] described in [AA1].
(Further explorations are discussed in [AA2].)
---
## Installation
From [Zef ecosystem](https://raku.land):
```
zef install Data::Cryptocurrencies
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-Data-Cryptocurrencies.git
```
---
## Usage examples
Here we get Bitcoin (BTC) data from 1/1/2020 until now:
```
use Data::Cryptocurrencies;
use Data::Summarizers;
use Text::Plot;
my @ts = cryptocurrency-data('BTC', dates => (DateTime.new(2020, 1, 1, 0, 0, 0), now), props => <DateTime Close>,
format => 'dataset'):!cache-all;
say @ts.elems;
```
```
# 1138
```
When we request the data to be returned as “dataset” then the result is an array of hashes.
When we request the data to be returned as "timeseries" the result is an array of pairs (sorted by date.)
Here are BTC values for the last week (at the point of retrieval):
```
.say for @ts.tail(7)
```
```
# {Close => 22955.666016, DateTime => 2023-02-05T00:00:00Z}
# {Close => 22760.109375, DateTime => 2023-02-06T00:00:00Z}
# {Close => 23264.291016, DateTime => 2023-02-07T00:00:00Z}
# {Close => 22939.398438, DateTime => 2023-02-08T00:00:00Z}
# {Close => 21819.039063, DateTime => 2023-02-09T00:00:00Z}
# {Close => 21651.183594, DateTime => 2023-02-10T00:00:00Z}
# {Close => 21737.310547, DateTime => 2023-02-11T00:00:00Z}
```
Here is a summary:
```
records-summary(@ts, field-names => <DateTime Close>);
```
```
# +--------------------------------+----------------------------+
# | DateTime | Close |
# +--------------------------------+----------------------------+
# | Min => 2020-01-01T00:00:37Z | Min => 4970.788086 |
# | 1st-Qu => 2020-10-11T00:00:37Z | 1st-Qu => 11779.773438 |
# | Mean => 2021-07-22T12:00:37Z | Mean => 28606.4418860167 |
# | Median => 2021-07-22T12:00:37Z | Median => 23127.9101565 |
# | 3rd-Qu => 2022-05-03T00:00:37Z | 3rd-Qu => 42412.433594 |
# | Max => 2023-02-11T00:00:37Z | Max => 67566.828125 |
# +--------------------------------+----------------------------+
```
Clean data:
```
@ts = @ts.grep({ $_<Close> ~~ Numeric }).Array;
say @ts.elems;
```
```
# 1138
```
Here is a text-based plot of the corresponding time series:
```
say text-list-plot(@ts.map(*<DateTime>.Instant.Int).List, @ts.map(*<Close>).List, width => 100, height => 20);
```
```
# +------+-----------------+-----------------+-----------------+-----------------+-----------------+-+
# + + 70000.00
# | * * |
# | * * *** |
# + ******* ***** + 60000.00
# | ******* * ** ** |
# + **** *** ** * *** + 50000.00
# | ** * ***** *** * ** |
# | * * ** ** ** ******* |
# + **** **** * ***** *** + 40000.00
# | *** ****** * * |
# + *** * * *** + 30000.00
# | * * * |
# | ** ********* ** *** |
# + *** *** ************ + 20000.00
# | * *** ** |
# + ****** ************** + 10000.00
# | ** ***** |
# + + 0.00
# +------+-----------------+-----------------+-----------------+-----------------+-----------------+-+
# 1580000000.00 1600000000.00 1620000000.00 1640000000.00 1660000000.00 1680000000.00
```
---
## Data caching
Since the downloading of the cryptocurrencies data can be time consuming ( close to 1 minute)
it is a good idea to do data caching.
Data caching is "triggered" with the adverb `:cache-all`. Here is an example:
```
cryptocurrency-data('BTC', dates => 'today'):cache-all;
```
```
# [{Close => 457.334015, DateTime => 2014-09-17T00:00:00Z} {Close => 424.440002, DateTime => 2014-09-18T00:00:00Z} {Close => 394.79599, DateTime => 2014-09-19T00:00:00Z} {Close => 408.903992, DateTime => 2014-09-20T00:00:00Z} {Close => 398.821014, DateTime => 2014-09-21T00:00:00Z} {Close => 402.152008, DateTime => 2014-09-22T00:00:00Z} {Close => 435.790985, DateTime => 2014-09-23T00:00:00Z} {Close => 423.204987, DateTime => 2014-09-24T00:00:00Z} {Close => 411.574005, DateTime => 2014-09-25T00:00:00Z} {Close => 404.424988, DateTime => 2014-09-26T00:00:00Z} {Close => 399.519989, DateTime => 2014-09-27T00:00:00Z} {Close => 377.181, DateTime => 2014-09-28T00:00:00Z} {Close => 375.46701, DateTime => 2014-09-29T00:00:00Z} {Close => 386.944, DateTime => 2014-09-30T00:00:00Z} {Close => 383.61499, DateTime => 2014-10-01T00:00:00Z} {Close => 375.071991, DateTime => 2014-10-02T00:00:00Z} {Close => 359.511993, DateTime => 2014-10-03T00:00:00Z} {Close => 328.865997, DateTime => 2014-10-04T00:00:00Z} {Close => 320.51001, DateTime => 2014-10-05T00:00:00Z} {Close => 330.07901, DateTime => 2014-10-06T00:00:00Z} {Close => 336.187012, DateTime => 2014-10-07T00:00:00Z} {Close => 352.940002, DateTime => 2014-10-08T00:00:00Z} {Close => 365.026001, DateTime => 2014-10-09T00:00:00Z} {Close => 361.562012, DateTime => 2014-10-10T00:00:00Z} {Close => 362.299011, DateTime => 2014-10-11T00:00:00Z} {Close => 378.549011, DateTime => 2014-10-12T00:00:00Z} {Close => 390.414001, DateTime => 2014-10-13T00:00:00Z} {Close => 400.869995, DateTime => 2014-10-14T00:00:00Z} {Close => 394.77301, DateTime => 2014-10-15T00:00:00Z} {Close => 382.556, DateTime => 2014-10-16T00:00:00Z} {Close => 383.757996, DateTime => 2014-10-17T00:00:00Z} {Close => 391.441986, DateTime => 2014-10-18T00:00:00Z} {Close => 389.54599, DateTime => 2014-10-19T00:00:00Z} {Close => 382.845001, DateTime => 2014-10-20T00:00:00Z} {Close => 386.475006, DateTime => 2014-10-21T00:00:00Z} {Close => 383.15799, DateTime => 2014-10-22T00:00:00Z} {Close => 358.416992, DateTime => 2014-10-23T00:00:00Z} {Close => 358.345001, DateTime => 2014-10-24T00:00:00Z} {Close => 347.270996, DateTime => 2014-10-25T00:00:00Z} {Close => 354.70401, DateTime => 2014-10-26T00:00:00Z} {Close => 352.989014, DateTime => 2014-10-27T00:00:00Z} {Close => 357.618011, DateTime => 2014-10-28T00:00:00Z} {Close => 335.591003, DateTime => 2014-10-29T00:00:00Z} {Close => 345.304993, DateTime => 2014-10-30T00:00:00Z} {Close => 338.321014, DateTime => 2014-10-31T00:00:00Z} {Close => 325.748993, DateTime => 2014-11-01T00:00:00Z} {Close => 325.891998, DateTime => 2014-11-02T00:00:00Z} {Close => 327.553986, DateTime => 2014-11-03T00:00:00Z} {Close => 330.492004, DateTime => 2014-11-04T00:00:00Z} {Close => 339.485992, DateTime => 2014-11-05T00:00:00Z} {Close => 349.290009, DateTime => 2014-11-06T00:00:00Z} {Close => 342.415009, DateTime => 2014-11-07T00:00:00Z} {Close => 345.488007, DateTime => 2014-11-08T00:00:00Z} {Close => 363.264008, DateTime => 2014-11-09T00:00:00Z} {Close => 366.924011, DateTime => 2014-11-10T00:00:00Z} {Close => 367.695007, DateTime => 2014-11-11T00:00:00Z} {Close => 423.561005, DateTime => 2014-11-12T00:00:00Z} {Close => 420.734985, DateTime => 2014-11-13T00:00:00Z} {Close => 397.817993, DateTime => 2014-11-14T00:00:00Z} {Close => 376.132996, DateTime => 2014-11-15T00:00:00Z} {Close => 387.881989, DateTime => 2014-11-16T00:00:00Z} {Close => 387.40799, DateTime => 2014-11-17T00:00:00Z} {Close => 375.197998, DateTime => 2014-11-18T00:00:00Z} {Close => 380.554993, DateTime => 2014-11-19T00:00:00Z} {Close => 357.839996, DateTime => 2014-11-20T00:00:00Z} {Close => 350.847992, DateTime => 2014-11-21T00:00:00Z} {Close => 352.920013, DateTime => 2014-11-22T00:00:00Z} {Close => 367.572998, DateTime => 2014-11-23T00:00:00Z} {Close => 376.901001, DateTime => 2014-11-24T00:00:00Z} {Close => 375.347992, DateTime => 2014-11-25T00:00:00Z} {Close => 368.369995, DateTime => 2014-11-26T00:00:00Z} {Close => 369.670013, DateTime => 2014-11-27T00:00:00Z} {Close => 376.446991, DateTime => 2014-11-28T00:00:00Z} {Close => 375.490997, DateTime => 2014-11-29T00:00:00Z} {Close => 378.046997, DateTime => 2014-11-30T00:00:00Z} {Close => 379.244995, DateTime => 2014-12-01T00:00:00Z} {Close => 381.315002, DateTime => 2014-12-02T00:00:00Z} {Close => 375.01001, DateTime => 2014-12-03T00:00:00Z} {Close => 369.604004, DateTime => 2014-12-04T00:00:00Z} {Close => 376.854004, DateTime => 2014-12-05T00:00:00Z} {Close => 374.785004, DateTime => 2014-12-06T00:00:00Z} {Close => 375.095001, DateTime => 2014-12-07T00:00:00Z} {Close => 361.908997, DateTime => 2014-12-08T00:00:00Z} {Close => 352.218994, DateTime => 2014-12-09T00:00:00Z} {Close => 346.36499, DateTime => 2014-12-10T00:00:00Z} {Close => 350.506012, DateTime => 2014-12-11T00:00:00Z} {Close => 352.541992, DateTime => 2014-12-12T00:00:00Z} {Close => 347.376007, DateTime => 2014-12-13T00:00:00Z} {Close => 351.631989, DateTime => 2014-12-14T00:00:00Z} {Close => 345.345001, DateTime => 2014-12-15T00:00:00Z} {Close => 327.062012, DateTime => 2014-12-16T00:00:00Z} {Close => 319.776001, DateTime => 2014-12-17T00:00:00Z} {Close => 311.395996, DateTime => 2014-12-18T00:00:00Z} {Close => 317.842987, DateTime => 2014-12-19T00:00:00Z} {Close => 329.955994, DateTime => 2014-12-20T00:00:00Z} {Close => 320.842987, DateTime => 2014-12-21T00:00:00Z} {Close => 331.885986, DateTime => 2014-12-22T00:00:00Z} {Close => 334.571991, DateTime => 2014-12-23T00:00:00Z} {Close => 322.533997, DateTime => 2014-12-24T00:00:00Z} {Close => 319.007996, DateTime => 2014-12-25T00:00:00Z} ...]
```
By default no data caching is done (i.e. `:!cache-all`.)
The data is stored in the `$XDG_DATA_HOME` directory. See [JS1]. Every day new data is obtained.
**Remark:** The use of cached data greatly speeds up the cryptocurrencies explorations with this package.
---
## CLI
The package provides a Command Line Interface (CLI) script. Here is its usage message:
```
cryptocurrency-data --help
```
```
# Usage:
# cryptocurrency-data [<symbol>] [-p|--properties=<Str>] [--start-date=<Str>] [--end-date=<Str>] [-c|--currency=<Str>] [--format=<Str>] -- Retrieves cryptocurrency data.
#
# [<symbol>] Cryptocurrency symbol. [default: 'BTC']
# -p|--properties=<Str> Properties to retrieve. [default: 'all']
# --start-date=<Str> Start date. [default: 'auto']
# --end-date=<Str> End date. [default: 'now']
# -c|--currency=<Str> Currency. [default: 'USD']
# --format=<Str> Format of the result [default: 'json']
```
---
## Additional usage examples
The notebook
["Cryptocurrency-explorations.ipynb"](./docs/Cryptocurrencies-explorations.ipynb)
provides additional usage examples using [D3.js](https://d3js.org) plots.
(It loosely follows [AA2].)
---
## References
### Articles
[AA1] Anton Antonov
["Crypto-currencies data acquisition with visualization"](https://mathematicaforprediction.wordpress.com/2021/06/19/crypto-currencies-data-acquisition-with-visualization/)
,
(2021),
[MathematicaForPrediction at WordPress](https://mathematicaforprediction.wordpress.com).
[AA2] Anton Antonov
["Cryptocurrencies data explorations"](https://mathematicaforprediction.wordpress.com/2021/06/22/cryptocurrencies-data-explorations/)
,
(2021),
[MathematicaForPrediction at WordPress](https://mathematicaforprediction.wordpress.com).
### Functions, packages
[AAf1] Anton Antonov,
[CryptocurrencyData](https://www.wolframcloud.com/obj/antononcube/DeployedResources/Function/CryptocurrencyData/)
Mathematica resource function,
(2021),
[WolframCloud/antononcube](https://www.wolframcloud.com/obj/antononcube).
[AAp1] Anton Antonov,
[Data::Summarizers Raku package](https://github.com/antononcube/Raku-Data-Summarizers),
(2021-2023),
[GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov,
[Text::Plot Raku package](https://github.com/antononcube/Raku-Text-Plot),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[JS1] Jonathan Stowe,
[XDG::BaseDirectory Raku package](https://raku.land/zef:jonathanstowe/XDG::BaseDirectory),
(2016-2023),
[Zef-ecosystem/jonathanstowe](https://raku.land/zef:jonathanstowe).
|
## dist_zef-tqdv-List-Operator-DoublePlus.md
*Generated from DoublePlus.rakumod, then manually edited.*
# NAME
List::Operator::DoublePlus
# SYNOPSIS
```
use List::Operator::DoublePlus;
# Concatenate two lists together
my @l = @l1 ++ @l2;
my @l' = @l1 ⧺ @l2;
# The operator also works with Arrays and Slips
```
# DESCRIPTION
Provides a `++` operator to join or concatenate two lists together. The operator `⧺` is also exported as its Unicode counterpart.
The `concat` subroutine that implements the operator's functionality is exported on demand using the `sub` tag.
This module is inspired by Aaron Sherman's `Operator::Listcat` which defines an infix `listcat` operator, as well as the infix `⊕` (CIRCLED PLUS) Unicode alias.
# FUNCTIONS
**infix:<++>**
The operator form of `&concat`.
**infix:<⧺>**
The Unicode operator variant of `++`.
**concat**
multi sub concat(@a, @b --> List) multi sub concat(Slip \a, Slip \b --> Slip) multi sub concat(Array \a, Array \b --> Array)
Calls `.Slip` (which calls `.list`) on both arguments and applies the infix `,` operator to join them into a list.
For Slips, it returns a new Slip instead of a List.
For Arrays, it calls `.append` on the first parameter with the second parameter as its argument, and returns the combined array.
This subroutine also works for Seqs and any class that does PositionalBindFailover.
# EXPORTS
**:DEFAULT**
Same as :op, it exports the ++ operator and its Unicode counterpart ⧺.
**:op**
Exports the ++ operator and its Unicode counterpart ⧺.
**:sub**
Exports the `concat` subroutine which implements the operator's functionality.
**:plusplus**
Only exports the `++` operator.
**:doubleplus**
Only exports the Unicode `⧺` operator.
# NOTES
The double plus was chosen as the list concatenation operator due to its similarity to the `+` operator applied to lists in Python an other languages. The `++` operator is also used to concatenate lists in Elixir, Haskell, and Scala. `++` was chosen over the `@` operator used in OCaml as I thought it would be too close to the `@` sigil. The Unicode counterpart ⧺ was inspired by this StackExchange question: [Is there a common symbol for concatenating two (finite) sequences?](https://math.stackexchange.com/questions/298648/is-there-a-common-symbol-for-concatenating-two-finite-sequences/3637741#3637741)
# AUTHOR
Tilwa Qendov
# LICENSE
Licensed under the [Artistic License 2.0](LICENSE).
# SEE ALSO
* `Operator::Listcat`, the module this was inspired by.
|
## dist_zef-lizmat-as-cli-arguments.md
[](https://github.com/lizmat/as-cli-arguments/actions) [](https://github.com/lizmat/as-cli-arguments/actions) [](https://github.com/lizmat/as-cli-arguments/actions)
# NAME
as-cli-arguments - stringify a Capture as command-line arguments
# SYNOPSIS
```
use as-cli-arguments;
sub MAIN(|c) { say as-cli-arguments c, :named-anywhere }
```
```
use as-cli-arguments;
my %*SUB-MAIN-OPTS = :named-anywhere;
sub MAIN(|c) { say as-cli-arguments c }
sub MAIN(*@pos, :$foo, :$bar, *%_) {
die "Found unexpected named arguments: &as-cli-arguments(%_)"
if %_;
}
```
```
say as-cli-arguments { :42a, :666b } # --a=42 --b=666
say as-cli-arguments (:42a, :666b) # --a=42 --b=666
say as-cli-arguments "a" => 42; # --a=42
```
# DESCRIPTION
The `as-cli-arguments` distrubution exports a single subroutine `as-cli-arguments` that takes either a `Capture` object, a hash with named arguments, a `Pair` or a list of `Pair`s and returns a string that represents the contents of the argument given as if they were command line arguments.
If a `Capture` object is specified, then the subroutine also takes an optional named arguments `:named-anywhere` to indicate whether or not the "named arguments anywhere" mode should be assumed. By default, this will use the `%*SUB-MAIN-OPTS<named-anywhere>` setting, if available. Else it will default to `False`.
This is mainly intended as a helper subroutine for command-line scripts and modules that want to give feedback about the given or perceived or unexpected command line parameters.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/as-cli-arguments> . Comments and Pull Requests are welcome.
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2022, 2024, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-perl6-Pod-To-Cached.md
# Pod::To::Cached
[](https://travis-ci.com/perl6/Pod-To-Cached)
[](https://ci.appveyor.com/api/projects/status/github/perl6/Pod-To-Cached?svg=true)
Create and Maintain a cache of precompiled pod files
Module to take a collection of pod files and create a precompiled cache. Methods / functions
to add a pod file to a cache.
## Install
This module is in the [Raku ecosystem](https://modules.raku.org), so you
install it in the usual way:
```
zef install Pod::To::Cached
```
Although this module is usable, it will be soon substituted by [`Pod::From::Cached`](https://github.com/finanalyst/raku-pod-from-cache). So it's
probably better if you try and adapt to that new module.
The module is now in maintenance mode, and only bugfixes will be released.
# SYNOPSIS
```
use Pod::To::Cached;
my Pod::To::Cached $cache .= new(:path<path-to-cache>, :source<path-to-directory-with-pod-files>);
$cache.update-cache;
for $cache.hash-files.kv -> $source-name, $status {
given $status {
when 'Current' {say "「$source-name」 is up to date with POD source"}
when 'Valid' {say "「$source-name」 has valid POD, but newer POD source contains invalid POD"}
when 'Failed' {say "「$source-name」 is not in cache, and source file contains invalid POD"}
when 'New' { say "「$source-name」 is not in cache and cache has not been updated"}
when 'Old' { say "「$source-name」 is in cache, but has no associated pod file in DOC"}
}
user-supplied-routine-for-processing-pod( $cache.pod( $source-name ) );
}
# Find files with status
say 'These pod files failed:';
.say for $cache.list-files( 'Failed' );
say 'These sources have valid pod:';
.say for $cache.list-files(<Current Valid>);
# Find date when pod added to cache
my $source = 'language/pod'; # name of a documentation source
say "「$source」 was added on 「{ $cache.cache-timestamp( $source ) }」";
# Remove the dependence on the pod source
$cache.freeze;
```
## Notes
* Str $!path = '.pod6-cache'
path to the directory where the cache will be created/kept
* Str $!source = 'doc'
path to the collection of pod files
ignored if cache frozen
* @!extensions =
the possible extensions for a POD file
* verbose = False
Whether processing information is sent to stderr.
* new
Instantiates class. On instantiation,
* get the cache from index, or creates a new cache if one does not exist
* if frozen, does not check the source directory
* if not frozen, or new cache being created, verifies
* source directory exists
* the source directory contains POD/POD6 etc files (recursively)
* no duplicate pod file names exist, eg. xx.pod & xx.pod6
* verifies whether the cache is valid
* update-cache
All files with a modified timestamp (reported by the filesystem) after the added instant are precompiled and added to the cache
* Status is changed to Updated (compiles Valid) or Fail (does not compile)
* Failed files that were previously Valid files still retain the old cache handle
* Throws an exception when called on a frozen cache
* freeze
Can be called only when there are only Valid or Updated (no New, Tainted or Failed files),
otherwise dies.
The intent of this method is to allow the pod-cache to be copied without the original pod-files.
update-cache will throw an error if used on a frozen cache
* list-files( Str $s --> Positional )
returns an Sequence of files with the given status
* list-files( Str $s1, $s2 --> Positional )
returns an Array of files with the given status list
* hash-files( \*@statuses? --> Associative )
returns a map of the source-name and its statuses
* explicitly give required status strings: C<< $cache.hash-files() >>
* return all files C< $cache.hash-files >
* cache-timestamp( $source --> Instant )
returns the Instant when a valid version of the Pod was added to the cache
* if the time-stamp is before the time the Pod was modified, then the pod has errors
* a Failed source has a timestamp of zero
* pod
* method pod(Str $source)
* Returns an array of POD Objects generated from the file associated with $source name.
* When a doc-set is being actively updated, then pod files may have failed, in which case they have Status Valid.
* To froze a cache, all files must have Current status
* Status is an enum with the following elements and semantics
* Current
There is a compiled source in the cache with an added date **after** the modified date
* Valid
There is a compiled source in the cache with an added date **before** the modified date and there has been an attempt to add the source to cache that did not compile
* Failed
There is not a compiled source in the cache, but there has been an attempt to add the source name to the cache that did not compile
* New
A new pod source has been detected that is not in cache, but C has not yet been called to compile the source. A transitional Status
* Old
A source name that is in the cache but no longer reflects an existing source.
## 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.
The META6.json file of this distribution may be distributed and modified without restrictions or attribution.
|
## dist_zef-dwarring-PDF-To-Cairo.md
[[Raku PDF Project]](https://pdf-raku.github.io)
/ [PDF::To::Cairo](https://pdf-raku.github.io/PDF-To-Cairo-raku)
# PDF::To::Cairo
## Example
To burst `my.pdf` to PNG images `my-001.png` `my-002.png` ...
### Via the shell
```
bin/pdf2image.raku my.pdf
```
### Via Raku
```
use PDF::Class;
use PDF::To::Cairo;
my PDF::Class $pdf .= open: "my.pdf";
my $outfile-templ = "my-%03d.png";
PDF::To::Cairo.save-as($pdf, $outfile-templ);
```
## Description
This module is an experimental work-in-progress PDF rendering via Cairo and the Raku PDF Tool-chain.
It is able to render from [PDF::Class](https://pdf-raku.github.io/PDF-Class-raku/) or [PDF::API6](https://pdf-raku.github.io/PDF-API6/) objects. Supported output formats are `PNG`, `PDF` (round trip) and `SVG`.
This module can currently render text (most fonts), simple colors, tiling patterns and basic graphics.
At this stage its main purpose is to exercise Raku modules related
to PDF, fonts and rendering, including:
* [PDF](https://pdf-raku.github.io/PDF-raku/) (threading)
* [PDF::Content](https://pdf-raku.github.io/PDF-Content-raku/) (graphics, images)
* [PDF::Font::Loader](https://pdf-raku.github.io/PDF-Font-Loader-raku/) (font loading, decoding, rendering, threading)
* [PDF::Class](https://pdf-raku.github.io/PDF-Class-raku/) (objects)
* [Font::FreeType](https://pdf-raku.github.io/Font-FreeType-raku/) (fonts and glyphs)
* [Cairo](https://github.com/timo/cairo-p6) (rendering)
## Scripts
#### `pdf2image.raku --page=n --batch=m --trace --password=*** <in>.pdf [out-fmt]`
Where
* `<in>.pdf` is a PDF file
* `[out-fmt]` is an option output file format specification (default -%03d.png).
##### `pdf2image.raku` Options
* `--page=n` render just the `n`th page in the PDF file
* `--batch=m` render to threads in batches of `m` pages
* `--trace` trace PDF graphics
#### `pdf-previews.raku <directory> --previews=<directory>`
Render all PDF files in a given input directory (default `.`) and render PNG previews
to a given output directory; by default to a `.previews` subdirectory in the input directory.
## Status
Implemented:
* basic text, including fonts, word and character spacing
* most drawing and graphics operators
* form XObjects
* some (mostly PNG like) image XObjects (depends on state
of PDF::Class PDF::Image.to-png() method)
* Gray, RGB, CMYK, DeviceN and Separation color-spaces
* Tiling patterns (not shading)
Nyi:
* advanced clipping and graphics settings
* many image types
* shading patterns
* some font types (in particular Type3 synthetic fonts)
|
## assignment.md
class X::TypeCheck::Assignment
Error due to a failed type check during assignment
```raku
class X::TypeCheck::Assignment is X::TypeCheck { }
```
Error class thrown when the type check of an assignment fails.
For example, this will die
```raku
my Int $x = "foo";
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $x; expected Int but got Str ("foo")»
```
though compilers are allowed to detect obvious cases like this example and complain at compile time with a different error.
|
## dist_cpan-NINE-Distribution-Builder-MakeFromJSON.md
[](https://travis-ci.org/niner/Distribution-Builder-MakeFromJSON)
# NAME
Distribution::Builder::MakeFromJSON - Makefile based distribution builder
# SYNOPSIS
```
use Distribution::Builder::MakeFromJSON;
```
# DESCRIPTION
Distribution::Builder::MakeFromJSON uses information from your META6.json and the running system to fill variabls in a Makefile.in template and build your distribution.
# AUTHOR
Stefan Seifert [nine@detonation.org](mailto:nine@detonation.org)
# COPYRIGHT AND LICENSE
Copyright 2017 Stefan Seifert
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-masukomi-Definitely.md
# Definitely (Maybe)
An implementation of the Maybe Monad in Raku
## DESCRIPTION
The [Maybe Monad](https://en.wikipedia.org/wiki/Monad_(functional_programming)#An_example:_Maybe) is a technique for avoiding unexpected Nil exceptions or having to explicitly test for Nil in a method's response. It removes a lot of ambiguity, which increases maintainability, and reduces surprises.
It's called "Definitely" because when you use this module's types, you'll "Definitely" know what you're working with:
* `Definitely::Maybe`
* `Definitely::Some`
* `Definitley::None`
For example:
```
sub never-int() returns Int { Nil }
#vs
sub maybe-int() returns Maybe[Int] {...}
```
The `never-int` function claims it'll return an `Int`, but it never does. The `maybe-int` function makes it explicit that *maybe* you'll get an Int, but *maybe* you won't.
`Some` & `None` both provide an `.is-something` method, if you want to explicitly test if you have something. You can also convert them to a Bool for quick testing (Some is True, None is False). You can explicitly extract the value from a Maybe/Some object by calling its `.value` method.
`None` provides a `FALLBACK` method that returns the same None object. This means that you can call method chains on it as if it were the thing you hoped for without blowing up. Obviously, you'd only do this if your system would be ok with nothing happening as a result of these calls. For example, logging is nice, but you probably want your system to carry on even if the logging mechanism is unavailable.
```
multi sub logger($x) returns Maybe[Logger] {
nothing(Logger)
}
logger().record_error("does nothing, and doesn't blow up")
```
Many racoons argue that because Raku has typed `Nil`s, the Maybe Monad is already built in. See [this Stack Overflow answer](https://stackoverflow.com/questions/55072228/creating-a-maybe-type-in-perl-6) for more details. Even if they're right, people like me would argue that there's a huge maintainability value to having code that makes it *explicit* that *Maybe* the value you get back from a method won't be what you were hoping for.
## USAGE
The core idea is simple. When creating a function specify it's return type as `Maybe` or `Maybe[Type]`. Within the function you'll use the `something(Any)` and `nothing()` or `nothing(Type)` helper functions to provide a `Maybe` / `Maybe[Type]` compatible object to your caller. The caller then has multiple choices for how to handle the result.
Note: you should not specify Maybe when calling `nothing(Type)`. For example, call `nothing(Int)` not `nothing(Maybe[Int])`. The function will take care of making sure it conforms to the Maybe Type for you.
```
use Definitely;
multi sub foo($x) returns Maybe[Int] {
$x ~~ Int ?? something($x) !! nothing(Int);
}
multi sub foo($x) returns Maybe {
2.rand.Int == 1 ?? something($x) !! nothing();
}
# explicitly handle questionable results
given foo(3) {
when $_ ~~ Some {say "'Tis a thing Papa!. Look: $_"}
default {say "'Tis nothing.'"}
}
# or, call the .is-something method
my Maybe[Int] $questionable_result = foo(3)
if $questionable_result.is-something {
# extract the value directly
return $questionable_result.value + 4;
}
# or, test truthyness (Some is True None is False)
my Maybe[Int] $questionable_result = foo(4);
?$questionable_result ?? $questionable_result.value !! die "oh no!"
# or, just assume it's good if you don't care if calls have no result
my Maybe[Logger] $maybe_log = logger();
$maybe_log.report_error("called if logger is Some, ignored if None")
```
## Installation
`zef install Definitely`
## AUTHORS
The seed of this comes from [This post by p6Steve](https://p6steve.wordpress.com/2022/08/16/raku-rust-option-some-none/). [masukomi](https://masukomi.org)) built it out into a full Maybe Monad implementation as a Raku module.
## LICENSE
MIT. See LICENSE file.
### method is-something
```
method is-something() returns Bool
```
Returns true for Some
### sub something
```
sub something(
::Type $value
) returns Mu
```
Simple creation of Some objects that also match the Maybe type.
### multi sub nothing
```
multi sub nothing(
::Type $
) returns Mu
```
Used to create None objects when your method returns a typed Maybe.
### multi sub nothing
```
multi sub nothing() returns Mu
```
Used to create None objects when your method returns an untyped Maybe.
### sub unwrap
```
sub unwrap(
Definitely::Maybe $maybe_obj,
Str $message
) returns Mu
```
extracts the value from a Maybe object or dies with your message
|
## dist_zef-lizmat-NYI.md
[](https://github.com/lizmat/NYI/actions)
# NAME
NYI - Provide shortcut to X::NYI
# SYNOPSIS
```
use NYI;
multi sub frobnicate("insert", |) { NYI "insert a frob" }
```
# DESCRIPTION
Provide a shortcut to doing:
```
Failure.new: X::NYI.new: feature => "feature";
```
This can be used as a return value in a subroutine or method:
```
multi method frobnicate("insert", |) { NYI "insert a frob" }
```
Or to fail or throw immediately:
```
fail NYI("insert a frob");
NYI("insert a frob").throw;
```
Reasons for using this subroutine are:
* reduce bytecode size of hot code paths
* better readability because of less noise
Should the core of the Raku Programming Language already provide a `NYI` subroutine, then this module will become a no-op.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/NYI> . Comments and Pull Requests are welcome.
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2022, 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-immutable.md
[](https://github.com/lizmat/immutable/actions) [](https://github.com/lizmat/immutable/actions) [](https://github.com/lizmat/immutable/actions)
# NAME
immutable - Make data structures immutable
# SYNOPSIS
```
use immutable;
my $ima := immutable @array;
my $imh := immutable %hash;
my $ims := immutable @array, %hash;
my $imp := immutable (a => 42);
```
# DESCRIPTION
The `immutable` distribution provides a single subroutine `immutable` that will return an immutable value-type data-structure for any data-structure given.
Inspired by a comment by Ralph Mellor on /r/rakulang.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/immutable> . Comments and Pull Requests are welcome.
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2022, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-SOFTMOTH-Pod-To-Markdown.md
[](https://travis-ci.org/softmoth/raku-Pod-To-Markdown) [](https://ci.appveyor.com/project/softmoth/raku-Pod-To-Markdown/branch/master)
# NAME
Pod::To::Markdown - Render Pod as Markdown
# SYNOPSIS
From command line:
```
$ raku --doc=Markdown lib/To/Class.rakumod
```
From Raku:
```
use Pod::To::Markdown;
=NAME
foobar.pl
=SYNOPSIS
foobar.pl <options> files ...
print pod2markdown($=pod);
```
# EXPORTS
```
class Pod::To::Markdown
sub pod2markdown
```
# DESCRIPTION
### method render
```
method render($pod, Bool :$no-fenced-codeblocks --> Str)
```
Render Pod as Markdown
To render without fenced codeblocks (`````), as some markdown engines don't support this, use the :no-fenced-codeblocks option. If you want to have code show up as ````raku` to enable syntax highlighting on certain markdown renderers, use:
```
=begin code :lang<raku>
```
### sub pod2markdown
```
sub pod2markdown($pod, Bool :$no-fenced-codeblocks --> Str)
```
Render Pod as Markdown, see .render()
# LICENSE
This is free software; you can redistribute it and/or modify it under the terms of The [Artistic License 2.0](http://www.perlfoundation.org/artistic_license_2_0).
|
## dist_github-salortiz-NativeHelpers-Blob.md
# NativeHelpers::Blob
## Introduction
Right now the support for `Blob`/`Buf` in Perl 6's NativeCall is incomplete.
You can use these as arguments for native functions, but not as attributes for
`CStruct` or `CUnion`, for example.
In a `CStruct` class, you can use a `Pointer` or a `CArray`, but those don't have the
flexibility of a `Blob` or `Buf`, moving data between them is slow, and with
big buffers the memory required increases dramatically.
At some point, these problems will be addressed in core, but in the meantime...
## Usage
```
use NativeHelpers::Blob;
```
### Run benchmarks
Use
```
zef install Bench
```
to install that module, and then you can run the benchmarks in the
root directory:
```
perl6 -Ilib bench.pl6
perl6 -Ilib bench-slurpy.pl6
```
## Exported functions
### multi sub pointer-to(Blob:D, :$typed -> Pointer)
Returns a `Pointer` to the contents of the `Blob`.
The type of the returned `Pointer` will be the same of the `Blob` if `:typed` was used
or `void` if not.
Should be noted that the memory is owned by Rakudo, so you must not attempt
to free it.
### multi sub pointer-to(array:D, :$typed -> Pointer)
Returns a `Pointer` to the contents of the native `array`.
The type of the returned `Pointer` will be the same of the `array` if `:typed` was used
or `void` if not.
Should be noted that the memory is owned by Rakudo, so you must not attempt
to free it.
### multi sub pointer-to(CArray:D, :$typed -> Pointer)
Returns a `Pointer` to the contents of the native `CArray`.
The type of the returned `Pointer` will be the same of the `CAarray` if `:typed` was used
or `void` if not.
Should be noted that the memory is owned by Rakudo, so you must not attempt
to free it.
### sub carray-from-blob(Blob:D, :$managed)
Returns a `CArray` constructed from de contents of the `Blob`.
If `:managed` was given, the returned `CArray` contains a copy of the original
content of the `Blob` and will be managed, otherwise the `CArray` holds a
reference to the `Blob` content.
### sub blob-allocate(Blob:U \blob, $elems)
Rakudo 2016.03+ provides `Blob.allocate` to create a Blob/Buf with a pre-allocated
initial size.
For older ones you can use this subroutine for the same effect. It create a `blob`
with `$elems` zeroed elements.
### sub blob-from-pointer(Pointer:D, Int :$elems!, Blob:U :$type = Buf)
Returns a `Blob` of type `:type` constructed from the memory pointed by the
given `Pointer` and the following `:elems` elements.
The type of the `Pointer` should be compatible with the type of the `Blob`,
Please note that the amount of memory copied depends of `$elems` **and** `:type`´s
native size.
### sub blob-from-carray(CArray:D, Int :$size)
Returns a `Blob` constructed from the contents of the `CArray`.
When the `CArray` is unmanaged, for example as returned by a native call function, you
should include de `:size` argument.
The type of the `Blob` is determined by the type of the `CArray`.
## WARNING
This module depends on internal details of the REPRs of the involved types in MoarVM,
so it can stop working without notice.
In the same way as when handling pointers in C, you should known what are you doing.
This is an early release to allow the interested people the testing and
discussion of the module: there is some missing features and you should
be aware that the API isn't in stone yet.
## COPYRIGHT
Copyright © 2016 by Salvador Ortiz
|
## dist_zef-rbt-Email-MIME.md
# Email::MIME
This is a port of perl 5's Email::MIME.
## Example Usage
```
use Email::MIME;
my $eml = Email::MIME.new($raw-mail-text);
say $eml.body-str;
my $new = Email::MIME.create(header-str => ['from' => 'root+github@retupmoca.com',
'subject' => 'This is a»test.'],
attributes => {'content-type' => 'text/plain',
'charset' => 'utf-8',
'encoding' => 'quoted-printable'},
body-str => 'Hello«World');
say ~$new;
```
## Faster Base64 Encoding
To benefit from faster Base64 encoding and decoding install the `Base64::Native` module
which will be auto-detected and used automatically.
## Methods
* `new(Str $text)`
To work around the current limitation of new() requiring a well formed unicode Str, you will
need to set the correct decoding on Slurp.
```
my $msg = Email::MIME.new($file.IO.slurp: enc => 'utf8-c8');
```
* `create(:$header, :$header-str, :$attributes, :$parts, :$body, :$body-str)`
* `filename($force = False)`
* `invent-filename($ct?)`
* `filename-set($filename)`
* `boundary-set($string)`
* `content-type()`
* `content-type-set($ct)`
* `charset-set($charset)`
* `name-set($name)`
* `format-set($format)`
* `disposition-set($disposition)`
* `encoding-set($enc)`
* `parts()`
Returns the subparts of the current message. If there are no subparts, will
return the current message.
* `subparts()`
Returns the subparts of the current message. If there are no subparts, will
return an empty list.
* `walk-parts($callback)`
Visits each MIME part once, calling `$callback($part)` on each.
* `debug-structure()`
Prints out the part structure of the email.
* `parts-set(@parts)`
Sets the passed `Email::MIME` objects as the parts of the email.
* `parts-add(@parts)`
Adds the passed `Email::MIME` objects to the list of parts in the email.
* `body-str( --> Str)`
Returns the mail body, decoded according to the charset and transfer encoding
headers.
* `body-str-set(Str $body)`
Sets the mail body to $body, encoding it using the charset and transfer
encoding configured.
* `body( --> Buf)`
Returns the mail body as a binary blob, after decoding it from the
transfer encoding.
* `body-set(Blob $data)`
Sets the mail body to `$data`. Will encode $data using the configured
transfer encoding.
* `body-raw()`
Returns the raw body of the email (What will appear when .Str is called)
* `body-raw-set($body)`
Sets the raw body of the email (What will appear when .Str is called)
* `header-str-pairs()`
Returns the full header data for an email.
* `header-str($name, :$multi)`
Returns the email header with the name `$name`. If `:$multi` is not passed, then
this will return the first header found. If `:$multi` is set, then this will
return a list of all headers with the name `$name` (note the change from v1.0!)
* `header-str-set($name, *@lines)`
Sets the header `$name`. Adds one `$name` header for each additional argument
passed.
* `header-names()`
Returns a list of header names in the email.
* `headers()`
Alias of `header-names()`
* `header($name)`
Returns a list of email headers with the name `$name`. If used in string context,
will act like the first value of the list. (So you can call
`say $eml.header('Subject')` and it will work correctly). Note that this will
not decode any encoded headers.
* `header-set($name, *@lines)`
Sets the header `$name`. Adds one `$name` header for each additional argument
passed. This will not encode any headers, even if they have non-ascii
characters.
* `header-pairs()`
Returns the full header data for an email. Note that this will not decode any
encoded headers.
```
$eml.header-pairs(); # --> [['Subject', 'test'], ['From', 'me@example.com']]
```
* `as-string()`, `Str()`
Returns the full raw email, suitable for piping into sendmail.
* `crlf()`
* `header-obj()`
* `header-obj-set($obj)`
## License
All files in this repository are licensed under the terms of the Creative Commons
CC0 License; for details, please see the LICENSE file
|
## dist_zef-lizmat-P5pack.md
[](https://github.com/lizmat/P5pack/actions) [](https://github.com/lizmat/P5pack/actions) [](https://github.com/lizmat/P5pack/actions)
# NAME
Raku port of Perl's pack() / unpack() built-ins
# SYNOPSIS
```
use P5pack; # exports pack(), unpack(), activates Buf.unpack()
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `pack` and `unpack` built-ins as closely as possible in the Raku Programming Language.
Currently supported directives are: a A c C h H i I l L n N q Q s S U v V w x Z
Drop-in replacement for `use experimental :pack`.
# ORIGINAL PERL 5 DOCUMENTATION
```
pack TEMPLATE,LIST
Takes a LIST of values and converts it into a string using the
rules given by the TEMPLATE. The resulting string is the
concatenation of the converted values. Typically, each converted
value looks like its machine-level representation. For example, on
32-bit machines an integer may be represented by a sequence of 4
bytes, which will in Perl be presented as a string that's 4
characters long.
See perlpacktut for an introduction to this function.
The TEMPLATE is a sequence of characters that give the order and
type of values, as follows:
a A string with arbitrary binary data, will be null padded.
A A text (ASCII) string, will be space padded.
Z A null-terminated (ASCIZ) string, will be null padded.
b A bit string (ascending bit order inside each byte,
like vec()).
B A bit string (descending bit order inside each byte).
h A hex string (low nybble first).
H A hex string (high nybble first).
c A signed char (8-bit) value.
C An unsigned char (octet) value.
W An unsigned char value (can be greater than 255).
s A signed short (16-bit) value.
S An unsigned short value.
l A signed long (32-bit) value.
L An unsigned long value.
q A signed quad (64-bit) value.
Q An unsigned quad value.
(Quads are available only if your system supports 64-bit
integer values _and_ if Perl has been compiled to support
those. Raises an exception otherwise.)
i A signed integer value.
I A unsigned integer value.
(This 'integer' is _at_least_ 32 bits wide. Its exact
size depends on what a local C compiler calls 'int'.)
n An unsigned short (16-bit) in "network" (big-endian) order.
N An unsigned long (32-bit) in "network" (big-endian) order.
v An unsigned short (16-bit) in "VAX" (little-endian) order.
V An unsigned long (32-bit) in "VAX" (little-endian) order.
j A Perl internal signed integer value (IV).
J A Perl internal unsigned integer value (UV).
f A single-precision float in native format.
d A double-precision float in native format.
F A Perl internal floating-point value (NV) in native format
D A float of long-double precision in native format.
(Long doubles are available only if your system supports
long double values _and_ if Perl has been compiled to
support those. Raises an exception otherwise.)
p A pointer to a null-terminated string.
P A pointer to a structure (fixed-length string).
u A uuencoded string.
U A Unicode character number. Encodes to a character in char-
acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in
byte mode.
w A BER compressed integer (not an ASN.1 BER, see perlpacktut
for details). Its bytes represent an unsigned integer in
base 128, most significant digit first, with as few digits
as possible. Bit eight (the high bit) is set on each byte
except the last.
x A null byte (a.k.a ASCII NUL, "\000", chr(0))
X Back up a byte.
@ Null-fill or truncate to absolute position, counted from the
start of the innermost ()-group.
. Null-fill or truncate to absolute position specified by
the value.
( Start of a ()-group.
One or more modifiers below may optionally follow certain letters
in the TEMPLATE (the second column lists letters for which the
modifier is valid):
! sSlLiI Forces native (short, long, int) sizes instead
of fixed (16-/32-bit) sizes.
! xX Make x and X act as alignment commands.
! nNvV Treat integers as signed instead of unsigned.
! @. Specify position as byte offset in the internal
representation of the packed string. Efficient
but dangerous.
> sSiIlLqQ Force big-endian byte-order on the type.
jJfFdDpP (The "big end" touches the construct.)
< sSiIlLqQ Force little-endian byte-order on the type.
jJfFdDpP (The "little end" touches the construct.)
The ">" and "<" modifiers can also be used on "()" groups to force
a particular byte-order on all components in that group, including
all its subgroups.
The following rules apply:
* Each letter may optionally be followed by a number indicating
the repeat count. A numeric repeat count may optionally be
enclosed in brackets, as in "pack("C[80]", @arr)". The repeat
count gobbles that many values from the LIST when used with
all format types other than "a", "A", "Z", "b", "B", "h", "H",
"@", ".", "x", "X", and "P", where it means something else,
described below. Supplying a "*" for the repeat count instead
of a number means to use however many items are left, except
for:
* "@", "x", and "X", where it is equivalent to 0.
* <.>, where it means relative to the start of the string.
* "u", where it is equivalent to 1 (or 45, which here is
equivalent).
One can replace a numeric repeat count with a template letter
enclosed in brackets to use the packed byte length of the
bracketed template for the repeat count.
For example, the template "x[L]" skips as many bytes as in a
packed long, and the template "$t X[$t] $t" unpacks twice
whatever $t (when variable-expanded) unpacks. If the template
in brackets contains alignment commands (such as "x![d]"), its
packed length is calculated as if the start of the template
had the maximal possible alignment.
When used with "Z", a "*" as the repeat count is guaranteed to
add a trailing null byte, so the resulting string is always
one byte longer than the byte length of the item itself.
When used with "@", the repeat count represents an offset from
the start of the innermost "()" group.
When used with ".", the repeat count determines the starting
position to calculate the value offset as follows:
* If the repeat count is 0, it's relative to the current
position.
* If the repeat count is "*", the offset is relative to the
start of the packed string.
* And if it's an integer n, the offset is relative to the
start of the nth innermost "( )" group, or to the start of
the string if n is bigger then the group level.
The repeat count for "u" is interpreted as the maximal number
of bytes to encode per line of output, with 0, 1 and 2
replaced by 45. The repeat count should not be more than 65.
* The "a", "A", and "Z" types gobble just one value, but pack it
as a string of length count, padding with nulls or spaces as
needed. When unpacking, "A" strips trailing whitespace and
nulls, "Z" strips everything after the first null, and "a"
returns data with no stripping at all.
If the value to pack is too long, the result is truncated. If
it's too long and an explicit count is provided, "Z" packs
only "$count-1" bytes, followed by a null byte. Thus "Z"
always packs a trailing null, except when the count is 0.
* Likewise, the "b" and "B" formats pack a string that's that
many bits long. Each such format generates 1 bit of the
result. These are typically followed by a repeat count like
"B8" or "B64".
Each result bit is based on the least-significant bit of the
corresponding input character, i.e., on "ord($char)%2". In
particular, characters "0" and "1" generate bits 0 and 1, as
do characters "\000" and "\001".
Starting from the beginning of the input string, each 8-tuple
of characters is converted to 1 character of output. With
format "b", the first character of the 8-tuple determines the
least-significant bit of a character; with format "B", it
determines the most-significant bit of a character.
If the length of the input string is not evenly divisible by
8, the remainder is packed as if the input string were padded
by null characters at the end. Similarly during unpacking,
"extra" bits are ignored.
If the input string is longer than needed, remaining
characters are ignored.
A "*" for the repeat count uses all characters of the input
field. On unpacking, bits are converted to a string of 0s and
1s.
* The "h" and "H" formats pack a string that many nybbles (4-bit
groups, representable as hexadecimal digits, "0".."9"
"a".."f") long.
For each such format, pack() generates 4 bits of result. With
non-alphabetical characters, the result is based on the 4
least-significant bits of the input character, i.e., on
"ord($char)%16". In particular, characters "0" and "1"
generate nybbles 0 and 1, as do bytes "\000" and "\001". For
characters "a".."f" and "A".."F", the result is compatible
with the usual hexadecimal digits, so that "a" and "A" both
generate the nybble "0xA==10". Use only these specific hex
characters with this format.
Starting from the beginning of the template to pack(), each
pair of characters is converted to 1 character of output. With
format "h", the first character of the pair determines the
least-significant nybble of the output character; with format
"H", it determines the most-significant nybble.
If the length of the input string is not even, it behaves as
if padded by a null character at the end. Similarly, "extra"
nybbles are ignored during unpacking.
If the input string is longer than needed, extra characters
are ignored.
A "*" for the repeat count uses all characters of the input
field. For unpack(), nybbles are converted to a string of
hexadecimal digits.
* The "p" format packs a pointer to a null-terminated string.
You are responsible for ensuring that the string is not a
temporary value, as that could potentially get deallocated
before you got around to using the packed result. The "P"
format packs a pointer to a structure of the size indicated by
the length. A null pointer is created if the corresponding
value for "p" or "P" is "undef"; similarly with unpack(),
where a null pointer unpacks into "undef".
If your system has a strange pointer size--meaning a pointer
is neither as big as an int nor as big as a long--it may not
be possible to pack or unpack pointers in big- or
little-endian byte order. Attempting to do so raises an
exception.
* The "/" template character allows packing and unpacking of a
sequence of items where the packed structure contains a packed
item count followed by the packed items themselves. This is
useful when the structure you're unpacking has encoded the
sizes or repeat counts for some of its fields within the
structure itself as separate fields.
For "pack", you write length-item"/"sequence-item, and the
length-item describes how the length value is packed. Formats
likely to be of most use are integer-packing ones like "n" for
Java strings, "w" for ASN.1 or SNMP, and "N" for Sun XDR.
For "pack", sequence-item may have a repeat count, in which
case the minimum of that and the number of available items is
used as the argument for length-item. If it has no repeat
count or uses a '*', the number of available items is used.
For "unpack", an internal stack of integer arguments unpacked
so far is used. You write "/"sequence-item and the repeat
count is obtained by popping off the last element from the
stack. The sequence-item must not have a repeat count.
If sequence-item refers to a string type ("A", "a", or "Z"),
the length-item is the string length, not the number of
strings. With an explicit repeat count for pack, the packed
string is adjusted to that length. For example:
This code: gives this result:
unpack("W/a", "\004Gurusamy") ("Guru")
unpack("a3/A A*", "007 Bond J ") (" Bond", "J")
unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".")
pack("n/a* w/a","hello,","world") "\000\006hello,\005world"
pack("a/W2", ord("a") .. ord("z")) "2ab"
The length-item is not returned explicitly from "unpack".
Supplying a count to the length-item format letter is only
useful with "A", "a", or "Z". Packing with a length-item of
"a" or "Z" may introduce "\000" characters, which Perl does
not regard as legal in numeric strings.
* The integer types "s", "S", "l", and "L" may be followed by a
"!" modifier to specify native shorts or longs. As shown in
the example above, a bare "l" means exactly 32 bits, although
the native "long" as seen by the local C compiler may be
larger. This is mainly an issue on 64-bit platforms. You can
see whether using "!" makes any difference this way:
printf "format s is %d, s! is %d\n",
length pack("s"), length pack("s!");
printf "format l is %d, l! is %d\n",
length pack("l"), length pack("l!");
"i!" and "I!" are also allowed, but only for completeness'
sake: they are identical to "i" and "I".
The actual sizes (in bytes) of native shorts, ints, longs, and
long longs on the platform where Perl was built are also
available from the command line:
$ perl -V:{short,int,long{,long}}size
shortsize='2';
intsize='4';
longsize='4';
longlongsize='8';
or programmatically via the "Config" module:
use Config;
print $Config{shortsize}, "\n";
print $Config{intsize}, "\n";
print $Config{longsize}, "\n";
print $Config{longlongsize}, "\n";
$Config{longlongsize} is undefined on systems without long
long support.
* The integer formats "s", "S", "i", "I", "l", "L", "j", and "J"
are inherently non-portable between processors and operating
systems because they obey native byteorder and endianness. For
example, a 4-byte integer 0x12345678 (305419896 decimal) would
be ordered natively (arranged in and handled by the CPU
registers) into bytes as
0x12 0x34 0x56 0x78 # big-endian
0x78 0x56 0x34 0x12 # little-endian
Basically, Intel and VAX CPUs are little-endian, while
everybody else, including Motorola m68k/88k, PPC, Sparc, HP
PA, Power, and Cray, are big-endian. Alpha and MIPS can be
either: Digital/Compaq uses (well, used) them in little-endian
mode, but SGI/Cray uses them in big-endian mode.
The names big-endian and little-endian are comic references to
the egg-eating habits of the little-endian Lilliputians and
the big-endian Blefuscudians from the classic Jonathan Swift
satire, Gulliver's Travels. This entered computer lingo via
the paper "On Holy Wars and a Plea for Peace" by Danny Cohen,
USC/ISI IEN 137, April 1, 1980.
Some systems may have even weirder byte orders such as
0x56 0x78 0x12 0x34
0x34 0x12 0x78 0x56
You can determine your system endianness with this
incantation:
printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678);
The byteorder on the platform where Perl was built is also
available via Config:
use Config;
print "$Config{byteorder}\n";
or from the command line:
$ perl -V:byteorder
Byteorders "1234" and "12345678" are little-endian; "4321" and
"87654321" are big-endian.
For portably packed integers, either use the formats "n", "N",
"v", and "V" or else use the ">" and "<" modifiers described
immediately below. See also perlport.
* Starting with Perl 5.10.0, integer and floating-point formats,
along with the "p" and "P" formats and "()" groups, may all be
followed by the ">" or "<" endianness modifiers to
respectively enforce big- or little-endian byte-order. These
modifiers are especially useful given how "n", "N", "v", and
"V" don't cover signed integers, 64-bit integers, or
floating-point values.
Here are some concerns to keep in mind when using an
endianness modifier:
* Exchanging signed integers between different platforms
works only when all platforms store them in the same
format. Most platforms store signed integers in
two's-complement notation, so usually this is not an
issue.
* The ">" or "<" modifiers can only be used on
floating-point formats on big- or little-endian machines.
Otherwise, attempting to use them raises an exception.
* Forcing big- or little-endian byte-order on floating-point
values for data exchange can work only if all platforms
use the same binary representation such as IEEE
floating-point. Even if all platforms are using IEEE,
there may still be subtle differences. Being able to use
">" or "<" on floating-point values can be useful, but
also dangerous if you don't know exactly what you're
doing. It is not a general way to portably store
floating-point values.
* When using ">" or "<" on a "()" group, this affects all
types inside the group that accept byte-order modifiers,
including all subgroups. It is silently ignored for all
other types. You are not allowed to override the
byte-order within a group that already has a byte-order
modifier suffix.
* Real numbers (floats and doubles) are in native machine format
only. Due to the multiplicity of floating-point formats and
the lack of a standard "network" representation for them, no
facility for interchange has been made. This means that packed
floating-point data written on one machine may not be readable
on another, even if both use IEEE floating-point arithmetic
(because the endianness of the memory representation is not
part of the IEEE spec). See also perlport.
If you know exactly what you're doing, you can use the ">" or
"<" modifiers to force big- or little-endian byte-order on
floating-point values.
Because Perl uses doubles (or long doubles, if configured)
internally for all numeric calculation, converting from double
into float and thence to double again loses precision, so
"unpack("f", pack("f", $foo)") will not in general equal $foo.
* Pack and unpack can operate in two modes: character mode ("C0"
mode) where the packed string is processed per character, and
UTF-8 mode ("U0" mode) where the packed string is processed in
its UTF-8-encoded Unicode form on a byte-by-byte basis.
Character mode is the default unless the format string starts
with "U". You can always switch mode mid-format with an
explicit "C0" or "U0" in the format. This mode remains in
effect until the next mode change, or until the end of the
"()" group it (directly) applies to.
Using "C0" to get Unicode characters while using "U0" to get
non-Unicode bytes is not necessarily obvious. Probably only
the first of these is what you want:
$ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)'
03B1.03C9
$ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
CE.B1.CF.89
$ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)'
CE.B1.CF.89
$ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
C3.8E.C2.B1.C3.8F.C2.89
Those examples also illustrate that you should not try to use
"pack"/"unpack" as a substitute for the Encode module.
* You must yourself do any alignment or padding by inserting,
for example, enough "x"es while packing. There is no way for
pack() and unpack() to know where characters are going to or
coming from, so they handle their output and input as flat
sequences of characters.
* A "()" group is a sub-TEMPLATE enclosed in parentheses. A
group may take a repeat count either as postfix, or for
unpack(), also via the "/" template character. Within each
repetition of a group, positioning with "@" starts over at 0.
Therefore, the result of
pack("@1A((@2A)@3A)", qw[X Y Z])
is the string "\0X\0\0YZ".
* "x" and "X" accept the "!" modifier to act as alignment
commands: they jump forward or back to the closest position
aligned at a multiple of "count" characters. For example, to
pack() or unpack() a C structure like
struct {
char c; /* one signed, 8-bit character */
double d;
char cc[2];
}
one may need to use the template "c x![d] d c[2]". This
assumes that doubles must be aligned to the size of double.
For alignment commands, a "count" of 0 is equivalent to a
"count" of 1; both are no-ops.
* "n", "N", "v" and "V" accept the "!" modifier to represent
signed 16-/32-bit integers in big-/little-endian order. This
is portable only when all platforms sharing packed data use
the same binary representation for signed integers; for
example, when all platforms use two's-complement
representation.
* Comments can be embedded in a TEMPLATE using "#" through the
end of line. White space can separate pack codes from each
other, but modifiers and repeat counts must follow
immediately. Breaking complex templates into individual
line-by-line components, suitably annotated, can do as much to
improve legibility and maintainability of pack/unpack formats
as "/x" can for complicated pattern matches.
* If TEMPLATE requires more arguments than pack() is given,
pack() assumes additional "" arguments. If TEMPLATE requires
fewer arguments than given, extra arguments are ignored.
Examples:
$foo = pack("WWWW",65,66,67,68);
# foo eq "ABCD"
$foo = pack("W4",65,66,67,68);
# same thing
$foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9);
# same thing with Unicode circled letters.
$foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
# same thing with Unicode circled letters. You don't get the
# UTF-8 bytes because the U at the start of the format caused
# a switch to U0-mode, so the UTF-8 bytes get joined into
# characters
$foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9);
# foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9"
# This is the UTF-8 encoding of the string in the
# previous example
$foo = pack("ccxxcc",65,66,67,68);
# foo eq "AB\0\0CD"
# NOTE: The examples above featuring "W" and "c" are true
# only on ASCII and ASCII-derived systems such as ISO Latin 1
# and UTF-8. On EBCDIC systems, the first example would be
# $foo = pack("WWWW",193,194,195,196);
$foo = pack("s2",1,2);
# "\001\000\002\000" on little-endian
# "\000\001\000\002" on big-endian
$foo = pack("a4","abcd","x","y","z");
# "abcd"
$foo = pack("aaaa","abcd","x","y","z");
# "axyz"
$foo = pack("a14","abcdefg");
# "abcdefg\0\0\0\0\0\0\0"
$foo = pack("i9pl", gmtime);
# a real struct tm (on my system anyway)
$utmp_template = "Z8 Z8 Z16 L";
$utmp = pack($utmp_template, @utmp1);
# a struct utmp (BSDish)
@utmp2 = unpack($utmp_template, $utmp);
# "@utmp1" eq "@utmp2"
sub bintodec {
unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
$foo = pack('sx2l', 12, 34);
# short 12, two zero bytes padding, long 34
$bar = pack('s@4l', 12, 34);
# short 12, zero fill to position 4, long 34
# $foo eq $bar
$baz = pack('s.l', 12, 4, 34);
# short 12, zero fill to position 4, long 34
$foo = pack('nN', 42, 4711);
# pack big-endian 16- and 32-bit unsigned integers
$foo = pack('S>L>', 42, 4711);
# exactly the same
$foo = pack('s<l<', -42, 4711);
# pack little-endian 16- and 32-bit signed integers
$foo = pack('(sl)<', -42, 4711);
# exactly the same
The same template may generally also be used in unpack().
unpack TEMPLATE,EXPR
unpack TEMPLATE
"unpack" does the reverse of "pack": it takes a string and expands
it out into a list of values. (In scalar context, it returns
merely the first value produced.)
If EXPR is omitted, unpacks the $_ string. See perlpacktut for an
introduction to this function.
The string is broken into chunks described by the TEMPLATE. Each
chunk is converted separately to a value. Typically, either the
string is a result of "pack", or the characters of the string
represent a C structure of some kind.
The TEMPLATE has the same format as in the "pack" function. Here's
a subroutine that does substring:
sub substr {
my($what,$where,$howmuch) = @_;
unpack("x$where a$howmuch", $what);
}
and then there's
sub ordinal { unpack("W",$_[0]); } # same as ord()
In addition to fields allowed in pack(), you may prefix a field
with a %<number> to indicate that you want a <number>-bit checksum
of the items instead of the items themselves. Default is a 16-bit
checksum. Checksum is calculated by summing numeric values of
expanded values (for string fields the sum of "ord($char)" is
taken; for bit fields the sum of zeroes and ones).
For example, the following computes the same number as the System
V sum program:
$checksum = do {
local $/; # slurp!
unpack("%32W*",<>) % 65535;
};
The following efficiently counts the number of set bits in a bit
vector:
$setbits = unpack("%32b*", $selectmask);
The "p" and "P" formats should be used with care. Since Perl has
no way of checking whether the value passed to "unpack()"
corresponds to a valid memory location, passing a pointer value
that's not known to be valid is likely to have disastrous
consequences.
If there are more pack codes or if the repeat count of a field or
a group is larger than what the remainder of the input string
allows, the result is not well defined: the repeat count may be
decreased, or "unpack()" may produce empty strings or zeros, or it
may raise an exception. If the input string is longer than one
described by the TEMPLATE, the remainder of that input string is
ignored.
```
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/P5pack> . Comments and Pull Requests are welcome.
If you like this module, or what I'm doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021, 2023, 2024 Elizabeth Mattijsen
Re-imagined from Perl as part of the CPAN Butterfly Plan and an earlier version that only lived in the Raku Ecosystem.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-TYIL-App-GTD.md
# NAME
App::GTD
# AUTHOR
Patrick Spek [p.spek@tyil.work](mailto:p.spek@tyil.work)
# VERSION
0.2.1
# Synopsis
* gtd [--help]
* gtd add <words...>
* gtd inbox
* gtd inbox
* gtd next
* gtd next [--prio[=<a..z>]] [words...]
* gtd someday
* gtd someday
* gtd done
# Description
A command line application to support the [Getting Things Done](https://gettingthingsdone.com/) methodology, written using the Raku programming language.
# Installation
## Through `zef`
[zef](https://github.com/ugexe/zef) is the standard distribution manager for [Raku](https://raku.org). If you're using an end-user distribution like [Rakudo Star](https://rakudo.org/files/star), it will be installed for you by default.
`zef` will install the latest available version from [CPAN](http://www.cpan.org/modules/index.html).
```
zef install App::GTD
```
# Documentation
Documentation is available as Pod6 documents in the module. You can use a module such as [`p6doc`](https://modules.raku.org/dist/p6doc:github:perl6) or [`App::Rakuman`](https://home.tyil.nl/git/raku/App::Rakuman/) to read through it.
```
rakuman App::GTD
rakuman App::GTD::Config
```
# Contributing
## Reporting bugs or other feedback
Any bugs or other feedback can be sent to my email address. I generally try to respond to all mail within 24 hours.
## Proposing code patches
Code patches can also be sent in through email. If you need help to send git patches through email, you may want to read up on [git-send-email.io](https://git-send-email.io/).
# License
This module is distributed under the terms of the GNU AGPL, version 3.0.
|
## dist_cpan-JNTHN-POFile.md
### NAME
POFile - Perl 6 module for manipulating data in PO files.
### SYNOPSIS
```
use POFile;
my $po = POFile.load('foo.po');
say $po.obsolete-messages; # list of obsolete messages
say $result[0]; # POFile::Entry object at 0 index
say $result{'Splash text'}; # POFile::Entry object with msgid `Splash text`
for @$po -> $item {
say $item.reference; # 'finddialog.cpp:38'
say $item.msgstr; # msgstr value
$item.msgstr = update($item.msgstr); # Do some update
}
$po.save('foo-updated.po');
```
### DESCRIPTION
The `.po` file as a whole is represented by the `POFile` class, which
holds a `POFile::Entry` object per entry in the PO file.
##### POFile::Entry
`POFile::Entry` represents a single record in PO file, and has its
fields as attributes: `msgid`, `msgid-plural`, `msgstr`, `msgctxt`,
`reference` (reference comment), `extracted` (extracted comment),
`comment` (translator comment), `format-style`, `fuzzy-msgid`,
`fuzzy-msgctxt`. All these attributes are set read/write.
You can create a single `POFile::Entry` object from a `Str` using the
`POFile::Entry.parse($str)` method.
The `msgid` and `msgstr` accessors always provided unquoted values;
the methods `msgid-quoted` and `msgstr-quoted` are present to provide
access to the quoted messages.
The value of `msgstr` attribute might be either `Str` or `Array`, and
is based on value of `msgid-plural` attribute:
```
with $po.msgid-plural {
say $po.msgid; # Singular form
say $_; # Plural form
for $po.msgstr -> $form {
say $form; # Every plural form of end language
}
}
```
You can serialize an entry with `Str` method or its `~` shortcut:
```
my $po-entry = $po[1]; # Get second entry
say ~$po-entry; # Serialized 1
say $po-entry.Str; # Serialized 2
```
Note that *no line wrapping* is done by the module.
##### POFile
`POFile` provides access to `POFile::Entry` objects using either index
(position in original file) or key (msgid value). It must be noted
that this module provides hash-like access by msgid, which might not
be unique. Please consider that *only array access* is stable in this
case. Use hash access you know *for sure* there are no items with the
same `msgid`, yet different `msgctxt`.
`POFile` also contains all obsolete messages, which can be accessed using
`obsolete-messages` attribute.
You can create from scratch a new `POFile` object and populate it with
entries, as well as delete entries by id or by key:
```
my $po = POFile.new;
$result.push(POFile::Entry.parse(...));
$result.push(POFile::Entry.parse(...));
$po[0]:delete;
$po{'my msgid'}:delete;
```
As well as `POFile::Entry`, you can serialize a `POFile` object
calling `Str` method on it.
##### Escaping
Additionally, two routines are available to escape and unescape strings accordingly to
rules described for PO format.
```
use POFile :quoting;
say po-unquote(「\t\"\\\n」); # 「\t"\\n」 <- unquoting
say po-quote(「\t"\\n\」); # 「\t\"\\\n\\」 <- quoting
```
|
## move.md
move
Combined from primary sources listed below.
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_routine_move "direct link")
See primary documentation
[in context](/type/IO/Path#routine_move)
for **routine move**.
```raku
method move(IO::Path:D: IO() $to, :$createonly --> Bool:D)
sub move(IO() $from, IO() $to, :$createonly --> Bool:D)
```
Copies a file and then removes the original. If removal fails, it's possible to end up with two copies of the file. Returns `True` on success; [fails](/routine/fail) with [`X::IO::Move`](/type/X/IO/Move) if `:$createonly` is `True` and the `$to` path already exists or if the operation failed for some other reason, such as when `$to` and `$from` are the same file.
To avoid copying, you can use [`rename`](/routine/rename), if the files are on the same storage device. It also works with directories, while `move` does not.
|
## dist_zef-elcaro-Inline-J.md
# NAME
Inline::J - Use the [J programming language](https://www.jsoftware.com) inside Raku.
# SYNOPSIS
```
use Inline::J;
my \j = Inline::J.new(:load-profile);
say j.eval('i. 6');
# 0 1 2 3 4 5
say my $n = j.noun('>: 2 4 $ i. 8');
# 1 2 3 4
# 5 6 7 8
say j.eval("{(1,2) »×» 10} + $n");
# 11 12 13 14
# 25 26 27 28
say my $a = $n.getm;
# [[1 2 3 4]
# [5 6 7 8]]
say $a.^name => $a.shape;
# Array[Int] => [2 4]
say j.gets(‘2 5 $ 'HelloWorld'’);
# [[H e l l o]
# [W o r l d]]
```
# WARNING
This module is under development. As such, the API is subject to change at any time, and there might be bugs.
The use of this module in Production is not recommended.
If you insist on using this module on important code during version 0, you should pin the exact point release as I reserve the right to break/change the API at any time before version 1.
# INSTALLATION
To install this module you need to have J already installed. See the [J Software Wiki](https://code.jsoftware.com/wiki/System/Installation) for more info.
During installation of this module, it will attempt to locate the `bin` path where J shared lib is located. It will search the most common install locations for POSIX or Windows depending on your system. Alternatively, you can export the `bin` location the environment variable `JBINPATH` before installation.
# GETTING STARTED
The start using `Inline::J`, first create a new `Inline::J` object.
To load the default J profile, pass a truthy `load-profile` named argument.
You should `load-profile` if you wish to use names defined in the [Standard Library](https://code.jsoftware.com/wiki/Standard_Library/Overview).
```
my \j = Inline::J.new(:load-profile);
say j.eval(‘toupper 'hello, world!'’);
# HELLO, WORLD!
```
Alternatively you can use the `load-profile` method, which return `self`.
```
my \y = Inline::J.new.load-profile;
```
Note that each object is it's own separate interpreter.
```
j.eval('n =: 1');
y.eval('echo n'); # fail: value error
```
# USAGE
## Inline::J
## do
The `do` method accepts a single J expression and passes it to the J interpreter. Any non-Str values will be coerced to a Str.
If there are any errors, it will return a [Failure](https://docs.raku.org/type/Failure) with the error message.
This method returns `self`, so that multiple expressions can be chained.
```
j.do('a =. i. 3').do('a =. 5 + a'); # ok
j.do('notaverb 1'); # fail: value error
```
## getr
The `getr` method returns the output of the last expression passed to `do`, with the trailing newline `chomp`d.
```
j.do('a').getr;
# 5 6 7
```
## eval
This is a convenience function that simply chains a `do` and `getr` call into one function
```
say j.eval('(+/ % #) 3 1 4 1 5 9');
# 3.83333
```
Since this wraps `do`, the `eval` method can also return a Failure.
## free
This calls the `JFree` C function to free the J interpreters memory. Ideally, this should not need to be run, as `Inline::J` objects call this method on `DESTROY`.
```
END { j.free }
```
## noun
This method creates an `Inline::J::Noun` object that references a noun in J. The `gist` of this object is the J representation of this noun.
If a noun already exists in J, you can create an `Inline::J::Noun` by providing it's name.
```
my $a = j.noun(name => 'a');
say $a;
# 5 6 7
```
**NOTE:** When an Inline::J::Noun object is `DESTROY`'d, the J noun will be erased and it's storage freed by calling `(4!:55) <'name'` in J.
Alternatively, you can declare a new variable in J by also providing an expression
```
my $b = j.noun('10 20 30', name => 'b');
say $b;
# 10 20 30
```
This is essentially the same as doing `j.eval(b =. 10 20 30)`, only now you have a Raku object that references the noun.
If you do not provide a name, a random name will be generated for you.
```
my $v = j.noun('42');
say $v.name;
# ijn_d63a244e
```
## Inline::J::Noun
An `Inline::J::Noun` (`IJN`) object references a noun in J. The `gist` of this object is the J representation of this noun.
**EXPERIMENTAL:** Currently, an `IJN` stringifies to it's name. This allows them to be interpolated into J expressions.
```
say j.eval("a + $b");
# 15 26 37
```
I'm not sure if this is a good idea yet, but it's fun. The alternative would be to explicitly interpolate it's name into expressions, eg.
```
say j.eval("a + {$b.name}");
```
Which is not as much fun.
### Methods
The following examples will use the following value
```
my $m = j.noun('2 3 4 $ i. 24');
```
## gist
Returns the J representation of the noun
An objects `.gist` method is called automatically by `say`.
```
say $m;
# 0 1 2 3
# 4 5 6 7
# 8 9 10 11
#
# 12 13 14 15
# 16 17 18 19
# 20 21 22 23
```
## name (Str)
Returns the name of the noun in J, which may be different from the variable name in Raku, and is randomly generated when not specified
This method is also called when coercing the object to a string (eg. `$m.Str`, `"$m"`, `~$m`, `put $m`, etc.)
```
say $m.name;
# ijn_f39324d1
```
## datatype
Returns an Inline::J::Datatype enum.
The numeric value of the enum will match J's type identifier
```
say $m.datatype;
# integer
say +$m.datatype;
# 4
```
## shape
Returns a Seq of Ints that count the length (number of items) in each axis.
```
say $m.shape;
# (2 3 4)
```
## tally
Returns an Int of the count of *items* in the array.
As per the J documentation
```
> The items of an array are the cells whose rank is 1 lower than the rank of the array.
> Thus, the items of a list are atoms, and the items of a table are lists.
```
The tally can also be derived from the shape by taking the first element of the shape.
```
say $m.tally;
# 2
```
## rank
Returns an Int of the count of axis in the array.
The rank can be derived from the shape by taking the count of element of the shape.
```
say $m.rank;
# 3
```
## elems
Returns an Int of the total count of scalar items in the array
The elems can be derived from the shape by taking the product of the shape.
```
say $m.elems;
# 24
```
## AT-POS
**EXPERIMENTAL**
I've added an `.AT-POS` method (which is called when you index into an object).
Currently this just returns a string from J.
```
say $m[1;0];
# 12 13 14 15
```
## Inline::J::Verb
Similar to `IJN`'s, an `Inline::J::Verb` (`IJV`) object references a verb defined in J. The object `does Callable` so that it acts like a Raku function. `IJV` callables accept 0, 1 or 2 arguments, and return an `IJN`.
When calling with 0 arguments, the J function is actually called with the empty string value.
The arguments can either be an existing `IJN`, or a Raku value that can be converted to a J value: `Bool`, `Int`, `Num`, `Str`, or a homogeneous array of one of those types). Raku types will be coerced to an `Array` and attempted to be converted to an `IJN` before being passed to J.
```
my &v = j.verb('>:');
my $y = j.noun('i. 5');
my $x = j.noun(2);
say v($y);
# 1 2 3 4 5
say v($y, $x);
# 0 0 1 1 1
say v($y, $x).getm;
# [False False True True True]
```
**LIMITATION:** The underlying method that converts Raku types to J only supports Arrays, so Scalars (J: nouns with no shape) are unu
coerce to `Array`, are currently unsupported.
**NOTE:** Since version 0.4.0, the `IJV`s `y` argument is always the first argument. This means you will need to explicitly swap the arguments if you are creating infix operators in Raku
```
sub infix:<minus>($x, $y) { j.verb('-')($y, $x) }
```
Or use `~` (reflex, aka: commute) on the J verb
```
my &infix:<minus> := j.verb('-~');
```
Example of passing a Raku Array to a J verb
```
# Raku shaped Array
say my Int @a[4;4] = ([1..4] xx 4);
# [[1 2 3 4]
# [1 2 3 4]
# [1 2 3 4]
# [1 2 3 4]]
# Passing it to a IJV, returns an IJN
# Convert back to Raku by calling .getm
say j.verb('|."_1~ i.@#')(@a).getm;
# [[1 2 3 4]
# [2 3 4 1]
# [3 4 1 2]
# [4 1 2 3]]
```
Like `IJN`s, `IJV`'s also get a random name (if none is provided)
```
my &t = j.verb('|:');
say &t.name;
# ijv_c79ce86a
```
They can tell you their rank, and have a hard-coded arity/count of 1/2.
```
say &t.rank;
# _ 1 _
say &t.arity;
# 1
say &t.count;
# 2
```
**LIMITATION:** Currently only monadic and dyadic verbs are supported, `(4!:0)` will be checked to ensure a value of `3` (verb) type, otherwise an Exception is thrown
```
my &c =. j.verb(';.'); # dies: Not a verb
```
**EXPERIMENTAL:** Since `IJV`'s are Raku objects, Raku operators could provide multi's specific for them. Once experiment I've added is a multi for `&infix:<∘>`, which will compose 2 `IJV`s in J using `@:` ([At](https://code.jsoftware.com/wiki/Vocabulary/atco))
```
my $x = j.noun(<1 2 3>);
my $y = j.noun(<2 2 2>);
my &f = j.verb('+/');
my &g = j.verb('*:');
my &h = j.verb('-');
#| sum of squared differences
my &sum-sq-diff = &f ∘ &g ∘ &h;
say sum-sq-diff($x, $y);
# 2
```
**NOTE:** Doing the compose (`∘`) *in J* avoids unnecessary `IJN` creation, which happens when `IJV`'s return data to Raku.
# DATA CONVERSION
**WARNING:** The code for handling data conversion is in a messy state and largely untested.
## J to Raku
J scalars, lists, and matrices can be converted to Raku scalars and arrays. Currently this module strongly prefers creating shaped & typed Raku arrays.
Currently the only J datatypes supported are:
* boolean -> Bool
* literal -> Str
* integer -> Int
* floating -> Num
* unicode -> Str
* unicode4 -> Str (**EXPERIMENTAL**)
unicode values are encoded as UTF-16 in J, but normalised to UTF-8 when converted to Raku.
unicode4 values are encoded as UTF-32 in J. Raku (specifically, it's VM) does not have a UTF-32 decoder, so I have written a naïve `utf32-to-utf8` function in pure Raku, which may be buggy, and is likely to be slow on large inputs.
Current notable omissions are 'extended', 'rational', and 'complex' numbers, as well as 'boxed' arrays.
## getm
The `Inline::J` object provides the following method to get a J noun and convert it to a Raku
```
my $arr = j.getm($m.name);
say $arr;
# [[[0 1 2 3]
# [4 5 6 7]
# [8 9 10 11]]
# [[12 13 14 15]
# [16 17 18 19]
# [20 21 22 23]]]
```
Note however, that `Inline::J::Noun` objects also have a `getm` method available, so the above could also be expressed as:
```
my $arr = $m.getm;
```
As stated, the Raku array returned is shaped and typed.
```
say $arr.^name => $arr.shape;
# Array[Int] => [2 3 4]
```
The only minor issue with `getm` is that it relies on the noun existing in J. This is probably fine on a small scale, but on a larger scale could cause an explosion of declared nouns in J if not handled properly.
## gets
Sometimes, you might want to create a Raku data structure from a J expression without declaring a noun. J provides a foreign function `(3!:3)` which displays an ASCII (hex) representation of the data, which `Inline::J` can parse.
```
say j.gets('2 5 $ i. 10');
# [[0 1 2 3 4]
# [5 6 7 8 9]]
```
For (currently) no obvious reason, `Inline::J::Noun` objects also have a `gets` method, which bypasses the underlying `JGetM` C function, and parses the ASCII representation instead
```
say $a.gets;
# [5 6 7]
```
**WARNING:** This relies on string output from J. By default, J truncates to 256 columns and 222 rows. I have increased this not truncate, but have still run into issues converting arrays of several thousand values.
## Raku to J
**WARNING:** Barely developed.
Currently, only Raku shaped and typed Arrays can be converted to J arrays and matrices.
The only Raku types currently supported are:
* Bool -> boolean
* Str -> literal (or unicode\*)
* Int -> integer
* Num -> floating
\* When converting an Array of Str to J, `Inline::J` will check if any codepoints are > 255, and if so, the Str's are encoded as UTF-16 (J's `unicode`) before passing to J.
## setm
The `Inline::J` object provides the following method to set a J noun from a Raku data structure
```
my Bool @b[2;2] = [(True, False), (False, True)];
j.setm('b', @b);
say j.eval('b');
# 1 0
# 0 1
```
In addition to creating a noun in the J instance, the `setm` method also returns an `IJN`.
```
my $b = j.setm('b', @b); # Eqv to `my $b = j.noun('b');`
say $b.^name;
# Inline::J::Noun
```
Existing `IJN` objects can also have their value over-written with the `setm` method
```
$m.setm(Array[Str].new(:shape(2;3), [<A B Ć>, <D E F>]));
say $m;
# ABĆ
# DEF
say $m.^name => $m.datatype;
# Inline::J::Noun => unicode
```
# CAVEATS AND LIMITATION
This module was developed on a x86-64 (little endian) system, and byte-data returned from J is assumed to be 64-bit little endian. Expect things to fail when running on 32-bit builds/systems, or systems that use big endian.
It should be possible to support 32-bit (and/or big endian) systems with a bit of effort, although I do not have a need for it, and will not be developing this support. Pull requests welcome.
# TODO
The following items are pending further development
* Support more values for `setm`
* Add support for Scalars
* Maybe allow non-shaped arrays (eg. infer shape recursive .elems?)
* export helper subs
* Ease passing of Raku data to J
Pull request welcome.
# FINAL THOUGHTS
I'm not a C programmer, and I've barely used NativeCall in the past, so it's entirely possibly I'm doing things in a less-than-optimum way. If anyone is a C/NativeCall guru, I would appreciate and feedback on whether there are better ways I could be handling the data conversions. The header file for `libj` is [here](https://github.com/jsoftware/jsource/blob/7a3945dc6f46176fd9c7741477c677ed114f32b0/jsrc/jlib.h).
So far it's just been me playing around with this module, trying to work out what useful methods and functionality would be useful. I haven't had a good look at it, but a potential source to mine ideas from is [Py'n'APL](https://github.com/Dyalog/pynapl/) library.
In general, I'm open to feedback from fellow J+Raku users on settling on the API of this module.
|
## dist_zef-lizmat-Method-Also.md
[](https://github.com/lizmat/Method-Also/actions) [](https://github.com/lizmat/Method-Also/actions) [](https://github.com/lizmat/Method-Also/actions)
# NAME
Method::Also - add "is also" trait to Methods
# SYNOPSIS
```
use Method::Also;
class Foo {
has $.foo;
method foo() is also<bar bazzy> { $!foo }
}
Foo.new(foo => 42).bar; # 42
Foo.new(foo => 42).bazzy; # 42
# separate multi methods can have different aliases
class Bar {
multi method foo() is also<bar> { 42 }
multi method foo($foo) is also<bazzy> { $foo }
}
Bar.foo; # 42
Bar.foo(666); # 666
Bar.bar; # 42
Bar.bazzy(768); # 768
```
# DESCRIPTION
This module adds a `is also` trait to `Method`s, allowing you to specify other names for the same method.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/Method-Also> . Comments and Pull Requests are welcome.
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2021, 2022, 2024, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-kjpye-Geo-WellKnownBinary.md
[](https://github.com/kjpye/Geo-WellKnownBinary/actions)
# TITLE
Geo::WellKnownBinary
# Geo::WellKnownBinary
The `Geo::WellKnownBinary` module contains a single function:
## from-wkb
`from-wkb` takes a single `Buf` parameter, and returns a single `Geo::Geometry` object corresponding to the wkb specification, or a `Failure` if the contents of the Buff cannot be interpreted as a geometry object.
## TODO
Many more tests are required. At the moment the tests are limited to fairly simple cases. Tests are definitely needed for polygons with holes (i.e. with those specifying more than one ring), and for multi-geometries with more than a single instance. But any additional test points will be gratefully received, especially if they are based on real data.
|
## dist_zef-atroxaper-App-Racoco-Report-ReporterCoveralls.md
[](https://github.com/atroxaper/raku-RaCoCo-Reporter-Coveralls/actions/workflows/ubuntu.yml)
[](https://github.com/atroxaper/raku-RaCoCo-Reporter-Coveralls/actions/workflows/macos.yml)
[](https://github.com/atroxaper/raku-RaCoCo-Reporter-Coveralls/actions/workflows/windows.yml)
[](https://coveralls.io/github/atroxaper/raku-RaCoCo-Reporter-Coveralls?branch=master)
# NAME
`App::RaCoCo::Report::ReporterCoveralls` - App::RaCoCo reporter for [Coveralls.io](http://coveralls.io) service.
# HOWTO USE
Generally, the reporter is for using on a CI like GitHub Actions or so. If you want to run RaCoCo with the reporter locally, you need to set some environment variables (for more information see [Coveralls.io documentation](https://docs.coveralls.io)). Currently, the reporter supports GitHub and GitLab CI. In any case, you need to create an account on [Coveralls.io](https://coveralls.io) and add your repository there. After that, you will get a unique `repository token`.
## GitHub Example
To use the reporter in GitHub Actions you need:
1. Add the secret environment variable for your repository with a name like `COVERALLS_REPO_TOKEN` and value equals the `repository token`. To do so go to YourRepoSettings -> Secrets -> New repository secret;
2. Add installation step in your workflow.yml file:
```
- name: Install Coveralls Reporter
run: zef install --/test App::Racoco::Report::ReporterCoveralls
```
1. Add `--reporter=coveralls` to RaCoCo run in your workflow.yml file. Also, you need to add `COVERALLS_REPO_TOKEN` environment variable:
```
- name: Run RaCoCo
run: racoco --reporter=coveralls
env:
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
```
## GitLab Example
To use the reporter in GitLab Pipelines you need:
1. Add the secret environment variable for your repository with a name like `COVERALLS_REPO_TOKEN` and value equals the `repository token`. To do so go to YourRepoSettings -> CI/CD -> Variables -> Expand -> Add variable;
2. Add installation step in your .gitlab-ci.yml file:
```
zef install --/test App::Racoco::Report::ReporterCoveralls
```
1. Add `--reporter=coveralls` to RaCoCo run in your .gitlab-ci.yml file. Also, you need to add `COVERALLS_REPO_TOKEN` environment variable:
```
workflow:
[...]
variables:
COVERALLS_REPO_TOKEN: "$COVERALLS_REPO_TOKEN"
[...]
racoco --reporter=coveralls
```
# AUTHOR
Mikhail Khorkov <atroxaper[at]cpan.org>
Sources can be found at: [github](https://github.com/atroxaper/raku-RaCoCo-Reporter-Coveralls). The new Issues and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2021 Mikhail Khorkov
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-librasteve-CLI-AWS-EC2-Simple.md
[](https://opensource.org/licenses/Artistic-2.0)
### *PLEASE EXERCISE CAUTION USING AWSCLI SINCE IT WILL CREATE BILLABLE AWS SERVICES IN YOUR ACCOUNT AND MAY NOT TERMINATE THEM AUTOMATICALLY*
# Raku CLI::AWS::EC2-Simple
This module provide a simple abstraction of the AWS command line interface, aka [awscli](https://aws.amazon.com/cli/), for Amazon's EC2 compute web service.
If you encounter a feature of EC2 you want that's not implemented by this module (and there are many), please consider sending a pull request.
## Getting Started
* apt-get update && apt-get install awscli [macOS brew update && brew install awscli]
* aws configure *[enter your config here]* (output format 'json')
* zef install CLI::AWS::EC2-Simple
* raws-ec2 *[enter your commands here]*
## Usage
```
./raws-ec2 [--id=<Str>] [--nsu] [--eip] [-y] <cmd>
<cmd> One of <list launch setup connect state stop start terminate nuke>
--id=<Str> Running InstanceId of form 'i-0785d8bd98b5f458b'
--nsu No setup (suppress launch from running setup)
--eip Allocates (if needed) and Associates Elastic IP
-y Silence confirmation <nuke> cmd only
```
Will make an (e.g.) `MyKeyPair1672164025.pem` from your credentials in your $\*HOME dir
## Config
`launch` reads `aws-ec2-launch.yaml` which is preloaded with the standard AWS Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2022-12-01.
Edit this yaml file to meet your needs...
* cat .raws-config/aws-ec2-launch.yaml
```
instance:
#image: ami-0f540e9f488cfa27d # <== the standard, clean AWS Ubuntu
image: ami-0c1163e529aeb9b20 # <== AWS Ubuntu plus raws-ec2 setup already applied (use --nsu flag)
#type: t2.micro # <== the basic, free tier eligible machine (12 credits/hr)
type: t3.medium # <== a step above t2.micro for more beefy server needs
#type: c6a.4xlarge # <== a mega machine for benchmarking
storage: 30 # <== EBS size for launch
security-group:
name: MySG
rules:
- inbound:
port: 22
cidr: 0.0.0.0/0
- inbound:
port: 80
cidr: 0.0.0.0/0
- inbound:
port: 443
cidr: 0.0.0.0/0
- inbound:
port: 8080
cidr: 0.0.0.0/0
- inbound:
port: 8888
cidr: 0.0.0.0/0
```
### *PLEASE REVIEW SECURITY GROUP RULES AND ADAPT TO YOUR NEEDS - SPECIFICALLY REMOVE THE PORT:22 RULE UNLESS YOU WANT ALL IPS TO HAVE ACCESS*
## Setup
`setup` deploys docker, docker-compose, raku and zef to the launchee...
* cat .raws-config/launch.pl
```
#!/usr/bin/perl
`sudo apt-get update -y`;
`curl https://rakubrew.org/install-on-perl.sh | sh`;
`eval "$(/home/ubuntu/.rakubrew/bin/rakubrew init Bash)"`;
`echo 'eval "$(/home/ubuntu/.rakubrew/bin/rakubrew init Bash)"' >> ~/.bashrc`;
`export PATH=/home/ubuntu/.rakubrew/bin/:$PATH`;
`rakubrew mode shim`;
`rakubrew download`;
`sudo apt-get install docker -y`;
`sudo apt-get install docker-compose -y`;
```
## NOTES
* unassigned Elastic IPs are chargeable ($5 per month ish), may be better to run one free tier instance
* rules about rules
* will always open port 22 (SSH) inbound from this client IP
* will re-use the existing named Security Group (or create if not present)
* only inbound are supported for now
* if you want to keep the name and change the rules, then delete via the aws console
### Copyright
copyright(c) 2022-2023 Henley Cloud Consulting Ltd.
|
## dist_zef-lizmat-IRC-Log.md
[](https://github.com/lizmat/IRC-Log/actions) [](https://github.com/lizmat/IRC-Log/actions) [](https://github.com/lizmat/IRC-Log/actions)
# NAME
IRC::Log - role providing interface to IRC logs
# SYNOPSIS
```
use IRC::Log;
class IRC::Log::Foo does IRC::Log {
method parse-log(
str $text,
$last-hour is raw,
$last-minute is raw,
$ordinal is raw,
$linenr is raw,
$nr-control-entries is raw,
$nr-conversation-entries is raw,
--> Nil) {
...
}
}
sub EXPORT() { IRC::Log::Foo.EXPORT } # Entry eqv Entry
my $log = IRC::Log::Foo.new($filename.IO);
say "Logs from $log.date()";
.say for $log.entries.List;
my $log = IRC::Log::Foo.new($text, $date);
```
# DESCRIPTION
IRC::Log provides a role providing an interface to IRC logs in various formats. Each log is supposed to contain all messages from a given date.
The `parse-log` method must be provided by the consuming class.
# METHODS TO BE PROVIDED BY CONSUMER
## parse-log
```
method parse-log(
str $text,
$last-hour is raw,
$last-minute is raw,
$ordinal is raw,
$linenr is raw,
$nr-control-entries is raw,
$nr-conversation-entries is raw,
--> Nil) {
...
}
```
The `parse-log` instance method should be provided by the consuming class. Examples of the implementation of this method can be found in the `IRC::Log::Colabti` and `IRC::Log::Textual` modules.
It is supposed to take 5 positional parameters that are assumed to be correctly updated by the logic in the `.parse-log` method.
* the text to be parsed
The (partial) log to be parsed.
* the last hour seen as a raw integer
An `is raw` variable that contains the last hour value seen in messages. It is set to -1 the first time, so that it is always unequal to any hour value that will be encountered.
* the last minute seen as a raw integer
An `is raw` variable that contains the last minute value seen in messages. It is set to -1 the first time, so that it is always unequal to any minute value that will be encountered.
* the last ordinal seen as a raw integer
An `is raw` variable that contains the last ordinal value seen in messages. It is set to 0 the first time.
* the line number of the line last parsed
An `is raw` variable that contains the line number last parsed in the log. It is set to -1 the first time, so that the first line parsed will be 0.
* the number of control messages seen
An `is raw` variable that needs to be incremented whenever a control message is created.
* the number of conversation messages seen
An `is raw` variable that needs to be incremented whenever a conversation message is created.
# CLASS METHODS
## new
```
my $log = IRC::Log::Foo.new($filename.IO);
my $log = IRC::Log::Foo.new($text, $date);
```
The `new` class method either takes an `IO` object as the first parameter, and a `Date` object as the optional second parameter (eliding the `Date` from the basename if not specified), and returns an instantiated object representing the entries in that log file.
Or it will take a `Str` as the first parameter for the text of the log, and a `Date` as the second parameter.
Any lines that can not be interpreted, are ignored: they are available with the `problems` method.
## EXPORT
```
sub EXPORT() { IRC::Log::Foo.EXPORT }
```
The `EXPORT` class method returns a `Map` to be used in an `EXPORT` sub to have the consuming class export an `eqv` infix operator that can quickly see if two `Entry` objects are equivalent (as in: same type, same `heartbeat` and same `message`).
## IO2Date
```
with IRC::Log::Foo.IO2Date($path) -> $date {
say "the date of $path is $date";
}
else {
say "$path does not appear to be a log file";
}
```
The `IO2Date` class method interpretes the given `IO::Path` object and attempts to elide a `Date` object from it. It returns `Nil` if it could not.
# INSTANCE METHODS
## date
```
dd $log.date; # "2021-04-22"
```
The `date` instance method returns the string of the date of the log.
## Date
```
dd $log.Date; # Date.new(2021,4,22)
```
The `Date` instance method returns the date of the log as a `Date` object..
## entries
```
.say for $log.entries.List; # all entries
.say for $log.entries.List.grep(*.conversation); # only actual conversation
```
The `entries` instance method returns an `IterationBuffer` with entries from the log. It contains instances of one of the following classes:
* IRC::Log::Joined
* IRC::Log::Left
* IRC::Log::Kick
* IRC::Log::Message
* IRC::Log::Mode
* IRC::Log::Nick-Change
* IRC::Log::Self-Reference
* IRC::Log::Topic
## entries-ge-target
```
.say for $log.entries-ge-target($target);
```
The `entries-from-target` instance method returns all entries that are `after` **and** including the given target.
## entries-gt-target
```
.say for $log.entries-gt-target($target);
```
The `entries-gt-target` instance method returns all entries that are `after` (so **not** including) the given target.
## entries-le-target
```
.say for $log.entries-le-target($target);
```
The `entries-le-target` instance method returns all entries that are `before` **and** including the given target.
## entries-lt-target
```
.say for $log.entries-lt-target($target);
```
The `entries-lt-target` instance method returns all entries that are `before` (so **not** including) the given target.
## entries-of-nick
```
.say for $log.entries-of-nick($nick);
```
The `entries-of-nick` instance method takes a `nick` as parameter and returns a `Seq` consisting of the entries of the given nick (if any).
## entries-of-nick-names
```
.say for $log.entries-of-nick-names(@nick-names);
```
The `entries-of-nick-names` instance method takes a list of `nick-names` and returns a `Seq` consisting of the entries of the given nick names (if any).
## first-entry
```
say $log.first-entry;
```
The `first-entry` instance method returns the first entry of the log.
## first-target
```
say $log.first-target; # 2021-04-23
```
The `first-target` instance method returns the `target` of the first entry.
## last-entry
```
say $log.last-entry;
```
The `last-entry` instance method returns the last entry of the log.
## last-target
```
say $log.last-target; # 2021-04-29
```
The `last-target` instance method returns the `target` of the last entry.
## last-topic-change
```
say $log.last-topic-change; # liz changed topic to "hello world"
```
The `last-topic-change` instance method returns the entry that contains the last change of topic. Returns `Nil` if there wasn't any topic change.
## nick-indices
```
.say for $log.nick-indices;
```
The `nick-indices` instance method returns a Hash with the nick names that have been found as keys, and the associated ordinal number as value.
## nick-names
```
.say for $log.nick-names;
```
The `nick-names` instance method returns a native str array with the nick names that have been found in the order they were found.
## nr-control-entries
```
say $log.nr-control-entries;
```
The `nr-control-entries` instance method returns an integer representing the number of control entries in this log. It is calculated lazily
## nr-conversation-entries
```
say $log.nr-conversation-entries;
```
The `nr-conversation-entries` instance method returns an integer representing the number of conversation entries in this log.
## problems
```
.say for $log.problems.List;
```
The `problems` instance method returns an `IterationBuffer` with `Pair`s of lines that could **not** be interpreted in the log. The key is a string with the line number and a reason it could not be interpreted. The value is the actual line.
## raw
```
say "contains 'foo'" if $log.raw.contains('foo');
```
The `raw` instance method returns the raw text version of the log. It can e.g. be used to do a quick check whether a string occurs in the raw text, before checking `entries` for a given string.
## search
```
.say for $channel.search; # all entries in chronological order
.say for $channel.search(:reverse); # all in reverse chronological order
.say for $channel.search(:control); # control messages only
.say for $channel.search(:conversation); # conversational messages only
.say for $channel.search(:matches(/ \d+ /); # matching regex
.say for $channel.search(:starts-with<m:>); # starting with text
.say for $channel.search(:contains<foo>); # containing string
.say for $channel.search(:words<foo>); # containing word
.say for $channel.search(:nick-names<lizmat timo>); # for one or more nick names
.say for $channel.search(:lt-target($target); # entries before target
.say for $channel.search(:le-target($target); # entries until target
.say for $channel.search(:ge-target($target); # entries from target
.say for $channel.search(:gt-target($target); # entries after target
.say for $channel.search(:@targets); # entries of these targets
.say for $channel.search(
:nick-names<lizmat japhb>,
:contains<question answer>, :all,
);
```
The `search` instance method provides a way to look for specific entries in the log by zero or more criteria and modifiers. The following criteria can be specified:
### all
Modifier. Boolean indicating that if multiple words are specified with `contains`, `starts-with` or `words`, then **all** words should match to include the entry.
### contains
A string consisting of one or more `.words` that the `.message` of an entry should contain to be selected. By default, any of the specified words will cause an entry to be included, unless the `all` modifier has been specified with a `True` value. By default, string matching will be case sensitive, unless the `ignorecase` modifier has been specified with a `True` value.
Implies `conversation` is specified with a `True` value.
### control
Boolean indicating to only include entries that return `True` on their `.control` method. Defaults to no filtering if not specified.
### conversation
Boolean indicating to only include entries that return `True` on their `.conversation` method. Defaults to no filtering if not specified.
### ge-target
A string indicating the `.target` of an entry should be equal to, or later than (alphabetically greater than or equal). Specified target may be of a different `date` than of the log.
### gt-target
A string indicating the `.target` of an entry should be later than (alphabetically greater than). Specified target may be of a different `date` than of the log.
### ignorecase
Modifier. Boolean indicating that string checking with `contains`, `starts-with` or `words`, should be done case-insensitively if specified with a `True` value.
### le-target
A string indicating the `.target` of an entry should be equal to, or before (alphabetically less than or equal). Specified target may be of a different `date` than of the log.
### lt-target
A string indicating the `.target` of an entry should be before (alphabetically less than). Specified target may be of a different `date` than of the log.
### matches
A regular expression (aka `Regex` object) that should match the `.message` of an entry to be selected. Implies `conversation` is specified with a `True` value.
### nick-names
A string consisting of one or more nick names that should match the sender of the entry to be included.
### reverse
Modifier. Boolean indicating to reverse the order of the selected entries.
### starts-with
A string consisting of one or more `.words` that the `.message` of an entry should start with to be selected. By default, any of the specified words will cause an entry to be included, unless the `all` modifier has been specified with a `True` value. By default, string matching will be case sensitive, unless the `ignorecase` modifier has been specified with a `True` value.
Implies `conversation` is specified with a `True` value.
### targets
One or more target strings indicating the entries to be returned. Will be returned in ascending order, unless `reverse` is specified with a `True` value.
### words
A string consisting of one or more `.words` that the `.message` of an entry should contain as a word (an alphanumeric string bounded by the non- alphanumeric characters, or the beginning or end of the string) to be selected. By default, any of the specified words will cause an entry to be included, unless the `all` modifier has been specified with a `True` value. By default, string matching will be case sensitive, unless the `ignorecase` modifier has been specified with a `True` value.
Implies `conversation` is specified with a `True` value.
## target-entry
```
say "$target has $_" with $log.target-entry($target);
```
The `target-entry` instance method returns the **entry** of the specified target, or it returns `Nil` if the entry of the target could not be found.
## target-index
```
say "$target at $_" with $log.target-index($target);
```
The `target-index` instance method returns the **position** of the specified target in the list of `entries`, or it returns `Nil` if the target could not be found.
## update
```
$log.update($filename.IO); # add any entries added to file
$log.update($slurped); # add any entries added to string
```
The `update` instance method allows updating a log with any additional entries. This is primarily intended to allow for updating a log on the current date, as logs of previous dates should probably be deemed immutable.
# CLASSES
All of the classes that are returned by the `entries` methods, have the following methods in common:
### control
Returns `True` if this entry is a control message. Else, it returns `False`.
These entry types are considered control messages:
* IRC::Log::Joined
* IRC::Log::Left
* IRC::Log::Kick
* IRC::Log::Mode
* IRC::Log::Nick-Change
* IRC::Log::Topic
### conversation
Returns `True` if this entry is part of a conversation. Else, it returns `False`.
These entry types are considered conversational messages:
* IRC::Log::Message
* IRC::Log::Self-Reference
* IRC::Log::Topic
### date
The `Date` of this entry.
### entries
The `entries` of the `log` of this entry as an `IterationBuffer`.
### gist
Create the string representation of the entry as it originally occurred in the log.
### heartbeat
An integer for the absolute minute in the day (basically the hh \* 60 + mm).
### hhmm
A string representation of the hour and the minute of this entry ("hhmm").
### hh-mm
A string representation of the hour and the minute of this entry ("hh:mm").
### hour
The hour (in UTC) the entry was added to the log.
### log
The `IRC::Log` object of which this entry is a part.
### message
The text representation of the entry.
### minute
The minute (in UTC) the entry was added to the log.
### next
The next entry in this log (if any).
### nick
The nick of the user that originated the entry in the log.
### nick-index
The index of the nick in the list of `nick-names` in the log.
### ordinal
Zero-based ordinal number of this entry within the minute it occurred.
### pos
The position of this entry in the `entries` of the `log` of this entry.
### prefix
The prefix used in creating the `gist` of this entry.
### prev
The previous entry in this log (if any).
### problems
The `problems` of the `log` of this entry.
### sender
A representation of the sender. The same as `nick` for the `Message` class, otherwise the empty string as then the nick is encoded in the `message`.
### target
Representation of an anchor in an HTML-file for deep linking to this entry. Can also be used as a sort key across entries from multiple dates.
## IRC::Log::Joined
No other methods are provided.
## IRC::Log::Left
No other methods are provided.
## IRC::Log::Kick
### kickee
The nick of the user that was kicked in this log entry.
### spec
The specification with which the user was kicked in this log entry.
## IRC::Log::Message
### text
The text that the user entered that resulted in this log entry.
## IRC::Log::Mode
### flags
The flags that the user entered that resulted in this log entry.
### nick-names
An array of nicknames (to which the flag setting should be applied) that the user entered that resulted in this log entry.
## IRC::Log::Nick-Change
### new-nick
The new nick of the user that resulted in this log entry.
## IRC::Log::Self-Reference
### text
The text that the user entered that resulted in this log entry.
## IRC::Log::Topic
### text
The new topic that the user entered that resulted in this log entry.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/IRC-Log> . 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 2021, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-antononcube-WWW-WolframAlpha.md
# WWW::WolframAlpha
[](https://github.com/antononcube/Raku-WWW-WolframAlpha/actions/workflows/macos.yml)
[](https://github.com/antononcube/Raku-WWW-WolframAlpha/actions/workflows/linux.yml)
[](https://github.com/antononcube/Raku-WWW-WolframAlpha/actions/workflows/windows.yml)
[](https://raku.land/zef:antononcube/WWW::WolframAlpha)
## In brief
This Raku package provides access to the answer engine [Wolfram|Alpha](https://www.wolframalpha.com), [WA1, Wk1].
For more details of the Wolfram|Alpha's API usage see [the documentation](https://products.wolframalpha.com/api/documentation), [WA2].
**Remark:** To use the Wolfram|Alpha API one has to register and obtain an authorization key.
---
## Installation
Package installations from both sources use [zef installer](https://github.com/ugexe/zef)
(which should be bundled with the "standard" Rakudo installation file.)
To install the package from [Zef ecosystem](https://raku.land/) use the shell command:
```
zef install WWW::WolframAlpha
```
To install the package from the GitHub repository use the shell command:
```
zef install https://github.com/antononcube/Raku-WWW-WolframAlpha.git
```
---
## Usage examples
**Remark:** When the authorization key, `auth-key`, is specified to be `Whatever`
then the functions `wolfam-alpha*` attempt to use the env variable `WOLFRAM_ALPHA_API_KEY`.
The package has an universal "front-end" function `wolfram-alpha` for the
[different endpoints provided by Wolfram|Alpha Web API](https://products.wolframalpha.com/api/documentation).
### (Plaintext) results
Here is a *result* call:
```
use WWW::WolframAlpha;
wolfram-alpha-result('How many calories in 4 servings of potato salad?');
```
```
# about 720 dietary Calories
```
### Simple (image) results
Here is a *simple* call (produces an image):
```
wolfram-alpha-simple('What is popularity of the name Larry?', format => 'md-image');
```

**Remark:** Pretty good conjectures of Larry Wall's birthday year or age can be made using the obtained graphs.
### Full queries
For the so called *full queries* Wolfram|Alpha returns complicated data of pods in either XML or JSON format;
see ["Explanation of Pods"](https://products.wolframalpha.com/api/documentation?scrollTo=explanation-of-pods).
Here we get the result of a full query and show its (complicated) data type (using ["Data::TypeSystem"](https://raku.land/zef:antononcube/Data::TypeSystem)):
```
use Data::TypeSystem;
my $podRes = wolfram-alpha-query('convert 44 lbs to kilograms', output => 'json', format => 'hash');
deduce-type($podRes)
```
```
# Assoc(Atom((Str)), Assoc(Vector(Atom((Str)), 18), Tuple([Atom((Int)) => 4, Atom((Rat)) => 2, Atom((Str)) => 10, Struct([count, template, type, values, word], [Int, Str, Str, Array, Str]) => 1, Tuple([Struct([error, expressiontypes, id, numsubpods, position, scanner, subpods, title], [Bool, Hash, Str, Int, Int, Str, Array, Str]), Struct([error, expressiontypes, id, numsubpods, position, primary, scanner, subpods, title], [Bool, Hash, Str, Int, Int, Bool, Str, Array, Str]), Struct([error, expressiontypes, id, numsubpods, position, scanner, states, subpods, title], [Bool, Array, Str, Int, Int, Str, Array, Array, Str]), Struct([error, expressiontypes, id, numsubpods, position, scanner, subpods, title], [Bool, Hash, Str, Int, Int, Str, Array, Str]), Struct([error, expressiontypes, id, numsubpods, position, scanner, states, subpods, title], [Bool, Hash, Str, Int, Int, Str, Array, Array, Str]), Struct([error, expressiontypes, id, numsubpods, position, scanner, subpods, title], [Bool, Array, Str, Int, Int, Str, Array, Str])]) => 1], 18), 18), 1)
```
Here we convert the query result into Markdown (`data-translation` can be also used):
```
wolfram-alpha-pods-to-markdown($podRes, header-level => 4):plaintext;
```
#### Input interpretation
**scanner:** Identity
convert 44 lb (pounds) to kilograms
#### Result
**scanner:** Identity
19.96 kg (kilograms)
#### Additional conversions
**scanner:** Unit
3 stone 2 pounds
19958 grams
#### Comparison as mass
**scanner:** Unit
≈ 1.6 × mass of a Good Delivery gold bar ( 400 oz t )
#### Interpretations
**scanner:** Unit
mass
#### Corresponding quantities
**scanner:** Unit
Relativistic energy E from E = mc^2:
| 1.794×10^18 J (joules)
| 1.12×10^37 eV (electronvolts)
Weight w of a body from w = mg:
| 44 lbf (pounds-force)
| 1.4 slugf (slugs-force)
| 196 N (newtons)
| 1.957×10^7 dynes
| 19958 ponds
Volume V of water from V = m/ρ\_(H\_2O):
| 5.3 gallons
| 42 pints
| 20 L (liters)
| 19958 cm^3 (cubic centimeters)
| (assuming conventional water density ≈ 1000 kg/m^3)
---
## Command Line Interface
### Playground access
The package provides a Command Line Interface (CLI) script:
```
wolfram-alpha --help
```
```
# Usage:
# wolfram-alpha [<words> ...] [--path=<Str>] [--output-format=<Str>] [-a|--auth-key=<Str>] [--timeout[=UInt]] [-f|--format=<Str>] [--method=<Str>] -- Command given as a sequence of words.
#
# --path=<Str> Path, one of 'result', 'simple', or 'query'. [default: 'result']
# --output-format=<Str> The format in which the response is returned. [default: 'Whatever']
# -a|--auth-key=<Str> Authorization key (to use WolframAlpha API.) [default: 'Whatever']
# --timeout[=UInt] Timeout. [default: 10]
# -f|--format=<Str> Format of the result; one of "json", "hash", "values", or "Whatever". [default: 'Whatever']
# --method=<Str> Method for the HTTP POST query; one of "tiny" or "curl". [default: 'tiny']
```
**Remark:** When the authorization key argument "auth-key" is specified set to "Whatever"
then `wolfram-alpha` attempts to use the env variable `WOLFRAM_ALPHA_API_KEY`.
---
## Mermaid diagram
The following flowchart corresponds to the steps in the package function `wolfram-alpha-query`:
```
graph TD
UI[/Some natural language text/]
TO[/"Wolfram|Alpha<br/>Processed output"/]
WR[[Web request]]
WolframAlpha{{http://api.wolframalpha.com}}
PJ[Parse JSON]
Q{Return<br>hash?}
MSTC[Compose query]
MURL[[Make URL]]
TTC[Process]
QAK{Auth key<br>supplied?}
EAK[["Try to find<br>WOLFRAM_ALPHA_API_KEY<br>in %*ENV"]]
QEAF{Auth key<br>found?}
NAK[/Cannot find auth key/]
UI --> QAK
QAK --> |yes|MSTC
QAK --> |no|EAK
EAK --> QEAF
MSTC --> TTC
QEAF --> |no|NAK
QEAF --> |yes|TTC
TTC -.-> MURL -.-> WR -.-> TTC
WR -.-> |URL|WolframAlpha
WolframAlpha -.-> |JSON|WR
TTC --> Q
Q --> |yes|PJ
Q --> |no|TO
PJ --> TO
```
---
## References
[AAp1] Anton Antonov,
[Data::TypeSystem Raku package](https://github.com/antononcube/Raku-Data-TypeSystem),
(2023),
[GitHub/antononcube](https://github.com/antononcube).
[WA1] Wolfram Alpha LLC, [Wolfram|Alpha](https://www.wolframalpha.com).
[WA2] Wolfram Alpha LLC, [Web API documentation](https://products.wolframalpha.com/api/documentation).
[Wk1] Wikipedia entry, [WolframAlpha](https://en.wikipedia.org/wiki/WolframAlpha).
|
## dist_zef-averna-Shodan.md
# NAME
Shodan
# DESCRIPTION
A [raku-lang](https://raku.org/) client for [Shodan](https://www.shodan.io/), a search engine for Internet-connected devices. This client provides an interface for the [Shodan API](https://developer.shodan.io).
# SYNOPSIS
```
use Shodan;
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
my $api-info = $shodan.api-info();
my $host = $shodan.host(ip => '8.8.8.8');
my $scan = $shodan.scan(
ips => '8.8.8.8,1.1.1.1',
service => [[53, 'dns-udp'], [443, 'https']]
);
my $alert = $shodan.alert-create(
name => 'test',
filters => {
ip => ['1.1.1.1', '8.8.8.8']
},
expires => 60
);
my $notifiers = $shodan.notifiers();
my $queries = $shodan.queries();
my $dns = $shodan.dns-domain(
domain => 'google.com',
history => True,
type => 'A',
page => 1
);
my $headers = $shodan.tools-http-headers();
my $exploit = $shodan.exploit-count(query => '2011-0349');
$shodan.stream-alerts(callback => {say $_; done;});
```
## REST API METHODS
Interface for the [Shodan REST API](https://developer.shodan.io/api).
### Search Methods
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Returns all services that have been found on the given host IP.
# Params:
# ip: [Str] Host IP address.
# history (optional): [Bool] Show all history (default: False).
# minify (optional): [Bool] Only return list of ports & host info (default: False).
$shodan.host(ip => '8.8.8.8');
$shodan.host(ip => '8.8.8.8', history => True, minify => True);
# Same as .host method except only returns the total number of results.
# Params:
# query: [Str] Shodan search query.
# facets (optional): [Str] Comma-separated list of properties to get info on.
$shodan.host-count(query => 'port:22');
$shodan.host-count(query => 'port:22', facets => 'org,os');
# Search Shodan, same query syntax as website. Use facets to get summary info.
# Params:
# query: [Str] Shodan search query.
# facets (optional): [Str] Comma-separated list of properties to get info on.
# page (optional): [UInt] Page num to page through results 100 per page (default: 1).
# minify (optional): [Bool] Whether or not to truncate larger fields (default: True).
$shodan.host-search(query => 'port:22');
$shodan.host-search(query => 'port:22', facets => 'org,os', page => 2, minify => True);
# Returns a list of facets to get a breakdown of the top values for a property.
$shodan.host-search-facets();
# Returns a list of search filters that can be used in the search query.
$shodan.host-search-filters();
# Shows which filters are used by query str & what params were provided to filters.
$shodan.search-tokens(query => 'Raspbian port:22');
```
### On-Demand Scanning
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Returns a list of port numbers that the crawlers are looking for.
$shodan.ports();
# List protocols that can be used with on-demand Internet scans via Shodan.
$shodan.protocols();
# Request Shodan to crawl a network.
# Params:
# ips: [Str] A comma-separated list of IPs or netblocks (CIDR) to get crawled.
# service (optional): [Array] List services to be scanned.
$shodan.scan(ips => '8.8.8.8,1.1.1.1');
$shodan.scan(ips => '8.8.8.8,1.1.1.1', service => [[53, 'dns-udp'], [443, 'https']]);
# Request Shodan to crawl the Internet for a specific port.
# Requires enterprise account.
# Params:
# port: [UInt] Port that Shodan should crawl the Internet for.
# protocol: [Str] Name of protocol to be used to interrogate the port.
$shodan.scan-internet(port => 80, protocol => 'http');
# Returns a list of all the scans that are currently active on the account.
$shodan.scans();
# Check the progress of a previously submitted scan request.
# Possible values for the status are: SUBMITTING, QUEUE, PROCESSING, DONE
# Params:
# id: [Str] The unique scan ID that was returned by /shodan/scan.
$shodan.scan-status(id => $scan-id);
```
### Network Alerts
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Create an alert to monitor a network range.
# Params:
# name: [Str] The name to describe the network alert.
# filters: [Hash] Specifying the criteria that an alert should trigger.
# filters{ip}: [Array] List of IPs or CIDR.
# expires (optional): [UInt] Number of seconds that the alert should be active.
my $alert = $shodan.alert-create(
name => 'test',
filters => {
ip => ['1.1.1.1', '8.8.8.8']
},
expires => 60
);
# Get the details for a network alert.
# Params:
# id: [Str] Alert ID.
$shodan.alert-info(id => $alert{'id'});
# Update the networks monitored in an alert.
# Params:
# id: [Str] Alert ID.
# filters: [Hash] Specifying the criteria that an alert should trigger.
# filters{ip}: [Array] List of IPs or CIDR.
$alert{'filters'}{'ip'}[0] = '8.8.4.4';
$shodan.alert-update(id => $alert{'id'}, filters => $alert{'filters'});
# Enable a trigger to get notifications when the specified trigger is met.
# Params:
# id: [Str] Alert ID.
# trigger: [Str] Comma-separated list of trigger names.
$shodan.alert-trigger-create(id => $alert{'id'}, trigger => 'new_service,vulnerable');
# Ignore the specified service when it is matched for the trigger.
# Params:
# id: [Str] Alert ID.
# trigger: [Str] Trigger name.
# service: [Str] Service specified in the format "ip:port" (ex. "1.1.1.1:80").
$shodan.alert-trigger-service-ignore(
id => $alert{'id'},
trigger => 'vulnerable',
service => '1.1.1.1:80'
);
# Start getting notifications again for the specified trigger.
# Params:
# id: [Str] Alert ID.
# trigger: [Str] Trigger name.
# service: [Str] Service specified in the format "ip:port" (ex. "1.1.1.1:80").
$shodan.alert-trigger-service-notify(
id => $alert{'id'},
trigger => 'vulnerable',
service => '1.1.1.1:80'
);
# Add the notifier to the alert.
# Params:
# id: [Str] Alert ID.
# notifier-id: [Str] Notifier ID.
$shodan.alert-notifier-create(id => $alert{'id'}, notifier-id => 'default');
# Remove the notifier from the alert
# Params:
# id: [Str] Alert ID.
# notifier-id: [Str] Notifier ID.
$shodan.alert-notifier-delete(id => $alert{'id'}, notifier-id => 'default');
# Disable a trigger to stop getting notifications for the specified trigger.
# Params:
# trigger: [Str] Trigger name.
# service: [Str] Service specified in the format "ip:port" (ex. "1.1.1.1:80").
$shodan.alert-trigger-delete(id => $alert{'id'}, trigger => 'new_service,vulnerable');
# Delete an alert.
# Params:
# id: [Str] Alert ID.
$shodan.alert-delete(id => $alert{'id'});
# Returns a list of all the network alerts that are active on the account.
$shodan.alerts();
# Returns a list of all the triggers that can be enabled on network alerts.
$shodan.alert-triggers();
```
### Notifiers
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Get a list of all the notifiers that the user has created.
$shodan.notifiers();
# List of available notification providers.
$shodan.notifier-providers();
# Create a new notification service for the user.
# Params:
# provider: [Str] Provider name as returned by notifier-providers.
# description: [Str] Description of the notifier.
# args: [Hash] Arguments required by the provider.
my $notifier = $shodan.notifier-create(
provider => 'email',
description => 'Email notifier',
args => {to => 'jmath@shodan.io'}
);
# Get information about a notifier.
# Params:
# id: [Str] Notifier ID.
$shodan.notifier(id => $notifier{'id'});
# Update the parameters of a notifier.
# Params:
# id: [Str] Notifier ID.
# args: [Hash] Arguments required by the provider.
$shodan.notifier-update(id => $notifier{'id'}, args => {to => 'e@shodan.io'});
# Remove the notification service created for the user.
# Params:
# id: [Str] Notifier ID.
$shodan.notifier-delete(id => $notifier{'id'});
```
### Directory Methods
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# List the saved search queries.
# Params:
# page (optional): [UInt] Page number to iterate over results (10 per page).
# sort (optional): [Str] Sort the list based on a property. Possible values are: votes, timestamp.
# order (optional): [Str] Whether to sort the list in ascending or descending order. Possible values are: asc, desc.
$shodan.queries();
$shodan.queries(page => 1, sort => 'timestamp', order => 'asc');
# Search the directory of saved search queries.
# Params:
# query: [Str] What to search for in the directory of saved search queries.
# page (optional): [UInt] Page number to iterate over results (10 per page).
$shodan.query-search(query => 'webcam');
$shodan.query-search(query => 'webcam', page => 1);
# List the most popular tags.
# Params:
# size (optional): [UInt] The number of tags to return (default: 10).
$shodan.query-tags();
$shodan.query-tags(size => 10);
```
### Bulk Data
Requires enterprise account.
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Get a list of available datasets.
$shodan.data();
# List the files for a dataset.
# Params:
# dataset: [Str] Name of the dataset.
$shodan.data-dataset();
```
### Manage Organization
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Get information about your organization.
$shodan.org();
# Add a Shodan user to the organization.
# Params:
# user: [Str] Username or email of the Shodan user.
# notify (optional): [Bool] Whether or not to send an email notification.
$shodan.org-member-create(user => 'averna');
# Remove a member.
# Params:
user: [Str] Username or email of the Shodan user.
$shodan.org-member-delete(user => 'averna');
```
### Account Methods
```
# Returns information about the Shodan account linked to this API key.
$shodan.account-profile();
```
### DNS Methods
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Get all the subdomains and other DNS entries for the given domain.
# Params:
# domain: [Str] Domain name to lookup; example "cnn.com".
# history (optional): [Bool] Show historical DNS data (default: False).
# type (optional): [Str] DNS type, possible values are: A, AAAA, CNAME, NS, SOA, MX, TXT.
# page (optional): [UInt] The page number to page through results 100 at a time (default: 1).
$shodan.dns-domain(domain => 'google.com');
$shodan.dns-domain(domain => 'google.com', history => True, type => 'A', page => 1);
# Look up the IP address for the provided list of hostnames.
# Params:
# hostnames: [Str] Comma-separated list of hostnames; example "google.com,bing.com".
$shodan.dns-resolve(hostnames => 'google.com');
# Look up the hostnames that have been defined for the given list of IP addresses.
# Params:
# ips: [Str] Comma-separated list of IP addresses; example "74.125.227.230,204.79.197.200".
$shodan.dns-reverse(ips => '8.8.8.8');
```
### Utility Methods
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Shows the HTTP headers that your client sends when connecting to a webserver.
$shodan.tools-http-headers();
# Get your current IP address as seen from the Internet.
$shodan.tools-myip();
```
### API Status Methods
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Returns information about the API plan belonging to the given API key.
$shodan.api-info();
```
See [Shodan::API::REST](https://github.com/averna-syd/Shodan/blob/main/README_REST_API.md) readme for more information.
## EXPLOIT API METHODS
Interface for the [Shodan Exploit API](https://developer.shodan.io/api/exploits/rest).
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Search across a variety of data sources for exploits and use facets to get summary information.
# Params:
# query: [Str] Search the database of known exploits. See https://developer.shodan.io/api/exploits/rest for list.
# facets (optional): [Str] A comma-separated list of properties to get summary info on. See https://developer.shodan.io/api/exploits/rest for list.
# page (optional): [UInt] The page number to page through results 100 at a time.
$shodan.exploit-search(query => '2011-0349');
# Search for Exploits without Results.
# Params:
# query: [Str] Search the database of known exploits. See https://developer.shodan.io/api/exploits/rest for list.
# facets (optional): [Str] A comma-separated list of properties to get summary info on. See https://developer.shodan.io/api/exploits/rest for list.
# page (optional): [UInt] The page number to page through results 100 at a time.
$shodan.exploit-count(query => '2011-0349');
```
See [Shodan::API::Exploit](https://github.com/averna-syd/Shodan/blob/main/README_EXPLOIT_API.md) readme for more information.
## STREAM API METHODS
Interface for the [Shodan Streaming API](https://developer.shodan.io/api/stream).
### Data Streams
Requires enterprise account.
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# This stream provides ALL of the data that Shodan collects.
# Params:
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-banners(callback => {say $_; done;});
# Filtered by ASN.
# Params:
# asn: [Str] Comma-separated list of ASNs; example "3303,32475".
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-asn(asn => '3303,32475', callback => {say $_; done;});
# Filtered by Country.
# Params:
# countries: [Str] Comma-separated list of countries indicated by their 2 letter code; example "DE,US".
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-countries(countries => 'DE,US', callback => {say $_; done;});
# Filtered by Ports.
# Params:
# ports: [Str] Comma-separated list of ports; example "22,443".
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-ports(ports => '22,443', callback => {say $_; done;});
# Filtered by Vulnerabilities.
# Params:
# vulns: [Str] Comma-separated list of case-insensitive vulns; example: "CVE-2017-7679,CVE-2018-15919".
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-vulns(vulns => 'CVE-2017-7679,CVE-2018-15919', callback => {say $_; done;});
# Filtered by Query
# Params:
# query: [Str] Space-separated list of key:value filters examplei: "port:22 SSH-2.0-OpenSSH_6.4"
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-custom(query => 'port:22 SSH-2.0-OpenSSH_6.4', callback => {say $_; done;});
```
### Network Alerts
```
my $shodan = Shodan.new(api-key => %*ENV{'SHODAN_API_KEY'});
# Subscribe to banners discovered on all IP ranges described in the network alerts.
# Params:
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-alerts(callback => {my $alert = $_; done;});
# Subscribe to banners discovered on the IP range defined in a specific network alert.
# Params:
# id: [Str] The unique ID of the network alert; example "OYPRB8IR9Z35AZPR".
# callback: [code] Code that's run within stream & passed stream data.
$shodan.stream-alert(id => 'ZLN92ZK9IHS22SDX', callback => {my $alert = $_; done;});
```
See [Shodan::API::Stream](https://github.com/averna-syd/Shodan/blob/main/README_STREAM_API.md) readme for more information.
## DISCLAIMER
This is an early version thus methods maybe subject to change. The author does not have access to an enterprise account. Therefore while ever effort was made to ensure enterprise method calls are correct, without adequate testing of enterprise calls the author can not be as confident when compared to method calls which can be adequately tested.
# AUTHOR
"Sarah Fuller", `<"sarah at averna . id . au">`
# COPYRIGHT AND LICENSE
Copyright 2022 Sarah Fuller
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-bbkr-Metropolis.md
# Metropolis generator for [Raku](https://www.raku.org) language
[](https://github.com/bbkr/Metropolis/actions/workflows/test.yml)
[Metropolis–Hastings algorithm](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm) is Markov chain Monte Carlo (MCMC) method for generating sequence of random samples from probability distribution function.
It can be used to generate naturally looking data for applications testing and presentation. For example let's assume that you have software for online marketing campaigns. And you have to generate fake traffic (100 000 site visits) that occurred after campaign started 10 days ago to record tutorial for users. It's obvious that such traffic is not constant. After campaign start traffic is low, then it quickly gains momentum, reaches interest peak and slowly fades away like this:

`f( x ) = 2x / ( x^3 + 0.5 ), { x > 0 }` generated using awesome [Desmos calculator](https://www.desmos.com/calculator).
With this module you will be able to generate such random samples with any probability distribution function within given domain.
**Note:** This is raw and fast implementation of Metropolis–Hastings algorithm. You may need to turn few dials to get best results for your cases. If you get bad results or timeouts be sure to read [TWEAKS](#tweaks) section.
# TABLE OF CONTENTS
* [SYNOPSIS](#synopsis)
* [METHODS](#methods)
* [new](#new)
* [sample](#sample)
* [graph](#graph)
* [TWEAKS](#tweaks)
* [CONTACT](#contact)
# SYNOPSIS
```
use Metropolis;
my $m = Metropolis.new(
function => -> $x { 2* $x / ( $x ** 3 + 0.5 ) },
domain => 0 .. 10
);
say $m.sample( ) for ^42;
```
# METHODS
## new
Params:
* `function` (mandatory) - probability distribution function, must accept exactly one positional argument.
* `domain` (mandatory) - range within which samples should be generated.
* `jumper` (optional) - function that will return new sample from given jumping distribution. Check [TWEAKS](#tweaks) section for more info.
## sample
Params:
* `timeout` (optional) - how long can algorithm look for next sample, no timeout by default.
Get next sample value of `Num` type. `Nil` will be returned in case of timeout.
## graph
Params:
* `samples` (mandatory) - how many samples should be gathered.
* `scale` (optional) - how high `y` axis should be, `100` characters by default.
Crude plotting to quickly visualize requested distribution. With **swapped** axis (x is vertical, turn your monitor). All values are rounded to nearest integer. All bars are rounded to nearest 1/8. For example to display distribution from [SYNOPSIS](#synopsis):
```
my $m = Metropolis.new(
function => -> $x { 2 * $x / ( $x ** 3 + 0.5 ) },
domain => 0 .. 10
);
$m.graph( samples => 10000, scale => 10 );
```
```
0 ███▋ (1622)
1 ██████████ (4545)
2 ████ (1800)
3 █▊ (803)
4 ▉ (417)
5 ▌ (251)
6 ▌ (208)
7 ▎ (135)
8 ▎ (106)
9 ▎ (91)
10 ▏ (22)
```
Potato-grade but useful :)
# TWEAKS
**Common issues:**
* Some places have accumulation of samples way too high for requested probability distribution there.
* Algorithm is not reaching every part of the domain. Some zero probability gaps (like in `f( x ) = sin x` function) are not crossed by algorithm at all, places beyond them do not generate samples.
* Sampling is realy, really slow.
**Solutions:**
* Don't go crazy with domain width. By default algorithm is tuned to work with domain of total width `<= 10`. Remember that you get `Num` values and you can project them to bigger domain (like for example 864\_000 timestamps from the last 10 days) if needed.
* Avoid functions with zero probability gaps within domain. This algorithm can handle them to some extend. But you will get best results if probability is always positive across whole domain. Sometimes it is better to generate samples for each positive probability area separately.
* Burn samples to forget initial state. This algorithm is based on Markov chain Monte Carlo method which needs warmup to eventually converge to the desired distribution. For example throw away first 1000 samples.
**Expert:**
You can provide your own jump function with desired distribution. By default [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) with `standard-deviation = 2` is used. [Uniform distribution](https://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29) is also provided with default `delta = 3`.
To use prebuilt and/or change its default:
```
my $m = Metropolis.new(
...,
# let's jump bigger zero probability gaps!
jumper => &uniform-distribution.assuming( delta => 15 )
);
```
To provide own:
```
my $m = Metropolis.new(
...,
# discrete decrease of longer jump distance probability
jumper => sub ( :$mean ) { # mean is current sample position
# roll jump distance within 0..1 range
my $jump = rand;
# make small jumps less probable by randomly re-rolling
$jump max= rand if $jump < 0.5;
# return new sampling point
# remember output must have equal chance to go both ways!
return $mean + (1, -1).pick * $jump;
}
);
```
|
## dist_zef-patrickb-BuildToolchainRepo.md
```
=begin pod
=NAME BuildToolchainRepo
A repository of compiler build toolchains
=head1 Synopsis
use BuildToolchainRepo::Lang::CRepo;
my $c-file = "hello.c";
my $o-file = "hello.o";
my $e-name = "hello";
my $t = BuildToolchainRepo::Lang::CRepo::get-toolchain().new;
my $cexit = $t.compile($c-file, $o-file);
my ($lexit, $e-file) = $t.link-executable(@$o-file, $dir, $e-name);
my $p = run $e-file;
=head1 Description
This module aims to provide a lightweight interface to build toolchains or in
other words: provide an easy way to build your C (or some other lang) code.
=head1 Compiling
Compilers can be searched automatically via C.
To directly use a specific compiler, just instanciate a C
class directly.
Such C toolchain objects provide a set of variables to modify their behavior
and a few methods to do the actual compiling.
=begin item
C Int>
Compile a single C file to an O file. Returns the compiler exit code.
=end item
=begin item
C List>
Link one or more O files to a shared object file. C<$out-path> is the folder
where the library should be placed in. C<$lib-name> is the name (not filename)
of the library.
Returns a list with two elements: The exit code of the compiler and a full path
of the generated library. The filename will differ from the given name, as it
will have the platform specific prefix and suffix added.
=end item
=begin item
C List)>
Link one or more O files to a shared object file. C<$out-path> is the folder
where the library should be placed in. C<$lib-name> is the name (not filename)
of the library.
Returns a list with two elements: The exit code of the compiler and a full path
of the generated library. The filename will differ from the given name, as it
will have the platform specific prefix and suffix added.
=end item
=begin item
C Bool)>
Is the toolchain at hand is available on the system?
=end item
=head1 Probes
Some tooling is provided, to simplify working with feature probes.
C provides two subs:
=item C Int)>
=item C Int)>
Both take a piece of C code and a toolchain and return the exit code of the
program or compiler respectively.
To write a probe, implement a function returning an object of type C.
Probes can then be added to toolchains via C<$t.probes.push: your-probe()>.
This causes a respective preprocessor define C with value 1 to
be set for all successful probes;
=head1 Environment Variables
=head2 C_TOOLCHAIN
Set this to the name of a C toolchain, to force using that specific toolchain.
=head GCC_PATH
When using the GCC toolchain, sets the path to look for the C executable.
=AUTHOR Patrick Böker
=head1 License
This module is distributed under the terms of the Artistic License 2.0.
=end pod
```
|
## dist_cpan-LEONT-Getopt-Long.md
[](https://travis-ci.org/Leont/getopt-long6)
# NAME
Getopt::Long
# SYNOPSIS
```
use Getopt::Long;
get-options("length=i" => my $length, # numeric
"file=s" => my $file, # string
"verbose" => my $verbose); # flag
use Getopt::Long;
my $options = get-options("length=i", # numeric
"file=s", # string
"verbose"); # flag
```
or
```
use Getopt::Long;
sub MAIN(Int :$length, Str :$file, Bool :$verbose) { ... }
```
# DESCRIPTION
The Getopt::Long module implements extended getopt functions called `get-options()` and `get-options-from`, as well as automatic argument parsing for a `MAIN` sub.
This function adheres to the POSIX syntax for command line options, with GNU extensions. In general, this means that options have long names instead of single letters, and are introduced with a double dash "--". Support for bundling of command line options, as was the case with the more traditional single-letter approach, is also provided.
# Command Line Options, an Introduction
Command line operated programs traditionally take their arguments from the command line, for example filenames or other information that the program needs to know. Besides arguments, these programs often take command line *options* as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behaviour. For example, a program could do its job quietly, but with a suitable option it could provide verbose information about what it did.
Command line options come in several flavours. Historically, they are preceded by a single dash `-`, and consist of a single letter.
```
-l -a -c
```
Usually, these single-character options can be bundled:
```
-lac
```
Options can have values, the value is placed after the option character. Sometimes with whitespace in between, sometimes not:
```
-s 24 -s24
```
Due to the very cryptic nature of these options, another style was developed that used long names. So instead of a cryptic `-l` one could use the more descriptive `--long`. To distinguish between a bundle of single-character options and a long one, two dashes are used to precede the option name. Also, option values could be specified either like
```
--size=24
```
or
```
--size 24
```
# Getting Started with Getopt::Long
To use Getopt::Long from a Raku program, you must include the following line in your program:
```
use Getopt::Long;
```
This will load the core of the Getopt::Long module and prepare your program for using it.
## Getopt::Long as a MAIN wrapper
Getopt::Long can be used as a argument parsing MAIN wrapper, replacing the builtin argument parsing. It will by default offer a Unix-typical command line interface, but various options allow it to be more similar to Raku's ideosyncratic parsing.
It supports the following types for named and positional arguments:
* Bool
* Any
* Str
* Int
* Rat
* Num
* Real
* Numeric
* Complex
* IO::Path
* DateTime
* Date
* Version
It also supports any enum type, and any coercion type that uses any of the aforementioned types as its contraint type (e.g. `Foo(Str)`).
An explicit converter can also be set using an `is option` trait, e.g.
```
sub MAIN(Foo :$foo is option(&foo-converter)) { ... }
```
## Simple options
The most simple options are the ones that take no values. Their mere presence on the command line enables the option. Popular examples are:
```
--all --verbose --quiet --debug
```
Handling simple options is straightforward:
```
sub MAIN(Bool :$verbose, Bool :$all) { ... }
```
or:
```
get-options('verbose' => my $verbose, 'all' => my $all);
```
The call to `get-options()` parses the command line arguments that are present in `@*ARGS` and sets the option variable to the value `True` if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called *enabling* the option.
The option name as specified to the `get-options()` function is called the option *specification*. Later we'll see that this specification can contain more than just the option name.
`get-options()` will return a `Capture` if the command line could be processed successfully. Otherwise, it will throw an error using die().
## A little bit less simple options
Getopt::Long supports two useful variants of simple options: *negatable* options and *incremental* options.
A negatable option is specified with an exclamation mark `!` after the option name or a default value for `MAIN` argument:
```
sub MAIN(Bool :$verbose = False) { ... }
```
or:
```
get-options('verbose!' => my $verbose);
```
or:
```
my $options = get-options('verbose!');
```
Now, using `--verbose` on the command line will enable `$verbose`, as expected. But it is also allowed to use `--noverbose` or `--no-verbose`, which will disable `$verbose` by setting its value to `False`.
An incremental option is specified with a plus `+` after the option name:
```
sub MAIN(Int :$verbose is option('+')) { ... }
```
or:
```
get-options('verbose+' => my $verbose);
```
or
```
my $options = get-options('verbose+');
```
Using `--verbose` on the command line will increment the value of `$verbose`. This way the program can keep track of how many times the option occurred on the command line. For example, each occurrence of `--verbose` could increase the verbosity level of the program.
## Mixing command line option with other arguments
Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash `--` on the command line:
```
--size 24 -- --all
```
In this example, `--all` will *not* be treated as an option, but passed to the program unharmed, in `@*ARGS`.
## Options with values
For options that take values it must be specified whether the option value is required or not, and what kind of value the option expects.
Three kinds of values are supported: integer numbers, floating point numbers, and strings.
If the option value is required, Getopt::Long will take the command line argument that follows the option and assign this to the option variable. If, however, the option value is specified as optional, this will only be done if that value does not look like a valid command line option itself.
```
sub MAIN(Str :$tag) { ... }
```
or
```
get-options('tag=s' => my $tag);
```
or my %options = get-options('tag=s');
In the option specification, the option name is followed by an equals sign `=` and the letter `s`. The equals sign indicates that this option requires a value. The letter `s` indicates that this value is an arbitrary string. Other possible value types are `i` for integer values, and `f` for floating point values. Using a colon `:` instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string `''` assigned, while numeric options are set to `0`.
## Options with multiple values
Options sometimes take several values. For example, a program could use multiple directories to search for library files:
```
--library lib/stdlib --library lib/extlib
```
You can specify that the option can have multiple values by adding a "@" to the format, or declare the argument as positional:
```
sub MAIN(Str :@library) { ... }
```
or
```
get-options('library=s@' => my @libraries);
```
or
```
my $options = get-options('library=s@');
```
Used with the example above, `@libraries`/`$options<library>` would contain two strings upon completion: `"lib/stdlib"` and `"lib/extlib"`, in that order. It is also possible to specify that only integer or floating point numbers are acceptable values.
Warning: What follows is an experimental feature.
Options can take multiple values at once, for example
```
--coordinates 52.2 16.4 --rgbcolor 255 255 149
```
This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the `{...}` repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows:
```
my $options = get-options('coordinates=f{2}', 'rgbcolor=i{3}');
```
or
```
sub MAIN(Rat :@coordinates is option('f{2}'),
Int :@rgbcolor is option('i{3}'))
get-options('coordinates=f{2}' => my @coordinates,
'rgbcolor=i{3}' => my @rgbcolor);
```
It is also possible to specify the minimal and maximal number of arguments an option takes. `foo=s{2,4}` indicates an option that takes at least two and at most 4 arguments. `foo=s{1,}` indicates one or more values; `foo:s{,}` indicates zero or more option values.
## Options with hash values
If you specify that the option can have multiple named values by adding a "%":
```
sub MAIN(Str :%define) { ... }
```
or
```
get-options("define=s%" => my %define);
```
or
```
my $options = get-options("define=s%");
```
When used with command line options:
```
--define os=linux --define vendor=redhat
```
the hash `%defines` or `$options<define>` will contain two keys, `"os"` with value `"linux"` and `"vendor"` with value `"redhat"`. It is also possible to specify that only integer or floating point numbers are acceptable values. The keys are always taken to be strings.
## Options with multiple names
Often it is user friendly to supply alternate mnemonic names for options. For example `--height` could be an alternate name for `--length`. Alternate names can be included in the option specification, separated by vertical bar `|` characters. To implement the above example:
```
sub MAIN(:height(:$length)) { ... }
```
or
```
get-options('length|height=f' => my $length);
```
or
```
$options = get-options('length|height=f');
```
The first name is called the *primary* name, the other names are called *aliases*. When using a hash to store options, the key will always be the primary name.
Multiple alternate names are possible.
## Summary of Option Specifications
Each option specifier consists of two parts: the name specification and the argument specification.
The name specification contains the name of the option, optionally followed by a list of alternative names separated by vertical bar characters.
```
length option name is "length"
length|size|l name is "length", aliases are "size" and "l"
```
The argument specification is optional. If omitted, the option is considered boolean, a value of `True` will be assigned when the option is used on the command line.
The argument specification can be
* !
The option does not take an argument and may be negated by prefixing it with "no" or "no-". E.g. `"foo!"` will allow `--foo` (a value of 1 will be assigned) as well as `--nofoo` and `--no-foo` (a value of 0 will be assigned). If the option has aliases, this applies to the aliases as well.
```
The option does not take an argument and will be incremented by 1 every time it appears on the command line. E.g. `"more+"`, when used with `--more --more --more`, will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at firs).
The `+` specifier is ignored if the option destination is not a scalar.
```
* = *type* [ *desttype* ] [ *repeat* ]
The option requires an argument of the given type. Supported types are:
```
* s
String(`Str`). An arbitrary sequence of characters. It is valid for the argument to start with `-` or `--`.
* i
Integer (`Int`). This can be either an optional leading plus or minus sign, followed by a sequence of digits, or an octal string (`0o`, optionally followed by '0', '1', .. '7'), or a hexadecimal string (`0x` followed by '0' .. '9', 'a' .. 'f', case insensitive), or a binary string (`0b` followed by a series of '0' and '1').
* r
Rational number (`Rat`). For example `3.14`.
* f
Floating-pointer number (`Num`). For example `3.14`, `-6.23E24` and so on.
* c
Complex number (`Complex`). For example `1+2i`.
* p
Path (`IO::Path`). For example `foo/bar.txt`.
* d
An ISO-8601 formatted date and time (`DateTime`). For example `2019-12-30T01:23:45-0700`.
* a
A ISO-8601 formatted date (`Date`). For example `2019-12-30`.
* v
A Version (`Version`). For example `1.2.3`.
```
The *desttype* can be `@` or `%` to specify that the option is list or a hash valued.
The *repeat* specifies the number of values this option takes per occurrence on the command line. It has the format `{` [ *min* ] [ `,` [ *max* ] ] `}`.
*min* denotes the minimal number of arguments. It defaults to `0`.
*max* denotes the maximum number of arguments. It must be at least *min*. If *max* is omitted, *but the comma is not*, there is no upper bound to the number of argument values taken.
* : *type* [ *desttype* ]
Like `=`, but designates the argument as optional. If omitted, an empty string will be assigned to string values options, and the value zero to numeric options.
Note that if a string argument starts with `-` or `--`, it will be considered an option on itself.
* : *number* [ *desttype* ]
Like `:i`, but if the value is omitted, the *number* will be assigned.
* : + [ *desttype* ]
Like `:i`, but if the value is omitted, the current value for the option will be incremented.
# Advanced Possibilities
## Object oriented interface
Getopt::Long can be used in an object oriented way as well:
```
use Getopt::Long;
my $p = Getopt::Long.new-from-patterns(@options);
my $o = $p.get-options(@args) ...
```
Configuration options can be passed to the constructor as named arguments:
```
$p = Getopt::Long.new-from-patterns(@options, :!permute);
```
## Parsing options from an arbitrary array
By default, get-options parses the options that are present in the global array `@*ARGS`. A special entry `get-options-from` can be used to parse options from an arbitrary array.
```
use Getopt::Long;
$ret = get-options-from(@myargs, ...);
```
The following two calls behave identically:
```
$ret = get-options( ... );
$ret = get-options-from(@*ARGS, :overwrite, ... );
```
# Configuring Getopt::Long
`get-options` and `get-options-from` take the following named options to configure. When using Getopt::Long as a `MAIN` wrapper, you can set them using the `%*SUB-MAIN-OPTS` variable:
* auto-abbreviate (default: `False`)
Enabling this allows option names to be abbreviated to uniqueness (e.g. `--foo` can be written as `--f` if no other option starts with an `f`).
* compat-builtin (default: `False`)
Enable all compatibility options that make argument parsing more like the builtin argument parsing. Currently that means disabling `bundling` and `permute`, and enabling `compat-singles`, `compat-negation`, `compat-positional` and `auto-help`)
* bundling (default: `!$compat-builtin`)
Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options *must* be introduced with `--` and bundles with `-`.
Note that, if you have options `a`, `l` and `all`, possible arguments and option settings are:
```
using argument sets option(s)
-------------------------------
-a, --a a
-l, --l l
-all a, l
--all all
```
* permute (default: `!$compat-builtin`)
Whether command line arguments are allowed to be mixed with options. Default is enabled unless `$compat-builtin` is set.
If `permute` is enabled, this means that
```
--foo arg1 --bar arg2 arg3
```
is equivalent to
```
--foo --bar arg1 arg2 arg3
```
* compat-singles (default: `$compat-builtin`)
Enabling this will allow single letter arguments with an `=` between the letter and its argument. E.g. `-j=2` instead of `-j2`. This is for compatibility with raku's built-in argument parsing.
* compat-negation (default: `$compat-builtin`)
Enabling this will allow one to one to use `--/foo` as an alias for `--no-foo`, for compatibility with raku's built-in argument parsing. Note that this still requires the presence of a `--no-foo` handler, typically by using the `!` modifier.
* compat-positional (default: `$compat-builtin`)
Enabling this will turn all positional arguments into allomorphs, if possible.
* compat-space (default: `$compat-builtin`)
By default, an option with an optional argument will take that as a separate argument unless that argument starts with `--`; e.g. `--foo bar`. If this option is enabled, no such separate arguments are allowed, and the only way to express such an argument is in the same argument: `--foo=bar`.
* auto-help (default: `$compat-builtin`)
This adds an extra --help option, that can hook into Raku's built-in usage message generator.
# Return values and Errors
`get-options` returns a capture to indicate success, or throws an `Getopt::Long::Exception` otherwise.
# Troubleshooting
## `get-options` does not fail when an option is not supplied
That's why they're called 'options'.
## `get-options` does not split the command line correctly
The command line is not split by get-options, but by the command line interpreter (CLI). On Unix, this is the shell. On Windows, it is CMD.EXE. Other operating systems have other CLIs.
It is important to know that these CLIs may behave different when the command line contains special characters, in particular quotes or backslashes. For example, with Unix shells you can use single quotes (`'`) and double quotes (`"`) to group words together. The following alternatives are equivalent on Unix:
```
"two words"
'two words'
two\ words
```
In case of doubt, insert the following statement in front of your Perl program:
```
note @*ARGS.join('|');
```
to verify how your CLI passes the arguments to the program.
# AUTHOR
Leon Timmermans [fawaka@gmail.com](mailto:fawaka@gmail.com)
|
## cygwin.md
class IO::Spec::Cygwin
Platform specific operations on file and directory paths for Cygwin
```raku
class IO::Spec::Cygwin is IO::Spec::Unix { }
```
An object of this type is available via the variable `$*SPEC` if the Raku interpreter is running on `Cygwin`.
About this class and its related classes also see [`IO::Spec`](/type/IO/Spec).
# [Methods](#class_IO::Spec::Cygwin "go to top of document")[§](#Methods "direct link")
## [method abs2rel](#class_IO::Spec::Cygwin "go to top of document")[§](#method_abs2rel "direct link")
```raku
method abs2rel(IO::Path:D $path, IO::Path:D $base = $*CWD --> Str:D)
```
Returns a string that represents `$path`, but relative to `$base` path. Both `$path` and `$base` may be relative paths. `$base` defaults to `$*CWD`. Uses [`IO::Spec::Win32`](/type/IO/Spec/Win32)'s semantics.
## [method canonpath](#class_IO::Spec::Cygwin "go to top of document")[§](#method_canonpath "direct link")
```raku
method canonpath(Str() $path, :$parent --> Str:D)
```
Returns a string that is a canonical representation of `$path`. If `:$parent` is set to true, will also clean up references to parent directories. **NOTE:** the routine does not access the filesystem.
```raku
IO::Spec::Cygwin.canonpath(「C:\foo\\..\bar\..\ber」).say;
# OUTPUT: «C:/foo/../bar/../ber»
IO::Spec::Cygwin.canonpath("foo///./../bar/../ber").say;
# OUTPUT: «foo/../bar/../ber»
IO::Spec::Cygwin.canonpath("foo///./../bar/../ber", :parent).say;
# OUTPUT: «ber»
```
## [method catdir](#class_IO::Spec::Cygwin "go to top of document")[§](#method_catdir "direct link")
```raku
method catdir (*@parts --> Str:D)
```
Concatenates multiple path fragments and returns the canonical representation of the resultant path as a string. The `@parts` are [`Str`](/type/Str) objects and are allowed to contain path separators.
```raku
IO::Spec::Cygwin.catdir(<foo/bar ber raku>).say;
# OUTPUT: «foo/bar/ber/raku»
```
## [method catpath](#class_IO::Spec::Cygwin "go to top of document")[§](#method_catpath "direct link")
```raku
method catpath (Str:D $volume, Str:D $dir, Str:D $file --> Str:D)
```
Same as [`IO::Spec::Win32.catpath`](/type/IO/Spec/Win32#method_catpath), except will also change all backslashes to slashes at the end:
```raku
IO::Spec::Cygwin.catpath('C:', '/some/dir', 'foo.txt').say;
# OUTPUT: «C:/some/dir/foo.txt»
IO::Spec::Cygwin.catpath('C:', '/some/dir', '').say;
# OUTPUT: «C:/some/dir»
IO::Spec::Cygwin.catpath('', '/some/dir', 'foo.txt').say;
# OUTPUT: «/some/dir/foo.txt»
IO::Spec::Cygwin.catpath('E:', '', 'foo.txt').say;
# OUTPUT: «E:foo.txt»
```
## [method is-absolute](#class_IO::Spec::Cygwin "go to top of document")[§](#method_is-absolute "direct link")
```raku
method is-absolute(Str:D $path --> Bool:D)
```
Returns `True` if the `$path` starts with a slash (`"/"`) or backslash (`"\"`), even if they have combining character on them, optionally preceded by a volume:
```raku
say IO::Spec::Cygwin.is-absolute: "/foo"; # OUTPUT: «True»
say IO::Spec::Cygwin.is-absolute: "/\x[308]foo"; # OUTPUT: «True»
say IO::Spec::Cygwin.is-absolute: 「C:\foo」; # OUTPUT: «True»
say IO::Spec::Cygwin.is-absolute: "bar"; # OUTPUT: «False»
```
## [method join](#class_IO::Spec::Cygwin "go to top of document")[§](#method_join "direct link")
```raku
method join(|c)
```
Same as [`IO::Spec::Win32.join`](/type/IO/Spec/Win32#method_join), except replaces backslashes with slashes in the final result.
## [method rel2abs](#class_IO::Spec::Cygwin "go to top of document")[§](#method_rel2abs "direct link")
```raku
method rel2abs(|c --> List:D)
```
Same as [`IO::Spec::Win32.rel2abs`](/type/IO/Spec/Win32#method_rel2abs), except replaces backslashes with slashes in the final result.
## [method split](#class_IO::Spec::Cygwin "go to top of document")[§](#method_split "direct link")
```raku
method split(IO::Spec::Cygwin: Cool:D $path)
```
Same as [`IO::Spec::Win32.split`](/type/IO/Spec/Win32#method_split), except it replaces backslashes with slashes in all the values of the final result.
## [method splitpath](#class_IO::Spec::Cygwin "go to top of document")[§](#method_splitpath "direct link")
```raku
method splitpath(|c --> List:D)
```
Same as [`IO::Spec::Win32.splitpath`](/type/IO/Spec/Win32#method_splitpath), except replaces backslashes with slashes in all the values of the final result.
## [method tmpdir](#class_IO::Spec::Cygwin "go to top of document")[§](#method_tmpdir "direct link")
```raku
method tmpdir(--> IO::Path:D)
```
Attempts to locate a system's temporary directory by checking several typical directories and environment variables. Uses current directory if no suitable directories are found.
|
## dist_zef-cro-Cro-TLS.md
# Cro::TLS Build Status
This is part of the Cro libraries for implementing services and distributed
systems in Raku. See the [Cro website](http://cro.services/) for further
information and documentation.
|
## hardware.md
hardware
Combined from primary sources listed below.
# [In Kernel](#___top "go to top of document")[§](#(Kernel)_method_hardware "direct link")
See primary documentation
[in context](/type/Kernel#method_hardware)
for **method hardware**.
```raku
method hardware
```
Instance method returning the hardware information of the Kernel object. Dies if the hardware information could not be established.
```raku
say $*KERNEL.hardware; # OUTPUT: «x86_64»
```
|
## dist_zef-librasteve-Math-Vector.md
```
[](https://opensource.org/licenses/Artistic-2.0)
#Math::Vector
This is a fork of https://github.com/colomon/Math-Vector from v0.6.0
# SYNOPSIS
```raku
#!/usr/bin/env raku
use Math::Vector;
my $v1 = Math::Vector.new(1, 2, 3);
my $v2 = Math::Vector.new(3, 4, 0);
say "My vector $v1 has {$v1.dim} dimensions"; #^(1, 2, 3)
say ~ ($v1 + $v2); #^(4, 6, 3)
say ~ ($v1 * 2); #^(2, 4, 6)
say ~ ($v1 ⋅ $v2); #11
say ~ ($v1 × $v2); #^(-12, 9, -2)
say ~ (⎡$v1⎤); #3.7416573867739413
say ~ (-$v1); #^(-1, -2, -3)
say ~ ($v1 cmp $v2); #Less
```
```
|
## dist_zef-jonathanstowe-Printing-Jdf.md
# Printing::Jdf
This is a module for parsing Adobe Job Definition Format files that use Kodak's
SSi extensions.

## Example
```
my $xml = slurp('/path/to/file.jdf');
my $jdf = Printing::Jdf.new($xml);
```
See the [imposition](examples/imposition) script for an example of using
this module to list the templates, adjustments and page details from a
JDF file.
## Documentation
### Printing::Jdf
#### .Auditpool
Returns a Printing::Jdf::AuditPool object for the provided JDF file
#### .ResourcePool
Returns a Printing::Jdf::ResourcePool object for the provided JDF file
#### ::mm (Str, Int, Rat) --> Int
Converts Pts to Millimetres, rounded to the closest millimetre
### Printing::Jdf::AuditPool
#### .Created
Returns a Hash with the following keys:
```
<Str> AgentName => the name of the generator used to create the JDF file
<Str> AgentVersion => the version of the generator
<DateTime> TimeStamp => object representing the date the file was created
```
### Printing::Jdf::ResourcePool
#### .ColorantOrder
Returns a List of Strings of the names of the colours in the document
#### .Layout
Returns a Hash with the following keys:
```
<Int> Bleed => the amount of bleed used in the document, in millimetres
PageAdjustments => a Hash representing the page offsets
Odd => odd page offsets
<Int> X => horizontal offset
<Int> Y => vertical offset
Even => even page offsets
<Int> X => horizontal offset
<Int> Y => vertical offset
Signatures => an array of the Signatures in the document
Each Signature is a Hash containing the following keys:
<Str> Name => the name of the signature
<Int> PressRun => the number of the press run
<IO::Path> Template => an IO::Path object of the template file
```
#### .Runlist
Returns an Array of Hashes representing each page in the runlist
```
<Int> Run => the run number of the page
<Int> Page => the page number
<IO::Path> Url => a IO::Path object for the file
<Bool> Centered => a Bool that is True if the page is centered
CenterOffset => a Hash of the page offsets of a centered page
see Layout<PageAdjustments>
Offsets => a Hash of the page offsets in millimetres
see Layout<PageAdjustments>
Scaling => a Hash with the keys <X> and <Y> representing the scaling percentage of the page
<Bool> IsBlank => a Bool that is True if the page is blank
```
## License
This module is licensed under the terms of the ISC License.
Adobe, Kodak, Preps and Creo are trademarks of their respective owners.
|
## dist_zef-avuserow-Audio-TagLib.md
[](https://github.com/avuserow/raku-audio-taglib/actions)
# NAME
Audio::TagLib - Read ID3 and other audio metadata with TagLib
# SYNOPSIS
```
use Audio::TagLib;
my $taglib = Audio::TagLib.new($path);
# Abstract API - aliases for simple fields
say $taglib.title ~ " by " ~ $taglib.artist;
say "$path has no album field set" unless $taglib.album.defined;
# Raw access to all tags in the file (as a list of pairs)
.say for $taglib.propertymap.grep(*.key eq 'ALBUMARTIST' | 'ALBUM ARTIST');
```
# DESCRIPTION
Audio::TagLib provides Raku bindings to the TagLib audio metadata library, providing a fast way to read metadata from many audio file formats: mp3, m4a, ogg, flac, opus, and more. See <https://taglib.org> for more details.
# Audio::TagLib vs Audio::Taglib::Simple
This module uses the C++ interface to TagLib rather than the C bindings. This means installation requires a C++ compiler, but provides the full API rather than the "abstract only" API.
This module is newer than Simple and does not yet provide tag writing functions.
This module does not keep a taglib object open and reads everything into memory initially, meaning there is no `free` method needed (unlike Simple).
`Audio::Taglib::Simple` has a lowercase 'l' in its name, where this module uses `TagLib` (as does the official website). I thought adjusting the case was a good idea at the time.
## Audio::TagLib
### new($path, :$load-raw-id3v2)
Loads the metadata from the given file. All metadata is read at this point.
The optional `:load-raw-id3v2` flag determines whether the `raw-id3v2` list is populated. This is false by default, since the `propertymap` provides similiar information for more types of files, and it's faster to not generate this mapping.
If any errors are encountered while reading the file or parsing the tags, a Failure is returned which contains an Exception explaining the error.
### Abstract API
TagLib provides what is known as the "abstract API", which provides an easy interface to common tags without having to know the format-specific identifier for a given tag. This module provides these as attributes of `Audio::TagLib`. The following fields are available as strings (Str):
* title
* artist
* album
* comment
* genre
The following are provided as integers (Int):
* year
* track
* length - length of the file, in seconds
These attributes will be undefined if they are not present in the file.
### @.propertymap
This is a List of Pairs of all the recognized tags within the file. The exact list of recognized tags differs from file to file, but the names are largely consistent between file types. For example, this allows the ID3v2 tag `TPE2` and the MP4 tag `aART` to be recognized as `ALBUMARTIST`.
If you are looking for a tag not found in the above abstract interface, you should be able to find it here.
### Bool has-id3v2
True if the file has an ID3v2 tag. This value is defined whether or not `:load-raw-id3v2` is specified.
### @.raw-id3v2
Similar to propertymap, this is a list of native ID3v2 tags, by their short identifier (e.g. `TPE2` instead of `ALBUMARTIST`). This list is empty if there are no ID3v2 Tag, and will return a `Failure` if the `:load-raw-id3v2` flag was not provided to the constructor.
## Album Art
Album art can be extracted from most types of audio files. This module provides access to the first picture data in the file. Most files only have a single picture attached, so this is usually the album art.
* album-art-size - the size of the album art in bytes
* album-art-mime - the mime type of the album art, such as 'image/png'
The data can be retrieved by calling one of the following methods:
* get-album-art - returns the data as a Blob[uint8]
* get-album-art-raw - returns the data as a CArray (call .elems to get the size)
The raw variant is much faster if you are passing the data to another function that uses a CArray. If speed is important, consider using NativeHelpers::Blob to convert the raw variant.
Note that the mime type is stored in the file, and not determined from the image, so it may be inaccurate.
# SEE ALSO
Audio::Taglib::Simple
<https://taglib.org>
# AUTHOR
Adrian Kreher [avuserow@gmail.com](mailto:avuserow@gmail.com)
# COPYRIGHT AND LICENSE
Copyright 2021-2023 Adrian Kreher
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-antononcube-Data-Translators.md
# Data::Translators
Raku package for translation of JSON specs or JSON-like data structures into other formats.
It is envisioned this package to have translators to multiple formats. For example:
* DONE HTML
* DONE JSON
* DONE R
* DONE WL
* TODO Plain text
* TODO Python
* TODO Mermaid-JS
* TODO Julia
* TODO SQL
The main motivation for making the package is to have convenient way of making tables while doing
[Literate programming](https://en.wikipedia.org/wiki/Literate_programming)
with Raku using:
* Computational Markdown documents, [AAp4]
* Jupyter notebooks, [BDp1]
* Mathematica notebooks, [AAp4]
The use of JSON came to focus, since when working Large Language Model (LLM) functions, [AAp3],
very often it is requested from LLMs to produce output in JSON format, [AA1, AA2].
The package "Data::Reshapers", [AAp1], would complement nicely "Data::Translators" and vice versa.
The package "Data::TypeSystem", [AAp2], is used for "translation decisions" and for conversions into more regular datasets.
The package "Mathematica::Serializer", [AAp5], has very similar mission --
it is for translating Raku data structures into Mathematica (aka Wolfram Language or WL) code.
In order to utilize "Data::Translators" while doing Literate programming with:
* Computational Markdown files, then use the code chunk argument `results=asis`.
* Jupyter notebooks, then use the code cell magic spec `%%html` or `%% > html`.
One can find concrete examples for:
* Computational Markdown files, in the [raw source code of this README](https://raw.githubusercontent.com/antononcube/Raku-Data-Translators/main/README.md)
* Jupyter notebooks, in the [magics examples notebook](https://github.com/bduggan/raku-jupyter-kernel/blob/master/eg/magics.ipynb) at [BDp1]
**Remark:** The provided converters are made for communication purposes, so they might not be
very performant. I have used or tested them with datasets that have less than 5000 rows.
---
## Installation
Package installations from both sources use [zef installer](https://github.com/ugexe/zef)
(which should be bundled with the "standard" Rakudo installation file.)
To install the package from [Zef ecosystem](https://raku.land/) use the shell command:
```
zef install Data::Translators
```
To install the package from the GitHub repository use the shell command:
```
zef install https://github.com/antononcube/Raku-JSON-Translators.git
```
---
## Basic usage
### Main use case
Here is a "main use case" example:
1. Get a dataset that is an array of hashes
2. Filter or sample the records
3. Make an HTML table with those records
The HTML table outputs can be used to present datasets nicely in:
* Markdown documents
* Jupyter notebooks
Here we get the Titanic dataset and sample it:
```
use Data::Reshapers;
use Data::TypeSystem;
use Data::Translators;
my $tbl = get-titanic-dataset.pick(3);
```
```
# ({id => 258, passengerAge => 40, passengerClass => 1st, passengerSex => female, passengerSurvival => survived} {id => 1211, passengerAge => 40, passengerClass => 3rd, passengerSex => male, passengerSurvival => died} {id => 1227, passengerAge => 20, passengerClass => 3rd, passengerSex => male, passengerSurvival => died})
```
Here is the corresponding dataset type:
```
deduce-type($tbl);
```
```
# Vector(Assoc(Atom((Str)), Atom((Str)), 5), 3)
```
Here is the corresponding HTML table:
```
$tbl ==> data-translation
```
| passengerClass | passengerSurvival | id | passengerAge | passengerSex |
| --- | --- | --- | --- | --- |
| 1st | survived | 258 | 40 | female |
| 3rd | died | 1211 | 40 | male |
| 3rd | died | 1227 | 20 | male |
We can specify field names and HTML table attributes:
```
$tbl ==> data-translation(field-names => <id passengerSurvival>, table-attributes => 'id="info-table" class="table table-bordered table-hover" text-align="center"');
```
| id | passengerSurvival |
| --- | --- |
| 258 | survived |
| 1211 | died |
| 1227 | died |
Here is how the transposed dataset is tabulated:
```
$tbl ==> transpose() ==> data-translation;
```
| | |
| --- | --- |
| id | * 258 * 1211 * 1227 |
| passengerSurvival | * survived * died * died |
| passengerClass | * 1st * 3rd * 3rd |
| passengerSex | * female * male * male |
| passengerAge | * 40 * 40 * 20 |
### From JSON strings
Here is a JSON string translation to HTML:
```
my $json1 = q:to/END/;
{
"sample": [
{"name": "json2html", "desc": "coverts json 2 html table format", "lang": "python"},
{"name": "testing", "desc": "clubbing same keys of array of objects", "lang": "python"}
]
}
END
data-translation($json1);
```
| | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| sample | | lang | name | desc | | --- | --- | --- | | python | json2html | coverts json 2 html table format | | python | testing | clubbing same keys of array of objects | |
### Cross-tabulated data
Here is a more involved data example:
```
data-translation(cross-tabulate(get-titanic-dataset, 'passengerSex', 'passengerSurvival'))
```
| | | | | | |
| --- | --- | --- | --- | --- | --- |
| male | | | | | --- | --- | | died | 682 | | survived | 161 | |
| female | | | | | --- | --- | | died | 127 | | survived | 339 | |
Compare the HTML table above with the following plain text table:
```
to-pretty-table(cross-tabulate(get-titanic-dataset, 'passengerSex', 'passengerSurvival'))
```
```
# +--------+----------+------+
# | | survived | died |
# +--------+----------+------+
# | female | 339 | 127 |
# | male | 161 | 682 |
# +--------+----------+------+
```
### Generation of R and WL code
Here is the R code version of the Titanic data sample:
```
$tbl ==> data-translation(target => 'R', field-names => <id passengerClass passengerSex passengerAge passengerSurvival>)
```
```
data.frame(`passengerClass` = c("1st", "3rd", "3rd"),
`passengerSurvival` = c("survived", "died", "died"),
`id` = c("258", "1211", "1227"),
`passengerAge` = c("40", "40", "20"),
`passengerSex` = c("female", "male", "male"))
```
Here is the R code version of the contingency table:
```
data-translation(cross-tabulate(get-titanic-dataset, 'passengerSex', 'passengerSurvival'), target => 'R')
```
```
list("male"=list("died"=682, "survived"=161), "female"=list("survived"=339, "died"=127))
```
Here is the WL code version of the contingency table:
```
data-translation(cross-tabulate(get-titanic-dataset, 'passengerSex', 'passengerSurvival'), target => 'WL')
```
```
Association["female"->Association["survived"->339, "died"->127], "male"->Association["survived"->161, "died"->682]]
```
### Nicer datasets
In order to obtain datasets or more regular datasets the function `to-dataset` can be used.
Here a rugged dataset is made regular and converted to an HTML table:
```
my @tbl2 = get-titanic-dataset.pick(6);
@tbl2 = @tbl2.map({ $_.pick((1..5).pick).Hash });
@tbl2 ==> to-dataset(missing-value=>'・') ==> data-translation
```
| passengerClass | passengerAge | passengerSurvival | passengerSex | id |
| --- | --- | --- | --- | --- |
| 3rd | 30 | survived | ・ | 881 |
| 3rd | 10 | survived | female | 1258 |
| 2nd | ・ | ・ | ・ | ・ |
| 3rd | 10 | died | female | 808 |
| ・ | ・ | ・ | male | ・ |
| 1st | 20 | survived | female | ・ |
Here a hash is transformed into dataset with columns `<Key Value>` and then converted into an HTML table:
```
{ 4 => 'a', 5 => 'b', 8 => 'c'} ==> to-dataset() ==> data-translation
```
| Value | Key |
| --- | --- |
| c | 8 |
| b | 5 |
| a | 4 |
---
## Implementation notes
* The "need" for this package became evident while working on the notebooks/articles [AA1, AA2].
* Initially, I translated plain text tables into HTML.
* Using LLMs or `md-interpret` provided by "Markdown::Grammar".
* I considered re-using the code behind `to-pretty-table` provided by "Data::Reshapers", [AAp1].
* This is "too much work" and I wanted a lighter weight package.
* Having a solution for the more general problem ***translating JSON to HTML*** seemed a much better and easier option.
* For example, I hoped that someone has already solved that problem for Raku.
* Since I did not find Raku packages for the translation I wanted, I looked for solutions into the Python ecosystem.
* ... And found ["json2html"](https://github.com/softvar/json2html).
* Using ChatGPT-4.0 I translated the only class of that package from Python into Raku.
* The obtained translation could be executed with relatively minor changes.
* I further refactored and enhanced the HTML translator to fit my most frequent Raku workflows.
* The ingestion of JSON strings is done with the package ["JSON::Fast"](https://raku.land/cpan:TIMOTIMO/JSON::Fast).
* Hence the conversion *to* JSON "comes for free" using `to-json` from that package.
* The initial versions of the package did not have the "umbrella" function `data-translation`.
* Only the "lower level" functions `json-to-html` and `json-to-r` were provided.
* The "lower level" functions, or shortcuts, can be used: `to-html`, `to-r`, `to-wl`.
---
## CLI
The package provides a Command Line Interface (CLI) script. Here is its usage message:
```
data-translation --help
```
```
# Usage:
# data-translation <data> [-t|--target=<Str>] [--encode] [--escape] [--field-names=<Str>] -- Convert data into another format.
#
# <data> Data to convert.
# -t|--target=<Str> Target to convert to, one of <JSON HTML R>. [default: 'HTML']
# --encode Whether to encode or not. [default: False]
# --escape Whether to escape or not. [default: False]
# --field-names=<Str> Field names to use for Map objects, separated with ';'. [default: '']
```
Here is an example application (to [this file](./resources/professionals.json)):
```
data-translation ./resources/professionals.json --field-names='data;id;name;age;profession'
```
| | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| data | | id | name | age | profession | | --- | --- | --- | --- | | 1 | Alice | 25 | Engineer | | 2 | Bob | 30 | Doctor | | 3 | Charlie | 28 | Artist | | 4 | Diana | 32 | Teacher | |
---
## References
### Articles
[AA1] Anton Antonov,
["Workflows with LLM functions"](https://rakuforprediction.wordpress.com/2023/08/01/workflows-with-llm-functions/),
(2023),
[RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com).
[AA2] Anton Antonov,
["TLDR LLM solutions for software manuals"](https://rakuforprediction.wordpress.com/2023/08/15/tldr-llm-solutions-for-software-manuals/),
(2023),
[RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com).
### Packages
[AAp1] Anton Antonov,
[Data::Reshapers Raku package](https://github.com/antononcube/Raku-Data-Reshapers),
(2021-2023),
[GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov,
[Data::TypeSystem Raku package](https://github.com/antononcube/Raku-Data-TypeSystem),
(2023),
[GitHub/antononcube](https://github.com/antononcube).
[AAp3] Anton Antonov,
[LLM::Functions Raku package](https://github.com/antononcube/Raku-LLM-Functions),
(2023),
[GitHub/antononcube](https://github.com/antononcube).
[AAp4] Anton Antonov,
[Text::CodeProcessing Raku package](https://github.com/antononcube/Raku-Text-CodeProcessing),
(2021-2023),
[GitHub/antononcube](https://github.com/antononcube).
[AAp5] Anton Antonov,
[Mathematica::Serializer Raku package](https://github.com/antononcube/Raku-Mathematica-Serializer),
(2021-2022),
[GitHub/antononcube](https://github.com/antononcube).
[BDp1] Brian Duggan,
[Jupyter:Kernel Raku package](https://github.com/bduggan/raku-jupyter-kernel),
(2017-2023),
[GitHub/bduggan](https://github.com/bduggan).
[VMp1] Varun Malhotra,
[json2html Python package](https://github.com/softvar/json2html),
(2013-2021),
[GitHub/softvar](https://github.com/softvar).
|
## dist_zef-jonathanstowe-Kivuli.md
# Kivuli
Get AWS IAM role credentials in EC2
[](https://github.com/jonathanstowe/Kivuli/actions/workflows/main.yml)
## Synopsis
```
# In some application running on EC2
use Kivuli;
use WebService::AWS::S3;
my $k = Kivuli.new(role-name => 'my-iam-role');
my $s3 = WebService::AWS::S3.new(secret-access-key => $k.secret-access-key, access-key-id => $k.access-key-id, security-token => $k.token, region => 'eu-west-2');
# Do something with the S3
```
## Description
This module enables access to AWS IAM role credentials from within an EC2 instance as [described here](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html).
The credentials supplied ( `AWS_ACCES_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`) can be used to authenticate with another AWS service that the role has been granted access to.
Because the credentials are supplied in a way that is private to the EC2 instance this is a more secure method of obtaining the credentials than, for example, putting them in a configuration file.
The `token` **must** be supplied in the headers (or as a query parameter,) for requests to the service, however some services differ as to whether it should or shouldn't be part of the
signed headers in the request - please see the documentation for the service you are implementing for details.
## Installation
Assuming you have a working *rakudo* installation then you should be able to install this with *zef*:
```
zef install Kivuli
```
Bear in mind that this will pass its tests and install outside an EC2 instance, which may be useful for example to build a Docker image to upload to AWS, but it will only work correctly on EC2.
## Support
This has some fairly specific environmental dependencies, so before raising an issue please check:
* You are running your application in an AWS EC2 instance
* That you have created the [IAM Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html), given it the required permissions and associated it your EC2 instance.
Any suggestions/issues/etc can be posted to [github](https://github.com/jonathanstowe/Kivuli/issues) and I'll see what I can do.
# Licence and Copyright
This is free software please see the <LICENCE> in the distribution files.
© Jonathan Stowe 2021
|
## dist_zef-Altai-man-Test-NoTabs.md
# Test::NoTabs
[](https://travis-ci.org/Altai-man/perl6-Test-NoTabs)
This is a port of Test::NoTabs in Perl 6. It checks your Perl 6 files that can contain tabs. If it's so, test will be failed.
# Functions
`notabs-ok` takes path as a string to the file and check it for tabs absence.
`all-perl-files-ok` takes path to the directory and checks all files with extensions: `pl`, `pm`, `pl6`, `pm6`, `p6`.
# Usage example
```
use Test::NoTabs;
# Very simple.
notabs-ok("test-without-tabs");
```
|
## dist_zef-raku-community-modules-Math-Quaternion.md
[](https://github.com/raku-community-modules/Math-Quaternion/actions) [](https://github.com/raku-community-modules/Math-Quaternion/actions) [](https://github.com/raku-community-modules/Math-Quaternion/actions)
# NAME
Math::Quaternion - Hyper-complex numbers as objects with operators
# SYNOPSIS
```
use Math::Quaternion;
```
# DESCRIPTION
This distribution implements an OO class for Quaternions, which are the simplest of the hyper-complex numbers. It adds the operators needed for basic math on the Qs, and should be a good base class for future modules to support the other hyper-complex numbers.
# RECOMMENDATIONS
I intend this module to be a high-quality example of Raku numeric OO, usable as a reference for future module authors.
# WARNINGS
This module is a mostly-from-scratch re-implementation of Quaternions; its API differs from the excellent Perl Math::Quaternion module.
# GLOSSARY
| Wikipedia | Raku | Boost | dwh | RAW |
| --- | --- | --- | --- | --- |
| a | $.r | R\_component\_1 | real | Real\_\_\_\_\_\_\_\_\_\_\_\_ part of a Q (as accessor) |
| b | $.i | R\_component\_2 | imag\_i | First\_ imaginary part of a Q (as accessor) |
| c | $.j | R\_component\_3 | imag\_j | Second imaginary part of a Q (as accessor) |
| d | $.k | R\_component\_4 | imag\_k | Third\_ imaginary part of a Q (as accessor) |
| | .coeffs | | | (r, i, j, k) # List, not arrayref nor vector |
| | .v | | | (i, j, k) # List, not arrayref nor vector |
| | | | | . |
| norm | | abs | abs | sum\_of\_squares( r,i,j,k ).sqrt |
| | | norm | norm | sum\_of\_squares( r,i,j,k ) |
| | | abs(unreal) | abs\_imag | sum\_of\_squares( i,j,k ).sqrt |
| | | norm(unreal) | norm\_imag | sum\_of\_squares( i,j,k ) |
| | | | arg | atan2( sum\_of\_squares( i,j,k ).sqrt, r ); |
| distance | | | | . |
| | | | | . |
| | | unreal | imag | self.( 0.0, i, j, k ); |
| | | | conj | self.( r, -i, -j, -k ); |
| | | | operator \* | self.( r, -i, -j, -k ); |
| | | | signum | absq = sum\_of\_squares( r,i,j,k ).sqrt; return ( absq == 0.0 ) ?? self !! self.new( r/absq, i/absq, j/absq, k/absq ); |
| | | | sqr | self.( r\*r - i\*i - j\*j - k\*k, 2\*r\*i, 2\*r\*j, 2\*r\*k ); |
| | | | inverse | self.new: (r,-i,-j,-k) / sum\_of\_squares( r,i,j,k ) |
| versor | | | | self / sum\_of\_squares( r,i,j,k ).sqrt |
| | | | | . |
| | | | is\_nan | r != r or i != i or j != j or k != k; |
| | | | is\_inf | any(r,i,j,k) == any(PosInf,NegInf) |
| | | | is\_neg\_inf | all(\_,i,j,k) == 0 and r == NEG\_INF; |
| | | | is\_pos\_inf | all(\_,i,j,k) == 0 and r == POS\_INF; |
| | | | is\_real\_inf | all(\_,i,j,k) == 0 and r == any(POS\_INF,NEG\_INF); |
| | is\_real | | is\_real | all(\_,i,j,k) == 0 |
| | is\_zero | | is\_zero | all(r,i,j,k) == 0 |
| | is\_complex | | | all(\_,\_,j,k) == 0 |
| | is\_imaginary | | is\_imaginary | r == 0 |
| | | | | . |
| | | | rotate | When |q| == 1 |
| | | | sqrt | . |
# ACKNOWLEDGEMENTS
Thanks to:
* Jonathan Chin for the original Perl Math::Quaternion module.
* Solomon "colomon" Foster for encouraging this module's release.
* Will "Coke" Coleda for fixes to match changes in Rakudo.
* RosettaCode for the [challenge that provoked the initial code](https://rosettacode.org/wiki/Quaternion_type#Raku).
# SEE ALSO
* <http://en.wikipedia.org/wiki/Quaternion>
* <http://en.wikipedia.org/wiki/Hypercomplex_number>
# AUTHOR
Bruce Gray
# COPYRIGHT AND LICENSE
Copyright 2010 - 2017 Bruce Gray
Copyright 2024 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## phasers.md
Phasers
Combined from primary sources listed below.
# [In Control flow](#___top "go to top of document")[§](#(Control_flow)_Phasers_Phasers "direct link")
See primary documentation
[in context](/language/control#Phasers)
for **Phasers**.
Blocks may have *phasers*: special labeled blocks that break their execution into phases that run in particular phases. See the page [phasers](/language/phasers) for the details.
|
## dist_zef-skaji-Acme-Test-Module-Zef.md
[](https://github.com/skaji/raku-Acme-Test-Module-Zef/actions)
# NAME
Acme::Test::Module::Zef - blah blah blah
# SYNOPSIS
```
use Acme::Test::Module::Zef;
```
# DESCRIPTION
Acme::Test::Module::Zef is ...
# AUTHOR
Shoichi Kaji [skaji@cpan.org](mailto:skaji@cpan.org)
# COPYRIGHT AND LICENSE
Copyright 2021 Shoichi Kaji
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-jonathanstowe-CheckSocket.md
# CheckSocket

A very simple Raku function to test if a TCP socket is listening on a given address or
a UNIX domain socket on the specified path
## Description
This module provides a very simple mechanism to determine whether
something is listening on a TCP socket at the given port and address,
or UNIX domain socket at a specified path. This is primarly for the
convenience of testing where there may be a dependency on an external
network service. For example:
```
use Test;
use CheckSocket;
if not check-socket(80, "localhost") {
skip-all "no web server";
exit;
}
# or
use Test;
use CheckSocket;
# Start some socket server concurrently
if wait-socket(80, "localhost") {
# do some tests
}
else {
skip-all "server didn't start in time";
}
```
## Installation
You can install directly with *zef*:
```
# From the source directory
zef install .
# Remote installation
zef install CheckSocket
```
## Support
Suggestions/patches are welcomed via github at
<https://github.com/jonathanstowe/CheckSocket/issues>
## Licence
Please see the LICENCE file in the distribution
© Jonathan Stowe 2015 - 2021
|
## fff-circumflex-accent.md
fff^
Combined from primary sources listed below.
# [In Operators](#___top "go to top of document")[§](#(Operators)_infix_fff^ "direct link")
See primary documentation
[in context](/language/operators#infix_fff^)
for **infix fff^**.
```raku
sub infix:<fff^>(Mu $a, Mu $b)
```
Like [fff](/routine/fff), except it does not return true for matches to the right argument.
```raku
my @list = <X A B C Y>;
say $_ if /A/ fff /C/ for @list; # OUTPUT: «ABC»
say $_ if /A/ fff^ /C/ for @list; # OUTPUT: «AB»
```
For the non-sed version, see [ff^](/routine/ff$CIRCUMFLEX_ACCENT).
This operator cannot be overloaded, as it's handled specially by the compiler.
|
## dist_zef-lizmat-Hash-Sorted.md
[](https://github.com/lizmat/Hash-Sorted/actions) [](https://github.com/lizmat/Hash-Sorted/actions) [](https://github.com/lizmat/Hash-Sorted/actions)
# NAME
Hash::Sorted - customizable role for sorted Hashes
# SYNOPSIS
```
use Hash::Sorted;
my %m is Hash::Sorted = a => 42, b => 666; # [str,Any]
my %n is Hash::Sorted[int,str] = 42 => "a", 666 => "b";
```
# DESCRIPTION
This module provides the `Hash::Sorted` role, that allows you to create a Hash that always keeps its keys in sorted order. It also allows you to customize exactly how you would like to type your keys and/or your values.
Internally, this implementation works off two arrays that are being kept in sync, so any standard constraints available to arrays, can be applied as types for the keys or values.
Since `Hash::Sorted` is a role, you can also use it as a base for creating your own custom implementations of hashes.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/Hash-Sorted> . 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 2021, 2023, 2024, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-ugexe-Net-HTTP.md
## Net::HTTP
Interfaces and default implementations for rolling your own http client and/or components
## Synopsis
```
use Net::HTTP::GET;
my %header = :Connection<keep-alive>;
my $response = Net::HTTP::GET("http://httpbin.org/ip", :%header);
say $response.content;
use Net::HTTP::POST;
my $body = Buf.new("a=b&c=d&f=".ords);
my $response = Net::HTTP::POST("http://httpbin.org/post", :$body);
say $response.content;
```
## How do I...?
#### Use a proxy
Simply add a proxy method to your client or transport object. For instance, to simply return a url
from a string you could do:
```
my $transport = Net::HTTP::Transport.new;
$transport does role {
method proxy { ::('Net::HTTP::URL').new("http://proxy-lord.org") }
}
```
But you could also implement rotating proxies, proxy from `$*ENV`, etc
## Client Implementations
#### Net::HTTP::GET
```
my $response = Net::HTTP::GET("http://httpbin.org/ip");
```
Simple access to the http `GET` client api.
#### Net::HTTP::POST
```
my $body = Buf.new("a=1&b=2".ords);
my $response = Net::HTTP::POST("http://httpbin.org/post", :$body);
```
Simple access to the http `POST` client api (Still lacking anything beyond basic functionality)
#### Net::HTTP::Transport
```
my $url = Net::HTTP::URL.new($abs-url);
my $req = Net::HTTP::Request.new(:$url, :method<GET>, :User-Agent<raku-net-http>);
my $transport = Net::HTTP::Transport.new;
my $response = $transport.round-trip($req);
```
A high level round-robin implementation that attempts connection caching and is thread safe.
For a user-agent level implementation that handles cookies, redirects, auth, etc then use
a `Net::HTTP::Client`. Can provide an alternative `Response` object as an argument.
```
> use HTTP::SomethingElse::Response;
> my \ALTRESPONSE = HTTP::SomethingElse::Response;
> my $response = $transport.round-trip($req, ALTRESPONSE);
```
#### Net::HTTP::Client
```
# NYI
```
Highest level of http client implementation.
## Interface Default Implementations
Most `Net::HTTP` components can be swapped out for generic alternatives. `Net::HTTP` provides a set of interfaces (see: [Net::HTTP::Interfaces](https://github.com/ugexe/Raku-Net--HTTP/blob/main/lib/Net/HTTP/Interfaces.rakumod) and the other included classes in `Net::HTTP` can be viewed as `default` implementations.
#### Net::HTTP::URL
```
my $url = Net::HTTP::URL.new("http://google.com/");
```
Create a `url` object to provide an api to the url parts, such as *scheme*, *host*, and *port*.
```
> say ~$url
http://google.com/
> say $url.host;
google.com
```
#### Net::HTTP::Request
```
my $url = Net::HTTP::URL.new("http://google.com/");
my $request = Net::HTTP::Request.new(:$url, :method<GET>, header => :Host<google.com>);
```
Create a `Request` object which provides an api to generating an over-the-wire or human readable representation
of an http request. `.raw` gives a binary representation, and `.Str` gives a utf8 encoded version.
```
> my $socket = IO::Socket::INET.new(:host<google.com>, :port(80));
> $socket.write($request.raw)
```
#### Net::HTTP::Response
```
my $response-from-args = Net::HTTP::Response.new(:$status-line, :%header, :$body);
my $response-from-buf = Net::HTTP::Response.new($response-as-buf);
```
Creates a `Response` object that provides an api to parsing an http response. It can be created with named arguments
representing the http message parts, or it can be given a raw `Blob`.
```
> my $data = buf8.new andthen while $socket.recv(:bin) -> d { $data ~= $d }
> my $response = Net::HTTP::Response.new($data)
```
#### Net::HTTP::Dialer
```
my $url = Net::HTTP::URL.new("http://google.com/");
my $request = Net::HTTP::Request.new(:$url, :method<GET>, header => :Host<google.com>);
my $socket = Net::HTTP::Dialer.new.dial($request);
```
A role for providing access to scheme appropriate socket connections.
|
## callframe.md
callframe
Combined from primary sources listed below.
# [In CallFrame](#___top "go to top of document")[§](#(CallFrame)_sub_callframe "direct link")
See primary documentation
[in context](/type/CallFrame#sub_callframe)
for **sub callframe**.
```raku
sub callframe(Int:D $level = 0)
```
Returns a `CallFrame` object for the given level. If no level is given, the default level is 0. Positive levels move up the frame stack and negative levels move down (into the call to `callframe` and deeper).
Returns [`Mu`](/type/Mu) if there is no call information for the given level. Negative levels may result in an exception.
|
## nodispatcher.md
class X::NoDispatcher
Error due to calling a dispatch command in an ineligible scope
```raku
class X::NoDispatcher is Exception { }
```
When a redispatcher like `nextsame` is called without being in the dynamic scope of a call where a redispatch is possible, an X::NoDispatcher is thrown.
For example
```raku
nextsame; # In the mainline
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::NoDispatcher: nextsame is not in the dynamic scope of a dispatcher»
```
# [Methods](#class_X::NoDispatcher "go to top of document")[§](#Methods "direct link")
## [method redispatcher](#class_X::NoDispatcher "go to top of document")[§](#method_redispatcher "direct link")
```raku
method redispatcher(--> Str:D)
```
Returns the name of the redispatcher function that did not succeed.
|
## dist_zef-lizmat-P5each.md
[](https://github.com/lizmat/P5each/actions)
# NAME
Raku port of Perl's each() built-in
# SYNOPSIS
```
use P5each;
```
# DESCRIPTION
This module tries to mimic the behaviour of the Perl's `each` built-in as closely as possible in the Raku Programming Language.
# ORIGINAL PERL 5 DOCUMENTATION
```
each HASH
each ARRAY
each EXPR
When called on a hash in list context, returns a 2-element list
consisting of the key and value for the next element of a hash. In
Perl 5.12 and later only, it will also return the index and value
for the next element of an array so that you can iterate over it;
older Perls consider this a syntax error. When called in scalar
context, returns only the key (not the value) in a hash, or the
index in an array.
Hash entries are returned in an apparently random order. The
actual random order is specific to a given hash; the exact same
series of operations on two hashes may result in a different order
for each hash. Any insertion into the hash may change the order,
as will any deletion, with the exception that the most recent key
returned by "each" or "keys" may be deleted without changing the
order. So long as a given hash is unmodified you may rely on
"keys", "values" and "each" to repeatedly return the same order as
each other. See "Algorithmic Complexity Attacks" in perlsec for
details on why hash order is randomized. Aside from the guarantees
provided here the exact details of Perl's hash algorithm and the
hash traversal order are subject to change in any release of Perl.
After "each" has returned all entries from the hash or array, the
next call to "each" returns the empty list in list context and
"undef" in scalar context; the next call following that one
restarts iteration. Each hash or array has its own internal
iterator, accessed by "each", "keys", and "values". The iterator
is implicitly reset when "each" has reached the end as just
described; it can be explicitly reset by calling "keys" or
"values" on the hash or array. If you add or delete a hash's
elements while iterating over it, the effect on the iterator is
unspecified; for example, entries may be skipped or duplicated--so
don't do that. Exception: It is always safe to delete the item
most recently returned by "each()", so the following code works
properly:
while (($key, $value) = each %hash) {
print $key, "\n";
delete $hash{$key}; # This is safe
}
This prints out your environment like the printenv(1) program, but
in a different order:
while (($key,$value) = each %ENV) {
print "$key=$value\n";
}
Starting with Perl 5.14, "each" can take a scalar EXPR, which must
hold reference to an unblessed hash or array. The argument will be
dereferenced automatically. This aspect of "each" is considered
highly experimental. The exact behaviour may change in a future
version of Perl.
while (($key,$value) = each $hashref) { ... }
As of Perl 5.18 you can use a bare "each" in a "while" loop, which
will set $_ on every iteration.
while(each %ENV) {
print "$_=$ENV{$_}\n";
}
To avoid confusing would-be users of your code who are running
earlier versions of Perl with mysterious syntax errors, put this
sort of thing at the top of your file to signal that your code
will work only on Perls of a recent vintage:
use 5.012; # so keys/values/each work on arrays
use 5.014; # so keys/values/each work on scalars (experimental)
use 5.018; # so each assigns to $_ in a lone while test
See also "keys", "values", and "sort".
```
# PORTING CAVEATS
Using list assignments in `while` loops will not work, because the assignment will happen anyway even if an empty list is returned, so that this:
```
while (($key, $value) = each %hash) { }
```
will loop forever. There is unfortunately no way to fix this in Raku module space at the moment. But a slightly different syntax, will work as expected:
```
while each(%hash) -> ($key,$value) { }
```
Also, this will alias the values in the list, so you don't actually need to define `$key` and `$value` outside of the `while` loop to make this work.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/P5each> . 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_cpan-LEMBARK-ProcStats.md
# NAME
ProcStats - dump rusage process statistics with optional label.
# SYNOPSIS
```
# display process stats provided by
# getrusage(2) & now() to stderr ($*ERR).
#
# Initial stats show all values as-is with an
# added "initial" and $*INIT-INSTANT.
#
# Successive calls print progressive stats
# for non-zero incremental differences with
# leading '+' to indicate differences.
#
# Final includes all values with totals from
# initial values and include a "Final" key
# with value of elapsed time from the program
# startup to the final sample.
#
# outputs are YAML array-of-hashes, with one
# document per print.
#
# see example/bare-for-loop
#!/usr/bin/env perl6
use v6.d;
use ProcStats; # or ( :Print ) for print-stats.
print-stats :label( $*PROGRAM );
print-stats
for 1 .. 3;
print-stats( final => True );
# output #0 has all parameters without any differences
# (there is no prior sample to diff).
# successive stats w/o prior will show only outputs with
# differenes in stats other than user and wallclock time
# using a leading '+' for the offset values.
#
# if 'final' is used then all stats are output, even if
# they are zero, and Final => True is added to the output.
# (:final defaults to :first, :force).
#
# label is output if provided (e.g., :label($*PROGRAM) );
---
label : ./bare-for-loop
output : 0
sample : 0
initial : 1563047524.012407 # $*INIT-INSTANT
wtime : 1563047524.627299 # now()
utime : 0.269591
stime : 0.038513
maxrss : 105852
minflt : 20822
majflt : 0
inblock : 0
oublock : 8
---
output : 1
sample : 1
maxrss : +760 # only stats with differnces
minflt : +173 # are listed.
utime : +0.018007 # utime and wtime will always grow,
wtime : +0.008687 # returned with :force or other diff's.
---
<snip...>
---
output : 4 # 4 == 4 => all samples were output
sample : 4
inblock : +0 # +0 => no change during execution
majflt : +0
maxrss : +1024 # >0 => growth compared to sample0
minflt : +247
oublock : +0
stime : +0.000745 # system time during samples.
utime : +0.038095 # user time during samples.
wtime : +0.019526 # elapsed wallclock from sample0
final : +0.804102 # elapsed wallclock from program init.
# Output is only provided if there are differences in
# the compared fields. If any of those are different
# then the wallclock, user, and system times are added
# the entire difference returned.
#
# :force & :first can be used with intermediate
# outputs to generate output for all fields or compute
# differenes with first sample.
#
# :final(True) defaults :force and :first to true.
print-stats :force; # ouput zeros.
print-stats :first; # compare to sample0.
print-stats :first :force; # all stats compared to sample0.
# see example/rand-user-table
print-stats label => "$*PROGRAM";
for 1 .. 100
{
(
&user-add => 0.10,
&user-drop => 0.10,
&user-op => 0.80,
).Mix.roll( 1_000 )».()
;
print-stats label => 'Keys: ' ~ %user-data.elems;
}
print-stats :final, label => 'Keys: ' ~ %user-data.elems;
# output
---
label : exmaple/rand-user-table
output : 0 # first sample:
sample : 0 # output = sample = 0.
wtime : 1563048388.1687117
utime : 0.579475
stime : 0
maxrss : 116448
minflt : 23573
majflt : 0
inblock : 0
oublock : 8
---
label : Keys: 19
output : 1
sample : 1
maxrss : +3884
minflt : +901
utime : +0.100587
wtime : +0.052823
---
<snip...>
---
label : Keys: 60
output : 14 # 1 .. 14 output have 1 .. 14
sample : 14 # samples: something changed each time.
maxrss : +264
minflt : +24
utime : +0.029787 # utime & wtime are alwyas output if
wtime : +0.020622 # there are other differences.
---
label : Keys: 117
output : 15 # 15th output has 18th sample:
sample : 18 # samples 15 .. 17 were unchanged.
minflt : +27 # minflt increased 27 in sample 18.
utime : +0.027277
wtime : +0.022936
---
<snip...>
---
label : Keys: 129
output : 61 # 39 samples had no differences
sample : 100
minflt : +10 # minflt increased by 10.
utime : +0.024304
wtime : +0.024276
---
label : Keys: 129
output : 62 # 62 changes.
sample : 101 # in 101 samples.
inblock : +0 # +0 values never changed.
majflt : +0
maxrss : +9424
minflt : +2323
oublock : +0
stime : +0
utime : +2.361321
wtime : +2.202044 # elapsed wallclock from first call.
final : +0.804102 # sec from initial -> final wtime.
```
# DESCRIPTION
This module exports print-stats (via DEFAULT or :Print) or extract-stats & diff-stats (via :Extract). Together these give a simple interface for accessing process statistics via getrusage(2) on systems which support it.
## Subroutines
### Exported by default or with :Print.
* print-stats
Formats the result of calling diff-stats on extract-stats, passing through :force & :final.
### Exported with :Extract.
* extract-stats
Calls getrusage(2), removes the parameters not supported by Linux (see Procstats::IGNORE). getrusage returns user and system times as separate int's for seconds and microseconds. These are removed from the initial input, combined into a rational, and rounded to microseconds as "stime" & "utime". Additionally now() is rounded to microseconds and returned as "wtime".
* diff-stats
If :force is used then all non-ignored values are compared; if :first is used then differnces are compared with the initial sample not the prior one.
Note that :force & :first have no effect on the initial sample.
Normally compared incrmental keys are:
```
stime
maxrss
minflt majflt
inblock oublock
```
If at least one of these does not provide non-zero differences then nothing is printed. Using ":force" will cause diff-stats to always generate a list of differences and will always yield
## Notes
* Sample & Output
Comparing sample & output counts allows verifying average rate at which parameters change: output only increments when something changes, %sample increments with every call to extract-stats.
* Wallclock Time (wtime)
This is derived from Perl's now() result (rounded to microseconds). Combined with the program name ($\*PROGRAM), this makes a reasonable candiate key for tracking execution history over mulitple tests.
## Sample code.
* rand-user-table
This performs a set of random operations on a hash by adding keys, dropping keys, and incrementing the stored values.
It prints the stats every 1000 iterations of the trial:
```
for 1 .. 1000
{
constant weighted_operations =
(
&user-add => 0.10,
&user-drop => 0.10,
&user-op => 0.80,
).Mix;
weighted_operations.roll( 1_000 )».();
print-stats label => 'Keys: ' ~ %user-data.elems;
}
```
The output illustrates adding progress information to the labels, and will [usually] show examples of the output count being lower than the sample count due to the compared statistics not changing.
Also note here that the final sample shows wallclock time less than user time: MOAR is threaded! Use wtime for elapsed:
stime will grow due to output from print-stats and overhead from calling getrusage(2). Where stime is very small it is probably due to overhead from ProcStats.
```
---
label : Keys: 13
```
* Final : True output : 53 sample : 101 inblock : +0 majflt : +0 maxrss : +5768 minflt : +1467 oublock : +0 stime : +0.018914 utime : +2.24491 # 2.24 > 2.12 due to threading! wtime : +2.123665
# NOTES
* Linux-specific
This could easily be split into extract-stats with O/S-specific extractors and a top module with diff-stats and print-stats. If anyone has access to BSD, Windows, VMS, or OSX systems with Perl6 feel free to send me the information on how to extract the stats and I'll break this up into platform-specific extractors and the rest.
# SEE ALSO
* getrusage(2) getrusage(3p)
getrusage is POSIX (3p).
Thing is that Linux does not maintain values for all of the contents (see getrusage(2) for descriptions).
```
struct rusage
{
struct timeval ru_utime; /* user CPU time used */
struct timeval ru_stime; /* system CPU time used */
long ru_maxrss; /* maximum resident set size */
* long ru_ixrss; /* integral shared memory size */
* long ru_idrss; /* integral unshared data size */
* long ru_isrss; /* integral unshared stack size */
long ru_minflt; /* page reclaims (soft page faults) */
long ru_majflt; /* page faults (hard page faults) */
* long ru_nswap; /* swaps */
long ru_inblock; /* block input operations */
long ru_oublock; /* block output operations */
* long ru_msgsnd; /* IPC messages sent */
* long ru_msgrcv; /* IPC messages received */
* long ru_nsignals; /* signals received */
long ru_nvcsw; /* voluntary context switches */
long ru_nivcsw; /* involuntary context switches */
};
```
* timeval (3bsd)
Struct timeval is a pair of ints for seconds + microseconds which are dealt with by dividing the microseconcs and adding to get utime and stime in the reported stats.
|
## dist_github-alabamenhu-IntlPromptYesNo.md
> *Το «ναι» και το «όχι», αν και είναι οι πιο σύντομες από όλες τις λέξεις, χρειάζεται να τις σκεφθεί κανείς πολύ προηγουμένως.*
> — Πυθαγόρας
# Intl::Prompt::YesNo
A module to ask a user for a yes/no response in a localized command line interface.
To use:
```
use Intl::Prompt::YesNo
my $answer = prompt-yes-no 'Queres falar em português?', :language<pt>;
# Queres falar em português? [s/n]
if $answer {
# they answered yes
} else {
# they answered no
}
```
If the user responds in an affirmative manner, the sub `prompt-yes-no` will return `True`.
If they respond in a negative manner, it returns `False`.
The sub accepts a single positional argument, which is the message to display alongside the prompt.
It would be best to obtain such a string through a module like `Fluent`.
There are two named arguments available:
* **`:language`**
The language should be a BCP-47 compliant language tag. It defaults to whatever `Intl::UserLanguage`'s `user-language` returns, so you don't know necessarily need to specify it.
* **`:long`**
Many languages have multiple strings that are acceptable for the two responses.
By default, the shortest ones are used (`y/n` in English, `s/n` for Portuguese).
If you use `:long`, the longer ones are used (`yes/no`, or `sim/não` for Portuguese).
In either case, all variants are accepted.
## Version history
* **v0.1**
* Initial release
## License and Copyright
© 2020 Matthew Stephen Stuckwisch. Licensed under the Artistic License 2.0.
But as this is very simple, feel free to hack this code up and integrate it in your own code without need for attribution.
|
## dist_zef-raku-community-modules-ake.md
## ake [Tests on source](https://github.com/Raku/ake/actions/workflows/test.yaml)
`ake` is a make-a-like implemented in Raku. It was inspired by
[rake](https://github.com/ruby/rake).
### Installation
Ake is easily installable with [`zef`](https://github.com/ugexe/zef):
```
zef install ake
```
If you are using `rakubrew` in `shim` mode you will need to run
`rakubrew rehash` to make the `ake` executable available.
### Current status
Ake is fully-functional but may lack some advanced features. Feature
requests and PRs are welcome!
### Example
Create a file named `Akefile` with these contents:
```
task 'buy-food', {
say 'Bought a salad.'
}
task 'shower', {
say 'Showered.'
}
task 'morning' => <shower buy-food>;
task 'dinner' => <buy-food>, {
say 'Yummy!'
}
```
Then you will be able to run `ake` from the same directory
(e.g. `ake morning`).
### License
Ake is available under Artistic License 2.0.
|
## paragraph.md
class RakuAST::Doc::Paragraph
Contains the information about a RakuDoc paragraph
```raku
class RakuAST::Doc::Paragraph { }
```
The `RakuAST::Doc::Paragraph` class contains the information about a logical paragraph in a `RakuDoc` block.
Support for [`RakuAST`](/type/RakuAST) functionality is available in language version `6.e+` and was added in Rakudo compiler release 2023.02. In earlier language versions it is only available when specifying:
```raku
use experimental :rakuast;
```
## [Object introspection](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#Object_introspection "direct link")
`RakuAST::Doc::Paragraph` objects are typically created when parsing Raku Programming Language code that has `RakuDoc` markers in it. So most developers will only need to know how to introspect the objects created.
### [method atoms](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_atoms "direct link")
```raku
.put for $paragraphs.atoms;
# Text before B<and> after markup
```
Returns the atoms of the paragraph. These are generally a mix of strings and [`RakuAST::Doc::Markup`](/type/RakuAST/Doc/Markup) objects.
### [method Str](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_Str "direct link")
```raku
put $paragraph; # Text before B<and> after markup
```
Returns the string for the paragraph, with any markup stringified.
### [method raku](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_raku "direct link")
```raku
# method .gist falls back to .raku
say $block; # RakuAST::Doc::Paragraph.new(...
```
Returns the string that is needed for the creation of the paragraph using [`RakuAST`](/type/RakuAST) calls.
# [Object creation](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#Object_creation "direct link")
One seldom creates `RakuAST::Doc::Paragraph` objects directly. This documentation is intended for those few people who'd like to devise their own way of programmatically building a `RakuAST::Doc::Paragraph` object.
## [method new](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_new "direct link")
```raku
method new(*@atoms)
```
The `new` method must be called to create a new `RakuAST::Doc::Paragraph` object. It takes any number of positional arguments as the atoms of the logical paragraph, where an atom is either a string or a [`RakuAST::Doc::Markup`](/type/RakuAST/Doc/Markup) object.
Typically a `RakuAST::Doc::Paragraph` object is only created if a logical paragraph has at least one markup object.
```raku
my $paragraph = RakuAST::Doc::Paragraph.new(
"Text before ",
RakuAST::Doc::Markup.new(:letter<B>, :atoms("and")),
" after markup\n"
);
```
# [Object modification](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#Object_modification "direct link")
## [method add-atom](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_add-atom "direct link")
```raku
$paragraph.add-atom("baz\n");
```
Add an atom: should be a string, or a [`RakuAST::Doc::Markup`](/type/RakuAST/Doc/Markup) object.
|
## dist_github-moznion-Stream-Buffered.md
[](https://travis-ci.org/moznion/p6-Stream-Buffered)
# NAME
Stream::Buffered - Temporary buffer to save bytes
# SYNOPSIS
```
use Stream::Buffered;
my $buf = Stream::Buffered.new($length);
$buf.print("foo");
my Int $size = $buf.size;
my IO::Handle $io = $buf.rewind;
```
# DESCRIPTION
Stream::Buffered is a buffer class to store arbitrary length of byte strings and then get a seekable IO::Handle once everything is buffered. It uses Blob and temporary file to save the buffer depending on the length of the size.
This library is a perl6 port of [perl5's Stream::Buffered](https://metacpan.org/pod/Stream::Buffered).
# METHODS
## `new(Int $length, Int $maxMemoryBufferSize = 1024 * 1024) returns Stream::Buffered`
Creates instance.
When you specify negative value as `$maxMemoryBufferSize`, Stream::Buffered always uses Blob as buffer. Or when you specify 0 as `$maxMemoryBufferSize`, Stream::Buffered always uses temporary file as buffer.
If you pass 0 to the first argument, Stream::Buffered decides what kind of buffer type (Blob or temp file) to use automatically.
## `print(Stream::Buffered:D: *@text) returns Bool`
Append text to buffer.
## `size(Stream::Buffered:D:) returns Int`
Return the size of buffer.
## `rewind(Stream::Buffered:D:) returns IO::Handle`
Seek to the head of buffer and return buffer.
# SEE ALSO
* [perl5's Stream::Buffered](https://metacpan.org/pod/Stream::Buffered)
# AUTHOR
moznion [moznion@gmail.com](mailto:moznion@gmail.com)
# COPYRIGHT AND LICENSE
```
Copyright 2015 moznion
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
```
And original perl5's Stream::Buffered is
```
The following copyright notice applies to all the files provided in
this distribution, including binary files, unless explicitly noted
otherwise.
Copyright 2009-2011 Tatsuhiko Miyagawa
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
```
|
## modules-extra.md
Module development utilities
What can help you write/test/improve your module(s)
Here is a list of modules that you can find in the Raku ecosystem which aim to make the experience of developing Raku modules more fun.
# [Module builder and authoring tools](#Module_development_utilities "go to top of document")[§](#Module_builder_and_authoring_tools "direct link")
Some modules and tools to help you with generating files that are part of a module distribution.
* [App::Mi6](https://raku.land/zef:skaji/App::Mi6) Minimal authoring tool for Raku
* [META6](https://raku.land/zef:jonathanstowe/META6) Do things with Raku `META` files
* [rakudoc](https://raku.land/cpan:SOFTMOTH/rakudoc) Generate documentation end-products
# [Tests](#Module_development_utilities "go to top of document")[§](#Tests "direct link")
Some tests of module quality.
* [Test::META](https://raku.land/zef:jonathanstowe/Test::META) Test your META6.json file
* [Test::Output](https://raku.land/zef:raku-community-modules/Test::Output) Test the output to STDOUT and STDERR your program generates
* [Test::Screen](https://raku.land/github:skids/Proc::Screen) Use **GNU screen** to test full screen VT applications
* [Test::When](https://raku.land/zef:raku-community-modules/Test::When) Control when your tests are run (author testing, online testing, etc.)
# [NativeCall](#Module_development_utilities "go to top of document")[§](#NativeCall "direct link")
Here some modules to help you work with NativeCall.
* [NativeHelpers::Array](https://raku.land/zef:jonathanstowe/NativeHelpers::Array) Provides routines to deal with CArray
* [App::GPTrixie](https://raku.land/github:Skarsnik/App::GPTrixie) Generate NativeCall code from C headers file
* [NativeCall::TypeDiag](https://raku.land/github:Skarsnik/NativeCall::TypeDiag) Provides routines to test your CStruct
# [Sample modules](#Module_development_utilities "go to top of document")[§](#Sample_modules "direct link")
Modules that exist only as minimalist examples, tests for installers, or skeletons.
* [Foo](https://raku.land/github:ugexe/Foo) A module with two distributions of different versions
|
## dist_zef-raku-community-modules-WWW-DuckDuckGo.md
[](https://github.com/raku-community-modules/WWW-DuckDuckGo/actions) [](https://github.com/raku-community-modules/WWW-DuckDuckGo/actions)
# NAME
WWW::DuckDuckGo - Bindings to DuckDuckGo search API
# SYNOPSIS
```
use WWW::DuckDuckGo;
my $duck = WWW::DuckDuckGo.new;
my $zeroclickinfo1 = $duck.zci('duck duck go');
my $zeroclickinfo2 = $duck.zci('one', 'another');
```
# DESCRIPTION
This class provides a way to get data from DuckDuckGo search service. The basic idea is to create a class instance that represents JSON answer from the server for every query.
This is a functional port of the Perl module of the same name, see [`WWW::DuckDuckGo`](https://metacpan.org/pod/WWW::DuckDuckGo).
# AUTHOR
Alexander Kiryuhin
# COPYRIGHT AND LICENSE
Copyright 2016 - 2021 Alexander Kiryuhin
Copyright 2024 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-moznion-Backtrace-AsHTML.md
[](https://travis-ci.org/moznion/p6-Backtrace-AsHTML)
# NAME
Backtrace::AsHTML - Displays back trace in HTML
# SYNOPSIS
```
use Backtrace::AsHTML;
my $trace = Backtrace.new;
my $html = $trace.as-html;
```
# DESCRIPTION
Backtrace::AsHTML adds `as-html` method to <Backtrace> which displays the back trace in beautiful HTML, with code snippet context.

This library is inspired by [Devel::StackTrace::AsHTML of perl5](https://metacpan.org/release/Devel-StackTrace-AsHTML) and much of code is taken from that.
# METHODS
* `as-html`
`as-html` shows the fully back trace in HTML.
This method will be added into <Backtrace> class automatically when used this.
# TODO
* show lexical variables for each frames (How?)
* show arguments for each frames? (How??)
# AUTHOR
moznion [moznion@gmail.com](mailto:moznion@gmail.com)
# COPYRIGHT AND LICENSE
```
Copyright 2015 moznion
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
```
And license of the original perl5's Devel::StackTrace::AsHTML is
```
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
```
|
## dist_zef-kuerbis-Term-Choose-Util.md
# NAME
Term::Choose::Util - TUI-related functions for selecting directories, files, numbers and subsets of lists.
# DESCRIPTION
This module provides TUI-related functions for selecting directories, files, numbers and subsets of lists.
# CONSTRUCTOR
The constructor method `new` can be called with optional named arguments:
```
my $new = Term::Choose::Util.new( :mouse( 1 ), ... )
```
# ROUTINES
Values in brackets are default values.
### Options available for all subroutines
* back
Customize the string of the menu entry "back".
Default: `BACK`
* clear-screen
If enabled, the screen is cleared before the output.
Values: [0],1.
* color
Enables the support for color and text formatting escape sequences.
Setting color to 1 enables the support for color and text formatting escape sequences except for the current selected element. If set to 2, also for the current selected element the color support is enabled (inverted colors).
Values: [0],1,2.
* confirm
Customize the string of the menu entry "confirm".
Default: `CONFIRM`.
* cs-label
The value of *cs-label* (current selection label) is a string which is placed in front of the current selection.
Defaults: `choose-directories`: 'Chosen Dirs: ', `choose-a-directory`: 'Directory: ', `choose-a-file`: 'File: '. For `choose-a-number`, `choose-a-subset` and `settings-menu` the default is undefined.
The current-selection output is placed between the info string and the prompt string.
* hide-cursor
Hide the cursor
Values: 0,[1].
* info
A string placed on top of of the output.
Default: undef
* margin
The option *margin* allows one to set a margin on all four sides.
*margin* expects a reference to an array with four elements in the following order:
* top margin (number of terminal lines)
* right margin (number of terminal columns)
* botton margin (number of terminal lines)
* left margin (number of terminal columns)
*margin* does not affect the *info* string. To add margins to the *info* string see *tabs-info*.
*margin* changes the default values of *tabs-prompt*.
Allowed values: 0 or greater. Elements beyond the fourth are ignored.
Default: undef
* mouse
Enable the mouse mode. An item can be chosen with the left mouse key, the right mouse key can be used instead of the SpaceBar key.
Values: [0],1.
* prompt
A string placed on top of the available choices.
If the *prompt* is set to the empty string, no prompt line is displayed.
Default: 'Your choice: '
* save-screen
0 - off (default)
1 - use the alternate screen
* tabs-info
The option *tabs-info* allows one to insert spaces at the beginning and the end of *info* lines.
*tabs-info* expects a reference to an array with one to three elements:
* the first element (initial tab) sets the number of spaces inserted at beginning of paragraphs
* the second element (subsequent tab) sets the number of spaces inserted at the beginning of all broken lines apart from the beginning of paragraphs
* the third element sets the number of spaces used as a right margin.
Allowed values: 0 or greater. Elements beyond the third are ignored.
default: If *margin* is set, the initial-tab and the subsequent-tab are set to left-*margin* and the right margin is set to right-*margin*. If *margin* is not defined, the default is undefined.
* tabs-prompt
The option *tabs-prompt* allows one to insert spaces at the beginning and the end of the current-selection and *prompt* lines.
*tabs-prompt* expects a reference to an array with one to three elements:
* the first element (initial tab) sets the number of spaces inserted at beginning of paragraphs
* the second element (subsequent tab) sets the number of spaces inserted at the beginning of all broken lines apart from the beginning of paragraphs
* the third element sets the number of spaces used as a right margin.
Allowed values: 0 or greater. Elements beyond the third are ignored.
default: If *margin* is set, the initial-tab and the subsequent-tab are set to left-*margin* and the right margin is set to right-*margin*. `choose-directories` and `choose-a-subset`: +2 for the subsequent-tab. Else the default is undefined.
## choose-a-directory
```
my $chosen-directory = choose-a-directory( :1layout, ... )
```
With `choose-a-directory` the user can browse through the directory tree and choose a directory which is returned.
To move around in the directory tree:
* select a directory and press `Return` to enter in the selected directory.
* choose the "parent-dir" menu entry to move upwards.
To return the current working-directory as the chosen directory choose the "confirm" menu entry.
The "back" menu entry causes `choose-a-directory` to return nothing.
Following options can be set:
* alignment
Elements in columns are aligned to the left if set to 0, aligned to the right if set to 1 and centered if set to 2.
Values: [0],1,2.
* init-dir
Set the starting point directory. Defaults to the home directory (`$*HOME`).
* layout
See the option *layout* in [Term::Choose](https://github.com/kuerbis/Term-Choose-p6)
Values: 0,[1],2.
* order
If set to 1, the items are ordered vertically else they are ordered horizontally.
This option has no meaning if *layout* is set to 2.
Values: 0,[1].
* parent-dir
Customize the string of the menu entry "parent-dir".
Default: `..`
* show-hidden
If enabled, hidden directories are added to the available directories.
Values: 0,[1].
* [Options available for all subroutines](#Options available for all subroutines)
## choose-a-file
```
my $chosen-file = choose-a-file( :1layout, ... )
```
Choose the file directory and then choose a file from the chosen directory. To return the chosen file select the "*confirm*" menu entry.
Options as in [choose-a-directory](#choose-a-directory) plus
* filter
If set, the value of this option is treated as a regex pattern.
Only files matching this pattern will be displayed.
The regex pattern is used as the value of `dir`s `:test` parameter.
* prompt2
While *prompt* is used in the directory menu, *prompt2* is the prompt in the menu where you select the file.
If *prompt2* is set to the empty string, no prompt line is displayed.
Default: value of *prompt*
## choose-directories
```
my @chosen-directories = choose-directories( :1layout, ... )
```
`choose-directories` is similar to `choose-a-directory` but it is possible to return multiple directories.
Options as in [choose-a-directory](#choose-a-directory) plus
* prompt2
While *prompt* is used in the "Change Location" menu, *prompt2* is the prompt in the menu where you select the directories.
If *prompt2* is set to the empty string, no prompt line is displayed.
Default: value of *prompt*
## choose-a-number
```
my $number = choose-a-number( 5, :cs-label<Testnumber>, ... );
```
This function lets you choose/compose a number (unsigned integer) which is then returned.
The fist argument is an integer and determines the range of the available numbers. For example setting the first argument to `4` would offer a range from `0` to `9999`. If not set, it defaults to `7`.
Options:
* default-number
Set a default number (unsigned integer in the range of the available numbers).
Default: undef
* small-first
Put the small number ranges on top.
* thousands-separator
Sets the thousands separator.
Default: `,`
* [Options available for all subroutines](#Options available for all subroutines)
## choose-a-subset
```
my $subset = choose-a-subset( @available-items, :1layout, ... )
```
`choose-a-subset` lets you choose a subset from a list.
The subset is returned as an array.
The first argument is the list of choices.
Options:
* all-by-default
If enabled, all elements are selected if `CONFIRM` is chosen without any selected elements.
* alignment
Elements in columns are aligned to the left if set to 0, aligned to the right if set to 1 and centered if set to 2.
Values: [0],1,2.
* index
If true, the index positions in the available list of the made choices are returned.
Values: [0],1.
* keep-chosen
If enabled, the chosen items are not removed from the available choices.
Values: [0],1;
* layout
See the option *layout* in Term::Choose.
Values: 0,1,2,[3].
* mark
Expects as its value a reference to an array with indexes. Elements corresponding to these indexes are pre-selected when `choose-a-subset` is called.
* order
If set to 1, the items are ordered vertically else they are ordered horizontally.
This option has no meaning if *layout* is set to 3.
Values: 0,[1].
* prefix
*prefix* expects as its value a string. This string is put in front of the elements of the available list in the menu. The chosen elements are returned without this *prefix*.
Default: empty string.
* cs-begin
Info output: the *cs-begin* string is placed between the *cs-label* string and the chosen elements as soon as an element has been chosen.
Default: empty string
* cs-separator
Info output: *cs-separator* is placed between the chosen list elements.
Default: `,`
* cs-end
Info output: as soon as elements have been chosen the *cs-end* string is placed at the end of the chosen elements.
Default: empty string
* [Options available for all subroutines](#Options available for all subroutines)
To return the chosen subset select the "confirm" menu entry.
The "back" menu entry removes the last added chosen items. If the list of chosen items is empty, "back" causes `choose-a-subset` to return nothing.
## settings-menu
```
my @menu = (
( 'enable-logging', "- Enable logging", ( 'NO', 'YES' ) ),
( 'case-sensitive', "- Case sensitive", ( 'NO', 'YES' ) ),
( 'attempts', "- Attempts" , ( '1', '2', '3' ) )
);
my %config = (
'enable-logging' => 0,
'case-sensitive' => 1,
'attempts' => 2
);
settings-menu( @menu, %config, :1mouse, ... );
```
The first argument is a list of lists. Each of the lists has three elements:
* The option name
* The prompt string
* A list of the available values for the option
The second argument is a hash:
* The hash keys are the option names
* The values are the indexes of the current value of the respective key/option. If an index is undefined or out of bonds, it is set to 0.
This hash is edited in place; the changes made by the user are saved in this hash.
Options:
* cs-begin
Info output: the *cs-begin* string is placed between the *cs-label* string and the key-value pairs.
Default: empty string
* cs-separator
Info output: *cs-separator* is placed between the key-value pairs.
Default: `,`
* cs-end
Info output: the *cs-end* string is placed at the end of the key-value pairs.
Default: empty string
* [Options available for all subroutines](#Options available for all subroutines)
The info output line is only shown if the option *cs-label* is set to a defined value.
When `settings-menu` is called, it displays for each list entry a row with the prompt string and the current value.
It is possible to scroll through the rows. If a row is selected, the set and displayed value changes to the next.After scrolling through the list once the cursor jumps back to the top row.
If the "back" menu entry is chosen, `settings-menu` does not apply the made changes and returns nothing. If the "confirm" menu entry is chosen, `settings-menu` applies the made changes in place to the passed configuration hash (second argument) and returns the number of made changes.
# REQUIREMENTS
Same requirements as Term::Choose.
# AUTHOR
Matthäus Kiem [cuer2s@gmail.com](mailto:cuer2s@gmail.com)
# CREDITS
Thanks to the people from [Perl-Community.de](http://www.perl-community.de), from [stackoverflow](http://stackoverflow.com) and from #perl6 on irc.freenode.net for the help.
# LICENSE AND COPYRIGHT
Copyright 2016-2024 Matthäus Kiem.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-raku-community-modules-Test-Scheduler.md
[](https://github.com/raku-community-modules/Test-Scheduler/actions) [](https://github.com/raku-community-modules/Test-Scheduler/actions) [](https://github.com/raku-community-modules/Test-Scheduler/actions)
# NAME
Test::Scheduler - A Raku scheduler with virtualized time
# SYNOPSIS
```
use Test;
use Test::Scheduler;
sub timeout($source, $timeout) {
supply {
whenever $source -> $value {
state $values++;
emit $value;
my $last-values = $values;
whenever Promise.in($timeout) {
if $last-values == $values {
die "Timed out";
}
}
}
}
}
{
my $*SCHEDULER = Test::Scheduler.new;
my $test-source = supply {
for 1, 2, 5 {
whenever Promise.in($_) {
emit 'badger';
}
}
}
my $timed-out = timeout($test-source, 2);
my @received;
my $died = False;
$timed-out.tap:
{ @received.push($_) },
quit => { $died = True }
is @received, [], 'No values yet';
$*SCHEDULER.advance-by(1);
is @received, ['badger'], 'one value after 1s';
nok $died, 'No timeout yet';
$*SCHEDULER.advance-by(1);
is @received, ['badger', 'badger'], 'Two value after 2s';
nok $died, 'No timeout yet';
$*SCHEDULER.advance-by(1);
is @received, ['badger', 'badger'], 'Still two value after 3s';
nok $died, 'Still not timed out yet';
$*SCHEDULER.advance-by(1);
is @received, ['badger', 'badger'], 'Still two value after 4s';
ok $died, 'And have timed out';
}
done-testing;
```
# DESCRIPTION
An implementation of the Raku `Scheduler` role that uses virtualized time. This allows for testing of code depending on constructs like `Promise.in(...)` and `Supply.interval(...)` more quickly and reliably than would be possible if real time were used.
# AUTHOR
Jonathan Worthington
# COPYRIGHT AND LICENSE
Copyright 2016 - 2024 Jonathan Worthington
Copyright 2024 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## trans.md
trans
Combined from primary sources listed below.
# [In Str](#___top "go to top of document")[§](#(Str)_method_trans "direct link")
See primary documentation
[in context](/type/Str#method_trans)
for **method trans**.
```raku
multi method trans(Str:D: Pair:D \what, *%n --> Str)
multi method trans(Str:D: *@changes, :complement(:$c), :squash(:$s), :delete(:$d) --> Str)
```
Replaces one or many characters with one or many characters. Ranges are supported, both for keys and values. Regexes work as keys. In case a list of keys and values is used, substrings can be replaced as well. When called with `:complement` anything but the matched value or range is replaced with a single value; with `:delete` the matched characters without corresponding replacement are removed. Combining `:complement` and `:delete` will remove anything but the matched values, *unless replacement characters have been specified*, in which case, `:delete` would be ignored. The adverb `:squash` will reduce repeated matched characters to a single character.
Example:
```raku
my $str = 'say $x<b> && $y<a>';
$str.=trans( '<' => '«' );
$str.=trans( '<' => '«', '>' => '»' );
$str.=trans( [ '<' , '>' , '&' ] =>
[ '<', '>', '&' ]);
$str.=trans( ['a'..'y'] => ['A'..'z'] );
"abcdefghij".trans(/<[aeiou]> \w/ => ''); # OUTPUT: «cdgh»
"a123b123c".trans(['a'..'z'] => 'x', :complement); # OUTPUT: «axxxbxxxc»
"aaa1123bb123c".trans('a'..'z' => 'A'..'Z', :squash); # OUTPUT: «A1123B123C»
"aaa1123bb123c".trans('a'..'z' => 'x', :complement, :squash); # OUTPUT: «aaaxbbxc»
```
In general, the strings will have the same length after the substitution:
```raku
say "a123b123c".trans('23' => '4'); # OUTPUT: «a144b144c»
say "a123b123c".trans('123' => 'þð'); # OUTPUT: «aþðþbþðþc»
```
`:squash` and `:delete` will have the same effect in this case making it a strict substitution:
```raku
say "a123b123c".trans('123' => 'þð', :squash); # OUTPUT: «aþðbþðc»
say "a123b123c".trans('123' => 'þð', :delete); # OUTPUT: «aþðbþðc»
```
`:delete` will also remove non-matched characters from the original string:
```raku
say "abc".trans("abc".comb => 1..2, :delete); # OUTPUT: «12»
```
Please note that the behavior of the two versions of the multi method is slightly different. The first form will transpose only one character if the origin is also one character:
```raku
say "abcd".trans( "a" => "zz" ); # OUTPUT: «zbcd»
say "abcd".trans( "ba" => "yz" ); # OUTPUT: «zycd»
```
In the second case, behavior is as expected, since the origin is more than one char long. However, if the [`Pair`](/type/Pair) in the multi method does not have a `Str` as an origin or target, it is handled to the second multi method, and behavior changes:
```raku
say "abcd".trans: ["a"] => ["zz"]; # OUTPUT: «zzbcd»
```
In this case, neither origin nor target in the [`Pair`](/type/Pair) are `Str`; the method with the [`Pair`](/type/Pair) signature then calls the second, making this call above equivalent to `"abcd".trans: ["a"] => ["zz"],` (with the comma behind, making it a [`Positional`](/type/Positional), instead of a [`Pair`](/type/Pair)), resulting in the behavior shown as output.
# [In Cool](#___top "go to top of document")[§](#(Cool)_method_trans "direct link")
See primary documentation
[in context](/type/Cool#method_trans)
for **method trans**.
```raku
method trans(|)
```
Coerces the invocant to [`Str`](/type/Str) and calls [Str.trans](/type/Str#method_trans)
|
## dist_zef-lizmat-Time-localtime.md
[](https://github.com/lizmat/Time-localtime/actions)
# NAME
Raku port of Perl's Time::localtime module
# SYNOPSIS
```
use Time::localtime;
printf "Year is %d\n", localtime.year + 1900;
$now = ctime();
use Time::localtime;
$date_string = ctime($file.IO.modified);
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `Time::gmtime` module as closely as possible in the Raku Programming Language.
This module's default exports a `localtime` and `ctime` functions. The `localtime` function returns a "Time::localtime" object. This object has methods that return the similarly named structure field name from the C's tm structure from time.h; namely sec, min, hour, mday, mon, year, wday, yday, and isdst.
You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. (Note that this still exports the functions.) Access these fields as variables named with a preceding tm\_. Thus, `$group_obj.year` corresponds to `$tm_year` if you import the fields.
The `ctime` function provides a way of getting at the scalar sense of the `localtime` function in Perl.
# PORTING CAVEATS
This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/Time-localtime> . 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_zef-knarkhov-Pheix.md
# Pheix dCMS implemented in Raku
**Pheix dCMS** is the [Raku](https://raku.org) driven decentralized Content Management System. It is extremely lightweight, flexible and customizable.
## Repository submodules
There are two external submodules in this repository.
1. `dcms-configuration`: <https://gitlab.com/pheix/dcms-configuration>
2. `dcms-resources`: <https://gitlab.com/pheix/dcms-resources>
These are mandatory for production-ready deployments and extended testing. Once you have cloned Pheix dCMS, run the command:
```
git submodule init && git submodule update --recursive --remote
```
## Installation guide
Check [Installation guide](https://gitlab.com/pheix/dcms-raku/-/wikis/installation-guide) section at our wiki for installation details, tips and tricks.
## API reference
Check [API reference — Pheix API](https://gitlab.com/pheix/dcms-raku/-/wikis/api-reference) section at our wiki for full API reference.
## Dependencies
Check the strict list of the [Pheix dCMS dependencies](https://gitlab.com/pheix/dcms-raku/wikis/module-dependencies) at our wiki.
## Borrowings
Pheix uses [CGI](https://github.com/viklund/november/blob/master/lib/November/CGI.pm) module from [November Wiki engine](https://github.com/viklund/november). Also the generic CGI tests are added to Pheix test bundle.
## License information
Pheix is free and open source software, so you can redistribute it and/or modify it under the terms of the [The Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0).
## Changelog
All latest changes to this project are documented [at Pheix official website](https://pheix.org/changelog.txt).
## Author
Please contact me via [Matrix](https://matrix.to/#/@k.narkhov:matrix.org) or [LinkedIn](https://www.linkedin.com/in/knarkhov/). Your feedback is welcome at [narkhov.pro](https://narkhov.pro/contact-information.html).
## Donate
Pheix dCMS is an independent and self-funded project. All contributions and donations are greatly appreciated. Your support is important to me and inspires me to create new releases. Transfers in USDT, Ethereum, Bitcoin and TON are accepted. Please check the official [Donate](https://pheix.org/embedded/donate) page for details.
|
## fff.md
fff
Combined from primary sources listed below.
# [In Operators](#___top "go to top of document")[§](#(Operators)_infix_fff "direct link")
See primary documentation
[in context](/language/operators#infix_fff)
for **infix fff**.
```raku
sub infix:<fff>(Mu $a, Mu $b)
```
Performs a sed-like flipflop operation, wherein it returns `False` until the left argument smartmatches against `$_`, then returns `True` until the right argument smartmatches against `$_`.
Works similarly to [ff](/routine/ff), except that it only tries one argument per invocation. That is, if `$_` smartmatches the left argument, `fff` will **not** then try to match that same `$_` against the right argument.
```raku
for <AB C D B E F> {
say $_ if /A/ fff /B/; # OUTPUT: «ABCDB»
}
```
The non-sed-like flipflop (which after successfully matching the left argument against `$_` will try that same `$_` against the right argument and act accordingly). See [ff](/routine/ff).
This operator cannot be overloaded, as it's handled specially by the compiler.
|
## typesystem.md
## Chunk 1 of 2
Type system
Introduction to the type system of Raku
# [Definition of a Raku type](#Type_system "go to top of document")[§](#Definition_of_a_Raku_type "direct link")
A type defines a new object by creating a type object that provides an interface to create instances of objects or to check values against. Any type object is a subclass of [`Any`](/type/Any) or [`Mu`](/type/Mu). Introspection methods are provided via inheritance from those base classes and the introspection metamethods ([.^](/language/operators#methodop_.^)). A new type is introduced to the current scope by one of the following type declarators at compile time or with the [metaobject protocol](/language/mop) at runtime. All type names must be unique in their scope.
## [Default types](#Type_system "go to top of document")[§](#Default_types "direct link")
If no type is provided by the user Raku assumes the type to be [`Any`](/type/Any). This includes [containers](/language/containers), base-classes, [parameters](/language/signatures#Type_constraints) and return types.
```raku
my $a = 1;
$a = Nil;
say $a.^name;
# OUTPUT: «Any»
class C {};
say C.^parents(:all);
# OUTPUT: «((Any) (Mu))»
```
For containers the default type is [`Any`](/type/Any) but the default type constraint is [`Mu`](/type/Mu). Please note that binding replaces the container, not just the value. The type constraint may change in this case.
## [Type objects](#Type_system "go to top of document")[§](#Type_objects "direct link")
To test if an object is a type object, use [smartmatch](/language/operators#index-entry-smartmatch_operator) against a type constrained with a [type smiley](/language/signatures#Constraining_argument_definiteness) or [`.DEFINITE`](/language/mop#DEFINITE) method:
```raku
my $a = Int;
say $a ~~ Mu:U;
# OUTPUT: «True»
say not $a.DEFINITE;
# OUTPUT: «True»
```
`.DEFINITE` will return `True` if the invocant is an instance. If it returns `False`, then the invocant is a type object.
### [Undefinedness](#Type_system "go to top of document")[§](#Undefinedness "direct link")
Undefined objects maintain type information in Raku. Type objects are used to represent both undefinedness and the type of the undefined value. To provide a general undefined value use [`Any`](/type/Any). If differentiation from [`Any`](/type/Any), the default type for containers and arguments, is required use [`Mu`](/type/Mu).
Instances of objects created by [.CREATE](/type/Mu#method_CREATE) are by convention defined. The method [.defined](/type/Mu#routine_defined) will return `Bool::True` to indicate definedness. The exceptions to that rule are [`Nil`](/type/Nil) and [`Failure`](/type/Failure). Please note that any object is able to overload `.defined` and as such can carry additional information. Also, Raku makes a clear distinction between definedness and trueness. Many values are defined even though they carry the meaning of wrongness or emptiness. Such values are `0`, [Bool::False](/type/Bool), [()](/language/operators#term_(_)) (empty list) and [`NaN`](/type/Num#NaN).
Values can become undefined at runtime via [mixin](/language/operators#infix_but).
```raku
my Int $i = 1 but role :: { method defined { False } };
say $i // "undefined";
# OUTPUT: «undefined»
```
To test for definedness call `.defined`, use [//](/language/operators#infix_//), [with/without](/language/control#with_orwith_without) and [signatures](/language/signatures#Constraining_argument_definiteness).
### [Coercion](#Type_system "go to top of document")[§](#Coercion "direct link")
Turning one type into another is done with coercion methods that have the same name as the target type. This convention is made mandatory by [Signatures](/language/signatures#Coercion_type). The source type has to know how to turn itself into the target type. To allow built-in types to turn themselves into user defined types use [augment](/language/variables#The_augment_declarator) or the [MOP](/language/mop).
```raku
class C {
has $.int;
method this-is-c { put 'oi' x $!int ~ '‽' }
}
use MONKEY-TYPING;
augment class Int {
method C { C.new(:int(self))}
}
my $i = 10;
$i.=C;
$i.this-is-c();
# OUTPUT: «oioioioioioioioioioi‽»
```
Raku provides methods defined in [`Cool`](/type/Cool) to convert to a target type before applying further operations. Most built-in types descend from [`Cool`](/type/Cool) and as such may provide implicit coercion that may be undesired. It is the responsibility of the user to care about trap-free usage of those methods.
```raku
my $whatever = "123.6";
say $whatever.round;
# OUTPUT: «124»
say <a b c d>.starts-with("ab");
# OUTPUT: «False»
```
# [Type declarators](#Type_system "go to top of document")[§](#Type_declarators "direct link")
Type declarators introduce a new type into the given scope. Nested scopes can be separated by `::`. New [packages](/language/packages) are created automatically if no such scope exists already.
```raku
class Foo::Bar::C {};
put Foo::Bar::.keys;
# OUTPUT: «C»
```
Forward declarations can be provided with a block containing only `...`, the ["stub" operator](/language/operators#listop_...). The compiler will check at the end of the current scope if the type is defined.
```raku
class C {...}
# many lines later
class C { has $.attr }
```
## [`class`](#Type_system "go to top of document")[§](#class "direct link")
The `class` declarator creates a compile time construct that is compiled into a type object. The latter is a simple Raku object and provides methods to construct instances by executing initializers and sub methods to fill all attributes declared in a class, and any parent class, with values. Initializers can be provided with the declaration of attributes or in constructors. It's the responsibility of the [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW) to know how to run them. This is the only magic part of building objects in Raku. The default parent type is [`Any`](/type/Any), which in turn inherits from [`Mu`](/type/Mu). The latter provides the default constructor `.new` which is named like this by convention. Aside from this, `.new` does not carry any special meaning nor is treated in any special way.
For more information how to use classes see the [Classes and objects](/language/classtut) tutorial.
### [Mixins](#Type_system "go to top of document")[§](#Mixins "direct link")
The type introduced by `class` can be extended with [infix:<but>](/language/operators#infix_but) at runtime. The original type is not modified, instead a new type object is returned and can be stored in a container that type checks successful against the original type or the role that is mixed in.
```raku
class A {}
role R { method m { say 'oi‽' } }
my R $A = A but R;
my $a1 = $A.new;
$a1.m;
say [$A ~~ R, $a1 ~~ R];
# OUTPUT: «oi‽[True True]»
```
### [Introspection](#Type_system "go to top of document")[§](#Introspection "direct link")
#### [Metaclass](#Type_system "go to top of document")[§](#Metaclass "direct link")
To test if a given type object is a class, test the metaobject method `.HOW` against [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW).
```raku
class C {};
say C.HOW ~~ Metamodel::ClassHOW;
# OUTPUT: «True»
```
### [Private attributes](#Type_system "go to top of document")[§](#Private_attributes "direct link")
Private [`Attribute`](/type/Attribute)s are addressed with any of the twigils `$!`, `@!` and `%!`. They do not have public accessor methods generated automatically. As such they can not be altered from outside the class they are defined in.
```raku
class C {
has $!priv;
submethod BUILD { $!priv = 42 }
};
say (.name, .package, .has_accessor) for C.new.^attributes;
# OUTPUT: «($!priv (C) False)»
```
### [Methods](#Type_system "go to top of document")[§](#Methods "direct link")
The `method` declarator defines objects of type [`Method`](/type/Method) and binds them to the provided name in the scope of a class. Methods in a class are `has` scoped by default. Methods that are `our` scoped are not added to the method cache by default and as such can not be called with the accessor sigil `$.`. Call them with their fully qualified name and the invocant as the first argument.
#### [Inheritance and multis](#Type_system "go to top of document")[§](#Inheritance_and_multis "direct link")
A normal method in a subclass does not compete with multis of a parent class.
```raku
class A {
multi method m(Int $i){ say 'Int' }
multi method m(int $i){ say 'int' }
}
class B is A {
method m(Int $i){ say 'B::Int' }
}
my int $i;
B.new.m($i);
# OUTPUT: «B::Int»
```
#### [Only method](#Type_system "go to top of document")[§](#Only_method "direct link")
To explicitly state that a method is not a multi method use the `only` method declarator.
```raku
class C {
only method m {};
multi method m {};
};
# OUTPUT: «X::Comp::AdHoc: Cannot have a multi candidate for 'm' when an only method is also in the package 'C'»
```
#### [submethod BUILD](#Type_system "go to top of document")[§](#submethod_BUILD "direct link")
The [submethod](/type/Submethod) `BUILD` is (indirectly) called by [.bless](/type/Mu#method_bless). It is meant to set private and public attributes of a class and receives all named attributes passed into `.bless`. The default constructor [.new](/type/Mu#method_new) defined in [`Mu`](/type/Mu) is the method that invokes it. Given that public accessor methods are not available in `BUILD`, you must use private attribute notation instead.
```raku
class C {
has $.attr;
submethod BUILD (:$attr = 42) {
$!attr = $attr
};
multi method new($positional) {
self.bless(:attr($positional), |%_)
}
};
C.new.say; C.new('answer').say;
# OUTPUT: «C.new(attr => 42)
# C.new(attr => "answer")»
```
#### [Fallback method](#Type_system "go to top of document")[§](#Fallback_method "direct link")
A method with the special name `FALLBACK` will be called when other means to resolve the name produce no result. The first argument holds the name and all following arguments are forwarded from the original call. Multi methods and [sub-signatures](/language/signatures#Sub-signatures) are supported.
```raku
class Magic {
method FALLBACK ($name, |c(Int, Str)) {
put "$name called with parameters {c.raku}" }
};
Magic.new.simsalabim(42, "answer");
# OUTPUT: «simsalabim called with parameters ⌈\(42, "answer")⌋»
```
#### [Reserved method names](#Type_system "go to top of document")[§](#Reserved_method_names "direct link")
Some built-in introspection methods are actually special syntax provided by the compiler, namely `WHAT`, `WHO`, `HOW` and `VAR`. Declaring methods with those names will silently fail. A dynamic call will work, what allows to call methods from foreign objects.
```raku
class A {
method WHAT { "ain't gonna happen" }
};
say A.new.WHAT; # OUTPUT: «(A)»
say A.new."WHAT"() # OUTPUT: «ain't gonna happen»
```
#### [Methods in package scope](#Type_system "go to top of document")[§](#Methods_in_package_scope "direct link")
Any `our` scoped method will be visible in the package scope of a class.
```raku
class C {
our method packaged {};
method loose {}
};
say C::.keys
# OUTPUT: «(&packaged)»
```
#### [Setting attributes with namesake variables and methods](#Type_system "go to top of document")[§](#Setting_attributes_with_namesake_variables_and_methods "direct link")
Instead of writing `attr => $attr` or `:attr($attr)`, you can save some typing if the variable (or method call) you're setting the attribute with shares the name with the attribute:
```raku
class A { has $.i = 42 };
class B {
has $.i = "answer";
method m() { A.new(:$.i) }
# ^^^^ Instead of i => $.i or :i($.i)
};
my $a = B.new.m;
say $a.i; # OUTPUT: «answer»
```
Since `$.i` method call is named `i` and the attribute is also named `i`, Raku lets us shortcut. The same applies to `:$var`, `:$!private-attribute`, `:&attr-with-code-in-it`, and so on.
### [trait `is nodal`](#Type_system "go to top of document")[§](#trait_is_nodal "direct link")
Marks a [`List`](/type/List) method to indicate to hyperoperator to not descend into inner [`Iterable`](/type/Iterable)s to call this method. This trait generally isn't something end users would be using, unless they're subclassing or augmenting core [`List`](/type/List) type.
In order to demonstrate the difference consider the following examples, the first using a method (`elems`) that `is nodal` and the second using a method ([`Int`](/type/Int)) which is not nodal.
```raku
say ((1.0, "2", 3e0), [^4], '5')».elems; # OUTPUT: «(3, 4, 1)»
say ((1.0, "2", 3e0), [^4], '5')».Int # OUTPUT: «((1 2 3) [0 1 2 3] 5)»
```
### [`handles`](#Type_system "go to top of document")[§](#trait_handles "direct link")
```raku
multi trait_mod:<handles>(Attribute:D $target, $thunk)
```
The [trait](/type/Sub#Traits) `handles` applied to an attribute of a class will delegate all calls to the provided method name to the method with the same name of the attribute. The object referenced by the attribute must be initialized. A type constraint for the object that the call is delegated to can be provided.
```raku
class A { method m(){ 'A::m has been called.' } }
class B is A { method m(){ 'B::m has been called.' } }
class C {
has A $.delegate handles 'm';
method new($delegate){ self.bless(delegate => $delegate) }
};
say C.new(B.new).m(); # OUTPUT: «B::m has been called.»
```
Instead of a method name, a [`Pair`](/type/Pair) (for renaming), a list of names or [`Pair`](/type/Pair)s, a [`Regex`](/type/Regex) or a [`Whatever`](/type/Whatever) can be provided. In the latter case existing methods, both in the class itself and its inheritance chain, will take precedence. If even local `FALLBACK`s should be searched, use a [`HyperWhatever`](/type/HyperWhatever).
```raku
class A {
method m1(){ 'A::m1 has been called.' }
method m2(){ 'A::m2 has been called.' }
}
class C {
has $.delegate handles <m1 m2> = A.new()
}
say C.new.m2; # OUTPUT: «A::m2 has been called.»
class D {
has $.delegate handles /m\d/ = A.new()
}
say D.new.m1; # OUTPUT: «A::m1 has been called.»
class E {
has $.delegate handles (em1 => 'm1') = A.new()
}
say E.new.em1; # OUTPUT: «A::m1 has been called.»
class F {
# Delegates all methods from A
has A $.delegate handles *;
}
say F.new.m1; # OUTPUT: «A::m1 has been called.»
say F.new.m2; # OUTPUT: «A::m2 has been called.»
```
### [trait `is`](#Type_system "go to top of document")[§](#trait_is "direct link")
```raku
multi trait_mod:<is>(Mu:U $child, Mu:U $parent)
```
The [trait](/type/Sub#Traits) `is` accepts a type object to be added as a parent class of a class in its definition. To allow multiple inheritance the trait can be applied more than once. Adding parents to a class will import their methods into the target class. If the same method name occurs in multiple parents, the first added parent will win.
If no `is` trait is provided the default of [`Any`](/type/Any) will be used as a parent class. This forces all Raku objects to have the same set of basic methods to provide an interface for introspection and coercion to basic types.
```raku
class A {
multi method from-a(){ 'A::from-a' }
}
say A.new.^parents(:all).raku;
# OUTPUT: «(Any, Mu)»
class B {
method from-b(){ 'B::from-b ' }
multi method from-a(){ 'B::from-A' }
}
class C is A is B {}
say C.new.from-a();
# OUTPUT: «A::from-a»
```
### [`is rw`](#Type_system "go to top of document")[§](#trait_is_rw "direct link")
```raku
sub trait_mod:<is>(Mu:U $type, :$rw!)
```
The [trait](/type/Sub#Traits) `is rw` on a class will create writable accessor methods on all public attributes of that class.
```raku
class C is rw {
has $.a;
};
my $c = C.new.a = 42;
say $c; # OUTPUT: «42»
```
### [trait `is required`](#Type_system "go to top of document")[§](#trait_is_required "direct link")
```raku
multi trait_mod:<is>(Attribute $attr, :$required!)
multi trait_mod:<is>(Parameter:D $param, :$required!)
```
Marks a class or roles attribute as required. If the attribute is not initialized at object construction time throws [`X::Attribute::Required`](/type/X/Attribute/Required).
```raku
class Correct {
has $.attr is required;
}
say Correct.new(attr => 42);
# OUTPUT: «Correct.new(attr => 42)»
class C {
has $.attr is required;
}
C.new;
CATCH { default { say .^name => .Str } }
# OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.»
```
Note a class with a private attribute will give the same error:
```raku
class D {
has $!attr is required;
}
D.new;
CATCH { default { say .^name => .Str } }
# OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.»
```
You can provide a reason why it's required as an argument to `is required`
```raku
class Correct {
has $.attr is required("it's so cool")
};
say Correct.new();
# OUTPUT: «The attribute '$!attr' is required because it's so cool,but you did not provide a value for it.»
```
### [trait `hides`](#Type_system "go to top of document")[§](#trait_hides "direct link")
The trait `hides` provides inheritance without being subject to [re-dispatching](/language/functions#Re-dispatching).
```raku
class A {
method m { say 'i am hidden' }
}
class B hides A {
method m { nextsame }
method n { self.A::m }
};
B.new.m; # No output
B.new.n; # OUTPUT: «i am hidden»
```
The trait `is hidden` allows a class to hide itself from [re-dispatching](/language/functions#Re-dispatching).
```raku
class A is hidden {
method m { say 'i am hidden' }
}
class B is A {
method m { nextsame }
method n { self.A::m }
}
B.new.m; # No output
B.new.n; # OUTPUT: «i am hidden»
```
Classes declared with `is hidden` also generate slightly different method signatures. To facilitate re-dispatch, typical methods are automatically provided with an extra `*%_` parameter that [captures extra named arguments](/type/Method#index-entry-*%___(extra_named_arguments)). Because classes declared with `is hidden` don't participate in re-dispatch, their methods don't receive this extra parameter.
### [trait `trusts`](#Type_system "go to top of document")[§](#trait_trusts "direct link")
To allow one class to access the private methods of another class use the trait `trusts`. A forward declaration of the trusted class may be required.
```raku
class B {...};
class A {
trusts B;
has $!foo;
method !foo { return-rw $!foo }
method raku { "A.new(foo => $!foo)" }
};
class B {
has A $.a .= new;
method change { $!a!A::foo = 42; self }
};
say B.new.change;
# OUTPUT: «B.new(a => A.new(foo => 42))»
```
### [Augmenting a class](#Type_system "go to top of document")[§](#Augmenting_a_class "direct link")
To add methods and attributes to a class at compile time use `augment` in front of a class definition fragment. The compiler will demand the pragmas `use MONKEY-TYPING` or `use MONKEY` early in the same scope. Please note that there may be performance implications, hence the pragmas.
```raku
use MONKEY; augment class Str {
method mark(Any :$set){
state $mark //= $set; $mark
}
};
my $s = "42";
$s.mark(set => "answer");
say $s.mark
# OUTPUT: «answer»
```
There are few limitations of what can be done inside the class fragment. One of them is the redeclaration of a method or sub into a multi. Using added attributes is not implemented. Please note that adding a multi candidate that differs only in its named parameters will add that candidate behind the already defined one and as such it won't be picked by the dispatcher.
## [`role`](#Type_system "go to top of document")[§](#role "direct link")
Roles are class fragments, which allow the definition of interfaces that are shared by classes. The `role` declarator also introduces a type object that can be used for type checks. Roles can be mixed into classes and objects at runtime and compile time. The `role` declarator returns the created type object thus allowing the definition of anonymous roles and in-place mixins.
```raku
role Serialize {
method to-string { self.Str }
method to-number { self.Num }
}
class A does Serialize {}
class B does Serialize {}
my Serialize @list;
@list.push: A.new;
@list.push: B.new;
say @list».to-string;
# OUTPUT: «[A<57192848> B<57192880>]»
```
Use `...` as the only element of a method body to declare a method to be abstract. Any class getting such a method mixed in has to overload it. If the method is not overloaded before the end of the compilation unit [`X::Comp::AdHoc`](/type/X/Comp/AdHoc) will be thrown.
```raku
EVAL 'role R { method overload-this(){...} }; class A does R {}; ';
CATCH { default { say .^name, ' ', .Str } }
# OUTPUT: «X::Comp::AdHoc Method 'overload-this' must be implemented by A because it is required by roles: R.»
```
### [Auto-punning](#Type_system "go to top of document")[§](#Auto-punning "direct link")
A role can be used instead of a class to create objects. Since roles can't exist at runtime, a class of the same name is created that will type check successful against the role.
```raku
role R { method m { say 'oi‽' } };
R.new.^mro.say;
# OUTPUT: «((R) (Any) (Mu))»
say R.new.^mro[0].HOW.^name;
# OUTPUT: «Perl6::Metamodel::ClassHOW»
say R.new ~~ R;
# OUTPUT: «True»
```
### [trait `does`](#Type_system "go to top of document")[§](#trait_does "direct link")
The trait `does` can be applied to roles and classes providing compile time mixins. To refer to a role that is not defined yet, use a forward declaration. The type name of the class with mixed in roles does not reflect the mixin, a type check does. If methods are provided in more than one mixed in role, the method that is defined first takes precedence. A list of roles separated by comma can be provided. In this case conflicts will be reported at compile time.
```raku
role R2 {...};
role R1 does R2 {};
role R2 {};
class C does R1 {};
say [C ~~ R1, C ~~ R2];
# OUTPUT: «[True True]»
```
For runtime mixins see [but](/language/operators#infix_but) and [does](/language/operators#infix_does).
### [Parameterized](#Type_system "go to top of document")[§](#Parameterized "direct link")
Roles can be provided with parameters in-between `[]` behind a roles name. [Type captures](/language/signatures#Type_captures) are supported.
```raku
role R[$d] { has $.a = $d };
class C does R["default"] { };
my $c = C.new;
say $c;
# OUTPUT: «C.new(a => "default")»
```
Parameters can have type constraints, `where` clauses are not supported for types but can be implemented via [`subset`s](#subset).
```raku
class A {};
class B {};
subset A-or-B where * ~~ A|B;
role R[A-or-B ::T] {};
R[A.new].new;
```
Default parameters can be provided.
```raku
role R[$p = fail("Please provide a parameter to role R")] {};
my $i = 1 does R;
CATCH { default { say .^name, ': ', .Str} }
# OUTPUT: «X::AdHoc: Could not instantiate role 'R':Please provide a parameter to role R»
```
### [As type constraints](#Type_system "go to top of document")[§](#As_type_constraints "direct link")
Roles can be used as type constraints wherever a type is expected. If a role is mixed in with `does` or `but`, its type-object is added to the type-object list of the object in question. If a role is used instead of a class (using auto-punning), the auto-generated class' type-object, of the same name as the role, is added to the inheritance chain.
```raku
role Unitish[$unit = fail('Please provide a SI unit quantifier as a parameter to the role Unitish')] {
has $.SI-unit-symbol = $unit;
method gist {
given self {
# ...
when * < 1 { return self * 1000 ~ 'm' ~ $.SI-unit-symbol }
when * < 1000 { return self ~ $.SI-unit-symbol }
when * < 1_000_000 { return self / 1_000 ~ 'k' ~ $.SI-unit-symbol }
# ...
}
}
}
role SI-second does Unitish[<s>] {}
role SI-meter does Unitish[<m>] {}
role SI-kilogram does Unitish[<g>] {}
sub postfix:<s>(Numeric $num) { ($num) does SI-second }
sub postfix:<m>(Numeric $num) { ($num) does SI-meter }
sub postfix:<g>(Numeric $num) { ($num) does SI-kilogram }
sub postfix:<kg>(Numeric $num){ ($num * 1000) does SI-kilogram }
constant g = 9.806_65;
role SI-Newton does Unitish[<N>] {}
multi N(SI-kilogram $kg, SI-meter $m, SI-second $s --> SI-Newton ){ ($kg * ($m / $s²)) does SI-Newton }
multi N(SI-kilogram $kg --> SI-Newton) { ($kg * g) does SI-Newton }
say [75kg, N(75kg)];
# OUTPUT: «[75kg 735.49875kN]»
say [(75kg).^name, N(75kg).^name];
# OUTPUT: «[Int+{SI-kilogram} Rat+{SI-Newton}]»
```
## [`enum`](#Type_system "go to top of document")[§](#enum "direct link")
Enumerations provide constant key-value-pairs with an associated type. Any key is of that type and injected as a symbol into the current scope. If the symbol is used, it is treated as a constant expression and the symbol is replaced with the value of the enum-pair. Any Enumeration inherits methods from the role [`Enumeration`](/type/Enumeration). Complex expressions for generating key-value pairs are not supported. In general, an `enum` is a [`Map`](/type/Map) whose elements have the [`Enumeration`](/type/Enumeration) role mixed in; this role includes, for each element, an index which creates an order on the map.
Stringification of the symbol, which is done automatically in string context and is exactly equal to its name, which is also the key of the enum-pair.
```raku
enum Names ( name1 => 1, name2 => 2 );
say name1, ' ', name2; # OUTPUT: «name1 name2»
say name1.value, ' ', name2.value; # OUTPUT: «1 2»
```
Comparing symbols will use type information and the value of the enum-pair. As value types [`Num`](/type/Num) and [`Str`](/type/Str) are supported.
```raku
enum Names ( name1 => 1, name2 => 2 );
sub same(Names $a, Names $b){
$a eqv $b
}
say same(name1, name1); # OUTPUT: «True»
say same(name1, name2); # OUTPUT: «False»
my $a = name1;
say $a ~~ Names; # OUTPUT: «True»
say $a.^name; # OUTPUT: «Names»
```
All keys have to be of the same type.
```raku
enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 );
say Mass.enums;
# OUTPUT: «Map.new((g => 1, kg => 1000, mg => 0.001))»
```
And you can use any kind of symbol:
```raku
enum Suit <♣ ♦ ♥ ♠>;
```
As long as you refer to that symbol using the full syntax:
```raku
say Suit::<♣>; # OUTPUT: «♣»
my $heart = '♥';
say Suit::«$heart»; # OUTPUT: «♥»
```
Attempting to access unicode enum keys without said syntax will result in an error:
```raku
say ♣ ; # OUTPUT: «(exit code 1) ===SORRY!===Argument to "say" seems to be malformed…
```
If no value is given [`Int`](/type/Int) will be assumed as the values type and incremented by one per key starting at zero. As enum key types [`Int`](/type/Int), [`Num`](/type/Num), [`Rat`](/type/Rat) and [`Str`](/type/Str) are supported.
```raku
enum Numbers <one two three four>;
say Numbers.enums;
# OUTPUT: «Map.new((four => 3, one => 0, three => 2, two => 1))»
```
A different starting value can be provided.
```raku
enum Numbers «:one(1) two three four»;
say Numbers.enums;
# OUTPUT: «Map.new((four => 4, one => 1, three => 3, two => 2))»
```
You can also do this with the **()** form of the initializer, but will need to quote keys that do not have a value:
```raku
enum Numbers (
one => 1,
'two',
'three',
'four'
);
```
Enums can also be anonymous, with the only difference with named `enum`s being that you cannot use it in [`Signature`](/type/Signature)s or to declare variables.
```raku
my $e = enum <one two three>;
say two; # OUTPUT: «two»
say one.^name; # OUTPUT: «»
say $e.^name; # OUTPUT: «Map»
```
There are various methods to get access to the keys and values of the symbols that have been defined. All of them turn the values into [`Str`](/type/Str), which may not be desirable. By treating the enum as a package, we can get a list of types for the keys.
```raku
enum E <one two>;
my @keys = E::.values;
say @keys.map: *.raku;
# OUTPUT: «(E::one E::two)» or «(E::two E::one)»
```
Note that, as the output above indicates, the iteration order of enums is not guaranteed. This is because the methods that "iterate over" an enum do not iterate *directly* on the enum (which, after all, is not iterable). Instead, these iteration methods create a [`Map`](/type/Map) with the same keys and values as the enum. Because [`Map`](/type/Map)s provide only unordered, iteration the iteration methods on an enum do as well. If you need to iterate an enum in order, you can sort on its `value`, for example with `E.enums.sort(*.value)`.
With the use of **()** parentheses, an enum can be defined using any arbitrary dynamically defined list. The list should consist of Pair objects:
For example, in file `config` we have:
「text」 without highlighting
```
```
a 1
b 2
```
```
We can create an enum using it with this code:
```raku
enum ConfigValues ('config'.IO.lines.map({ my ($key, $value) = $_.words |
## typesystem.md
## Chunk 2 of 2
; $key => $value }));
say ConfigValues.enums; # OUTPUT: «Map.new((a => 1, b => 2))»
```
Firstly, we read lines from `config` file, split every line using `words` method and return resulting pair for every line, thus creating a List of Pairs.
### [Typing Enums](#Type_system "go to top of document")[§](#Typing_Enums "direct link")
When declaring enums with an explicit scope, a type may be provided, which will be used to typecheck the enum's values:
```raku
my Str enum Foo (foo => 'foo');
```
All enum pairs are typed as [`Enumeration`](/type/Enumeration). In addition, when the enum values are typed as [`Numeric`](/type/Numeric), [`Stringy`](/type/Stringy), or a combination of these two types, enum pairs also do the `NumericEnumeration`, `StringyEnumeration`, and `NumericStringyEnumeration` roles respectively. These simply determine how enum pairs get stringified with the [`Str`](/type/Str) method.
Given that these types are roles, naturally you can provide your own roles when declaring an enum, which allows you to give them custom behavior and state. For example, to make it simpler to check if a number matches a flag in a bitmask enum, you could write a `BitmaskEnumeration` role with an `ACCEPTS` method to handle this via smartmatching:
```raku
role BitmaskEnumeration {
multi method ACCEPTS(::?CLASS:D: Int:D $value --> Bool:D) {
so $value +& self.value
}
}
enum Flags does BitmaskEnumeration (
FLAG_FOO => 0b001,
FLAG_BAR => 0b010,
FLAG_BAZ => 0b100,
);
say 0b111 ~~ FLAG_FOO & FLAG_BAR & FLAG_BAZ; # OUTPUT: «True»
```
### [Metaclass](#Type_system "go to top of document")[§](#Metaclass_0 "direct link")
To test if a given type object is an `enum`, test the metaobject method `.HOW` against [`Metamodel::EnumHOW`](/type/Metamodel/EnumHOW) or simply test against the [`Enumeration`](/type/Enumeration) role.
```raku
enum E(<a b c>);
say E.HOW ~~ Metamodel::EnumHOW; # OUTPUT: «True»
say E ~~ Enumeration; # OUTPUT: «True»
```
### [Methods](#Type_system "go to top of document")[§](#Methods_0 "direct link")
See the [`Enumeration`](/type/Enumeration) role for available methods on enum types and enum-pairs.
### [Coercion](#Type_system "go to top of document")[§](#Coercion_0 "direct link")
If you want to coerce the value of an enum element to its proper enum object, use the coercer with the name of the enum:
```raku
my enum A (sun => 42, mon => 72);
A(72).pair.say; # OUTPUT: «mon => 72»
A(1000).say; # OUTPUT: «(A)»
```
The last example shows what happens if there is no enum-pair that includes that as a value.
## [`module`](#Type_system "go to top of document")[§](#module "direct link")
Modules are usually one or more source files that expose Raku constructs, such as classes, roles, grammars, subroutines and variables. Modules are usually used for distributing Raku code as libraries which can be used in another Raku program.
For a full explanation see [Modules](/language/modules).
## [`package`](#Type_system "go to top of document")[§](#package "direct link")
Packages are nested namespaces of named program elements. Modules, classes and grammars are all types of package.
For a full explanation see [Packages](/language/packages).
## [`grammar`](#Type_system "go to top of document")[§](#grammar "direct link")
Grammars are a specific type of class intended for parsing text. Grammars are composed of rules, tokens and regexes which are actually methods, since grammars are classes.
For a full explanation see [Grammars](/language/grammars).
## [`subset`](#Type_system "go to top of document")[§](#subset "direct link")
A `subset` declares a new type that will re-dispatch to its base type. If a [`where`](/language/signatures#index-entry-where_clause) clause is supplied any assignment will be checked against the given code object.
```raku
subset Positive of Int where * > -1;
my Positive $i = 1;
$i = -42;
CATCH { default { put .^name,': ', .Str } }
# OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $i; expected Positive but got Int (-42)»
```
Subsets can be used in signatures, e.g. by typing the output:
```raku
subset Foo of List where (Int,Str);
sub a($a, $b, --> Foo) { $a, $b }
# Only a List with the first element being an Int and the second a Str will pass the type check.
a(1, "foo"); # passes
a("foo", 1); # fails
```
If you skip the base type, it defaults to [`Any`](/type/Any). So the following two are equivalent:
```raku
subset A-or-B where * ~~ A | B
```
```raku
subset A-or-B of Any where * ~~ A | B
```
Subsets can be anonymous, allowing inline placements where a subset is required but a name is neither needed nor desirable.
```raku
my enum E1 <A B>;
my enum E2 <C D>;
sub g(@a where { .all ~~ subset :: where E1|E2 } ) {
say @a
}
g([A, C]);
# OUTPUT: «[A C]»
```
Subsets can be used to check types dynamically, which can be useful in conjunction with [require](/language/modules#require).
```raku
require ::('YourModule');
subset C where ::('YourModule::C');
```
# [Versioning, authorship, and API version.](#Type_system "go to top of document")[§](#Versioning,_authorship,_and_API_version. "direct link")
When you declare a type you can pass it a version, author, and/or API number, all of which you can subsequently introspect. The versioning, authorship, and/or API number of a type can be applied via the adverbs `:ver<>`, `:auth<>`, and `:api<>` respectively. All of them take a string as argument; for `:ver` the string is converted to a [`Version`](/type/Version) object, and for `:api` the string is converted into an [allomorph](/language/glossary#Allomorph) [`IntStr`](/type/IntStr) object. `:auth` generally takes the form `hosting:ID`, as in `github:github-user` or `gitlab:gitlab-user`.
To query the version, author, and API version of a type use [`.^ver`](/type/Metamodel/Versioning#method_ver), [`.^auth`](/type/Metamodel/Versioning#method_auth), and [`.^api`](/type/Metamodel/Versioning#method_api) respectively, as illustrated down below by querying a `class`.
```raku
class C:ver<4.2.3>:auth<github:jane>:api<1> {}
say C.^ver; # OUTPUT: «v4.2.3»
say C.^ver.parts; # OUTPUT: «(4 2 3)»
say C.^auth; # OUTPUT: «github:jane»
say C.^api; # OUTPUT: «1»
```
In a similar fashion, `role`s, `grammar`s, and `module`s can be queried about the aforementioned information.
|
## dist_cpan-JJATRIA-App-Lorea.md
# lorea
A command line utility to execute commands on filesystem changes.
The interface should be fairly familiar for users of [reflex](https://github.com/cespare/reflex). See
[the examples section](#examples) below for some possible ways to use it.
## Installation
```
$ zef install App::Lorea
```
## Usage
```
lorea [options] -- command [args]
```
## Options
```
--all Include all normally ignored files
-c, --config STRING The path to a configuration file
--help Display usage information
-R, --ignore REGEX ... A regular expression to ignore filenames
-r, --regex REGEX ... A regular expression to match filenames
-e, --sequential Run commands sequentially from config file
-s, --start-service Run command as a service
--substitute STRING Set the string to be used as placeholder
-v, --verbose Print tracing information
--version Print the version of the command and compiler
```
Options marked with `...` can be provided multiple times.
Values marked as `REGEX` must be compilable as Raku [regular expressions](https://docs.raku.org/language/regexes).
## Overview
When `lorea` is run, it will monitor your current directory, and any
directories under it, for any file-system changes. When a file is changed
or added, it will be matched against the patterns you've specified (see
[below](#matching) for details about how the matching is done).
If the event matches, the command you've specified will be run, or
restarted if you enabled the `--start-service` flag.
If the command you've specified includes the `{}` string, this will be
replaced by the absolute path of the file that has changed. All instances
of this placeholder string will be replaced. If you need to use the `{}`
string for something else, you can specify a different placeholder string
with the `--substitute` option.
### Matching
Patterns to match can be specified to `lorea` with either `--regex` or
`--ignore`. Both of these options take Raku regular expressions, with the
difference that any match for the former will trigger an event, while every
match for the latter will eplicitly *not* trigger one.
Paths are normalised before being matched, and converted to paths relative
to the current directory without a leading `./`. Matching directories will
have a trailing slash (`/`).
If no pattern is specified, all file-system changes will match.
### Default ignores
By default, `lorea` ignores some common patterns to make it easier to use
in most cases.
* Files and directories with a leading dot (`.`), which are considered
hidden in Unix-like systems.
* Common swap files, including those ending in `.swp`, `.swx`, and `~`.
The `--all` option disables these defaults. This flag will take effect if
set either at the top level, or in any of the watchers specified in the
configuration file (see below).
You can see the global ignores by setting the `--verbose` option.
## Configuration
The `--config` option can be used to specify a configuration to use to start
several watchers at the same time. The behaviour of these watchers can be
set independently.
The format of this file is intentionally very limited. A valid file will look
something like this:
```
# Rebuild SCSS when it changes
-r '\.scss$' -- \
sh -c 'sass {} `basename {} .scss`.css'
# Restart server when ruby code changes
-s -r '\.rb$' -- \
./bin/run_server.sh
```
Each line will be interpreted as the parameters to a separate invokation of
`lorea`. Lines must not include the executable name (that will be filled in
internally). The parameters to a single invokation can be broken into multiple
lines if they end with a trailing backslash (`\`).
Empty lines, and lines begininng with a hash (`#`) will be ignored.
With the exception of `--help` , `--sequential, and` --config`itself, all options are valid within a configuration file. If the`--config`option is set, the only other flags that are allowed at the top level are`--verbose`and`--sequential`.
### Sequential execution
When using a config file to run multiple simultaneous commands, each of them
will be started asynchronously whenever posible. This means that, while there
will only be one instance of a particular command, two different commands may
overlap. This is usually what you want.
As a concrete example, consider this config file:
```
-- sh -c 'for i in `seq 1 5`; do sleep 0.1; echo first; done'
-- sh -c 'for i in `seq 1 5`; do sleep 0.1; echo second; done'
```
When this runs, you might see something like this:
```
second
first
second
first
first
second
second
first
second
first
```
Note that, since both commands started at the same time, the output of both is
interleaved. If this is not what you want, you can ensure only one command runs
at a time with the `--sequential` flag used at the top-level (it is not allowed
in config files). In this case, the output might instead look like this:
```
second
second
second
second
second
first
first
first
first
first
```
Note in this case that even when using `--sequential` there is no guarantee
that the commands will be executed in the order they appear in the config
file.
## Batching
Part of what `lorea` does is apply some heuristics to batch together file
changes. There are many reasons that files change on disk, and these changes
frequently come in large bursts. For instance, when you save a file in your
editor, it probably makes a tempfile and then copies it over the target,
leading to several different changes. A more dramatic example will happen
when you do a source-control checkout, in which case there is no limit to
the number of files that might change at once.
If `lorea` did not batch these changes, this could lead to your computer
slowing down to a crawl, or the whole process crashing.
There are two modes to batch these changes.
If your command is marked as a service, or has no placeholders in it, then
`lorea` assumes that individual changes are not as important as the fact that
*a change took place*. In this case changes will be collected, and a single
command execution will trigger once a short amount of time has passed
between them.
Otherwise, changes will be collected using the same logic as above, but
*every unique file change* will trigger a separate execution of your command.
## Examples
Every time a `.raku` or `.rakumod` file changes, print a string with the
name of the modified file:
```
lorea --regex '\.raku(mod)?$' -- echo "Change in {}"
```
or the same thing, but taking advantage of Raku's [regular expressions](https://docs.raku.org/language/regexes):
```
lorea --regex '".raku" [mod]? $' -- echo "Change in {}"
```
|
## dist_zef-lizmat-Sub-Util.md
[](https://github.com/lizmat/Sub-Util/actions)
# NAME
Raku port of Perl's Sub::Util module 1.55
# SYNOPSIS
```
use Sub::Util <subname set_subname>
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `Sub::Util` module as closely as possible in the Raku Programming Language.
`Sub::Util` contains a selection of subroutines that people have expressed would be nice to have in the perl core, but the usage would not really be high enough to warrant the use of a keyword, and the size would be so small that being individual extensions would be wasteful.
By default `Sub::Util` does not export any subroutines.
## subname
```
my $name = subname( $callable );
```
Returns the name of the given Callable, if it has one. Normal named subs will give a fully-qualified name consisting of the package and the localname separated by `::`. Anonymous Callables will give `__ANON__` as the localname. If a name has been set using `set_subname`, this name will be returned instead.
*Users of Sub::Name beware*: This function is **not** the same as `Sub::Name::subname`; it returns the existing name of the sub rather than changing it. To set or change a name, see instead `set_subname`.
## set\_subname
```
my $callable = set_subname $name, $callable;
```
Sets the name of the function given by the Callable. Returns the Callable itself. If the `$name` is unqualified, the package of the caller is used to qualify it.
This is useful for applying names to anonymous Callables so that stack traces and similar situations, to give a useful name rather than having the default. Note that this name is only used for this situation; the `set_subname` will not install it into the symbol table; you will have to do that yourself if required.
However, since the name is not used by perl except as the return value of `caller`, for stack traces or similar, there is no actual requirement that the name be syntactically valid as a perl function name. This could be used to attach extra information that could be useful in debugging stack traces.
This function was copied from `Sub::Name::subname` and renamed to the naming convention of this module.
# FUNCTIONS NOT PORTED
It did not make sense to port the following functions to Raku, as they pertain to specific Pumpkin Perl internals.
```
prototype set_prototype
```
Attempting to import these functions will result in a compilation error with hopefully targeted feedback. Attempt to call these functions using the fully qualified name (e.g. `Sub::Util::set_prototype($a)`) will result in a run time error with the same feedback.
# SEE ALSO
Sub::Name
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/Sub-Util> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version originally developed by Paul Evans.
|
## dist_zef-lizmat-P5getservbyname.md
[](https://github.com/lizmat/P5getservbyname/actions)
# NAME
Raku port of Perl's getservbyname() and associated built-ins
# SYNOPSIS
```
use P5getservbyname;
# exports getservbyname, getservbyport, getservent, setservent, endservent
say getservbyport(Scalar, 25, "tcp"); # "smtp"
my @result_byname = getservbyname("smtp");
my @result_byport = getservbyport(|@result_byname[3,4]);
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `getservbyname` and associated built-ins as closely as possible in the Raku Programming Language.
It exports by default:
```
endservent getservbyname getservbyport getservent setservent
```
# ORIGINAL PERL 5 DOCUMENTATION
```
getservbyname NAME,PROTO
getservbyport PORT,PROTO
getservent
setservent STAYOPEN
endservent
These routines are the same as their counterparts in the system C
library. In list context, the return values from the various get
routines are as follows:
# 0 1 2 3 4
( $name, $aliases, $port, $proto ) = getserv*
(If the entry doesn't exist you get an empty list.)
In scalar context, you get the name, unless the function was a
lookup by name, in which case you get the other thing, whatever it
is. (If the entry doesn't exist you get the undefined value.)
```
# PORTING CAVEATS
This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
Source can be located at: <https://github.com/lizmat/P5getservbyname> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen
Re-imagined from Perl as part of the CPAN Butterfly Plan.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-antononcube-DateTime-Grammar.md
# DateTime::Grammar Raku package
## Introduction
This Raku package provides grammar (role) and interpreters for parsing
[datetime specifications](https://docs.raku.org/type/DateTime).
Most of the code is from [FS1]. The original code of the file
["Parse.rakumod"](https://github.com/sergot/datetime-parse/blob/master/lib/DateTime/Parse.rakumod)
(from [FS1]) was separated into the files
["Grammarish.rakumod"](./lib/DateTime/Grammarish.rakumod)
and
["Actions/Raku.rakumod"](./lib/DateTime/Actions/Raku.rakumod).
The code in
["Grammar.rakumod"](./lib/DateTime/Grammar.rakumod)
provides the "top-level" functions:
* `datetime-parse`
* `datetime-subparse`
* `datetime-interpret`
**Remark:** The code `DateTime::Parse.new` can be replaced with `datetime-interpret`.
Compare the test files of this repository that have names starting with "01-" with the corresponding files in [FS1].
---
## Installation
From Zef ecosystem:
```
zef install DateTime::Grammar
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-DateTime-Grammar.git
```
---
## Usage examples
Interpret a full blown datetime spec:
```
use DateTime::Grammar;
my $rfc1123 = datetime-interpret('Sun, 06 Nov 1994 08:49:37 GMT');
$rfc1123.raku
```
```
# DateTime.new(1994,11,6,8,49,37)
```
Just the date:
```
$rfc1123.Date;
```
```
# 1994-11-06
```
7th day of week:
```
datetime-interpret('Sun', :rule<wkday>) + 1;
```
```
# 7
```
With the adverb `extended` we can control whether the datetime specs can be just dates.
Here are examples:
```
datetime-interpret('1/23/1089'):extended;
```
```
# 1089-01-23T00:00:00Z
```
```
datetime-interpret('1/23/1089'):!extended;
```
```
# (Any)
```
---
## Using the role in "external" grammars
Here is how the role "Grammarish" of "DateTime::Grammar" can be used in "higher order" grammars:
```
my grammar DateTimeInterval
does DateTime::Grammarish {
rule TOP($*extended) { 'from' <from=.datetime-param-spec> 'to' <to=.datetime-param-spec> }
};
DateTimeInterval.parse('from 2022-12-02 to Oct 4 2023', args => (True,))
```
```
# 「from 2022-12-02 to Oct 4 2023」
# from => 「2022-12-02」
# date-spec => 「2022-12-02」
# date5 => 「2022-12-02」
# year => 「2022」
# month => 「12」
# day => 「02」
# to => 「Oct 4 2023」
# date-spec => 「Oct 4 2023」
# date8 => 「Oct 4 2023」
# month => 「Oct」
# month-short-name => 「Oct」
# day => 「4」
# year => 「2023」
```
The parameter `$*extended` can be eliminated by using `<datetime-spec>` instead of `<datetime-param-spec>`:
```
my grammar DateTimeInterval2
does DateTime::Grammarish {
rule TOP { 'from' <from=.datetime-spec> 'to' <to=.datetime-spec> }
};
DateTimeInterval2.parse('from 2022-12-02 to Oct 4 2023')
```
```
# 「from 2022-12-02 to Oct 4 2023」
# from => 「2022-12-02」
# date-spec => 「2022-12-02」
# date5 => 「2022-12-02」
# year => 「2022」
# month => 「12」
# day => 「02」
# to => 「Oct 4 2023」
# date-spec => 「Oct 4 2023」
# date8 => 「Oct 4 2023」
# month => 「Oct」
# month-short-name => 「Oct」
# day => 「4」
# year => 「2023」
```
---
## CLI
The package provides a Command Line Interface (CLI) script. Here is its usage message:
```
datetime-interpretation --help
```
```
# Usage:
# datetime-interpretation <spec> [-t|--target=<Str>] -- Interpret datetime spec.
# datetime-interpretation [<words> ...] [-t|--target=<Str>] -- Interpret datetime spec obtained by a sequence of strings.
# datetime-interpretation [-t|--target=<Str>] -- Interpret datetime spec from pipeline input
#
# <spec> Datetime specification.
# -t|--target=<Str> Interpretation target. [default: 'Raku']
# [<words> ...] Datetime specification.
```
---
## References
[FPS1] Filip Sergot,
[DateTime::Parse Raku package](https://github.com/sergot/datetime-parse),
(2017-2022),
[GitHub/sergot](https://github.com/sergot).
|
## is-20rw.md
is rw
Combined from primary sources listed below.
# [In Type system](#___top "go to top of document")[§](#(Type_system)_trait_is_rw "direct link")
See primary documentation
[in context](/language/typesystem#trait_is_rw)
for **trait is rw**.
```raku
sub trait_mod:<is>(Mu:U $type, :$rw!)
```
The [trait](/type/Sub#Traits) `is rw` on a class will create writable accessor methods on all public attributes of that class.
```raku
class C is rw {
has $.a;
};
my $c = C.new.a = 42;
say $c; # OUTPUT: «42»
```
# [In Routine](#___top "go to top of document")[§](#(Routine)_trait_is_rw "direct link")
See primary documentation
[in context](/type/Routine#trait_is_rw)
for **trait is rw**.
```raku
multi trait_mod:<is>(Routine $r, :$rw!)
```
When a routine is modified with this trait, its return value will be writable. This is useful when returning variables or writable elements of hashes or arrays, for example:
```raku
sub walk(\thing, *@keys) is rw {
my $current := thing;
for @keys -> $k {
if $k ~~ Int {
$current := $current[$k];
}
else {
$current := $current{$k};
}
}
$current;
}
my %hash;
walk(%hash, 'some', 'key', 1, 2) = 'autovivified';
say %hash.raku;
```
produces
```raku
("some" => {"key" => [Any, [Any, Any, "autovivified"]]}).hash
```
Note that `return` marks return values as read only; if you need an early exit from an `is rw` routine, you have to use `return-rw` instead.
|
## dist_zef-antononcube-Text-Plot.md
# Raku Text::Plot
[](http://ci.sparrowhub.io)
This repository has a Raku package for textual (terminal) plots.
Here is the list of functions:
* DONE DONE `text-list-plot`
* DONE DONE `text-pareto-principle-plot`
* DONE DONE `text-histogram`
* TODO TODO `text-plot`
* TODO TODO `text-bar-chart`
***Currently only `text-list-plot`, `text-pareto-principle-plot`, `text-histogram` are implemented.***
It would be nice to also have the function:
* TODO `text-box-plot`
But that would require dependency on a certain statistical package.
(I think it is best to keep this package simple.)
---
## Installation
From zef-ecosystem:
```
zef install Text::Plot
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-Text-Plot.git
```
---
## Usage examples
### `text-list-plot`
Simple plot with y-values only:
```
use Text::Plot;
say text-list-plot((^30)>>.sqrt);
```
```
# +---+-------+--------+--------+--------+--------+--------+-+
# | |
# + * * * ** + 5.00
# | * * * ** |
# + * * ** + 4.00
# | * * ** |
# + ** * + 3.00
# | * * |
# + ** * + 2.00
# | * |
# + * * + 1.00
# | |
# + * + 0.00
# | |
# +---+-------+--------+--------+--------+--------+--------+-+
# 0.00 5.00 10.00 15.00 20.00 25.00 30.00
```
Plot using both x- and y-values, and with specified axes labels, y-tick-labels format, and plot width, height, and
title:
```
my @xs = (0, 0.2 ... 5);
say text-list-plot(@xs, @xs>>.sin,
x-label => 'x-points',
y-label => 'value',
y-tick-labels-format => '%10.2e',
width => 80,
height => 18,
title => 'SINE PLOT');
```
```
# SINE PLOT
# +---+-------------+-------------+-------------+-------------+-------------+----+
# | |
# + * * * * * + 1.00e+00
# | * * |
# | * * |
# + * * + 5.00e-01
# | * * | v
# | * | a
# | * | l
# + * * + 0.00e+00 u
# | * | e
# | |
# + * + -5.00e-01
# | * |
# | * * |
# + * * * * + -1.00e+00
# | |
# +---+-------------+-------------+-------------+-------------+-------------+----+
# 0.00 1.00 2.00 3.00 4.00 5.00
# x-points
```
Smallish plot with custom point character spec:
```
my @xs = (0, 0.05 ... 10);
say text-list-plot(@xs, -1 <<*>> @xs>>.sqrt,
point-char => '·',
width => 40,
height => 12);
```
```
# +--+-----+------+------+------+-----+--+
# + · + 0.00
# | · |
# + ··· + -0.50
# + ··· + -1.00
# + ···· + -1.50
# | ······ |
# + ······ + -2.00
# + ········ + -2.50
# + ········ + -3.00
# + · + -3.50
# +--+-----+------+------+------+-----+--+
# 0.00 2.00 4.00 6.00 8.00 10.00
```
Plot a list of two-element lists:
```
say text-list-plot((^@xs.elems Z @xs>>.cos).List, title => 'Some list of lists'),
```
```
# Some list of lists
# +---+------------+-----------+------------+------------+---+
# | |
# + *** ******* + 1.00
# | ** ** *** |
# + ** *** ** + 0.50
# | ** ** ** |
# | ** * ** |
# + ** * * + 0.00
# | ** * * |
# | ** * * |
# + ** * ** + -0.50
# | *** ** ** |
# + ******* ******* + -1.00
# | |
# +---+------------+-----------+------------+------------+---+
# 0.00 50.00 100.00 150.00 200.00
```
Here is a more complicated example using a randomly generated dataset, [AAp1, AAp2]:
```
use Data::Generators;
use Data::Summarizers;
my @dsRand = random-tabular-dataset(70, <x y>,
generators => [{ random-variate(NormalDistribution.new(4, 2), $_) },
{ random-variate(NormalDistribution.new(12, 3), $_) }]);
records-summary(@dsRand);
```
```
# +------------------------------+-------------------------------+
# | y | x |
# +------------------------------+-------------------------------+
# | Min => 6.728751608514747 | Min => -0.6342550664377802 |
# | 1st-Qu => 10.115185606162802 | 1st-Qu => 2.127501347786245 |
# | Mean => 11.977061937904317 | Mean => 3.701060338012048 |
# | Median => 11.884934801827065 | Median => 3.8810775440571463 |
# | 3rd-Qu => 14.052282754607848 | 3rd-Qu => 5.0641235729310745 |
# | Max => 17.825472186365246 | Max => 8.115595725328749 |
# +------------------------------+-------------------------------+
```
```
text-list-plot(@dsRand.map({ $_<x y> })>>.List,
x-limit => (-2, 10), y-limit => (0, 25),
title => 'Random Normal distribution variates')
```
```
# Random Normal distribution variates
# ++---------+--------+---------+--------+---------+--------++
# + + 25.00
# | |
# + + 20.00
# | * |
# | ** ** * * |
# + * * * * * *** * * + 15.00
# | * *** * * ** **** **** * * |
# + * ** * * * **** * * * * + 10.00
# | * * * * * ** |
# | * * |
# + + 5.00
# | |
# + + 0.00
# ++---------+--------+---------+--------+---------+--------++
# -2.00 0.00 2.00 4.00 6.00 8.00 10.00
```
**Remark:** The function `text-list-plot` has camel case aliases for the multi-word named arguments.
For example, `xLimit` for `x-limit` and `xTickLabelsFormat` for `x-tick-labels-format`.
Here is an example of a multi-list plot:
```
say text-list-plot([([1,1], [2,5], [3,2], [4,5]),
([1,1], [3,3], [3,2]),
([1,3], [2,1], [5,2])], point-char => Whatever);
```
```
# +---+------------+-----------+------------+------------+---+
# | |
# + * * + 5.00
# | |
# + + 4.00
# | |
# | |
# + ▽ □ + 3.00
# | |
# | |
# + □ ▽ + 2.00
# | |
# + □ ▽ + 1.00
# | |
# +---+------------+-----------+------------+------------+---+
# 1.00 2.00 3.00 4.00 5.00
```
**Remark:** Note that the points `[1,1]` and `[3,2]` of the second list overlay the same points of first list.
### `text-pareto-principle-plot`
Assume we have a data vector with all numeric or with all string elements.
The adherence of the data vector to the Pareto principle can be easily verified with the plots of
`text-pareto-principle-plot`.
Here is an example with a numeric vector:
```
text-pareto-principle-plot( random-real(10, 300), title => 'Random reals')
```
```
# Random reals
# 0.00 0.17 0.33 0.50 0.67 0.83 1.00
# +---+-------+--------+--------+-------+--------+-------+---+
# | |
# + *************** + 1.00
# | ******** |
# + ***** + 0.80
# | **** |
# + **** + 0.60
# | ***** |
# + **** + 0.40
# | **** |
# + *** + 0.20
# | *** |
# | *** |
# + + 0.00
# +---+-------+--------+--------+-------+--------+-------+---+
# 0.00 50.00 100.00 150.00 200.00 250.00 300.00
```
Here is an example with a vector of strings:
```
text-pareto-principle-plot( random-pet-name(500), title => 'Random pet names')
```
```
# Random pet names
# 0.00 0.24 0.47 0.71 0.94
# +---+-----------+-----------+-----------+-----------+------+
# | |
# + ****** + 1.00
# | ****** |
# + ******* + 0.80
# | ****** |
# + ****** + 0.60
# | ******* |
# + ****** + 0.40
# | ******* |
# + **** + 0.20
# | **** |
# | ** |
# + + 0.00
# +---+-----------+-----------+-----------+-----------+------+
# 0.00 100.00 200.00 300.00 400.00
```
### `text-histogram`
Here is a vector with normal distribution numbers:
```
my ($μ, $σ) = (5, 2);
my @data = (^500).map({ $μ + $σ * (2 * pi * (1 - rand)).cos * (- 2 * log rand).sqrt });
@data.elems
```
```
# 500
```
Here is a histogram with counts:
```
text-histogram(@data, 30, type => 'count', :filled, point-char => <* *>);
```
```
# +-------------+-----------------+-----------------+--------+
# | |
# + * + 50.00
# | * * |
# + * * * * * + 40.00
# | * ** * * ** |
# + * ** * * ** * + 30.00
# | * * ** * * ** * |
# + * ** * ** * * ** * * + 20.00
# | * ** * ** * * ** * * |
# + * * * ** * ** * * ** * ** * + 10.00
# | ** * * ** * ** * * ** * ** * * * |
# + * * * * ** * * ** * ** * * ** * ** * * * * + 0.00
# | |
# +-------------+-----------------+-----------------+--------+
# 0.00 5.00 10.00
```
Here is a histogram with density function estimate:
```
text-histogram(@data, 30, type => 'cdf', height => 20, :filled, point-char => <* ⏺>);
```
```
# +-------------+-----------------+-----------------+--------+
# | |
# + ⏺ ⏺ ⏺ ⏺ + 1.00
# | ⏺⏺ * * * * |
# | ⏺ ** * * * * |
# + ⏺ * ** * * * * + 0.80
# | ⏺* * ** * * * * |
# | ⏺ ** * ** * * * * |
# + * ** * ** * * * * + 0.60
# | ⏺ * ** * ** * * * * |
# | ⏺ * * ** * ** * * * * |
# + ⏺* * * ** * ** * * * * + 0.40
# | ** * * ** * ** * * * * |
# | ⏺ ** * * ** * ** * * * * |
# + ⏺ * ** * * ** * ** * * * * + 0.20
# | ⏺ ⏺* * ** * * ** * ** * * * * |
# | ⏺ ⏺ * ** * ** * * ** * ** * * * * |
# + ⏺ ⏺ ⏺ ⏺ ⏺* * * ** * ** * * ** * ** * * * * + 0.00
# | |
# +-------------+-----------------+-----------------+--------+
# 0.00 5.00 10.00
```
**Remark:** The second argument is for the number of histogram bins.
The value of the option `:$type` is expected to be one of "count", "probability", "PDF", or "CDF".
---
## Command Line Interface (CLI)
The package function `text-list-plot` can be used through the corresponding CLI:
```
text-list-plot --help
```
```
# Usage:
# text-list-plot [<points> ...] [-p|--point-char=<Str>] [-w|--width[=Int]] [-h|--height[=Int]] [-t|--title=<Str>] [--xLabel|--x-label=<Str>] [--yLabel|--y-label=<Str>] [--xTickLabelsFormat|--x-tick-labels-format=<Str>] [--yTickLabelsFormat|--y-tick-labels-format=<Str>] -- Makes textual (terminal) plots.
# text-list-plot <words> [-p|--point-char=<Str>] [-w|--width[=Int]] [-h|--height[=Int]] [-t|--title=<Str>] [--xLabel|--x-label=<Str>] [--yLabel|--y-label=<Str>] [--xTickLabelsFormat|--x-tick-labels-format=<Str>] [--yTickLabelsFormat|--y-tick-labels-format=<Str>] -- Makes textual (terminal) plots by splitting a string of data points.
# text-list-plot [-p|--point-char=<Str>] [-w|--width[=Int]] [-h|--height[=Int]] [-t|--title=<Str>] [--xLabel|--x-label=<Str>] [--yLabel|--y-label=<Str>] [--xTickLabelsFormat|--x-tick-labels-format=<Str>] [--yTickLabelsFormat|--y-tick-labels-format=<Str>] -- Makes textual (terminal) plots from pipeline input
#
# [<points> ...] Data points.
# -p|--point-char=<Str> Plot points character. [default: '*']
# -w|--width[=Int] Width of the plot. (-1 for Whatever.) [default: -1]
# -h|--height[=Int] Height of the plot. (-1 for Whatever.) [default: -1]
# -t|--title=<Str> Title of the plot. [default: '']
# --xLabel|--x-label=<Str> Label of the X-axis. If Whatever, then no label is placed. [default: '']
# --yLabel|--y-label=<Str> Label of the Y-axis. If Whatever, then no label is placed. [default: '']
# --xTickLabelsFormat|--x-tick-labels-format=<Str> X-axis tick labels format. [default: '']
# --yTickLabelsFormat|--y-tick-labels-format=<Str> Y-axis tick labels format. [default: '']
# <words> String with data points.
```
Here is an example of a simple, y-axis values only call:
```
text-list-plot 33 12 21 10 3 4
```
Here is an example of 2D points call:
```
text-list-plot "22,32 10,39 13,32 14,20"
```
Here is an example pipeline:
```
raku -e 'say (^1000).roll(21)' | text-list-plot
```
**Remark:** Attempt is made plot's width and height are determined automatically, using terminal's number of columns and
lines. If that fails `width=60` is used. In the pipeline example above `text-list-plot` fails to automatically determine
the width and height. (The other example do succeed.)
---
## Implementation notes
* The package functions and their signatures design are easy to come up with, but it is very helpful to have a "good
example" to follow.
* I consider the R-package "txtplot", [BB1], to be such good example.
* There are at least three Python packages for text plots, but only tried them out once. None was as complete and "nice"
as the R-package "txtplot".
* The points and ticks are rescaled with a version of the Mathematica-function
[`Rescale`](https://reference.wolfram.com/language/ref/Rescale.html).
* The axes ticks are computed with a version of the R-function
[`pretty`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/pretty.html).
---
## TODO
* DONE Plotting a list of two-element lists.
* DONE Optional tick labels format specs.
* DONE CLI design and implementation.
* DONE Make use kebab-case for named arguments and make corresponding camel-case aliases.
* DONE Multi-list plot support.
* DONE Plot title.
* DONE `text-pareto-principle-plot`
* DONE `text-histogram`
* TODO Proper respect of width and height.
* Currently, the width and height are for the plot frame -- title, axes- and tick labels are "extra."
* TODO Make the axes ticks to be on the left.
* It was just much easier to put them on the right.
* BTW, this is probably a bug -- the width of the "total plot" is larger than the specified.
* TODO Optional placement of tick values.
* TODO `text-plot`
* Easy to implement inlined with `text-plot`, but it might give a simpler interface.
* TODO `text-bar-chart`
---
## References
[AAp0] Anton Antonov,
[Text::Plot Raku package](https://github.com/antononcube/Raku-Text-Plot),
(2022),
[GitHub/antononcube](https://github.com/antononcube).
[AAp1] Anton Antonov,
[Data::Generators Raku package](https://github.com/antononcube/Raku-Data-Generators),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov,
[Data::Summarizers Raku package](https://github.com/antononcube/Raku-Data-Summarizers),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[BB1] Bjoern Bornkamp,
[txtplot R package](https://github.com/bbnkmp/txtplot),
([CRAN](https://github.com/cran/txtplot)),
(2020),
[GitHub/bbnkmp](https://github.com/bbnkmp).
|
## dist_zef-lizmat-Net-netent.md
[](https://github.com/lizmat/Net-netent/actions)
# NAME
Raku port of Perl's Net::netent module
# SYNOPSIS
```
use Net::netent;
my $n = getnetbyname("loopback") or die "bad net";
printf "%s is %08X\n", $n.name, $n.net;
use Net::netent qw(:FIELDS);
getnetbyname("loopback") or die "bad net";
printf "%s is %08X\n", $n_name, $n_net;
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `Net::netent` module as closely as possible in the Raku Programming Language.
This module's exports `getnetbyname`, `getnetbyaddrd`, and `getnetent` functions that return `Netr::netent` objects. This object has methods that return the similarly named structure field name from the C's netent structure from netdb.h, stripped of their leading "n\_" parts, namely name, aliases, addrtype and net.
You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. Access these fields as variables named with a preceding n\_ in front their method names. Thus, $net\_obj.name corresponds to $n\_name if you import the fields.
The `getnet` function is a simple front-end that forwards a numeric argument to `getnetbyaddr` and the rest to `getnetbyname`.
# PORTING CAVEATS
This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows.
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/Net-netent> . 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_zef-FRITH-Archive-Libarchive.md
[](https://github.com/frithnanth/perl6-Archive-Libarchive/actions)
# NAME
Archive::Libarchive - High-level bindings to libarchive
# SYNOPSIS
```
use v6;
use Archive::Libarchive;
use Archive::Libarchive::Constants;
sub MAIN(:$file! where { .IO.f // die "file '$file' not found" })
{
my Archive::Libarchive $a .= new:
operation => LibarchiveExtract,
file => $file,
flags => ARCHIVE_EXTRACT_TIME +| ARCHIVE_EXTRACT_PERM +| ARCHIVE_EXTRACT_ACL +| ARCHIVE_EXTRACT_FFLAGS;
try {
$a.extract: sub (Archive::Libarchive::Entry $e --> Bool) { $e.pathname eq 'test2' };
CATCH {
say "Can't extract files: $_";
}
}
$a.close;
}
```
For more examples see the `example` directory.
# DESCRIPTION
**Archive::Libarchive** provides an OO interface to libarchive using Archive::Libarchive::Raw.
As the Libarchive site (<http://www.libarchive.org/>) states, its implementation is able to:
* Read a variety of formats, including tar, pax, cpio, zip, xar, lha, ar, cab, mtree, rar, and ISO images.
* Write tar, pax, cpio, zip, xar, ar, ISO, mtree, and shar archives.
* Handle automatically archives compressed with gzip, bzip2, lzip, xz, lzma, or compress.
## new(LibarchiveOp :$operation!, Any :$file?, Int :$flags?, Str :$format?, :@filters?)
Creates an **Archive::Libarchive** object. It takes one *mandatory* argument: `operation`, what kind of operation will be performed.
The list of possible operations is provided by the `LibarchiveOp` enum:
* `LibarchiveRead`: open the archive to list its content.
* `LibarchiveWrite`: create a new archive. The file must not be already present.
* `LibarchiveOverwrite`: create a new archive. The file will be overwritten if present.
* `LibarchiveExtract`: extract the archive content.
When extracting one can specify some options to be applied to the newly created files. The default options are:
`ARCHIVE_EXTRACT_TIME +| ARCHIVE_EXTRACT_PERM +| ARCHIVE_EXTRACT_ACL +| ARCHIVE_EXTRACT_FFLAGS`
Those constants are defined in Archive::Libarchive::Constants, part of the Archive::Libarchive::Raw distribution. More details about those operation modes can be found on the libarchive site: <http://www.libarchive.org/>
If the optional argument `$file` is provided, then it will be opened; if not provided during the initialization, the program must call the `open` method later.
If the optional `$format` argument is provided, then the object will select that specific format while dealing with the archive.
List of possible read formats:
* 7zip
* ar
* cab
* cpio
* empty
* gnutar
* iso9660
* lha
* mtree
* rar
* raw
* tar
* warc
* xar
* zip
List of possible write formats:
* 7zip
* ar
* cpio
* gnutar
* iso9660
* mtree
* pax
* raw
* shar
* ustar
* v7tar
* warc
* xar
* zip
If the optional `@filters` parameter is provided, then the object will add those filter to the archive. Multiple filters can be specified, so a program can manage a file.tar.gz.uu for example. The order of the filters is significant, in order to correctly deal with such files as *file.tar.uu.gz* and *file.tar.gz.uu*.
List of possible read filters:
* bzip2
* compress
* gzip
* grzip
* lrzip
* lz4
* lzip
* lzma
* lzop
* none
* rpm
* uu
* xz
List of possible write filters:
* b64encode
* bzip2
* compress
* grzip
* gzip
* lrzip
* lz4
* lzip
* lzma
* lzop
* none
* uuencode
* xz
### Note
Recent versions of libarchive implement an automatic way to determine the best mix of format and filters. If one's using a pretty recent libarchive, both $format and @filters may be omitted: the **new** method will determine automatically the right combination of parameters. Older versions though don't have that capability and the programmer has to define explicitly both parameters.
## open(Str $filename!, Int :$size?, :$format?, :@filters?)
## open(Buf $data!)
Opens an archive; the first form is used on files, while the second one is used to open an archive that resides in memory. The first argument is always mandatory, while the other ones might been omitted. `$size` is the size of the internal buffer and defaults to 10240 bytes.
**Note:** this module does't apply `$*CWD` to the file name under the hood, so this will create a file in the original directory.
```
use Archive::Libarchive;
my Archive::Libarchive $a .= new: operation => LibarchiveWrite;
chdir 'subdir';
$a.open: 'file.tar.gz', format => 'gnutar', filters => ['gzip'];
…
```
## close
Closes the internal archive object, frees the memory and cleans up.
## extract-opts(Int $flags?)
Sets the options for the files created when extracting files from an archive. The default options are:
`ARCHIVE_EXTRACT_TIME +| ARCHIVE_EXTRACT_PERM +| ARCHIVE_EXTRACT_ACL +| ARCHIVE_EXTRACT_FFLAGS`
## next-header(Archive::Libarchive::Entry:D $e! --> Bool)
When reading an archive this method fills the Entry object and returns True till it reaches the end of the archive.
The Entry object is pubblicly defined inside the Archive::Libarchive module. It's initialized this way:
```
my Archive::Libarchive::Entry $e .= new;
```
So a complete archive lister can be implemented in few lines:
```
use Archive::Libarchive;
sub MAIN(Str :$file! where { .IO.f // die "file '$file' not found" })
{
my Archive::Libarchive $a .= new: operation => LibarchiveRead, file => $file;
my Archive::Libarchive::Entry $e .= new;
while $a.next-header($e) {
$e.pathname.say;
$a.data-skip;
}
$a.close;
}
```
## data-skip(--> Int)
When reading an archive this method skips file data to jump to the next header. It returns `ARCHIVE_OK` or `ARCHIVE_EOF` (defined in Archive::Libarchive::Constants)
## read-file-content(Archive::Libarchive::Entry $e! --> Buf)
This method reads the content of a file represented by its Entry object and returns it.
## write-header(Str $file, Str :$pathname?, Int :$size?, Int :$filetype?, Int :$perm?, Int :$atime?, Int :$mtime?, Int :$ctime?, Int :$birthtime?, Int :$uid?, Int :$gid?, Str :$uname?, Str :$gname? --> Bool)
When creating an archive this method writes the header entry for the file being inserted into the archive. The only mandatory argument is the file name, every other argument has a reasonable default. If the being inserted into the archive is a symbolic link, the target will be composed as a pathname relative to the base directory of the file, not as a full pathname. More details can be found on the libarchive site.
Each optional argument is available as a method of the Archive::Libarchive::Entry object and it can be set when needed.
*Note* `write-header` has a lot of optional arguments whose values are collected from the file one is adding to the archive. When using the second form of `write-data` one has to provide at least these arguments:
* $size
* $atime
* $mtime
* $ctime
For example:
```
$a.write-header($filename,
:size($buffer.bytes),
:atime(now.Int),
:mtime(now.Int),
:ctime(now.Int));
```
## write-data(Str $path --> Bool)
## write-data(Buf $data --> Bool)
When creating an archive this method writes the data for the file being inserted into the archive. `$path` is the pathname of the file to be archived, while `$data` is a data buffer.
## extract(Str $destpath? --> Bool)
## extract(&callback:(Archive::Libarchive::Entry $e --> Bool)!, Str $destpath? --> Bool)
When extracting files from an archive this method does all the dirty work. If used in the first form it extracts all the files. The second form takes a callback function, which receives a Archive::Libarchive::Entry object.
For example, this will extract only the file whose name is *test2*:
```
$a.extract: sub (Archive::Libarchive::Entry $e --> Bool) { $e.pathname eq 'test2' };
```
In both cases one can specify the directory into which the files will be extracted.
## lib-version
Returns a hash with the version number of libarchive and of each library used internally.
# Archive::Libarchive::Entry
This class encapsulate an entry of the archive. It provides the following methods.
### pathname(Str $path)
### pathname(--> Str)
Sets or gets a pathname.
### size(Int $size)
### size(--> int64)
Sets or gets the object's size.
### filetype(Int $type)
### filetype(--> int64)
### filetype(:$decode where :so --> List)
Sets or gets the object's file type. If the first form of the getter is used a bit-mapped value is returned, that can be queried using the AE\_\* constants defined in Archive::Libarchive::Constants. If the second form of the getter is used a list is returned, which contain True or False values for each possible file type, listed in the following order:
* regular file
* directory
* symbolic link
* socket
* character device
* block device
* fifo (named pipe)
This module exports several subs to test the file type:
### is-file(Int $val --> Bool)
### is-dir(Int $val --> Bool)
### is-link(Int $val --> Bool)
### is-sock(Int $val --> Bool)
### is-chr(Int $val --> Bool)
### is-blk(Int $val --> Bool)
### is-fifo(Int $val --> Bool)
### mode(Int $mode)
### mode(--> int64)
Sets or gets the object's mode.
### perm(Int $perm)
### perm(--> int64)
Sets or gets the object's permissions.
### atime(Int $atime)
### atime(--> int64)
Sets or gets the object's access time.
### ctime(Int $ctime)
### ctime(--> int64)
Sets or gets the object's change time.
### mtime(Int $mtime)
### mtime(--> int64)
Sets or gets the object's modification time.
### birthtime(Int $birthtime)
### birthtime()
Sets or resets the object's birth time.
### uid(Int $uid)
### uid(--> int64)
Sets or gets the object's uid.
### gid(Int $gid)
### gid(--> int64)
Sets or gets the object's gid.
### uname(Str $uname)
### uname(--> Str)
Sets or gets the object's user name.
### gname(Str $gname)
### gname(--> Str)
Sets or gets the object's group name.
# Errors
When the underlying library returns an error condition, the methods will return a Failure object, which can be trapped and the exception can be analyzed and acted upon.
The exception object has two fields: `$errno` and `$error`, and return a message stating the error number and the associated message as delivered by libarchive.
# Prerequisites
This module requires the libarchive library to be installed. Please follow the instructions below based on your platform:
## Debian Linux
```
sudo apt-get install libarchive13
```
The module uses Archive::Libarchive::Raw which looks for a library called libarchive.so.
# Installation
To install it using zef (a module management tool):
```
$ zef update
$ zef install Archive::Libarchive
```
# Author
Fernando Santagata
# Contributions
Many thanks to Haythem Elganiny for implementing some multi methods in the **Entry** class.
# License The Artistic License 2.0
|
## accepts.md
ACCEPTS
Combined from primary sources listed below.
# [In Signature](#___top "go to top of document")[§](#(Signature)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Signature#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Signature:D: Signature $topic)
multi method ACCEPTS(Signature:D: Capture $topic)
multi method ACCEPTS(Signature:D: Mu \topic)
```
If `$topic` is a `Signature` returns `True` if anything accepted by `$topic` would also be accepted by the invocant, otherwise returns `False`:
```raku
:($a, $b) ~~ :($foo, $bar, $baz?); # OUTPUT: «True»
:(Int $n) ~~ :(Str); # OUTPUT: «False»
```
The `$topic` is a [`Capture`](/type/Capture), returns `True` if it can be bound to the invocant, i.e., if a function with invocant's `Signature` would be able to be called with the `$topic`:
```raku
\(1, 2, :foo) ~~ :($a, $b, :foo($bar)); # OUTPUT: «True»
\(1, :bar) ~~ :($a); # OUTPUT: «False»
```
Lastly, the candidate with `Mu \topic` converts `topic` to [`Capture`](/type/Capture) and follows the same semantics as [`Capture`](/type/Capture) `$topic`:
```raku
<a b c d> ~~ :(Int $a); # OUTPUT: «False»
42 ~~ :(Int); # OUTPUT: «False» (Int.Capture throws)
set(<a b>) ~~ :(:$a, :$b); # OUTPUT: «True»
```
Since [`where` clauses](/language/signatures#index-entry-where_clause) are not introspectable, the method cannot determine whether two signatures [ACCEPTS](/type/Signature#method_ACCEPTS) the same sort of `where`-constrained parameters. Such comparisons will return `False`. This includes signatures with literals, which are just sugar for the `where`-constraints:
```raku
say :(42) ~~ :($ where 42) # OUTPUT: «False»
```
# [In List](#___top "go to top of document")[§](#(List)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/List#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(List:D: $topic)
```
If `$topic` is an [`Iterable`](/type/Iterable), returns `True` or `False` based on whether the contents of the two [`Iterable`](/type/Iterable)s match. A [`Whatever`](/type/Whatever) element in the invocant matches anything in the corresponding position of the `$topic` [`Iterable`](/type/Iterable). A [`HyperWhatever`](/type/HyperWhatever) matches any number of any elements, including no elements:
```raku
say (1, 2, 3) ~~ (1, *, 3); # OUTPUT: «True»
say (1, 2, 3) ~~ (9, *, 5); # OUTPUT: «False»
say (1, 2, 3) ~~ ( **, 3); # OUTPUT: «True»
say (1, 2, 3) ~~ ( **, 5); # OUTPUT: «False»
say (1, 3) ~~ (1, **, 3); # OUTPUT: «True»
say (1, 2, 4, 5, 3) ~~ (1, **, 3); # OUTPUT: «True»
say (1, 2, 4, 5, 6) ~~ (1, **, 5); # OUTPUT: «False»
say (1, 2, 4, 5, 6) ~~ ( ** ); # OUTPUT: «True»
say () ~~ ( ** ); # OUTPUT: «True»
```
In addition, returns `False` if either the invocant or `$topic` [is a lazy](/routine/is-lazy) [`Iterable`](/type/Iterable), unless `$topic` is the same object as the invocant, in which case `True` is returned.
If `$topic` is *not* an [`Iterable`](/type/Iterable), returns the invocant if the invocant has no elements or its first element is a [`Match`](/type/Match) object (this behavior powers `m:g//` smartmatch), or `False` otherwise.
# [In role Baggy](#___top "go to top of document")[§](#(role_Baggy)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Baggy#method_ACCEPTS)
for **method ACCEPTS**.
```raku
method ACCEPTS($other --> Bool:D)
```
Used in smartmatching if the right-hand side is a `Baggy`.
If the right-hand side is the type object, i.e. `Baggy`, the method returns `True` if `$other` [does](/type/Mu#routine_does) `Baggy` otherwise `False` is returned.
If the right-hand side is a `Baggy` object, `True` is returned only if `$other` has the same elements, with the same weights, as the invocant.
```raku
my $breakfast = bag <eggs bacon>;
say $breakfast ~~ Baggy; # OUTPUT: «True»
say $breakfast.does(Baggy); # OUTPUT: «True»
my $second-breakfast = (eggs => 1, bacon => 1).Mix;
say $breakfast ~~ $second-breakfast; # OUTPUT: «True»
my $third-breakfast = (eggs => 1, bacon => 2).Bag;
say $second-breakfast ~~ $third-breakfast; # OUTPUT: «False»
```
# [In enum Bool](#___top "go to top of document")[§](#(enum_Bool)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Bool#method_ACCEPTS)
for **method ACCEPTS**.
```raku
method ACCEPTS(Bool:D: --> Bool:D)
```
Used for smartmatch comparison. When the right side is `True` returns always `True`, when the right side of the match is `False` returns always `False`. In particular, `ACCEPTS` returns always the instance on which it is invoked, that is the right side of a smartmatch. As an example:
```raku
my $b = Bool.new( True );
# when True on the right side returns
# always True
True ~~ $b; # True
False ~~ $b; # True
$b = Bool.new( False );
# when False on the right side
# returns always False
False ~~ $b; # False
True ~~ $b; # False
```
# [In Regex](#___top "go to top of document")[§](#(Regex)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Regex#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Regex:D: Mu --> Match:D)
multi method ACCEPTS(Regex:D: @)
multi method ACCEPTS(Regex:D: %)
```
Matches the regex against the argument passed in. If the argument is [`Positional`](/type/Positional), it returns the first successful match of any list item. If the argument is [`Associative`](/type/Associative), it returns the first successful match of any key. Otherwise it interprets the argument as a [`Str`](/type/Str) and matches against it.
In the case of Positional and Associative matches, [`Nil`](/type/Nil) is returned on failure.
# [In Str](#___top "go to top of document")[§](#(Str)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Str#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Str:D: $other)
```
Returns `True` if the string is [the same as](/routine/eq) `$other`.
# [In Range](#___top "go to top of document")[§](#(Range)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Range#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Range:D: Mu \topic)
multi method ACCEPTS(Range:D: Range \topic)
multi method ACCEPTS(Range:D: Cool:D \got)
multi method ACCEPTS(Range:D: Complex:D \got)
```
Indicates if the `Range` contains (overlaps with) another `Range`. As an example:
```raku
my $p = Range.new( 3, 5 );
my $r = Range.new( 1, 10 );
say $p.ACCEPTS( $r ); # OUTPUT: «False»
say $r.ACCEPTS( $p ); # OUTPUT: «True»
say $r ~~ $p; # OUTPUT: «False» (same as $p.ACCEPTS( $r )
say $p ~~ $r; # OUTPUT: «True» (same as $r.ACCEPTS( $p )
```
An infinite `Range` always contains any other `Range`, therefore:
```raku
say 1..10 ~~ -∞..∞; # OUTPUT: «True»
say 1..10 ~~ -∞^..^∞; # OUTPUT: «True»
```
Similarly, a `Range` with open boundaries often includes other ranges:
```raku
say 1..2 ~~ *..10; # OUTPUT: «True»
say 2..5 ~~ 1..*; # OUTPUT: «True»
```
It is also possible to use non-numeric ranges, for instance string based ones:
```raku
say 'a'..'j' ~~ 'b'..'c'; # OUTPUT: «False»
say 'b'..'c' ~~ 'a'..'j'; # OUTPUT: «True»
say 'raku' ~~ -∞^..^∞; # OUTPUT: «True»
say 'raku' ~~ -∞..∞; # OUTPUT: «True»
say 'raku' ~~ 1..*; # OUTPUT: «True»
```
When smartmatching a `Range` of integers with a [`Cool`](/type/Cool) (string) the `ACCEPTS` methods exploits the [before](/routine/before) and [after](/routine/after) operators in order to check that the [`Cool`](/type/Cool) value is overlapping the range:
```raku
say 1..10 ~~ '5'; # OUTPUT: «False»
say '5' before 1; # OUTPUT: «False»
say '5' after 10; # OUTPUT: «True»
say '5' ~~ *..10; # OUTPUT: «False»
```
In the above example, since the `'5'` string is *after* the `10` integer value, the `Range` does not overlap with the specified value.
When matching with a [`Mu`](/type/Mu) instance (i.e., a generic instance), the [cmp](/routine/cmp) operator is used.
# [In Map](#___top "go to top of document")[§](#(Map)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Map#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Map:D: Positional $topic)
multi method ACCEPTS(Map:D: Cool:D $topic)
multi method ACCEPTS(Map:D: Regex $topic)
multi method ACCEPTS(Map:D: Any $topic)
```
Used in smartmatching if the right-hand side is a `Map`.
If the topic is list-like ([`Positional`](/type/Positional)), returns True if any of the list elements exist as a key in the Map.
If the topic is of type [`Cool`](/type/Cool) (strings, integers etc.), returns True if the topic exists as a key.
If the topic is a regex, returns True if any of the keys match the regex.
As a fallback, the topic is coerced to a list, and the [`Positional`](/type/Positional) behavior is applied.
# [In Pair](#___top "go to top of document")[§](#(Pair)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Pair#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Pair:D $: %topic)
multi method ACCEPTS(Pair:D $: Pair:D $topic)
multi method ACCEPTS(Pair:D $: Mu $topic)
```
If `%topic` is an [`Associative`](/type/Associative), looks up the value using invocant's key in it and checks invocant's value `.ACCEPTS` that value:
```raku
say %(:42a) ~~ :42a; # OUTPUT: «True»
say %(:42a) ~~ :10a; # OUTPUT: «False»
```
If `$topic` is another `Pair`, checks the invocant's key and value `.ACCEPTS` the `$topic`'s key and value respectively:
```raku
say :42a ~~ :42a; # OUTPUT: «True»
say :42z ~~ :42a; # OUTPUT: «False»
say :10a ~~ :42a; # OUTPUT: «False»
```
If `$topic` is any other value, the invocant `Pair`'s key is treated as a method name. This method is called on `$topic`, the [`Bool`](/type/Bool) result of which is compared against the invocant `Pair`'s [`Bool`](/type/Bool) value. For example, primality can be tested using smartmatch:
```raku
say 3 ~~ :is-prime; # OUTPUT: «True»
say 3 ~~ is-prime => 'truthy'; # OUTPUT: «True»
say 4 ~~ :is-prime; # OUTPUT: «False»
```
This form can also be used to check [`Bool`](/type/Bool) values of multiple methods on the same object, such as [`IO::Path`](/type/IO/Path), by using [`Junction`](/type/Junction)s:
```raku
say "foo" .IO ~~ :f & :rw; # OUTPUT: «False»
say "/tmp".IO ~~ :!f; # OUTPUT: «True»
say "." .IO ~~ :f | :d; # OUTPUT: «True»
```
# [In Whatever](#___top "go to top of document")[§](#(Whatever)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Whatever#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Whatever:D: Mu $other)
multi method ACCEPTS(Whatever:U: Mu $other)
```
If the invocant is [an instance](/language/classtut#A_word_on_types), always returns `True`. If the invocant is a type object, performs a typecheck.
```raku
say 42 ~~ (*); # OUTPUT: «True»
say 42 ~~ Whatever; # OUTPUT: «False»
```
# [In Any](#___top "go to top of document")[§](#(Any)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Any#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Any:D: Mu $other)
```
Usage:
「pseudo」 without highlighting
```
```
EXPR.ACCEPTS(EXPR);
```
```
Returns `True` if `$other === self` (i.e. it checks object identity).
Many built-in types override this for more specific comparisons.
# [In Mu](#___top "go to top of document")[§](#(Mu)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Mu#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Mu:U: $other)
```
`ACCEPTS` is the method that smartmatching with the [infix ~~](/routine/~~) operator and given/when invokes on the right-hand side (the matcher).
The `Mu:U` multi performs a type check. Returns `True` if `$other` conforms to the invocant (which is always a type object or failure).
```raku
say 42 ~~ Mu; # OUTPUT: «True»
say 42 ~~ Int; # OUTPUT: «True»
say 42 ~~ Str; # OUTPUT: «False»
```
Note that there is no multi for defined invocants; this is to allow autothreading of [junctions](/type/Junction), which happens as a fallback mechanism when no direct candidate is available to dispatch to.
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/IO/Path#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(IO::Path:D: Cool:D $other --> Bool:D)
```
Coerces the argument to `IO::Path`, if necessary. Returns `True` if [`.absolute`](/routine/absolute) method on both paths returns the same string. **NOTE:** it's possible for two paths that superficially point to the same resource to NOT smartmatch as `True`, if they were constructed differently and were never fully resolved:
```raku
say "foo/../bar".IO ~~ "bar".IO # False
```
The reason is the two paths above may point to different resources when fully resolved (e.g. if `foo` is a symlink). Resolve the paths before smartmatching to check they point to same resource:
```raku
say "foo/../bar".IO.resolve(:completely) ~~ "bar".IO.resolve(:completely) # True
```
# [In Code](#___top "go to top of document")[§](#(Code)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Code#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Code:D: Mu $topic)
```
Usually calls the code object and passes `$topic` as an argument. However, when called on a code object that takes no arguments, the code object is invoked with no arguments and `$topic` is dropped. The result of the call is returned.
# [In role Numeric](#___top "go to top of document")[§](#(role_Numeric)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Numeric#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Numeric:D: $other)
```
Returns `True` if `$other` can be coerced to `Numeric` and is [numerically equal](/routine/==, infix ⩵) to the invocant (or both evaluate to `NaN`).
# [In role Setty](#___top "go to top of document")[§](#(role_Setty)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Setty#method_ACCEPTS)
for **method ACCEPTS**.
```raku
method ACCEPTS($other)
```
Returns `True` if `$other` and `self` contain all the same elements, and no others.
# [In Allomorph](#___top "go to top of document")[§](#(Allomorph)_method_ACCEPTS "direct link")
See primary documentation
[in context](/type/Allomorph#method_ACCEPTS)
for **method ACCEPTS**.
```raku
multi method ACCEPTS(Allomorph:D: Any:D \a)
```
If the `a` parameter is [`Numeric`](/type/Numeric) (including another [allomorph](/language/glossary#Allomorph)), checks if invocant's [`Numeric`](/type/Numeric) value [ACCEPTS](/type/Numeric#method_ACCEPTS) `a`. If the `a` parameter is [`Str`](/type/Str), checks if invocant's [`Str`](/type/Str) value [ACCEPTS](/type/Str#method_ACCEPTS) `a`. If the `a` parameter is anything else, checks if both [`Numeric`](/type/Numeric) and [`Str`](/type/Str) values of the invocant `ACCEPTS` `a`.
```raku
say "5.0" ~~ <5>; # OUTPUT: «False»
say 5.0 ~~ <5>; # OUTPUT: «True»
say <5.0> ~~ <5>; # OUTPUT: «True»
```
|
## dist_zef-bduggan-AI-Gator.md
[](https://github.com/bduggan/raku-ai-gator/actions/workflows/linux.yml)
[](https://github.com/bduggan/raku-ai-gator/actions/workflows/macos.yml)
# NAME
AI::Gator - Ailigator -- your AI Generic Assistant with a Tool-Oriented REPL

# SYNOPSIS
Put this into $HOME/ai-gator/tools/weather.raku:
```
#| Get real time weather for a given city
our sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
```
Then start the AI Gator REPL:
```
$ ai-gator
You: Is it raining in Toledo?
[tool] get_weather city Toledo
[tool] get_weather done
Gator: No, it is not raining in Toledo. The weather is sunny.
You: What about Philadelphia or San Francisco?
[tool] get_weather city Philadelphia
[tool] get_weather done
[tool] get_weather city San Francisco
[tool] get_weather done
Gator: It is sunny in both Philadelphia and San Francisco.
```
For other options, run:
```
$ ai-gator -h
```
This module can also be used programmatically:
```
use AI::Gator;
my AI::Gator $gator = AI::Gator::Gemini.new: model => 'gemini-2.0-flash';
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello, Gator!";
react whenever $gator.chat($session) -> $chunk {
print $chunk;
}
# Hello! How can I help you today?
```
To use tools programmatically, here is an example:
```
use AI::Gator;
#| Get real time weather for a given city
sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
my AI::Gator $gator = AI::Gator::Gemini.new:
model => 'gemini-2.0-flash',
:quiet,
tools => @( &get_weather, );
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello ailigator!";
react whenever $gator.chat($session) { .print }
# Hello! How can I help you today? 🐊
my $tool-promise = start $gator.tool-builder($session);
$session.add-message: "What is the weather in Paris?";
react whenever $gator.chat($session) { .print }
await $tool-promise;
$gator.do-tool-calls: $session;
react whenever $gator.chat($session) { .print }
# The weather in Paris is sunny.
```
# DESCRIPTION
AI::Gator is an AI assistant oriented towards using tools and a REPL interface.
Features:
* streaming responses
* tool definitions in Raku
* tool calls
* session storage
* Gemini and OpenAI support
* REPL interface with history
Tools are defined as Raku functions and converted into an OpenAI or Gemini specification using declarator pod and other native Raku features.
All sessions are stored in the sessions/ directory, and the REPL stores the history in a .history file, readline-style.
# COMMAND LINE OPTIONS
`ai-gator resume-last` will resume the last session, if it exists.
`ai-gator resume session-id` will resume the specified session.
`ai-gator sessions` will list all sessions.
Also in the REPL:
```
`\history` will show user + assistant commands
`\history all` will show all commands, including tool calls
`\history mine` will show just the user commands
```
# CONFIGURATION
Set AI\_GATOR\_HOME to ai-gator's home (by default $HOME/ai-gator).
In this directory, the following files and directories are used:
* config.toml: configuration file
* tools/: directory with files containing tools
* sessions/: directory with session files (created by the REPL)
* .history: file with readline history (also created by the REPL)
# CONFIGURATION FILE
Sample configuration to use Gemini:
```
model = "gemini-2.0-flash"
adapter = 'Gemini'
```
Sample configuration to use OpenAI:
```
model = "gpt-4o"
base-uri = "https://api.openai.com/v1"
```
# ENVIRONMENT
* AI\_GATOR\_HOME: home directory for AI::Gator (default: $HOME/ai-gator)
* GEMINI\_API\_KEY: API key for Gemini (if using Gemini)
* OPENAI\_API\_KEY: API key for OpenAI (if using OpenAI)
# NOTES
This is all pretty rough and experimental. Expect the api to change. Patches welcome!
# AUTHOR
Brian Duggan
|
## dist_zef-guifa-Polyglot-Brainfuck.md
# Polyglot::Brainfuck
A basic module showing off how Brainfuck can be integrated into Raku.
Instead of using `sub` to declare a subroutine, use `bf` and you can code in BF!
BF subs do not accept signatures. They always have a single optional `buf8` parameter.
BF subs always output a `buf8`;
```
use Polyglot::Brainfuck;
bf hi {
++++++++[>++++[>++>+++>+++>+<<<<-]>
+>+>->>+[<]<-]>>.>---.+++++++..+++.
>>.<-.<.+++.------.--------.>>+.>++.
}
say hi.decode; # Hello World!
bf plus-two {
,++.
}
say plus-two(buf8.new: 40).head; # 42
```
## Version History
* v0.1 Initial release
|
## heading.md
class Pod::Heading
Heading in a Pod document
```raku
class Pod::Heading is Pod::Block { }
```
Class for headings in a Pod document.
# [Methods](#class_Pod::Heading "go to top of document")[§](#Methods "direct link")
## [method level](#class_Pod::Heading "go to top of document")[§](#method_level "direct link")
```raku
method level(--> Int)
```
Returns the level of the heading, starting at 1.
|
## dist_cpan-DMAESTRO-SQL-Lexer.md
# SQL::Lexer
\*\* Under Construction - Pull requests welcome \*\*
## Description
This grammer is a foundation for SQL Language parsers. It handles the common
lexical constructs of SQL.
## Primary Tokens
### Special Characters
* `singlequote`
* `doublequote`
* `quote` - either single or double
* `backquote`
* `period`
* `underscore`
* `plus-sign`
* `minus-sign`
* `left-paren`
* `right-paren`
* `colon`
* `semicolon`
* `comma`
* `solidus` - ordinary forward slash
### Comments
* `simple-comment` - '--' or '#' to end-of-line
* `bracketed-comment` - '/\*' to '\*/' multi-line comment
* `comment` - either of the above
### Literals
* `literal`
* `signed-numeric-literal`
* `unsigned-numeric-literal`
* `char-sting-literal`
* `datetime-literal`
* `interval-literal`
* `date-string`
* `time-string`
* `timestamp-string`
* `boolean-literal`
### Operators
* `operator-symbol`
* `equals-operator`
* `non-equals-operator`
* `less-than-operator`
* `greater-than-operator`
* `plus-operator`
* `minus-operator`
* `multiply-operator`
* `divide-operator`
* `greater-than-or-equals-operator`
* `less-than-or-equals-operator`
### Identifiers
* `quoted-label` quoted with backtick
* `regular-identifier`
* `keyword`
* `non-reserved-word`
* `reserved-word`
=== Other ===
* `variable`
|
## dist_zef-lizmat-eigenstates.md
[](https://github.com/lizmat/eigenstates/actions)
# NAME
eigenstates - expose the eigenstates of an object
# SYNOPSIS
```
use eigenstates;
say eigenstates(1|2|3); # 1 2 3
say eigenstates(42); # 42
```
# DESCRIPTION
The eigenstates distribution exports a single subroutine called `eigenstates` that returns a list of the eigenstates of an object. For all objects except `Junction`s, that's a list with the given object. For a `Junction`, it returns the internal values (aka "eigenstates") as a List.
# TECHNICAL BACKGROUND
Developers starting to use Raku often wonder why there is `Mu` class that is the parent of the `Any` class, with the `Any` class being the default class. The reason for this is the existence of `Junction`s. If you look at the parent classes of e.g. `Int`:
```
say Int.^mro; # ((Int) (Cool) (Any) (Mu))
```
However, if you look at the parent classes of `Junction`:
```
say Junction.^mro; # ((Junction) (Mu))
```
you will notice that `Junction` is **NOT** a subclass of `Any`. It is **that** fact that makes autothreading of values inheriting from `Any` work.
As a consequence, if you want to create a subroutine / method with a signature that will take a `Junction` "as is", you will need to give it a `Mu` constraint. Compare the behaviour of:
```
sub auto-threading($value) { # implicit Any
say $value;
}
auto-threading( 42 | 666 ); # 42666
```
with:
```
sub non-threading(Mu $value) {
say $value;
}
non-threading( 42 | 666 ); # any(42, 666)
```
# AUTHOR
Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)
Source can be located at: <https://github.com/lizmat/eigenstates> . Comments and Pull Requests are welcome.
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2020, 2021, 2022, 2024 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## pick.md
pick
Combined from primary sources listed below.
# [In List](#___top "go to top of document")[§](#(List)_routine_pick "direct link")
See primary documentation
[in context](/type/List#routine_pick)
for **routine pick**.
```raku
multi pick($count, *@list --> Seq:D)
multi method pick(List:D: $count --> Seq:D)
multi method pick(List:D: --> Mu)
multi method pick(List:D: Callable $calculate --> Seq:D)
```
If `$count` is supplied: Returns `$count` elements chosen at random and without repetition from the invocant. If `*` is passed as `$count`, or `$count` is greater than or equal to the size of the list, then all elements from the invocant list are returned in a random sequence; i.e. they are returned shuffled.
In *method* form, if `$count` is omitted: Returns a single random item from the list, or Nil if the list is empty
Examples:
```raku
say <a b c d e>.pick; # OUTPUT: «b»
say <a b c d e>.pick: 3; # OUTPUT: «(c a e)»
say <a b c d e>.pick: *; # OUTPUT: «(e d a b c)»
```
As of the 2021.06 release of the Rakudo compiler, it is also possible to specify `**` (aka [`HyperWhatever`](/type/HyperWhatever)) as the count.
In that case, `.pick` will start picking again on the original list after it has been exhausted, again and again, indefinitely.
```raku
say <a b c>.pick(**).head(10); # OUTPUT: «((a c b c a b b c a b))»
```
# [In role Baggy](#___top "go to top of document")[§](#(role_Baggy)_method_pick "direct link")
See primary documentation
[in context](/type/Baggy#method_pick)
for **method pick**.
```raku
multi method pick(Baggy:D: --> Any)
multi method pick(Baggy:D: $count --> Seq:D)
```
Like an ordinary list [pick](/type/List#routine_pick), but returns keys of the invocant weighted by their values, as if the keys were replicated the number of times indicated by the corresponding value and then list pick used. The underlying metaphor for picking is that you're pulling colored marbles out a bag. (For "picking with replacement" see [roll](#method_roll) instead). If `*` is passed as `$count`, or `$count` is greater than or equal to the [total](#method_total) of the invocant, then `total` elements from the invocant are returned in a random sequence.
Note that each `pick` invocation maintains its own private state and has no effect on subsequent `pick` invocations.
```raku
my $breakfast = bag <eggs bacon bacon bacon>;
say $breakfast.pick; # OUTPUT: «eggs»
say $breakfast.pick(2); # OUTPUT: «(eggs bacon)»
say $breakfast.total; # OUTPUT: «4»
say $breakfast.pick(*); # OUTPUT: «(bacon bacon bacon eggs)»
```
# [In enum Bool](#___top "go to top of document")[§](#(enum_Bool)_routine_pick "direct link")
See primary documentation
[in context](/type/Bool#routine_pick)
for **routine pick**.
```raku
multi method pick(Bool:U: --> Bool:D)
multi method pick(Bool:U: $count --> Seq:D)
```
Returns a random pick of `True` and/or `False`.
If it's called without an argument then it returns just one pick:
```raku
say Bool.pick; # OUTPUT: «True»
```
If it's called with a `$count` of one then it returns a [`Seq`](/type/Seq) with just one pick:
```raku
say Bool.pick(1); # OUTPUT: «(False)»
```
If `$count` is `*` or greater than or equal to two then it returns a [`Seq`](/type/Seq) with *two* elements -- either `True` then `False`, or `False` then `True`:
```raku
say Bool.pick(*); # OUTPUT: «(False True)»
```
# [In role Enumeration](#___top "go to top of document")[§](#(role_Enumeration)_method_pick "direct link")
See primary documentation
[in context](/type/Enumeration#method_pick)
for **method pick**.
```raku
multi method pick(::?CLASS:U:)
multi method pick(::?CLASS:U: \n)
multi method pick(::?CLASS:D: *@pos)
```
It works on the defined class, selecting one element and eliminating it.
```raku
say Norse-gods.pick() for ^3; # OUTPUT: «ÞorFreijaOðin»
```
# [In Range](#___top "go to top of document")[§](#(Range)_method_pick "direct link")
See primary documentation
[in context](/type/Range#method_pick)
for **method pick**.
```raku
multi method pick(Range:D: --> Any:D)
multi method pick(Range:D: $number --> Seq:D)
```
Performs the same function as `Range.list.pick`, but attempts to optimize by not actually generating the list if it is not necessary.
# [In Any](#___top "go to top of document")[§](#(Any)_method_pick "direct link")
See primary documentation
[in context](/type/Any#method_pick)
for **method pick**.
```raku
multi method pick(--> Any)
multi method pick($n --> Seq)
```
Coerces the invocant to a [`List`](/type/List) by applying its [`.list`](/routine/list) method and uses [`List.pick`](/type/List#routine_pick) on it.
```raku
my Range $rg = 'α'..'ω';
say $rg.pick(3); # OUTPUT: «(β α σ)»
```
# [In role Setty](#___top "go to top of document")[§](#(role_Setty)_method_pick "direct link")
See primary documentation
[in context](/type/Setty#method_pick)
for **method pick**.
```raku
multi method pick($count = 1)
```
Returns `$count` elements chosen at random (without repetition) from the set.
If `*` is passed as `$count`, or `$count` is greater than or equal to the size of the set, then all its elements are returned in random order (shuffled).
# [In role Mixy](#___top "go to top of document")[§](#(role_Mixy)_method_pick "direct link")
See primary documentation
[in context](/type/Mixy#method_pick)
for **method pick**.
```raku
method pick($?)
```
Throws an exception. The feature is not supported on the type, since there's no clear value to subtract from non-integral weights, to make it work.
|
## dist_zef-raku-community-modules-OpenSSL.md
[](https://github.com/raku-community-modules/OpenSSL/actions) [](https://github.com/raku-community-modules/OpenSSL/actions) [](https://github.com/raku-community-modules/OpenSSL/actions)
# NAME
OpenSSL - OpenSSL bindings
# SYNOPSIS
```
use OpenSSL;
my $openssl = OpenSSL.new;
$openssl.set-fd(123);
$openssl.write("GET / HTTP/1.1\r\nHost: somehost\r\n\r\n");
```
# DESCRIPTION
A module which provides OpenSSL bindings, making us able to set up a TLS/SSL connection.
# METHODS
## method new
```
method new(Bool :$client = False, Int :$version?)
```
A constructor. Initializes OpenSSL library, sets method and context. If $version is not specified, the highest possible version is negotiated.
## method set-fd
```
method set-fd(OpenSSL:, int32 $fd)
```
Assigns connection's file descriptor (file handle) $fd to the SSL object.
To get the $fd we should use C to set up the connection. (See <NativeCall>) I hope we will be able to use Raku's IO::Socket module instead of connecting through C soon-ish.
## method set-connect-state
```
method set-connect-state(OpenSSL:)
```
Sets SSL object to connect (client) state.
Use it when you want to connect to SSL servers.
## method set-accept-state
```
method set-accept-state(OpenSSL:)
```
Sets SSL object to accept (server) state.
Use it when you want to provide an SSL server.
## method connect
```
method connect(OpenSSL:)
```
Connects to the server using $fd (passed using .set-fd).
Does all the SSL stuff like handshaking.
## method accept
```
method accept(OpenSSL:)
```
Accepts new client connection.
Does all the SSL stuff like handshaking.
## method write
```
method write(OpenSSL:, Str $s)
```
Sends $s to the other side (server/client).
## method read
```
method read(OpenSSL:, Int $n, Bool :$bin)
```
Reads $n bytes from the other side (server/client).
Bool :$bin if we want it to return Buf instead of Str.
## method use-certificate-file
```
method use-certificate-file(OpenSSL:, Str $file)
```
Assings a certificate (from file) to the SSL object.
## method use-privatekey-file
```
method use-privatekey-file(OpenSSL:, Str $file)
```
Assings a private key (from file) to the SSL object.
## method check-private-key
```
method check-private-key(OpenSSL:)
```
Checks if private key is valid.
## method shutdown
```
method shutdown(OpenSSL:)
```
Turns off the connection.
## method ctx-free
```
method ctx-free(OpenSSL:)
```
Frees C's SSL\_CTX struct.
## method ssl-free
```
method ssl-free(OpenSSL:)
```
Frees C's SSL struct.
## method close
```
method close(OpenSSL:)
```
Closes the connection.
Unlike .shutdown it calls ssl-free, ctx-free, and then it shutdowns.
# TOOLS
Public key signing tools.
## OpenSSL::RSATools
```
use OpenSSL::RSATools;
my $pem = slurp 'key.pem';
my $rsa = OpenSSL::RSAKey.new(private-pem => $pem);
my $data = 'as df jk l';
my $signature = $rsa.sign($data.encode);
my $rsa = OpenSSL::RSAKey.new(public-pem => $public);
if $rsa.verify($data.encode, $signature) { ... }
```
## OpenSSL::CryptTools
Symmetric encryption tools (currently only AES256/192/128 encrypt/decrypt)
```
use OpenSSL::CryptTools;
my $ciphertext = encrypt("asdf".encode,
:aes256,
:iv(("0" x 16).encode),
:key(('x' x 32).encode));
my $plaintext = decrypt($ciphertext,
:aes256,
:iv(("0" x 16).encode),
:key(('x' x 32).encode));
```
## OpenSSL::Digest
Digest Functions (currently only md5/sha1/sha256/sha384/sha512)
```
use OpenSSL::Digest;
my Blob $digest = md5("xyz".encode);
```
## OpenSSL::Digest::MD5
OO-Interface supporting incremental digesting
```
use OpenSSL::Digest::MD5;
my $md5 = OpenSSL::Digest::MD5.new; # Create fresh object
$md5.add('abc'); # pass in Str or Blob
$md5.add('def'); # Add some more data
my $digest = $md5.hash; # Blob hash (and reset)
$md5.addfile('myfile'); # Read a file
my $hexdigest = $md5.hex; # hex hash (and reset)
```
# CAVEATS
## MacOS
Many native libraries on MacOS are installed with the `brew` command line interface. For this module one would typically have to do a `brew install openssl`.
The use of native libraries is slightly more complicated on the MacOS operating system than on other operating systems. This generally means that a symlink needs to be installed in a trusted filesystem location. If the [`MacOS::NativeLib`](https://raku.land/zef:lizmat/MacOS::NativeLib) distribution is installed, then these symlinks will be automatically created when this module is built.
# SEE ALSO
IO::Socket::SSL
# AUTHOR
* Filip Sergot
Source can be located at: <https://github.com/raku-community-modules/OpenSSL> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2014 - 2022 Filip Sergot
Copyright 2023 - 2025 The Raku Community
This library is free software; you can redistribute it and/or modify it under the MIT License.
|
## dist_zef-demanuel-HTML-EscapeUtils.md
# HTML-EscapeUtils
Functionalities to escape and unescape HTML
# SYNOPSIS
```
use HTML::EscapeUtils;
escape("<^o^>"); # => '<^o^>'
unescape("<^o^>"); #=> '<^o^>'
unescape("Foo © bar 𝌆 baz ☃ qux"); #=> 'Foo © bar 𝌆 baz ☃ qux'
```
# DESCRIPTION
HTML::Escape provides functions to escape and unescape HTML's special characters.
Supports named entities (like for example: ' ') and numeric ones as well (like for example ' ' or '&xA0;')
# Functions
## `escape(Str $raw-str) returns Str`
Escapes HTML's special characters in given string.
## `unescape(Str $raw-str) returns Str`
Unescapes HTML's special characters in given string.
# COPYRIGHT AND LICENSE
```
Copyright 2023- demanuel <demanuel+cb@ymail.com>
This library is free software; you can redistribute it and/or modify it under the EU 1.2 public license
```
|
## default.md
class X::Parameter::Default
Compilation error due to an unallowed default value in a signature
```raku
class X::Parameter::Default does X::Comp { }
```
Compile-time error thrown when a parameter in a signature has default value, but isn't allowed to have one. That is the case with slurpy parameters (because a slurpy always binds successfully, even to zero arguments) and with mandatory parameters.
Example:
```raku
sub f($x! = 3) { }
```
dies with
「text」 without highlighting
```
```
===SORRY!===
Cannot put default on required parameter $x
```
```
And
```raku
sub f(*@ = 3) { }
```
dies with
「text」 without highlighting
```
```
===SORRY!===
Cannot put default on anonymous slurpy parameter
```
```
# [Methods](#class_X::Parameter::Default "go to top of document")[§](#Methods "direct link")
## [method how](#class_X::Parameter::Default "go to top of document")[§](#method_how "direct link")
Returns a string describing how the parameter is qualified that makes it disallow default values, for example `"slurpy"` or `"mandatory"`.
## [method parameter](#class_X::Parameter::Default "go to top of document")[§](#method_parameter "direct link")
Returns the parameter name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.